mainsequence 9.0.35.dev82__tar.gz → 9.0.36__tar.gz

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 (120) hide show
  1. {mainsequence-9.0.35.dev82/mainsequence.egg-info → mainsequence-9.0.36}/PKG-INFO +1 -1
  2. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/__init__.py +3 -0
  3. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/_transport.py +8 -0
  4. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/bootstrap.py +6 -1
  5. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/inference.py +4 -1
  6. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/utils.py +171 -0
  7. mainsequence-9.0.36/mainsequence/instrumentation/utils.py +197 -0
  8. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/logconf.py +3 -0
  9. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/runtime_credential_exchange.py +23 -1
  10. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/server/fastapi.py +24 -1
  11. mainsequence-9.0.36/mainsequence/workload_identity.py +234 -0
  12. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36/mainsequence.egg-info}/PKG-INFO +1 -1
  13. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence.egg-info/SOURCES.txt +4 -1
  14. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/pyproject.toml +1 -1
  15. mainsequence-9.0.36/tests/test_caller_context.py +608 -0
  16. mainsequence-9.0.36/tests/test_workload_identity.py +648 -0
  17. mainsequence-9.0.35.dev82/mainsequence/instrumentation/utils.py +0 -99
  18. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/LICENSE +0 -0
  19. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/README.md +0 -0
  20. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/a2a_sdk_execution/SKILL.md +0 -0
  21. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/application_surfaces/api_surfaces/SKILL.md +0 -0
  22. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/mainsequence-inference/SKILL.md +0 -0
  23. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/maintenance/bug_auditor/SKILL.md +0 -0
  24. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/maintenance/code_repository_maintenance/SKILL.md +0 -0
  25. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/maintenance/metatables_transition/SKILL.md +0 -0
  26. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/platform_operations/access_control_and_sharing/SKILL.md +0 -0
  27. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/platform_operations/orchestration_and_releases/SKILL.md +0 -0
  28. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/agent_scaffold/skills/sdk_code_repository_execution/SKILL.md +0 -0
  29. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/__main__.py +0 -0
  30. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/_request_identity.py +0 -0
  31. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/_team_memberships.py +0 -0
  32. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/__init__.py +0 -0
  33. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/api.py +0 -0
  34. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/browser_auth.py +0 -0
  35. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/cli.py +0 -0
  36. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/code_repository_status.py +0 -0
  37. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/config.py +0 -0
  38. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/docker_utils.py +0 -0
  39. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/doctor.py +0 -0
  40. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/local_ops.py +0 -0
  41. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/model_filters.py +0 -0
  42. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/pydantic_cli.py +0 -0
  43. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/sdk_utils.py +0 -0
  44. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/ssh_utils.py +0 -0
  45. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/cli/ui.py +0 -0
  46. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/__init__.py +0 -0
  47. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/access_catalog.py +0 -0
  48. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/agent_runtime_models.py +0 -0
  49. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/base.py +0 -0
  50. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/client.py +0 -0
  51. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/compute_validation.py +0 -0
  52. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/exceptions.py +0 -0
  53. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/github_issues.py +0 -0
  54. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/models_foundry.py +0 -0
  55. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/models_helpers.py +0 -0
  56. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/models_user.py +0 -0
  57. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/object_access.py +0 -0
  58. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/observability.py +0 -0
  59. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/client/value_sets.py +0 -0
  60. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/code_repository_context.py +0 -0
  61. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/code_repository_skills.py +0 -0
  62. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/defaults.py +0 -0
  63. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/instrumentation/__init__.py +0 -0
  64. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/repository_identity_security.py +0 -0
  65. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/runtime_flags.py +0 -0
  66. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/scaffold_skills.py +0 -0
  67. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/server/__init__.py +0 -0
  68. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/server/_mcp_skills_upstream/__init__.py +0 -0
  69. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/server/_mcp_skills_upstream/server.py +0 -0
  70. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/server/_mcp_skills_upstream/shared.py +0 -0
  71. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/server/caller_assertions.py +0 -0
  72. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence/server/mcp_skills.py +0 -0
  73. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence.egg-info/dependency_links.txt +0 -0
  74. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence.egg-info/entry_points.txt +0 -0
  75. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence.egg-info/requires.txt +0 -0
  76. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/mainsequence.egg-info/top_level.txt +0 -0
  77. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/setup.cfg +0 -0
  78. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_access_catalog_client.py +0 -0
  79. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_auth_bootstrap.py +0 -0
  80. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_auth_precedence.py +0 -0
  81. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_caller_assertions.py +0 -0
  82. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_canonical_api_route_contract.py +0 -0
  83. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_cli_auth_contract.py +0 -0
  84. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_cli_browser_auth.py +0 -0
  85. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_cli_request_budget.py +0 -0
  86. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_cli_secure_storage.py +0 -0
  87. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_client.py +0 -0
  88. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_code_repository_branch_contract.py +0 -0
  89. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_code_repository_documentation_contract.py +0 -0
  90. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_code_repository_runtime_context.py +0 -0
  91. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_code_repository_skills.py +0 -0
  92. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_credential_repr.py +0 -0
  93. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_dependency_extras.py +0 -0
  94. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_dev_release_version.py +0 -0
  95. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_environment_resource_context.py +0 -0
  96. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_environment_response_contracts.py +0 -0
  97. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_fastapi_mcp.py +0 -0
  98. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_fastapi_request_identity.py +0 -0
  99. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_github_issues_client.py +0 -0
  100. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_http_retry_budget.py +0 -0
  101. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_independent_context.py +0 -0
  102. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_inference_client.py +0 -0
  103. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_instrumentation.py +0 -0
  104. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_job_client.py +0 -0
  105. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_local_ops.py +0 -0
  106. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_logconf.py +0 -0
  107. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_mcp_skills.py +0 -0
  108. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_models_user_request_bound_auth.py +0 -0
  109. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_notification_uid_contract.py +0 -0
  110. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_object_access_client.py +0 -0
  111. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_observability_client.py +0 -0
  112. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_runtime_credential_exchange.py +0 -0
  113. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_scaffold_skills.py +0 -0
  114. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_secret_client_model.py +0 -0
  115. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_source_ownership.py +0 -0
  116. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_ssh_utils.py +0 -0
  117. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_team_memberships.py +0 -0
  118. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_tolerant_response_reading.py +0 -0
  119. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_tolerant_value_sets.py +0 -0
  120. {mainsequence-9.0.35.dev82 → mainsequence-9.0.36}/tests/test_user_application_facts.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mainsequence
