airbyte-agent-hubspot 0.15.20__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 (55) hide show
  1. airbyte_agent_hubspot/__init__.py +86 -0
  2. airbyte_agent_hubspot/_vendored/__init__.py +1 -0
  3. airbyte_agent_hubspot/_vendored/connector_sdk/__init__.py +82 -0
  4. airbyte_agent_hubspot/_vendored/connector_sdk/auth_strategies.py +1123 -0
  5. airbyte_agent_hubspot/_vendored/connector_sdk/auth_template.py +135 -0
  6. airbyte_agent_hubspot/_vendored/connector_sdk/cloud_utils/__init__.py +5 -0
  7. airbyte_agent_hubspot/_vendored/connector_sdk/cloud_utils/client.py +213 -0
  8. airbyte_agent_hubspot/_vendored/connector_sdk/connector_model_loader.py +957 -0
  9. airbyte_agent_hubspot/_vendored/connector_sdk/constants.py +78 -0
  10. airbyte_agent_hubspot/_vendored/connector_sdk/exceptions.py +23 -0
  11. airbyte_agent_hubspot/_vendored/connector_sdk/executor/__init__.py +31 -0
  12. airbyte_agent_hubspot/_vendored/connector_sdk/executor/hosted_executor.py +197 -0
  13. airbyte_agent_hubspot/_vendored/connector_sdk/executor/local_executor.py +1504 -0
  14. airbyte_agent_hubspot/_vendored/connector_sdk/executor/models.py +190 -0
  15. airbyte_agent_hubspot/_vendored/connector_sdk/extensions.py +655 -0
  16. airbyte_agent_hubspot/_vendored/connector_sdk/http/__init__.py +37 -0
  17. airbyte_agent_hubspot/_vendored/connector_sdk/http/adapters/__init__.py +9 -0
  18. airbyte_agent_hubspot/_vendored/connector_sdk/http/adapters/httpx_adapter.py +251 -0
  19. airbyte_agent_hubspot/_vendored/connector_sdk/http/config.py +98 -0
  20. airbyte_agent_hubspot/_vendored/connector_sdk/http/exceptions.py +119 -0
  21. airbyte_agent_hubspot/_vendored/connector_sdk/http/protocols.py +114 -0
  22. airbyte_agent_hubspot/_vendored/connector_sdk/http/response.py +102 -0
  23. airbyte_agent_hubspot/_vendored/connector_sdk/http_client.py +679 -0
  24. airbyte_agent_hubspot/_vendored/connector_sdk/logging/__init__.py +11 -0
  25. airbyte_agent_hubspot/_vendored/connector_sdk/logging/logger.py +264 -0
  26. airbyte_agent_hubspot/_vendored/connector_sdk/logging/types.py +92 -0
  27. airbyte_agent_hubspot/_vendored/connector_sdk/observability/__init__.py +11 -0
  28. airbyte_agent_hubspot/_vendored/connector_sdk/observability/models.py +19 -0
  29. airbyte_agent_hubspot/_vendored/connector_sdk/observability/redactor.py +81 -0
  30. airbyte_agent_hubspot/_vendored/connector_sdk/observability/session.py +94 -0
  31. airbyte_agent_hubspot/_vendored/connector_sdk/performance/__init__.py +6 -0
  32. airbyte_agent_hubspot/_vendored/connector_sdk/performance/instrumentation.py +57 -0
  33. airbyte_agent_hubspot/_vendored/connector_sdk/performance/metrics.py +93 -0
  34. airbyte_agent_hubspot/_vendored/connector_sdk/schema/__init__.py +75 -0
  35. airbyte_agent_hubspot/_vendored/connector_sdk/schema/base.py +161 -0
  36. airbyte_agent_hubspot/_vendored/connector_sdk/schema/components.py +238 -0
  37. airbyte_agent_hubspot/_vendored/connector_sdk/schema/connector.py +131 -0
  38. airbyte_agent_hubspot/_vendored/connector_sdk/schema/extensions.py +109 -0
  39. airbyte_agent_hubspot/_vendored/connector_sdk/schema/operations.py +146 -0
  40. airbyte_agent_hubspot/_vendored/connector_sdk/schema/security.py +213 -0
  41. airbyte_agent_hubspot/_vendored/connector_sdk/secrets.py +182 -0
  42. airbyte_agent_hubspot/_vendored/connector_sdk/telemetry/__init__.py +10 -0
  43. airbyte_agent_hubspot/_vendored/connector_sdk/telemetry/config.py +32 -0
  44. airbyte_agent_hubspot/_vendored/connector_sdk/telemetry/events.py +58 -0
  45. airbyte_agent_hubspot/_vendored/connector_sdk/telemetry/tracker.py +151 -0
  46. airbyte_agent_hubspot/_vendored/connector_sdk/types.py +241 -0
  47. airbyte_agent_hubspot/_vendored/connector_sdk/utils.py +60 -0
  48. airbyte_agent_hubspot/_vendored/connector_sdk/validation.py +822 -0
  49. airbyte_agent_hubspot/connector.py +1104 -0
  50. airbyte_agent_hubspot/connector_model.py +2660 -0
  51. airbyte_agent_hubspot/models.py +438 -0
  52. airbyte_agent_hubspot/types.py +217 -0
  53. airbyte_agent_hubspot-0.15.20.dist-info/METADATA +105 -0
  54. airbyte_agent_hubspot-0.15.20.dist-info/RECORD +55 -0
  55. airbyte_agent_hubspot-0.15.20.dist-info/WHEEL +4 -0
