airbyte-agent-jira 0.1.22__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. airbyte_agent_jira/__init__.py +91 -0
  2. airbyte_agent_jira/_vendored/__init__.py +1 -0
  3. airbyte_agent_jira/_vendored/connector_sdk/__init__.py +82 -0
  4. airbyte_agent_jira/_vendored/connector_sdk/auth_strategies.py +1123 -0
  5. airbyte_agent_jira/_vendored/connector_sdk/auth_template.py +135 -0
  6. airbyte_agent_jira/_vendored/connector_sdk/cloud_utils/__init__.py +5 -0
  7. airbyte_agent_jira/_vendored/connector_sdk/cloud_utils/client.py +213 -0
  8. airbyte_agent_jira/_vendored/connector_sdk/connector_model_loader.py +965 -0
  9. airbyte_agent_jira/_vendored/connector_sdk/constants.py +78 -0
  10. airbyte_agent_jira/_vendored/connector_sdk/exceptions.py +23 -0
  11. airbyte_agent_jira/_vendored/connector_sdk/executor/__init__.py +31 -0
  12. airbyte_agent_jira/_vendored/connector_sdk/executor/hosted_executor.py +197 -0
  13. airbyte_agent_jira/_vendored/connector_sdk/executor/local_executor.py +1574 -0
  14. airbyte_agent_jira/_vendored/connector_sdk/executor/models.py +190 -0
  15. airbyte_agent_jira/_vendored/connector_sdk/extensions.py +694 -0
  16. airbyte_agent_jira/_vendored/connector_sdk/http/__init__.py +37 -0
  17. airbyte_agent_jira/_vendored/connector_sdk/http/adapters/__init__.py +9 -0
  18. airbyte_agent_jira/_vendored/connector_sdk/http/adapters/httpx_adapter.py +251 -0
  19. airbyte_agent_jira/_vendored/connector_sdk/http/config.py +98 -0
  20. airbyte_agent_jira/_vendored/connector_sdk/http/exceptions.py +119 -0
  21. airbyte_agent_jira/_vendored/connector_sdk/http/protocols.py +114 -0
  22. airbyte_agent_jira/_vendored/connector_sdk/http/response.py +102 -0
  23. airbyte_agent_jira/_vendored/connector_sdk/http_client.py +686 -0
  24. airbyte_agent_jira/_vendored/connector_sdk/introspection.py +262 -0
  25. airbyte_agent_jira/_vendored/connector_sdk/logging/__init__.py +11 -0
  26. airbyte_agent_jira/_vendored/connector_sdk/logging/logger.py +264 -0
  27. airbyte_agent_jira/_vendored/connector_sdk/logging/types.py +92 -0
  28. airbyte_agent_jira/_vendored/connector_sdk/observability/__init__.py +11 -0
  29. airbyte_agent_jira/_vendored/connector_sdk/observability/models.py +19 -0
  30. airbyte_agent_jira/_vendored/connector_sdk/observability/redactor.py +81 -0
  31. airbyte_agent_jira/_vendored/connector_sdk/observability/session.py +94 -0
  32. airbyte_agent_jira/_vendored/connector_sdk/performance/__init__.py +6 -0
  33. airbyte_agent_jira/_vendored/connector_sdk/performance/instrumentation.py +57 -0
  34. airbyte_agent_jira/_vendored/connector_sdk/performance/metrics.py +93 -0
  35. airbyte_agent_jira/_vendored/connector_sdk/schema/__init__.py +75 -0
  36. airbyte_agent_jira/_vendored/connector_sdk/schema/base.py +161 -0
  37. airbyte_agent_jira/_vendored/connector_sdk/schema/components.py +239 -0
  38. airbyte_agent_jira/_vendored/connector_sdk/schema/connector.py +131 -0
  39. airbyte_agent_jira/_vendored/connector_sdk/schema/extensions.py +109 -0
  40. airbyte_agent_jira/_vendored/connector_sdk/schema/operations.py +146 -0
  41. airbyte_agent_jira/_vendored/connector_sdk/schema/security.py +223 -0
  42. airbyte_agent_jira/_vendored/connector_sdk/secrets.py +182 -0
  43. airbyte_agent_jira/_vendored/connector_sdk/telemetry/__init__.py +10 -0
  44. airbyte_agent_jira/_vendored/connector_sdk/telemetry/config.py +32 -0
  45. airbyte_agent_jira/_vendored/connector_sdk/telemetry/events.py +58 -0
  46. airbyte_agent_jira/_vendored/connector_sdk/telemetry/tracker.py +151 -0
  47. airbyte_agent_jira/_vendored/connector_sdk/types.py +245 -0
  48. airbyte_agent_jira/_vendored/connector_sdk/utils.py +60 -0
  49. airbyte_agent_jira/_vendored/connector_sdk/validation.py +822 -0
  50. airbyte_agent_jira/connector.py +978 -0
  51. airbyte_agent_jira/connector_model.py +2827 -0
  52. airbyte_agent_jira/models.py +741 -0
  53. airbyte_agent_jira/types.py +117 -0
  54. airbyte_agent_jira-0.1.22.dist-info/METADATA +113 -0
  55. airbyte_agent_jira-0.1.22.dist-info/RECORD +56 -0
  56. airbyte_agent_jira-0.1.22.dist-info/WHEEL +4 -0