3
- Version: 9.0.35.dev82
3
+ Version: 9.0.36
4
4
  Summary: Main Sequence SDK
5
5
  Author-email: Main Sequence GmbH <dev@main-sequence.io>
6
6
  License-Expression: MIT
@@ -1,8 +1,11 @@
1
1
  # ruff: noqa: E402
2
2
  from .bootstrap import prime_runtime_env
3
+ from .instrumentation.utils import _attach_environment_context
3
4
 
4
5
  # Restore CLI credentials before any client module freezes its endpoint/provider.
5
6
  prime_runtime_env()
7
+ # A Job run's TRACEPARENT and BAGGAGE, before its first log line or call (ADR 0040).
8
+ _attach_environment_context()
6
9
 
7
10
  from .logconf import (
8
11
  logger as logger,
@@ -12,6 +12,8 @@ from requests.adapters import HTTPAdapter
12
12
  from urllib3.exceptions import InvalidHeader
13
13
  from urllib3.util import Retry, Timeout
14
14
 
15
+ from .instrumentation import tracer_instrumentator
16
+
15
17
  DEFAULT_ALLOWED_METHODS = frozenset({"HEAD", "GET", "OPTIONS"})
16
18
  DEFAULT_STATUS_FORCELIST = (429, 500, 502, 503, 504)
17
19
  DEFAULT_TIMEOUT = (5.0, 120.0)
@@ -97,7 +99,13 @@ def request_within_budget(method, url, *, timeout, **kwargs):
97
99
  deadline. Then the response, when it has started, is shut down and
98
100
  ``requests.Timeout`` is raised. The request may already have reached the
99
101
  server.
102
+
103
+ The current ``traceparent`` and ``baggage`` go with the request; a header
104
+ the caller sets wins (ADR 0040).
100
105
  """
106
+ carrier = tracer_instrumentator.get_telemetry_carrier()
107
+ if carrier:
108
+ kwargs["headers"] = {**carrier, **(kwargs.get("headers") or {})}
101
109
  with request_budget(timeout) as budget:
102
110
  attempt_timeout = budget.timeout()
103
111
  lock = threading.Lock()
@@ -54,7 +54,8 @@ def prime_runtime_env() -> None:
54
54
 
55
55
  Only the endpoint is read from the checkout `.env`. Credentials come from the
56
56
  process environment when it already has them, and otherwise from the saved
57
- CLI session.
57
+ CLI session, except with `MAINSEQUENCE_AUTH_MODE=workload_identity`, where
58
+ the saved session is not read.
58
59
  """
59
60
  global _credential_source
60
61
 
@@ -77,6 +78,10 @@ def prime_runtime_env() -> None:
77
78
 
78
79
  _set_if_missing("MAINSEQUENCE_ENDPOINT", backend)
79
80
 
81
+ if (os.environ.get("MAINSEQUENCE_AUTH_MODE") or "").strip().lower() == "workload_identity":
82
+ # A workload signs in with its own identity, never with a person's saved session.
83
+ return
84
+
80
85
  try:
81
86
  tokens = cli_config.get_tokens()
82
87
  except Exception:
@@ -9,6 +9,7 @@ from uuid import UUID
9
9
  import requests
10
10
  from pydantic import BaseModel, ConfigDict, Field, ValidationError
11
11
 
12
+ from ..instrumentation import tracer_instrumentator
12
13
  from . import utils
13
14
  from .exceptions import raise_for_response
14
15
 
@@ -74,7 +75,9 @@ class InferenceClient:
74
75
  # Inference opts out of safe-read retries as well: an uncertain outcome
75
76
  # must preserve the caller's explicit idempotency key.
76
77
  with utils.build_session(loaders=utils.loaders, retries=0) as session:
77
- headers = dict(utils.loaders.refresh_headers(force=False, session=session))
78
+ # The caller context goes with the call (ADR 0040).
79
+ headers = dict(tracer_instrumentator.get_telemetry_carrier())
80
+ headers.update(utils.loaders.refresh_headers(force=False, session=session))
78
81
  if key is not None:
79
82
  headers["Idempotency-Key"] = key
80
83
  try:
@@ -20,12 +20,21 @@ import requests
20
20
  from requests.structures import CaseInsensitiveDict
21
21
 
22
22
  from mainsequence.defaults import resolve_backend_endpoint
23
+ from mainsequence.instrumentation import tracer_instrumentator
23
24
  from mainsequence.logconf import logger
24
25
  from mainsequence.runtime_credential_exchange import (
25
26
  RUNTIME_CREDENTIAL_ID_ENV,
26
27
  RuntimeIdentityTokenError,
27
28
  exchange_runtime_credential,
28
29
  identity_token_file_from_environment,
30
+ send_with_exchange_retries,
31
+ )
32
+ from mainsequence.workload_identity import (
33
+ WORKLOAD_IDENTITY_AUTH_MODE,
34
+ SubjectTokenError,
35
+ SubjectTokenSource,
36
+ subject_token_source_from_environment,
37
+ token_exchange_body,
29
38
  )
30
39
 
31
40
  from .._transport import DEFAULT_ALLOWED_METHODS as DEFAULT_ALLOWED_METHODS
@@ -224,6 +233,9 @@ def _default_auth_provider_kind() -> str | None:
224
233
  if mode == "runtime_credential":
225
234
  return "runtime_credential"
226
235
 
236
+ if mode == WORKLOAD_IDENTITY_AUTH_MODE:
237
+ return WORKLOAD_IDENTITY_AUTH_MODE
238
+
227
239
  if mode == "session_jwt":
228
240
  if has_access or has_refresh:
229
241
  return "session_jwt"
@@ -467,6 +479,139 @@ class RuntimeCredentialAuthProvider(BaseAuthProvider):
467
479
  )