@@ -0,0 +1,957 @@
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 from components if available
397
+ schema = None
398
+ if spec.components:
399
+ # Look for a schema matching the entity name
400
+ for schema_name, schema_def in spec.components.schemas.items():
401
+ if schema_def.x_airbyte_entity_name == entity_name or schema_name.lower() == entity_name.lower():
402
+ schema = schema_def.model_dump(by_alias=True)
403
+ break
404
+
405
+ entity = EntityDefinition(name=entity_name, actions=actions, endpoints=endpoints_dict, schema=schema)
406
+ entities.append(entity)
407
+
408
+ # Extract retry config from x-airbyte-retry-config extension
409
+ retry_config = spec.info.x_airbyte_retry_config
410
+ connector_id = spec.info.x_airbyte_connector_id
411
+ if not connector_id:
412
+ raise InvalidOpenAPIError("Missing required x-airbyte-connector-id field")
413
+
414
+ # Create ConnectorModel
415
+ model = ConnectorModel(
416
+ id=connector_id,
417
+ name=name,
418
+ version=version,
419
+ base_url=base_url,
420
+ auth=auth_config,
421
+ entities=entities,
422
+ openapi_spec=spec,
423
+ retry_config=retry_config,
424
+ )
425
+
426
+ return model
427
+
428
+
429
+ def _get_attribute_flexible(obj: Any, *names: str) -> Any:
430
+ """Get attribute from object, trying multiple name variants.
431
+
432
+ Supports both snake_case and camelCase attribute names.
433
+ Returns None if no variant is found.
434
+
435
+ Args:
436
+ obj: Object to get attribute from
437
+ *names: Attribute names to try in order
438
+
439
+ Returns:
440
+ Attribute value if found, None otherwise
441
+
442
+ Example:
443
+ # Try both "refresh_url" and "refreshUrl"
444
+ url = _get_attribute_flexible(flow, "refresh_url", "refreshUrl")
445
+ """
446
+ for name in names:
447
+ value = getattr(obj, name, None)
448
+ if value is not None:
449
+ return value
450
+ return None
451
+
452
+
453
+ def _select_oauth2_flow(flows: Any) -> Any:
454
+ """Select the best OAuth2 flow from available flows.
455
+
456
+ Prefers authorizationCode (most secure for web apps), but falls back
457
+ to other flow types if not available.
458
+
459
+ Args:
460
+ flows: OAuth2 flows object from OpenAPI spec
461
+
462
+ Returns:
463
+ Selected flow object, or None if no flows available
464
+ """
465
+ # Priority order: authorizationCode > clientCredentials > password > implicit
466
+ flow_names = [
467
+ ("authorization_code", "authorizationCode"), # Preferred
468
+ ("client_credentials", "clientCredentials"), # Server-to-server
469
+ ("password", "password"), # Resource owner
470
+ ("implicit", "implicit"), # Legacy, less secure
471
+ ]
472
+
473
+ for snake_case, camel_case in flow_names:
474
+ flow = _get_attribute_flexible(flows, snake_case, camel_case)
475
+ if flow:
476
+ return flow
477
+
478
+ return None
479
+
480
+
481
+ def _parse_oauth2_config(scheme: Any) -> dict[str, str]:
482
+ """Parse OAuth2 authentication configuration from OpenAPI scheme.
483
+
484
+ Extracts configuration from standard OAuth2 flows and custom x-airbyte-token-refresh
485
+ extension for additional refresh behavior customization.
486
+
487
+ Args:
488
+ scheme: OAuth2 security scheme from OpenAPI spec
489
+
490
+ Returns:
491
+ Dictionary with OAuth2 configuration including:
492
+ - header: Authorization header name (default: "Authorization")
493
+ - prefix: Token prefix (default: "Bearer")
494
+ - refresh_url: Token refresh endpoint (from flows)
495
+ - auth_style: How to send credentials (from x-airbyte-token-refresh)
496
+ - body_format: Request encoding (from x-airbyte-token-refresh)
497
+ """
498
+ config: dict[str, str] = {
499
+ "header": "Authorization",
500
+ "prefix": "Bearer",
501
+ }
502
+
503
+ # Extract flow information for refresh_url
504
+ if scheme.flows:
505
+ flow = _select_oauth2_flow(scheme.flows)
506
+ if flow:
507
+ # Try to get refresh URL (supports both naming conventions)
508
+ refresh_url = _get_attribute_flexible(flow, "refresh_url", "refreshUrl")
509
+ if refresh_url:
510
+ config["refresh_url"] = refresh_url
511
+
512
+ # Extract custom refresh configuration from x-airbyte-token-refresh extension
513
+ x_token_refresh = getattr(scheme, "x_token_refresh", None)
514
+ if x_token_refresh:
515
+ auth_style = getattr(x_token_refresh, "auth_style", None)
516
+ if auth_style:
517
+ config["auth_style"] = auth_style
518
+
519
+ body_format = getattr(x_token_refresh, "body_format", None)
520
+ if body_format:
521
+ config["body_format"] = body_format
522
+
523
+ # Extract token_extract fields from x-airbyte-token-extract extension
524
+ x_token_extract = getattr(scheme, "x_airbyte_token_extract", None)
525
+ if x_token_extract:
526
+ config["token_extract"] = x_token_extract
527
+
528
+ return config
529
+
530
+
531
+ def _validate_token_extract(spec: OpenAPIConnector) -> None:
532
+ """Validate x-airbyte-token-extract against server variables.
533
+
534
+ Ensures that fields specified in x-airbyte-token-extract match defined
535
+ server variables. This catches configuration errors at load time rather
536
+ than at runtime during token refresh.
537
+
538
+ Args:
539
+ spec: OpenAPI connector specification
540
+
541
+ Raises:
542
+ TokenExtractValidationError: If token_extract fields don't match server variables
543
+ """
544
+ # Get server variables
545
+ server_variables: set[str] = set()
546
+ if spec.servers:
547
+ for server in spec.servers:
548
+ if server.variables:
549
+ server_variables.update(server.variables.keys())
550
+
551
+ # Get token_extract from security scheme
552
+ if not spec.components or not spec.components.security_schemes:
553
+ return
554
+
555
+ for scheme_name, scheme in spec.components.security_schemes.items():
556
+ if scheme.type != "oauth2":
557
+ continue
558
+
559
+ token_extract = getattr(scheme, "x_airbyte_token_extract", None)
560
+ if not token_extract:
561
+ continue
562
+
563
+ # Validate each field matches a server variable
564
+ for field in token_extract:
565
+ if field not in server_variables:
566
+ raise TokenExtractValidationError(
567
+ f"x-airbyte-token-extract field '{field}' does not match any defined "
568
+ f"server variable. Available server variables: {sorted(server_variables) or 'none'}. "
569
+ f"Please define '{{{field}}}' in your server URL and add a variable definition."
570
+ )
571
+
572
+
573
+ def _generate_default_auth_config(auth_type: AuthType) -> AirbyteAuthConfig:
574
+ """Generate default x-airbyte-auth-config for an auth type.
575
+
576
+ When x-airbyte-auth-config is not explicitly defined in the OpenAPI spec,
577
+ we generate a sensible default that maps user-friendly field names to
578
+ the auth scheme's parameters.
579
+
580
+ Args:
581
+ auth_type: The authentication type (BEARER, BASIC, API_KEY)
582
+
583
+ Returns:
584
+ Default auth config spec with properties and auth_mapping
585
+ """
586
+ if auth_type == AuthType.BEARER:
587
+ return AirbyteAuthConfig(
588
+ title=None,
589
+ description=None,
590
+ type="object",
591
+ required=["token"],
592
+ properties={
593
+ "token": AuthConfigFieldSpec(
594
+ type="string",
595
+ title="Bearer Token",
596
+ description="Authentication bearer token",
597
+ format=None,
598
+ pattern=None,
599
+ airbyte_secret=False,
600
+ default=None,
601
+ )
602
+ },
603
+ auth_mapping={"token": "${token}"},
604
+ oneOf=None,
605
+ )
606
+ elif auth_type == AuthType.BASIC:
607
+ return AirbyteAuthConfig(
608
+ title=None,
609
+ description=None,
610
+ type="object",
611
+ required=["username", "password"],
612
+ properties={
613
+ "username": AuthConfigFieldSpec(
614
+ type="string",
615
+ title="Username",
616
+ description="Authentication username",
617
+ format=None,
618
+ pattern=None,
619
+ airbyte_secret=False,
620
+ default=None,
621
+ ),
622
+ "password": AuthConfigFieldSpec(
623
+ type="string",
624
+ title="Password",
625
+ description="Authentication password",
626
+ format=None,
627
+ pattern=None,
628
+ airbyte_secret=False,
629
+ default=None,
630
+ ),
631
+ },
632
+ auth_mapping={"username": "${username}", "password": "${password}"},
633
+ oneOf=None,
634
+ )
635
+ elif auth_type == AuthType.API_KEY:
636
+ return AirbyteAuthConfig(
637
+ title=None,
638
+ description=None,
639
+ type="object",
640
+ required=["api_key"],
641
+ properties={
642
+ "api_key": AuthConfigFieldSpec(
643
+ type="string",
644
+ title="API Key",
645
+ description="API authentication key",
646
+ format=None,
647
+ pattern=None,
648
+ airbyte_secret=False,
649
+ default=None,
650
+ )
651
+ },
652
+ auth_mapping={"api_key": "${api_key}"},
653
+ oneOf=None,
654
+ )
655
+ elif auth_type == AuthType.OAUTH2:
656
+ # OAuth2: No fields are strictly required to support both modes:
657
+ # 1. Full token mode: user provides access_token (and optionally refresh credentials)
658
+ # 2. Refresh-token-only mode: user provides refresh_token, client_id, client_secret
659
+ # The auth_mapping includes all fields, but apply_auth_mapping
660
+ # will skip mappings for fields not provided by the user.
661
+ return AirbyteAuthConfig(
662
+ title=None,
663
+ description=None,
664
+ type="object",
665
+ required=[],
666
+ properties={
667
+ "access_token": AuthConfigFieldSpec(
668
+ type="string",
669
+ title="Access Token",
670
+ description="OAuth2 access token",
671
+ format=None,
672
+ pattern=None,
673
+ airbyte_secret=False,
674
+ default=None,
675
+ ),
676
+ "refresh_token": AuthConfigFieldSpec(
677
+ type="string",
678
+ title="Refresh Token",
679
+ description="OAuth2 refresh token (optional)",
680
+ format=None,
681
+ pattern=None,
682
+ airbyte_secret=False,
683
+ default=None,
684
+ ),
685
+ "client_id": AuthConfigFieldSpec(
686
+ type="string",
687
+ title="Client ID",
688
+ description="OAuth2 client ID (optional)",
689
+ format=None,
690
+ pattern=None,
691
+ airbyte_secret=False,
692
+ default=None,
693
+ ),
694
+ "client_secret": AuthConfigFieldSpec(
695
+ type="string",
696
+ title="Client Secret",
697
+ description="OAuth2 client secret (optional)",
698
+ format=None,
699
+ pattern=None,
700
+ airbyte_secret=False,
701
+ default=None,
702
+ ),
703
+ },
704
+ auth_mapping={
705
+ "access_token": "${access_token}",
706
+ "refresh_token": "${refresh_token}",
707
+ "client_id": "${client_id}",
708
+ "client_secret": "${client_secret}",
709
+ },
710
+ oneOf=None,
711
+ )
712
+ else:
713
+ # Unknown auth type - return minimal config
714
+ return AirbyteAuthConfig(
715
+ title=None,
716
+ description=None,
717
+ type="object",
718
+ required=None,
719
+ properties={},
720
+ auth_mapping={},
721
+ oneOf=None,
722
+ )
723
+
724
+
725
+ def _parse_auth_from_openapi(spec: OpenAPIConnector) -> AuthConfig:
726
+ """Parse authentication configuration from OpenAPI spec.
727
+
728
+ Supports both single and multiple security schemes. For backwards compatibility,
729
+ single-scheme connectors continue to use the legacy AuthConfig format.
730
+ If no security schemes are defined, generates a default Bearer auth config.
731
+
732
+ Args:
733
+ spec: OpenAPI connector specification
734
+
735
+ Returns:
736
+ AuthConfig with either single or multiple auth options
737
+ """
738
+ if not spec.components or not spec.components.security_schemes:
739
+ # Backwards compatibility: generate default Bearer auth when no schemes defined
740
+ default_config = _generate_default_auth_config(AuthType.BEARER)
741
+ return AuthConfig(
742
+ type=AuthType.BEARER,
743
+ config={"header": "Authorization", "prefix": "Bearer"},
744
+ user_config_spec=default_config,
745
+ options=None,
746
+ )
747
+
748
+ schemes = spec.components.security_schemes
749
+
750
+ # Single scheme: backwards compatible mode
751
+ if len(schemes) == 1:
752
+ scheme_name, scheme = next(iter(schemes.items()))
753
+ return _parse_single_security_scheme(scheme)
754
+
755
+ # Multiple schemes: new multi-auth mode
756
+ options = []
757
+ for scheme_name, scheme in schemes.items():
758
+ try:
759
+ auth_option = _parse_security_scheme_to_option(scheme_name, scheme)
760
+ options.append(auth_option)
761
+ except Exception as e:
762
+ # Log warning but continue - skip invalid schemes
763
+ import logging
764
+
765
+ logger = logging.getLogger(__name__)
766
+ logger.warning(f"Skipping invalid security scheme '{scheme_name}': {e}")
767
+ continue
768
+
769
+ if not options:
770
+ raise InvalidOpenAPIError("No valid security schemes found. Connector must define at least one valid security scheme.")
771
+
772
+ return AuthConfig(
773
+ type=None,
774
+ config={},
775
+ user_config_spec=None,
776
+ options=options,
777
+ )
778
+
779
+
780
+ def _parse_single_security_scheme(scheme: Any) -> AuthConfig:
781
+ """Parse a single security scheme into AuthConfig.
782
+
783
+ This extracts the existing single-scheme parsing logic for reuse.
784
+
785
+ Args:
786
+ scheme: SecurityScheme from OpenAPI spec
787
+
788
+ Returns:
789
+ AuthConfig in single-auth mode
790
+ """
791
+ auth_type = AuthType.API_KEY # Default
792
+ auth_config = {}
793
+
794
+ if scheme.type == "http":
795
+ if scheme.scheme == "bearer":
796
+ auth_type = AuthType.BEARER
797
+ auth_config = {"header": "Authorization", "prefix": "Bearer"}
798
+ elif scheme.scheme == "basic":
799
+ auth_type = AuthType.BASIC
800
+ auth_config = {}
801
+
802
+ elif scheme.type == "apiKey":
803
+ auth_type = AuthType.API_KEY
804
+ auth_config = {
805
+ "header": scheme.name or "Authorization",
806
+ "in": scheme.in_ or "header",
807
+ }
808
+
809
+ elif scheme.type == "oauth2":
810
+ # Parse OAuth2 configuration
811
+ oauth2_config = _parse_oauth2_config(scheme)
812
+ # Use explicit x-airbyte-auth-config if present, otherwise generate default
813
+ auth_config_obj = scheme.x_airbyte_auth_config or _generate_default_auth_config(AuthType.OAUTH2)
814
+ return AuthConfig(
815
+ type=AuthType.OAUTH2,
816
+ config=oauth2_config,
817
+ user_config_spec=auth_config_obj,
818
+ options=None,
819
+ )
820
+
821
+ # Use explicit x-airbyte-auth-config if present, otherwise generate default
822
+ auth_config_obj = scheme.x_airbyte_auth_config or _generate_default_auth_config(auth_type)
823
+
824
+ return AuthConfig(
825
+ type=auth_type,
826
+ config=auth_config,
827
+ user_config_spec=auth_config_obj,
828
+ options=None,
829
+ )
830
+
831
+
832
+ def _parse_security_scheme_to_option(scheme_name: str, scheme: Any) -> AuthOption:
833
+ """Parse a security scheme into an AuthOption for multi-auth connectors.
834
+
835
+ Args:
836
+ scheme_name: Name of the security scheme (e.g., "githubOAuth")
837
+ scheme: SecurityScheme from OpenAPI spec
838
+
839
+ Returns:
840
+ AuthOption containing the parsed configuration
841
+
842
+ Raises:
843
+ ValueError: If scheme is invalid or unsupported
844
+ """
845
+ # Parse using existing single-scheme logic
846
+ single_auth = _parse_single_security_scheme(scheme)
847
+
848
+ # Convert to AuthOption
849
+ return AuthOption(
850
+ scheme_name=scheme_name,
851
+ type=single_auth.type,
852
+ config=single_auth.config,
853
+ user_config_spec=single_auth.user_config_spec,
854
+ )
855
+
856
+
857
+ def load_connector_model(definition_path: str | Path) -> ConnectorModel:
858
+ """Load connector model from YAML definition file.
859
+
860
+ Supports both OpenAPI 3.1 format and legacy format.
861
+
862
+ Args:
863
+ definition_path: Path to connector.yaml file
864
+
865
+ Returns:
866
+ Parsed ConnectorModel
867
+
868
+ Raises:
869
+ FileNotFoundError: If definition file doesn't exist
870
+ ValueError: If YAML is invalid
871
+ """
872
+ definition_path = Path(definition_path)
873
+
874
+ if not definition_path.exists():
875
+ raise FileNotFoundError(f"Connector definition not found: {definition_path}")
876
+
877
+ # Load YAML with error handling
878
+ try:
879
+ with open(definition_path) as f:
880
+ raw_definition = yaml.safe_load(f)
881
+ except yaml.YAMLError as e:
882
+ raise InvalidYAMLError(f"Invalid YAML syntax in {definition_path}: {e}")
883
+ except Exception as e:
884
+ raise ConnectorModelLoaderError(f"Error reading definition file {definition_path}: {e}")
885
+
886
+ if not raw_definition:
887
+ raise ValueError("Invalid connector.yaml: empty file")
888
+
889
+ # Detect format: OpenAPI if 'openapi' key exists
890
+ if "openapi" in raw_definition:
891
+ spec = parse_openapi_spec(raw_definition)
892
+ return convert_openapi_to_connector_model(spec)
893
+
894
+ # Legacy format
895
+ if "connector" not in raw_definition:
896
+ raise ValueError("Invalid connector.yaml: missing 'connector' or 'openapi' key")
897
+
898
+ # Parse connector metadata
899
+ connector_meta = raw_definition["connector"]
900
+
901
+ # Parse auth config
902
+ auth_config = raw_definition.get("auth", {})
903
+
904
+ # Parse entities
905
+ entities = []
906
+ for entity_data in raw_definition.get("entities", []):
907
+ # Parse endpoints for each action
908
+ endpoints_dict = {}
909
+ for action_str in entity_data.get("actions", []):
910
+ action = Action(action_str)
911
+ endpoint_data = entity_data["endpoints"].get(action_str)
912
+
913
+ if endpoint_data:
914
+ # Extract path parameters from the path template
915
+ path_params = extract_path_params(endpoint_data["path"])
916
+
917
+ endpoint = EndpointDefinition(
918
+ method=endpoint_data["method"],
919
+ path=endpoint_data["path"],
920
+ description=endpoint_data.get("description"),
921
+ body_fields=endpoint_data.get("body_fields", []),
922
+ query_params=endpoint_data.get("query_params", []),
923
+ path_params=path_params,
924
+ graphql_body=None, # GraphQL only supported in OpenAPI format (via x-airbyte-body-type)
925
+ )
926
+ endpoints_dict[action] = endpoint
927
+
928
+ entity = EntityDefinition(
929
+ name=entity_data["name"],
930
+ actions=[Action(a) for a in entity_data["actions"]],
931
+ endpoints=endpoints_dict,
932
+ schema=entity_data.get("schema"),
933
+ )
934
+ entities.append(entity)
935
+
936
+ # Get connector ID
937
+ connector_id_value = connector_meta.get("id")
938
+ if connector_id_value:
939
+ # Try to parse as UUID (handles string UUIDs)
940
+ if isinstance(connector_id_value, str):
941
+ connector_id = UUID(connector_id_value)
942
+ else:
943
+ connector_id = connector_id_value
944
+ else:
945
+ raise ValueError
946
+
947
+ # Build ConnectorModel
948
+ model = ConnectorModel(
949
+ id=connector_id,
950
+ name=connector_meta["name"],
951
+ version=connector_meta.get("version", OPENAPI_DEFAULT_VERSION),
952
+ base_url=raw_definition.get("base_url", connector_meta.get("base_url", "")),
953
+ auth=auth_config,
954
+ entities=entities,
955
+ )
956
+
957
+ return model