@@ -0,0 +1,965 @@
1
+ """Load and parse connector YAML definitions into ConnectorModel objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Any
8
+ from uuid import UUID
9
+
10
+ import jsonref
11
+ import yaml
12
+ from pydantic import ValidationError
13
+
14
+ from .constants import (
15
+ OPENAPI_DEFAULT_VERSION,
16
+ OPENAPI_VERSION_PREFIX,
17
+ )
18
+
19
+ from .schema import OpenAPIConnector
20
+ from .schema.components import GraphQLBodyConfig, RequestBody
21
+ from .schema.security import AirbyteAuthConfig, AuthConfigFieldSpec
22
+ from .types import (
23
+ Action,
24
+ AuthConfig,
25
+ AuthOption,
26
+ AuthType,
27
+ ConnectorModel,
28
+ ContentType,
29
+ EndpointDefinition,
30
+ EntityDefinition,
31
+ )
32
+
33
+
34
+ class ConnectorModelLoaderError(Exception):
35
+ """Base exception for connector model loading errors."""
36
+
37
+ pass
38
+
39
+
40
+ class InvalidYAMLError(ConnectorModelLoaderError):
41
+ """Raised when YAML syntax is invalid."""
42
+
43
+ pass
44
+
45
+
46
+ class InvalidOpenAPIError(ConnectorModelLoaderError):
47
+ """Raised when OpenAPI specification is invalid."""
48
+
49
+ pass
50
+
51
+
52
+ class DuplicateEntityError(ConnectorModelLoaderError):
53
+ """Raised when duplicate entity names are detected."""
54
+
55
+ pass
56
+
57
+
58
+ class TokenExtractValidationError(ConnectorModelLoaderError):
59
+ """Raised when x-airbyte-token-extract references invalid server variables."""
60
+
61
+ pass
62
+
63
+
64
+ def extract_path_params(path: str) -> list[str]:
65
+ """Extract parameter names from path template.
66
+
67
+ Example: '/v1/customers/{id}/invoices/{invoice_id}' -> ['id', 'invoice_id']
68
+ """
69
+ return re.findall(r"\{(\w+)\}", path)
70
+
71
+
72
+ def resolve_schema_refs(schema: Any, spec_dict: dict) -> dict[str, Any]:
73
+ """Resolve all $ref references in a schema using jsonref.
74
+
75
+ This handles:
76
+ - Simple $refs to components/schemas
77
+ - Nested $refs within schemas
78
+ - Circular references (jsonref handles these gracefully)
79
+
80
+ Args:
81
+ schema: The schema that may contain $refs (can be dict or Pydantic model)
82
+ spec_dict: The full OpenAPI spec as a dict (for reference resolution)
83
+
84
+ Returns:
85
+ Resolved schema as a dictionary with all $refs replaced by their definitions
86
+ """
87
+ if not schema:
88
+ return {}
89
+
90
+ # Convert schema to dict if it's a Pydantic model
91
+ if hasattr(schema, "model_dump"):
92
+ schema_dict = schema.model_dump(by_alias=True, exclude_none=True)
93
+ elif isinstance(schema, dict):
94
+ schema_dict = schema
95
+ else:
96
+ return {}
97
+
98
+ # If there are no $refs, return as-is
99
+ if "$ref" not in str(schema_dict):
100
+ return schema_dict
101
+
102
+ # Use jsonref to resolve all references
103
+ # We need to embed the schema in the spec for proper reference resolution
104
+ temp_spec = spec_dict.copy()
105
+ temp_spec["__temp_schema__"] = schema_dict
106
+
107
+ try:
108
+ # Resolve all references
109
+ resolved_spec = jsonref.replace_refs( # type: ignore[union-attr]
110
+ temp_spec,
111
+ base_uri="",
112
+ jsonschema=True, # Use JSONSchema draft 7 semantics
113
+ lazy_load=False, # Resolve everything immediately
114
+ )
115
+
116
+ # Extract our resolved schema
117
+ resolved_schema = dict(resolved_spec.get("__temp_schema__", {}))
118
+
119
+ # Remove any remaining jsonref proxy objects by converting to plain dict
120
+ return _deproxy_schema(resolved_schema)
121
+ except (AttributeError, KeyError, RecursionError, Exception):
122
+ # If resolution fails, return the original schema
123
+ # This allows the system to continue even with malformed $refs
124
+ # AttributeError covers the case where jsonref might be None
125
+ # Exception catches jsonref.JsonRefError and other jsonref exceptions
126
+ return schema_dict
127
+
128
+
129
+ def _deproxy_schema(obj: Any) -> Any:
130
+ """Recursively convert jsonref proxy objects to plain dicts/lists.
131
+
132
+ jsonref returns proxy objects that behave like dicts but aren't actual dicts.
133
+ This converts them to plain Python objects for consistent behavior.
134
+ """
135
+ if isinstance(obj, dict) or (hasattr(obj, "__subject__") and hasattr(obj, "keys")):
136
+ # Handle both dicts and jsonref proxy objects
137
+ try:
138
+ return {str(k): _deproxy_schema(v) for k, v in obj.items()}
139
+ except (AttributeError, TypeError):
140
+ return obj
141
+ elif isinstance(obj, (list, tuple)):
142
+ return [_deproxy_schema(item) for item in obj]
143
+ else:
144
+ return obj
145
+
146
+
147
+ def parse_openapi_spec(raw_config: dict) -> OpenAPIConnector:
148
+ """Parse OpenAPI specification from YAML.
149
+
150
+ Args:
151
+ raw_config: Raw YAML configuration
152
+
153
+ Returns:
154
+ Parsed OpenAPIConnector with full validation
155
+
156
+ Raises:
157
+ InvalidOpenAPIError: If OpenAPI spec is invalid or missing required fields
158
+ """
159
+ # Validate OpenAPI version
160
+ openapi_version = raw_config.get("openapi", "")
161
+ if not openapi_version:
162
+ raise InvalidOpenAPIError("Missing required field: 'openapi' version")
163
+
164
+ # Check if version is 3.1.x (we don't support 2.x or 3.0.x)
165
+ if not openapi_version.startswith(OPENAPI_VERSION_PREFIX):
166
+ raise InvalidOpenAPIError(f"Unsupported OpenAPI version: {openapi_version}. Only {OPENAPI_VERSION_PREFIX}x is supported.")
167
+
168
+ # Validate required top-level fields
169
+ if "info" not in raw_config:
170
+ raise InvalidOpenAPIError("Missing required field: 'info'")
171
+
172
+ if "paths" not in raw_config:
173
+ raise InvalidOpenAPIError("Missing required field: 'paths'")
174
+
175
+ # Validate paths is not empty
176
+ if not raw_config["paths"]:
177
+ raise InvalidOpenAPIError("OpenAPI spec must have at least one path definition")
178
+
179
+ # Parse with Pydantic validation
180
+ try:
181
+ spec = OpenAPIConnector(**raw_config)
182
+ except ValidationError as e:
183
+ raise InvalidOpenAPIError(f"OpenAPI validation failed: {e}")
184
+
185
+ return spec
186
+
187
+
188
+ def _extract_request_body_config(
189
+ request_body: RequestBody | None, spec_dict: dict[str, Any]
190
+ ) -> tuple[list[str], dict[str, Any] | None, dict[str, Any] | None]:
191
+ """Extract request body configuration (GraphQL or standard).
192
+
193
+ Args:
194
+ request_body: RequestBody object from OpenAPI operation
195
+ spec_dict: Full OpenAPI spec dict for $ref resolution
196
+
197
+ Returns:
198
+ Tuple of (body_fields, request_schema, graphql_body)
199
+ - body_fields: List of field names for standard JSON/form bodies
200
+ - request_schema: Resolved request schema dict (for standard bodies)
201
+ - graphql_body: GraphQL body configuration dict (for GraphQL bodies)
202
+ """
203
+ body_fields: list[str] = []
204
+ request_schema: dict[str, Any] | None = None
205
+ graphql_body: dict[str, Any] | None = None
206
+
207
+ if not request_body:
208
+ return body_fields, request_schema, graphql_body
209
+
210
+ # Check for GraphQL extension and extract GraphQL body configuration
211
+ if request_body.x_airbyte_body_type:
212
+ body_type_config = request_body.x_airbyte_body_type
213
+
214
+ # Check if it's GraphQL type (it's a GraphQLBodyConfig Pydantic model)
215
+ if isinstance(body_type_config, GraphQLBodyConfig):
216
+ # Convert Pydantic model to dict, excluding None values
217
+ graphql_body = body_type_config.model_dump(exclude_none=True, by_alias=False)
218
+ return body_fields, request_schema, graphql_body
219
+
220
+ # Parse standard request body
221
+ for content_type_key, media_type in request_body.content.items():
222
+ # media_type is now a MediaType object with schema_ field
223
+ schema = media_type.schema_ or {}
224
+
225
+ # Resolve all $refs in the schema using jsonref
226
+ request_schema = resolve_schema_refs(schema, spec_dict)
227
+
228
+ # Extract body field names from resolved schema
229
+ if isinstance(request_schema, dict) and "properties" in request_schema:
230
+ body_fields = list(request_schema["properties"].keys())
231
+
232
+ return body_fields, request_schema, graphql_body
233
+
234
+
235
+ def convert_openapi_to_connector_model(spec: OpenAPIConnector) -> ConnectorModel:
236
+ """Convert OpenAPI spec to ConnectorModel format.
237
+
238
+ Args:
239
+ spec: OpenAPI connector specification (fully validated)
240
+
241
+ Returns:
242
+ ConnectorModel with entities and endpoints
243
+ """
244
+ # Validate x-airbyte-token-extract against server variables
245
+ _validate_token_extract(spec)
246
+
247
+ # Convert spec to dict for jsonref resolution
248
+ spec_dict = spec.model_dump(by_alias=True, exclude_none=True)
249
+
250
+ # Extract connector name and version
251
+ name = spec.info.x_airbyte_connector_name or spec.info.title.lower().replace(" ", "-")
252
+ version = spec.info.version
253
+
254
+ # Parse authentication first to get token_extract fields
255
+ auth_config = _parse_auth_from_openapi(spec)
256
+
257
+ # Extract base URL from servers - keep variable placeholders intact
258
+ # Variables will be substituted at runtime by HTTPClient using:
259
+ # - config_values: for user-provided values like subdomain
260
+ # - token_extract: for OAuth dynamic values like instance_url
261
+ # DO NOT substitute defaults here - that would prevent runtime substitution
262
+ base_url = ""
263
+ if spec.servers:
264
+ base_url = spec.servers[0].url
265
+
266
+ # Group operations by entity
267
+ entities_map: dict[str, dict[str, EndpointDefinition]] = {}
268
+
269
+ for path, path_item in spec.paths.items():
270
+ # Check each HTTP method
271
+ for method_name in ["get", "post", "put", "delete", "patch"]:
272
+ operation = getattr(path_item, method_name, None)
273
+ if not operation:
274
+ continue
275
+
276
+ # Extract entity and action from x-airbyte-entity and x-airbyte-action
277
+ entity_name = operation.x_airbyte_entity
278
+ action_name = operation.x_airbyte_action
279
+ path_override = operation.x_airbyte_path_override
280
+ record_extractor = operation.x_airbyte_record_extractor
281
+ meta_extractor = operation.x_airbyte_meta_extractor
282
+
283
+ if not entity_name:
284
+ raise InvalidOpenAPIError(
285
+ f"Missing required x-airbyte-entity in operation {method_name.upper()} {path}. All operations must specify an entity."
286
+ )
287
+
288
+ if not action_name:
289
+ raise InvalidOpenAPIError(
290
+ f"Missing required x-airbyte-action in operation {method_name.upper()} {path}. All operations must specify an action."
291
+ )
292
+
293
+ # Convert to Action enum
294
+ try:
295
+ action = Action(action_name)
296
+ except ValueError:
297
+ # Provide clear error for invalid actions
298
+ valid_actions = ", ".join([a.value for a in Action])
299
+ raise InvalidOpenAPIError(
300
+ f"Invalid action '{action_name}' in operation {method_name.upper()} {path}. Valid actions are: {valid_actions}"
301
+ )
302
+
303
+ # Determine content type
304
+ content_type = ContentType.JSON
305
+ if operation.request_body and operation.request_body.content:
306
+ if "application/x-www-form-urlencoded" in operation.request_body.content:
307
+ content_type = ContentType.FORM_URLENCODED
308
+ elif "multipart/form-data" in operation.request_body.content:
309
+ content_type = ContentType.FORM_DATA
310
+
311
+ # Extract parameters with their schemas (including defaults)
312
+ path_params: list[str] = []
313
+ path_params_schema: dict[str, dict[str, Any]] = {}
314
+ query_params: list[str] = []
315
+ query_params_schema: dict[str, dict[str, Any]] = {}
316
+ deep_object_params: list[str] = []
317
+
318
+ if operation.parameters:
319
+ for param in operation.parameters:
320
+ param_schema = param.schema_ or {}
321
+ schema_info = {
322
+ "type": param_schema.get("type", "string"),
323
+ "required": param.required or False,
324
+ "default": param_schema.get("default"),
325
+ }
326
+
327
+ if param.in_ == "path":
328
+ path_params.append(param.name)
329
+ # Path params are always required
330
+ schema_info["required"] = True
331
+ path_params_schema[param.name] = schema_info
332
+ elif param.in_ == "query":
333
+ query_params.append(param.name)
334
+ query_params_schema[param.name] = schema_info
335
+ # Check if this is a deepObject style parameter
336
+ if hasattr(param, "style") and param.style == "deepObject":
337
+ deep_object_params.append(param.name)
338
+
339
+ # Extract body fields from request schema
340
+ body_fields, request_schema, graphql_body = _extract_request_body_config(operation.request_body, spec_dict)
341
+
342
+ # Extract response schema
343
+ response_schema = None
344
+ if "200" in operation.responses:
345
+ response = operation.responses["200"]
346
+ if response.content and "application/json" in response.content:
347
+ media_type = response.content["application/json"]
348
+ schema = media_type.schema_ if media_type else {}
349
+
350
+ # Resolve all $refs in the response schema using jsonref
351
+ response_schema = resolve_schema_refs(schema, spec_dict)
352
+
353
+ # Extract file_field for download operations
354
+ file_field = getattr(operation, "x_airbyte_file_url", None)
355
+
356
+ # Extract untested flag
357
+ untested = getattr(operation, "x_airbyte_untested", None) or False
358
+
359
+ # Create endpoint definition
360
+ endpoint = EndpointDefinition(
361
+ method=method_name.upper(),
362
+ action=action,
363
+ path=path,
364
+ path_override=path_override,
365
+ record_extractor=record_extractor,
366
+ meta_extractor=meta_extractor,
367
+ description=operation.description or operation.summary,
368
+ body_fields=body_fields,
369
+ query_params=query_params,
370
+ query_params_schema=query_params_schema,
371
+ deep_object_params=deep_object_params,
372
+ path_params=path_params,
373
+ path_params_schema=path_params_schema,
374
+ content_type=content_type,
375
+ request_schema=request_schema,
376
+ response_schema=response_schema,
377
+ graphql_body=graphql_body,
378
+ file_field=file_field,
379
+ untested=untested,
380
+ )
381
+
382
+ # Add to entities map
383
+ if entity_name not in entities_map:
384
+ entities_map[entity_name] = {}
385
+ entities_map[entity_name][action] = endpoint
386
+
387
+ # Note: No need to check for duplicate entity names - the dict structure
388
+ # automatically ensures uniqueness. If the OpenAPI spec contains duplicate
389
+ # operationIds, only the last one will be kept.
390
+
391
+ # Convert entities map to EntityDefinition list
392
+ entities = []
393
+ for entity_name, endpoints_dict in entities_map.items():
394
+ actions = list(endpoints_dict.keys())
395
+
396
+ # Get schema and stream_name from components if available
397
+ schema = None
398
+ entity_stream_name = None
399
+ if spec.components:
400
+ # Look for a schema matching the entity name
401
+ for schema_name, schema_def in spec.components.schemas.items():
402
+ if schema_def.x_airbyte_entity_name == entity_name or schema_name.lower() == entity_name.lower():
403
+ schema = schema_def.model_dump(by_alias=True)
404
+ entity_stream_name = schema_def.x_airbyte_stream_name
405
+ break
406
+
407
+ entity = EntityDefinition(
408
+ name=entity_name,
409
+ stream_name=entity_stream_name,
410
+ actions=actions,
411
+ endpoints=endpoints_dict,
412
+ schema=schema,
413
+ )
414
+ entities.append(entity)
415
+
416
+ # Extract retry config from x-airbyte-retry-config extension
417
+ retry_config = spec.info.x_airbyte_retry_config
418
+ connector_id = spec.info.x_airbyte_connector_id
419
+ if not connector_id:
420
+ raise InvalidOpenAPIError("Missing required x-airbyte-connector-id field")
421
+
422
+ # Create ConnectorModel
423
+ model = ConnectorModel(
424
+ id=connector_id,
425
+ name=name,
426
+ version=version,
427
+ base_url=base_url,
428
+ auth=auth_config,
429
+ entities=entities,
430
+ openapi_spec=spec,
431
+ retry_config=retry_config,
432
+ )
433
+
434
+ return model
435
+
436
+
437
+ def _get_attribute_flexible(obj: Any, *names: str) -> Any:
438
+ """Get attribute from object, trying multiple name variants.
439
+
440
+ Supports both snake_case and camelCase attribute names.
441
+ Returns None if no variant is found.
442
+
443
+ Args:
444
+ obj: Object to get attribute from
445
+ *names: Attribute names to try in order
446
+
447
+ Returns:
448
+ Attribute value if found, None otherwise
449
+
450
+ Example:
451
+ # Try both "refresh_url" and "refreshUrl"
452
+ url = _get_attribute_flexible(flow, "refresh_url", "refreshUrl")
453
+ """
454
+ for name in names:
455
+ value = getattr(obj, name, None)
456
+ if value is not None:
457
+ return value
458
+ return None
459
+
460
+
461
+ def _select_oauth2_flow(flows: Any) -> Any:
462
+ """Select the best OAuth2 flow from available flows.
463
+
464
+ Prefers authorizationCode (most secure for web apps), but falls back
465
+ to other flow types if not available.
466
+
467
+ Args:
468
+ flows: OAuth2 flows object from OpenAPI spec
469
+
470
+ Returns:
471
+ Selected flow object, or None if no flows available
472
+ """
473
+ # Priority order: authorizationCode > clientCredentials > password > implicit
474
+ flow_names = [
475
+ ("authorization_code", "authorizationCode"), # Preferred
476
+ ("client_credentials", "clientCredentials"), # Server-to-server
477
+ ("password", "password"), # Resource owner
478
+ ("implicit", "implicit"), # Legacy, less secure
479
+ ]
480
+
481
+ for snake_case, camel_case in flow_names:
482
+ flow = _get_attribute_flexible(flows, snake_case, camel_case)
483
+ if flow:
484
+ return flow
485
+
486
+ return None
487
+
488
+
489
+ def _parse_oauth2_config(scheme: Any) -> dict[str, str]:
490
+ """Parse OAuth2 authentication configuration from OpenAPI scheme.
491
+
492
+ Extracts configuration from standard OAuth2 flows and custom x-airbyte-token-refresh
493
+ extension for additional refresh behavior customization.
494
+
495
+ Args:
496
+ scheme: OAuth2 security scheme from OpenAPI spec
497
+
498
+ Returns:
499
+ Dictionary with OAuth2 configuration including:
500
+ - header: Authorization header name (default: "Authorization")
501
+ - prefix: Token prefix (default: "Bearer")
502
+ - refresh_url: Token refresh endpoint (from flows)
503
+ - auth_style: How to send credentials (from x-airbyte-token-refresh)
504
+ - body_format: Request encoding (from x-airbyte-token-refresh)
505
+ """
506
+ config: dict[str, str] = {
507
+ "header": "Authorization",
508
+ "prefix": "Bearer",
509
+ }
510
+
511
+ # Extract flow information for refresh_url
512
+ if scheme.flows:
513
+ flow = _select_oauth2_flow(scheme.flows)
514
+ if flow:
515
+ # Try to get refresh URL (supports both naming conventions)
516
+ refresh_url = _get_attribute_flexible(flow, "refresh_url", "refreshUrl")
517
+ if refresh_url:
518
+ config["refresh_url"] = refresh_url
519
+
520
+ # Extract custom refresh configuration from x-airbyte-token-refresh extension
521
+ x_token_refresh = getattr(scheme, "x_token_refresh", None)
522
+ if x_token_refresh:
523
+ auth_style = getattr(x_token_refresh, "auth_style", None)
524
+ if auth_style:
525
+ config["auth_style"] = auth_style
526
+
527
+ body_format = getattr(x_token_refresh, "body_format", None)
528
+ if body_format:
529
+ config["body_format"] = body_format
530
+
531
+ # Extract token_extract fields from x-airbyte-token-extract extension
532
+ x_token_extract = getattr(scheme, "x_airbyte_token_extract", None)
533
+ if x_token_extract:
534
+ config["token_extract"] = x_token_extract
535
+
536
+ return config
537
+
538
+
539
+ def _validate_token_extract(spec: OpenAPIConnector) -> None:
540
+ """Validate x-airbyte-token-extract against server variables.
541
+
542
+ Ensures that fields specified in x-airbyte-token-extract match defined
543
+ server variables. This catches configuration errors at load time rather
544
+ than at runtime during token refresh.
545
+
546
+ Args:
547
+ spec: OpenAPI connector specification
548
+
549
+ Raises:
550
+ TokenExtractValidationError: If token_extract fields don't match server variables
551
+ """
552
+ # Get server variables
553
+ server_variables: set[str] = set()
554
+ if spec.servers:
555
+ for server in spec.servers:
556
+ if server.variables:
557
+ server_variables.update(server.variables.keys())
558
+
559
+ # Get token_extract from security scheme
560
+ if not spec.components or not spec.components.security_schemes:
561
+ return
562
+
563
+ for scheme_name, scheme in spec.components.security_schemes.items():
564
+ if scheme.type != "oauth2":
565
+ continue
566
+
567
+ token_extract = getattr(scheme, "x_airbyte_token_extract", None)
568
+ if not token_extract:
569
+ continue
570
+
571
+ # Validate each field matches a server variable
572
+ for field in token_extract:
573
+ if field not in server_variables:
574
+ raise TokenExtractValidationError(
575
+ f"x-airbyte-token-extract field '{field}' does not match any defined "
576
+ f"server variable. Available server variables: {sorted(server_variables) or 'none'}. "
577
+ f"Please define '{{{field}}}' in your server URL and add a variable definition."
578
+ )
579
+
580
+
581
+ def _generate_default_auth_config(auth_type: AuthType) -> AirbyteAuthConfig:
582
+ """Generate default x-airbyte-auth-config for an auth type.
583
+
584
+ When x-airbyte-auth-config is not explicitly defined in the OpenAPI spec,
585
+ we generate a sensible default that maps user-friendly field names to
586
+ the auth scheme's parameters.
587
+
588
+ Args:
589
+ auth_type: The authentication type (BEARER, BASIC, API_KEY)
590
+
591
+ Returns:
592
+ Default auth config spec with properties and auth_mapping
593
+ """
594
+ if auth_type == AuthType.BEARER:
595
+ return AirbyteAuthConfig(
596
+ title=None,
597
+ description=None,
598
+ type="object",
599
+ required=["token"],
600
+ properties={
601
+ "token": AuthConfigFieldSpec(
602
+ type="string",
603
+ title="Bearer Token",
604
+ description="Authentication bearer token",
605
+ format=None,
606
+ pattern=None,
607
+ airbyte_secret=False,
608
+ default=None,
609
+ )
610
+ },
611
+ auth_mapping={"token": "${token}"},
612
+ oneOf=None,
613
+ )
614
+ elif auth_type == AuthType.BASIC:
615
+ return AirbyteAuthConfig(
616
+ title=None,
617
+ description=None,
618
+ type="object",
619
+ required=["username", "password"],
620
+ properties={
621
+ "username": AuthConfigFieldSpec(
622
+ type="string",
623
+ title="Username",
624
+ description="Authentication username",
625
+ format=None,
626
+ pattern=None,
627
+ airbyte_secret=False,
628
+ default=None,
629
+ ),
630
+ "password": AuthConfigFieldSpec(
631
+ type="string",
632
+ title="Password",
633
+ description="Authentication password",
634
+ format=None,
635
+ pattern=None,
636
+ airbyte_secret=False,
637
+ default=None,
638
+ ),
639
+ },
640
+ auth_mapping={"username": "${username}", "password": "${password}"},
641
+ oneOf=None,
642
+ )
643
+ elif auth_type == AuthType.API_KEY:
644
+ return AirbyteAuthConfig(
645
+ title=None,
646
+ description=None,
647
+ type="object",
648
+ required=["api_key"],
649
+ properties={
650
+ "api_key": AuthConfigFieldSpec(
651
+ type="string",
652
+ title="API Key",
653
+ description="API authentication key",
654
+ format=None,
655
+ pattern=None,
656
+ airbyte_secret=False,
657
+ default=None,
658
+ )
659
+ },
660
+ auth_mapping={"api_key": "${api_key}"},
661
+ oneOf=None,
662
+ )
663
+ elif auth_type == AuthType.OAUTH2:
664
+ # OAuth2: No fields are strictly required to support both modes:
665
+ # 1. Full token mode: user provides access_token (and optionally refresh credentials)
666
+ # 2. Refresh-token-only mode: user provides refresh_token, client_id, client_secret
667
+ # The auth_mapping includes all fields, but apply_auth_mapping
668
+ # will skip mappings for fields not provided by the user.
669
+ return AirbyteAuthConfig(
670
+ title=None,
671
+ description=None,
672
+ type="object",
673
+ required=[],
674
+ properties={
675
+ "access_token": AuthConfigFieldSpec(
676
+ type="string",
677
+ title="Access Token",
678
+ description="OAuth2 access token",
679
+ format=None,
680
+ pattern=None,
681
+ airbyte_secret=False,
682
+ default=None,
683
+ ),
684
+ "refresh_token": AuthConfigFieldSpec(
685
+ type="string",
686
+ title="Refresh Token",
687
+ description="OAuth2 refresh token (optional)",
688
+ format=None,
689
+ pattern=None,
690
+ airbyte_secret=False,
691
+ default=None,
692
+ ),
693
+ "client_id": AuthConfigFieldSpec(
694
+ type="string",
695
+ title="Client ID",
696
+ description="OAuth2 client ID (optional)",
697
+ format=None,
698
+ pattern=None,
699
+ airbyte_secret=False,
700
+ default=None,
701
+ ),
702
+ "client_secret": AuthConfigFieldSpec(
703
+ type="string",
704
+ title="Client Secret",
705
+ description="OAuth2 client secret (optional)",
706
+ format=None,
707
+ pattern=None,
708
+ airbyte_secret=False,
709
+ default=None,
710
+ ),
711
+ },
712
+ auth_mapping={
713
+ "access_token": "${access_token}",
714
+ "refresh_token": "${refresh_token}",
715
+ "client_id": "${client_id}",
716
+ "client_secret": "${client_secret}",
717
+ },
718
+ oneOf=None,
719
+ )
720
+ else:
721
+ # Unknown auth type - return minimal config
722
+ return AirbyteAuthConfig(
723
+ title=None,
724
+ description=None,
725
+ type="object",
726
+ required=None,
727
+ properties={},
728
+ auth_mapping={},
729
+ oneOf=None,
730
+ )
731
+
732
+
733
+ def _parse_auth_from_openapi(spec: OpenAPIConnector) -> AuthConfig:
734
+ """Parse authentication configuration from OpenAPI spec.
735
+
736
+ Supports both single and multiple security schemes. For backwards compatibility,
737
+ single-scheme connectors continue to use the legacy AuthConfig format.
738
+ If no security schemes are defined, generates a default Bearer auth config.
739
+
740
+ Args:
741
+ spec: OpenAPI connector specification
742
+
743
+ Returns:
744
+ AuthConfig with either single or multiple auth options
745
+ """
746
+ if not spec.components or not spec.components.security_schemes:
747
+ # Backwards compatibility: generate default Bearer auth when no schemes defined
748
+ default_config = _generate_default_auth_config(AuthType.BEARER)
749
+ return AuthConfig(
750
+ type=AuthType.BEARER,
751
+ config={"header": "Authorization", "prefix": "Bearer"},
752
+ user_config_spec=default_config,
753
+ options=None,
754
+ )
755
+
756
+ schemes = spec.components.security_schemes
757
+
758
+ # Single scheme: backwards compatible mode
759
+ if len(schemes) == 1:
760
+ scheme_name, scheme = next(iter(schemes.items()))
761
+ return _parse_single_security_scheme(scheme)
762
+
763
+ # Multiple schemes: new multi-auth mode
764
+ options = []
765
+ for scheme_name, scheme in schemes.items():
766
+ try:
767
+ auth_option = _parse_security_scheme_to_option(scheme_name, scheme)
768
+ options.append(auth_option)
769
+ except Exception as e:
770
+ # Log warning but continue - skip invalid schemes
771
+ import logging
772
+
773
+ logger = logging.getLogger(__name__)
774
+ logger.warning(f"Skipping invalid security scheme '{scheme_name}': {e}")
775
+ continue
776
+
777
+ if not options:
778
+ raise InvalidOpenAPIError("No valid security schemes found. Connector must define at least one valid security scheme.")
779
+
780
+ return AuthConfig(
781
+ type=None,
782
+ config={},
783
+ user_config_spec=None,
784
+ options=options,
785
+ )
786
+
787
+
788
+ def _parse_single_security_scheme(scheme: Any) -> AuthConfig:
789
+ """Parse a single security scheme into AuthConfig.
790
+
791
+ This extracts the existing single-scheme parsing logic for reuse.
792
+
793
+ Args:
794
+ scheme: SecurityScheme from OpenAPI spec
795
+
796
+ Returns:
797
+ AuthConfig in single-auth mode
798
+ """
799
+ auth_type = AuthType.API_KEY # Default
800
+ auth_config = {}
801
+
802
+ if scheme.type == "http":
803
+ if scheme.scheme == "bearer":
804
+ auth_type = AuthType.BEARER
805
+ auth_config = {"header": "Authorization", "prefix": "Bearer"}
806
+ elif scheme.scheme == "basic":
807
+ auth_type = AuthType.BASIC
808
+ auth_config = {}
809
+
810
+ elif scheme.type == "apiKey":
811
+ auth_type = AuthType.API_KEY
812
+ auth_config = {
813
+ "header": scheme.name or "Authorization",
814
+ "in": scheme.in_ or "header",
815
+ }
816
+
817
+ elif scheme.type == "oauth2":
818
+ # Parse OAuth2 configuration
819
+ oauth2_config = _parse_oauth2_config(scheme)
820
+ # Use explicit x-airbyte-auth-config if present, otherwise generate default
821
+ auth_config_obj = scheme.x_airbyte_auth_config or _generate_default_auth_config(AuthType.OAUTH2)
822
+ return AuthConfig(
823
+ type=AuthType.OAUTH2,
824
+ config=oauth2_config,
825
+ user_config_spec=auth_config_obj,
826
+ options=None,
827
+ )
828
+
829
+ # Use explicit x-airbyte-auth-config if present, otherwise generate default
830
+ auth_config_obj = scheme.x_airbyte_auth_config or _generate_default_auth_config(auth_type)
831
+
832
+ return AuthConfig(
833
+ type=auth_type,
834
+ config=auth_config,
835
+ user_config_spec=auth_config_obj,
836
+ options=None,
837
+ )
838
+
839
+
840
+ def _parse_security_scheme_to_option(scheme_name: str, scheme: Any) -> AuthOption:
841
+ """Parse a security scheme into an AuthOption for multi-auth connectors.
842
+
843
+ Args:
844
+ scheme_name: Name of the security scheme (e.g., "githubOAuth")
845
+ scheme: SecurityScheme from OpenAPI spec
846
+
847
+ Returns:
848
+ AuthOption containing the parsed configuration
849
+
850
+ Raises:
851
+ ValueError: If scheme is invalid or unsupported
852
+ """
853
+ # Parse using existing single-scheme logic
854
+ single_auth = _parse_single_security_scheme(scheme)
855
+
856
+ # Convert to AuthOption
857
+ return AuthOption(
858
+ scheme_name=scheme_name,
859
+ type=single_auth.type,
860
+ config=single_auth.config,
861
+ user_config_spec=single_auth.user_config_spec,
862
+ )
863
+
864
+
865
+ def load_connector_model(definition_path: str | Path) -> ConnectorModel:
866
+ """Load connector model from YAML definition file.
867
+
868
+ Supports both OpenAPI 3.1 format and legacy format.
869
+
870
+ Args:
871
+ definition_path: Path to connector.yaml file
872
+
873
+ Returns:
874
+ Parsed ConnectorModel
875
+
876
+ Raises:
877
+ FileNotFoundError: If definition file doesn't exist
878
+ ValueError: If YAML is invalid
879
+ """
880
+ definition_path = Path(definition_path)
881
+
882
+ if not definition_path.exists():
883
+ raise FileNotFoundError(f"Connector definition not found: {definition_path}")
884
+
885
+ # Load YAML with error handling
886
+ try:
887
+ with open(definition_path) as f:
888
+ raw_definition = yaml.safe_load(f)
889
+ except yaml.YAMLError as e:
890
+ raise InvalidYAMLError(f"Invalid YAML syntax in {definition_path}: {e}")
891
+ except Exception as e:
892
+ raise ConnectorModelLoaderError(f"Error reading definition file {definition_path}: {e}")
893
+
894
+ if not raw_definition:
895
+ raise ValueError("Invalid connector.yaml: empty file")
896
+
897
+ # Detect format: OpenAPI if 'openapi' key exists
898
+ if "openapi" in raw_definition:
899
+ spec = parse_openapi_spec(raw_definition)
900
+ return convert_openapi_to_connector_model(spec)
901
+
902
+ # Legacy format
903
+ if "connector" not in raw_definition:
904
+ raise ValueError("Invalid connector.yaml: missing 'connector' or 'openapi' key")
905
+
906
+ # Parse connector metadata
907
+ connector_meta = raw_definition["connector"]
908
+
909
+ # Parse auth config
910
+ auth_config = raw_definition.get("auth", {})
911
+
912
+ # Parse entities
913
+ entities = []
914
+ for entity_data in raw_definition.get("entities", []):
915
+ # Parse endpoints for each action
916
+ endpoints_dict = {}
917
+ for action_str in entity_data.get("actions", []):
918
+ action = Action(action_str)
919
+ endpoint_data = entity_data["endpoints"].get(action_str)
920
+
921
+ if endpoint_data:
922
+ # Extract path parameters from the path template
923
+ path_params = extract_path_params(endpoint_data["path"])
924
+
925
+ endpoint = EndpointDefinition(
926
+ method=endpoint_data["method"],
927
+ path=endpoint_data["path"],
928
+ description=endpoint_data.get("description"),
929
+ body_fields=endpoint_data.get("body_fields", []),
930
+ query_params=endpoint_data.get("query_params", []),
931
+ path_params=path_params,
932
+ graphql_body=None, # GraphQL only supported in OpenAPI format (via x-airbyte-body-type)
933
+ )
934
+ endpoints_dict[action] = endpoint
935
+
936
+ entity = EntityDefinition(
937
+ name=entity_data["name"],
938
+ actions=[Action(a) for a in entity_data["actions"]],
939
+ endpoints=endpoints_dict,
940
+ schema=entity_data.get("schema"),
941
+ )
942
+ entities.append(entity)
943
+
944
+ # Get connector ID
945
+ connector_id_value = connector_meta.get("id")
946
+ if connector_id_value:
947
+ # Try to parse as UUID (handles string UUIDs)
948
+ if isinstance(connector_id_value, str):
949
+ connector_id = UUID(connector_id_value)
950
+ else:
951
+ connector_id = connector_id_value
952
+ else:
953
+ raise ValueError
954
+
955
+ # Build ConnectorModel
956
+ model = ConnectorModel(
957
+ id=connector_id,
958
+ name=connector_meta["name"],
959
+ version=connector_meta.get("version", OPENAPI_DEFAULT_VERSION),
960
+ base_url=raw_definition.get("base_url", connector_meta.get("base_url", "")),
961
+ auth=auth_config,
962
+ entities=entities,
963
+ )
964
+
965
+ return model