468
480
 
469
481
 
482
+ @dataclass
483
+ class WorkloadIdentityAuthProvider(BaseAuthProvider):
484
+ """
485
+ Exchange the program's cloud identity for short-lived access tokens.
486
+
487
+ For a program outside Main Sequence, selected with
488
+ `MAINSEQUENCE_AUTH_MODE=workload_identity`. Each exchange obtains a subject
489
+ token from `subject_token_source` (by default the source that
490
+ `MAINSEQUENCE_WORKLOAD_IDENTITY_SOURCE` selects) and posts it to
491
+ `/api/v1/workload-identity/token/` as an RFC 8693 token exchange. The
492
+ returned access token is kept on this provider only, out of `repr()`, and
493
+ is exchanged again before `expires_in` runs out; it cannot be refreshed.
494
+ The subject token is never kept.
495
+ Throttled (`429`) and temporarily unavailable (`503`) exchanges are retried
496
+ within the timeout budget; a refused one (`401`) fails at once, without
497
+ asking the source for another token.
498
+ """
499
+
500
+ subject_token_source: SubjectTokenSource | None = field(default=None, repr=False)
501
+ token_url: str | None = None
502
+ token_type: str = "Bearer"
503
+ refresh_skew_seconds: int = 30
504
+ timeout: tuple[float, float] = DEFAULT_TIMEOUT
505
+ access_token: str | None = field(default=None, repr=False)
506
+ expires_at: float | None = None
507
+ _lock: threading.RLock = field(default_factory=threading.RLock, init=False, repr=False)
508
+
509
+ def __post_init__(self):
510
+ if not self.token_url:
511
+ self.token_url = f"{API_ENDPOINT}/workload-identity/token/"
512
+
513
+ def _needs_exchange(self) -> bool:
514
+ if not self.access_token:
515
+ return True
516
+
517
+ if self.expires_at is not None:
518
+ return self.expires_at <= time.time() + self.refresh_skew_seconds
519
+
520
+ exp = _decode_jwt_exp(self.access_token)
521
+ if exp is None:
522
+ # Use an uninspectable access token until a 401 forces an exchange.
523
+ return False
524
+
525
+ return exp <= int(time.time()) + self.refresh_skew_seconds
526
+
527
+ @staticmethod
528
+ def _log_exchange_retry(status: int, delay: float) -> None:
529
+ logger.warning(
530
+ f"Workload identity token exchange returned {status}; retrying in {delay:.1f} s."
531
+ )
532
+
533
+ def _exchange(self) -> requests.Response:
534
+ # One budget for the subject token, every attempt and every wait,
535
+ # inside the caller's budget if any.
536
+ with request_budget(self.timeout) as budget:
537
+ try:
538
+ source = self.subject_token_source or subject_token_source_from_environment()
539
+ body = token_exchange_body(source())
540
+ except SubjectTokenError as exc:
541
+ raise AuthError(f"No workload identity subject token: {exc}") from None
542
+
543
+ def post() -> requests.Response:
544
+ return requests.post(
545
+ self.token_url,
546
+ data=body,
547
+ headers={"Accept": "application/json"},
548
+ timeout=budget.timeout(),
549
+ allow_redirects=False,
550
+ )
551
+
552
+ return send_with_exchange_retries(
553
+ post,
554
+ deadline=budget.deadline,
555
+ on_retry=self._log_exchange_retry,
556
+ )
557
+
558
+ def refresh(
559
+ self,
560
+ *,
561
+ force: bool = False,
562
+ session: requests.Session | None = None,
563
+ ) -> None:
564
+ _ = session
565
+ with self._lock:
566
+ if not force and not self._needs_exchange():
567
+ return
568
+
569
+ response = self._exchange()
570
+ if response.status_code == 401:
571
+ raise AuthError(
572
+ f"Main Sequence did not accept this workload's subject token at "
573
+ f"{self.token_url} (HTTP 401). Check that a federated credential of an "
574
+ "active external workload names the token's issuer, subject and "
575
+ "audience, and that its claim conditions match; the platform does not "
576
+ "say which check failed."
577
+ )
578
+ if response.status_code < 200 or response.status_code >= 300:
579
+ raise AuthError(
580
+ f"Workload identity token exchange failed with status {response.status_code}."
581
+ )
582
+
583
+ try:
584
+ data = response.json()
585
+ except ValueError:
586
+ data = None
587
+ if not isinstance(data, dict):
588
+ raise AuthError("Workload identity token exchange did not answer with JSON.")
589
+ access = str(data.get("access_token") or "").strip()
590
+ if not access:
591
+ raise AuthError(
592
+ "Workload identity token exchange response did not include access_token."
593
+ )
594
+
595
+ token_type = str(data.get("token_type") or "Bearer").strip()
596
+ self.token_type = token_type or "Bearer"
597
+ try:
598
+ expires_in = int(data.get("expires_in"))
599
+ except (TypeError, ValueError):
600
+ expires_in = None
601
+ self.expires_at = time.time() + expires_in if expires_in and expires_in > 0 else None
602
+ self.access_token = access
603
+
604
+ def get_headers(self) -> CaseInsensitiveDict:
605
+ if self._needs_exchange():
606
+ self.refresh(force=False)
607
+
608
+ return CaseInsensitiveDict(
609
+ {
610
+ "Authorization": f"{self.token_type} {self.access_token}",
611
+ }
612
+ )
613
+
614
+
470
615
  @dataclass
471
616
  class JWTAuthProvider(BaseAuthProvider):
472
617
  # Tokens stay out of repr() and str(), so logging the provider never shows them.
@@ -622,6 +767,9 @@ def build_default_auth_provider() -> BaseAuthProvider:
622
767
  if provider_kind == "runtime_credential":
623
768
  return RuntimeCredentialAuthProvider()
624
769
 
770
+ if provider_kind == WORKLOAD_IDENTITY_AUTH_MODE:
771
+ return WorkloadIdentityAuthProvider()
772
+
625
773
  if provider_kind == "jwt":
626
774
  return JWTAuthProvider()
627
775
 
@@ -645,6 +793,10 @@ class AuthLoaders:
645
793
  self.provider, RuntimeCredentialAuthProvider
646
794
  ):
647
795
  self.provider = RuntimeCredentialAuthProvider()
796
+ elif provider_kind == WORKLOAD_IDENTITY_AUTH_MODE and not isinstance(
797
+ self.provider, WorkloadIdentityAuthProvider
798
+ ):
799
+ self.provider = WorkloadIdentityAuthProvider()
648
800
  elif provider_kind == "session_jwt" and not isinstance(
649
801
  self.provider, SessionJWTAuthProvider
650
802
  ):
@@ -674,6 +826,20 @@ class AuthLoaders:
674
826
  def use_session_jwt(self, *, access: str | None = None):
675
827
  self.provider = SessionJWTAuthProvider(access_token=access, refresh_token=None)
676
828
 
829
+ def use_workload_identity(self, subject_token_source: SubjectTokenSource):
830
+ """
831
+ Exchange subject tokens from `subject_token_source`, a callable returning one.
832
+
833
+ The process must run with `MAINSEQUENCE_AUTH_MODE=workload_identity`:
834
+ another mode would replace this provider on the next request.
835
+ """
836
+ if _default_auth_provider_kind() != WORKLOAD_IDENTITY_AUTH_MODE:
837
+ raise AuthError(
838
+ "use_workload_identity() requires "
839
+ f"MAINSEQUENCE_AUTH_MODE={WORKLOAD_IDENTITY_AUTH_MODE}."
840
+ )
841
+ self.provider = WorkloadIdentityAuthProvider(subject_token_source=subject_token_source)
842
+
677
843
  def clear_auth(self):
678
844
  self.provider = None
679
845
 
@@ -711,6 +877,11 @@ def make_request(
711
877
  else:
712
878
  request_kwargs = dict(payload)
713
879
  request_kwargs.setdefault("allow_redirects", False)
880
+ # The caller context goes with the call, per request: the session is shared.
881
+ # A header the caller sets wins (ADR 0040).
882
+ carrier = tracer_instrumentator.get_telemetry_carrier()
883
+ if carrier:
884
+ request_kwargs["headers"] = {**carrier, **(request_kwargs.get("headers") or {})}
714
885
  req = getattr(s, r_type.lower())
715
886
 
716
887
  if accept_gzip:
@@ -0,0 +1,197 @@
1
+ import logging
2
+ import os
3
+ from contextvars import ContextVar
4
+
5
+ import structlog
6
+ from opentelemetry import baggage, trace
7
+ from opentelemetry import context as otel_context
8
+ from opentelemetry.baggage.propagation import W3CBaggagePropagator
9
+ from opentelemetry.sdk.trace import (
10
+ TracerProvider,
11
+ )
12
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
13
+ from opentelemetry.trace import (
14
+ ProxyTracerProvider,
15
+ get_current_span,
16
+ get_tracer,
17
+ get_tracer_provider,
18
+ set_tracer_provider,
19
+ )
20
+ from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
21
+
22
+
23
+ def is_port_in_use(port: int, agent_host: str) -> bool:
24
+ import socket
25
+
26
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
27
+ return s.connect_ex((agent_host, port)) == 0
28
+
29
+
30
+ class TracerInstrumentator:
31
+ __doc__ = """
32
+ Main instrumentator class controlls building and exporting of traces
33
+ """
34
+
35
+ def build_tracer(self) -> TraceContextTextMapPropagator:
36
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
37
+ from opentelemetry.sdk.resources import SERVICE_NAME, Resource
38
+
39
+ provider = get_tracer_provider()
40
+ if isinstance(provider, ProxyTracerProvider):
41
+ resource = Resource(attributes={SERVICE_NAME: "tdag"})
42
+ provider = TracerProvider(resource=resource)
43
+ set_tracer_provider(provider)
44
+
45
+ end_point = os.environ.get("OTLP_ENDPOINT")
46
+
47
+ if end_point is not None:
48
+ otlp_exporter = OTLPSpanExporter(endpoint=end_point)
49
+ if is_port_in_use(4317, agent_host=self.agent_host):
50
+ get_tracer_provider().add_span_processor(BatchSpanProcessor(otlp_exporter))
51
+ else:
52
+ get_tracer_provider().add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
53
+ tracer = get_tracer("tdag")
54
+ return tracer
55
+
56
+ def get_current_trace_id(self):
57
+ current_span = get_current_span()
58
+ return format(current_span.context.trace_id, "032x")
59
+
60
+ def get_telemetry_carrier(self):
61
+ """The W3C ``traceparent`` and ``baggage`` headers of the current context.
62
+
63
+ Empty when the current context has neither. The SDK sends them on its
64
+ calls to Main Sequence and to the applications on it (ADR 0040).
65
+ """
66
+ telemetry_carrier = {}
67
+ TraceContextTextMapPropagator().inject(carrier=telemetry_carrier)
68
+ W3CBaggagePropagator().inject(carrier=telemetry_carrier)
69
+ return telemetry_carrier
70
+
71
+ def append_attribute_to_current_span(self, attribute_key, attribute_value):
72
+ current_span = get_current_span()
73
+ current_span.set_attribute(attribute_key, attribute_value)
74
+
75
+
76
+ def add_otel_trace_context(logger, method_name, event_dict):
77
+ """
78
+ Enrich log records with OpenTelemetry trace context (trace_id, span_id).
79
+ """
80
+ span = trace.get_current_span()
81
+ if not span.is_recording():
82
+ event_dict["span"] = None
83
+ return event_dict
84
+
85
+ ctx = span.get_span_context()
86
+ parent = getattr(span, "parent", None)
87
+
88
+ event_dict["span"] = {
89
+ "span_id": format(ctx.span_id, "016x"),
90
+ "trace_id": format(ctx.trace_id, "032x"),
91
+ "parent_span_id": None if not parent else format(parent.span_id, "016x"),
92
+ }
93
+
94
+ return event_dict
95
+
96
+
97
+ class OTelJSONRenderer(structlog.processors.JSONRenderer):
98
+ """
99
+ A custom JSON renderer that injects OTel trace/span fields
100
+ immediately before serializing to JSON.
101
+ """
102
+
103
+ def __call__(self, logger, method_name, event_dict):
104
+ # 1) Grab the current active span from OpenTelemetry
105
+ event_dict = add_otel_trace_context(logger, method_name, event_dict)
106
+
107
+ # 3) Now call the base JSONRenderer to produce final JSON
108
+ return super().__call__(logger, method_name, event_dict)
109
+
110
+
111
+ # Caller context (ADR 0040): the W3C ``traceparent`` and ``baggage`` an
112
+ # application receives and passes on. The SDK carries every baggage key the
113
+ # same way and gives none of them a meaning.
114
+
115
+ _parsing_baggage: ContextVar[bool] = ContextVar("mainsequence_parsing_baggage", default=False)
116
+
117
+
118
+ class _QuietBaggageParser(logging.Filter):
119
+ """Drop the parser's warnings while the SDK parses: they quote the header."""
120
+
121
+ def filter(self, record):
122
+ return not _parsing_baggage.get()
123
+
124
+
125
+ logging.getLogger("opentelemetry.baggage.propagation").addFilter(_QuietBaggageParser())
126
+
127
+
128
+ def _with_baggage_header(header, context):
129
+ """``context`` with the members of one W3C ``baggage`` header added.
130
+
131
+ The parser's limits apply: a header over 8192 bytes is ignored whole, a
132
+ member over 4096 bytes is skipped and at most 180 members are read. W3C
133
+ properties, after a member's ``;``, are dropped, as the platform drops them,
134
+ so each value reads as the platform records it. Malformed input is skipped
135
+ and never raises.
136
+ """
137
+ if not header or len(header.encode()) > W3CBaggagePropagator._MAX_HEADER_LENGTH:
138
+ return context
139
+ # Properties follow an unencoded ';', so an encoded ';' inside a value survives.
140
+ members = ",".join(member.split(";", 1)[0] for member in header.split(","))
141
+ token = _parsing_baggage.set(True)
142
+ try:
143
+ return W3CBaggagePropagator().extract({"baggage": members}, context=context)
144
+ except Exception:
145
+ return context
146
+ finally:
147
+ _parsing_baggage.reset(token)
148
+
149
+
150
+ def _request_context(carrier, *, with_baggage):
151
+ """The OpenTelemetry context of one inbound request, from its headers.
152
+
153
+ Its baggage is exactly the request's ``baggage`` header, or none without
154
+ ``with_baggage``: never the process's or another request's. Its trace
155
+ parent is the request's ``traceparent``, unless instrumentation already
156
+ records a span for the request.
157
+ """
158
+ context = baggage.clear(context=otel_context.get_current())
159
+ if with_baggage:
160
+ context = _with_baggage_header(carrier.get("baggage"), context)
161
+ if not trace.get_current_span(context).is_recording():
162
+ context = TraceContextTextMapPropagator().extract(carrier, context=context)
163
+ return context
164
+
165
+
166
+ def _attach_environment_context():
167
+ """Attach a Job run's ``TRACEPARENT`` and ``BAGGAGE`` as the process's context.
168
+
169
+ The platform starts a run created by a request that carried caller context
170
+ with both variables, in W3C header format. Without either, nothing changes.
171
+ The context is attached to the calling thread, as any OpenTelemetry context.
172
+ """
173
+ traceparent = os.environ.get("TRACEPARENT")
174
+ baggage_header = os.environ.get("BAGGAGE")
175
+ if not traceparent and not baggage_header:
176
+ return
177
+ context = _with_baggage_header(
178
+ baggage_header, baggage.clear(context=otel_context.get_current())
179
+ )
180
+ if traceparent:
181
+ context = TraceContextTextMapPropagator().extract(
182
+ {"traceparent": traceparent}, context=context
183
+ )
184
+ otel_context.attach(context)
185
+
186
+
187
+ def _add_log_baggage(logger, method_name, event_dict):
188
+ """Add the current context's ``mainsequence.`` baggage keys as ``baggage``."""
189
+ if "baggage" not in event_dict:
190
+ members = {
191
+ key: str(value)
192
+ for key, value in baggage.get_all().items()
193
+ if key.startswith("mainsequence.")
194
+ }
195
+ if members:
196
+ event_dict["baggage"] = members
197
+ return event_dict
@@ -22,6 +22,7 @@ from structlog.stdlib import BoundLogger
22
22
  from ._transport import DeadlineHTTPAdapter, request_budget
23
23
  from .defaults import resolve_backend_endpoint
24
24
  from .instrumentation import OTelJSONRenderer
25
+ from .instrumentation.utils import _add_log_baggage
25
26
  from .repository_identity_security import UNSUPPORTED_SOURCE_IDENTITY_ENV_NAMES
26
27
  from .runtime_credential_exchange import (
27
28
  RUNTIME_CREDENTIAL_ID_ENV,
@@ -345,6 +346,7 @@ def build_application_logger(application_name: str = "ms-sdk", **metadata):
345
346
  pre_chain = [
346
347
  structlog.stdlib.add_log_level,
347
348
  structlog.stdlib.ExtraAdder(),
349
+ _add_log_baggage,
348
350
  timestamper,
349
351
  ]
350
352
 
@@ -413,6 +415,7 @@ def build_application_logger(application_name: str = "ms-sdk", **metadata):
413
415
  structlog.configure(
414
416
  processors=[
415
417
  structlog.contextvars.merge_contextvars, # context that always appears in the logs
418
+ _add_log_baggage, # the caller context's mainsequence. keys (ADR 0040)
416
419
  structlog.stdlib.add_log_level,
417
420
  structlog.stdlib.PositionalArgumentsFormatter(),
418
421
  structlog.processors.CallsiteParameterAdder(
@@ -143,8 +143,30 @@ def exchange_runtime_credential(
143
143
  on_retry:
144
144
  Called with the status and the delay before each retry.
145
145
  """
146
+ return send_with_exchange_retries(
147
+ lambda: send(_request_body(credential_id, identity_token_file)),
148
+ deadline=deadline,
149
+ on_retry=on_retry,
150
+ )
151
+
152
+
153
+ def send_with_exchange_retries(
154
+ send_attempt: Callable[[], Any],
155
+ *,
156
+ deadline: float,
157
+ on_retry: Callable[[int, float], None] | None = None,
158
+ ) -> Any:
159
+ """
160
+ Send one token exchange attempt, retry it on ``429`` or ``503``, and return the last response.
161
+
162
+ This is the retry policy of every token exchange the SDK makes: at most
163
+ ``EXCHANGE_RETRIES`` retries, each after the longer of the exponential backoff
164
+ and the answer's ``Retry-After``, and none whose wait would not end before
165
+ ``deadline``. Any other answer, ``401`` included, is returned at once.
166
+ ``send_attempt`` is called once per attempt.
167
+ """
146
168
  for attempt in range(EXCHANGE_RETRIES + 1):
147
- response = send(_request_body(credential_id, identity_token_file))
169
+ response = send_attempt()
148
170
  status = response.status_code
149
171
  if status not in RETRYABLE_EXCHANGE_STATUSES or attempt == EXCHANGE_RETRIES:
150
172
  return response
@@ -12,6 +12,7 @@ from urllib.parse import urlsplit
12
12
  from uuid import UUID
13
13
 
14
14
  import requests
15
+ from opentelemetry import context as otel_context
15
16
 
16
17
  from mainsequence._request_identity import (
17
18
  RequestIdentityError,
@@ -21,6 +22,7 @@ from mainsequence._request_identity import (
21
22
  )
22
23
  from mainsequence._team_memberships import TeamMembershipCache
23
24
  from mainsequence.client.models_user import RequestUserIdentity
25
+ from mainsequence.instrumentation.utils import _request_context
24
26
 
25
27
  from .caller_assertions import (
26
28
  ASSERTION_HEADER,
@@ -107,6 +109,17 @@ def _header(scope, name):
107
109
  return values[0] if values else None
108
110
 
109
111
 
112
+ def _trace_carrier(scope):
113
+ """The request's W3C trace context and baggage headers; repeated fields are joined."""
114
+ carrier = {}
115
+ for key, value in scope.get("headers", ()):
116
+ name = key.lower()
117
+ if name in {b"traceparent", b"tracestate", b"baggage"}:
118
+ name, value = name.decode("latin-1"), value.decode("latin-1")
119
+ carrier[name] = f"{carrier[name]},{value}" if name in carrier else value
120
+ return carrier
121
+
122
+
110
123
  def _local_user(scope):
111
124
  authorization = _header(scope, b"authorization") or ""
112
125
  scheme, separator, token = authorization.partition(" ")
@@ -201,6 +214,7 @@ class _RequestIdentityMiddleware:
201
214
  return
202
215
  state = scope.setdefault("state", {})
203
216
  state.update(user=None, user_uid=None, auth_outcome="anonymous")
217
+ caller_verified = False
204
218
  with _request_scope() as context:
205
219
  try:
206
220
  public = (
@@ -248,6 +262,7 @@ class _RequestIdentityMiddleware:
248
262
  else:
249
263
  user = await asyncio.to_thread(_local_user, scope)
250
264
  context.user = user
265
+ caller_verified = True
251
266
  state.update(user=user, user_uid=user.uid, auth_outcome="authenticated")
252
267
  scope["headers"] = [
253
268
  (k, v)
@@ -264,7 +279,15 @@ class _RequestIdentityMiddleware:
264
279
  state["auth_outcome"] = "unavailable" if error.status == 503 else "rejected"
265
280
  await _deny(scope, receive, send, error)
266
281
  return
267
- await self.app(scope, receive, send)
282
+ # The caller context arrives next to the caller verified above, and
283
+ # only with one: a public or preflight request has no baggage (ADR 0040).
284
+ context_token = otel_context.attach(
285
+ _request_context(_trace_carrier(scope), with_baggage=caller_verified)
286
+ )
287
+ try:
288
+ await self.app(scope, receive, send)
289
+ finally:
290
+ otel_context.detach(context_token)
268
291
 
269
292
 
270
293
  def install_request_identity(app, *, team_membership_cache_seconds=0):