mainsequence 9.0.35.dev82__py3-none-any.whl → 9.0.36.dev84__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.
mainsequence/__init__.py CHANGED
@@ -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()
mainsequence/bootstrap.py CHANGED
@@ -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:
@@ -1,7 +1,11 @@
1
+ import logging
1
2
  import os
3
+ from contextvars import ContextVar
2
4
 
3
5
  import structlog
4
- from opentelemetry import trace
6
+ from opentelemetry import baggage, trace
7
+ from opentelemetry import context as otel_context
8
+ from opentelemetry.baggage.propagation import W3CBaggagePropagator
5
9
  from opentelemetry.sdk.trace import (
6
10
  TracerProvider,
7
11
  )
@@ -54,9 +58,14 @@ class TracerInstrumentator:
54
58
  return format(current_span.context.trace_id, "032x")
55
59
 
56
60
  def get_telemetry_carrier(self):
57
- prop = TraceContextTextMapPropagator()
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
+ """
58
66
  telemetry_carrier = {}
59
- prop.inject(carrier=telemetry_carrier)
67
+ TraceContextTextMapPropagator().inject(carrier=telemetry_carrier)
68
+ W3CBaggagePropagator().inject(carrier=telemetry_carrier)
60
69
  return telemetry_carrier
61
70
 
62
71
  def append_attribute_to_current_span(self, attribute_key, attribute_value):
@@ -97,3 +106,92 @@ class OTelJSONRenderer(structlog.processors.JSONRenderer):
97
106
 
98
107
  # 3) Now call the base JSONRenderer to produce final JSON
99
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
mainsequence/logconf.py CHANGED
@@ -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):
@@ -0,0 +1,234 @@
1
+ """
2
+ Subject tokens for workload identity federation.
3
+
4
+ A program that runs outside Main Sequence (a service in your own cloud, a CI job,
5
+ a scheduler) can sign in with the identity its cloud already gives it instead of
6
+ an API token. With ``MAINSEQUENCE_AUTH_MODE=workload_identity`` the SDK obtains a
7
+ token from that identity provider, the *subject token*, and exchanges it at
8
+ ``POST /api/v1/workload-identity/token/`` for a short-lived Main Sequence access
9
+ token, as an RFC 8693 token exchange.
10
+
11
+ A subject token source is any callable that takes no argument and returns the
12
+ subject token as a string. It is called once per exchange, so a source may
13
+ return a new token every time. This module provides three, selected by
14
+ ``MAINSEQUENCE_WORKLOAD_IDENTITY_SOURCE``:
15
+
16
+ ``environment``
17
+ The token in ``MAINSEQUENCE_WORKLOAD_IDENTITY_TOKEN``.
18
+ ``file``
19
+ The token in the file ``MAINSEQUENCE_WORKLOAD_IDENTITY_TOKEN_FILE`` names,
20
+ read for every exchange because such files are rotated.
21
+ ``azure_managed_identity``
22
+ A token the Azure managed identity of the host issues for the audience in
23
+ ``MAINSEQUENCE_WORKLOAD_IDENTITY_AUDIENCE``; a user-assigned identity is
24
+ chosen by ``MAINSEQUENCE_WORKLOAD_IDENTITY_AZURE_CLIENT_ID``.
25
+
26
+ A subject token is never kept on an object, written to the environment or a
27
+ file, logged, or included in an error message.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import os
33
+ from collections.abc import Callable
34
+ from dataclasses import dataclass
35
+
36
+ import requests
37
+
38
+ from mainsequence._transport import DEFAULT_TIMEOUT, remaining_timeout
39
+
40
+ WORKLOAD_IDENTITY_AUTH_MODE = "workload_identity"
41
+ WORKLOAD_IDENTITY_SOURCE_ENV = "MAINSEQUENCE_WORKLOAD_IDENTITY_SOURCE"
42
+ WORKLOAD_IDENTITY_TOKEN_ENV = "MAINSEQUENCE_WORKLOAD_IDENTITY_TOKEN"
43
+ WORKLOAD_IDENTITY_TOKEN_FILE_ENV = "MAINSEQUENCE_WORKLOAD_IDENTITY_TOKEN_FILE"
44
+ WORKLOAD_IDENTITY_AUDIENCE_ENV = "MAINSEQUENCE_WORKLOAD_IDENTITY_AUDIENCE"
45
+ WORKLOAD_IDENTITY_AZURE_CLIENT_ID_ENV = "MAINSEQUENCE_WORKLOAD_IDENTITY_AZURE_CLIENT_ID"
46
+
47
+ SOURCE_ENVIRONMENT = "environment"
48
+ SOURCE_FILE = "file"
49
+ SOURCE_AZURE_MANAGED_IDENTITY = "azure_managed_identity"
50
+ SOURCES = (SOURCE_ENVIRONMENT, SOURCE_FILE, SOURCE_AZURE_MANAGED_IDENTITY)
51
+
52
+ # RFC 8693 token exchange.
53
+ TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
54
+ JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt"
55
+
56
+ # The managed identity endpoint of Azure Container Apps, App Service and Functions,
57
+ # announced by these two variables, and the instance metadata service of Azure
58
+ # virtual machines and scale sets, used when they are absent.
59
+ AZURE_IDENTITY_ENDPOINT_ENV = "IDENTITY_ENDPOINT"
60
+ AZURE_IDENTITY_HEADER_ENV = "IDENTITY_HEADER"
61
+ AZURE_IDENTITY_ENDPOINT_API_VERSION = "2019-08-01"
62
+ AZURE_IMDS_TOKEN_URL = "http://169.254.169.254/metadata/identity/oauth2/token"
63
+ AZURE_IMDS_API_VERSION = "2018-02-01"
64
+
65
+ SubjectTokenSource = Callable[[], str]
66
+
67
+
68
+ class SubjectTokenError(Exception):
69
+ """No subject token could be obtained. The message never holds a token."""
70
+
71
+
72
+ def _environment_value(name: str) -> str:
73
+ return (os.getenv(name) or "").strip()
74
+
75
+
76
+ def _non_empty(token: str, source: str) -> str:
77
+ token = token.strip()
78
+ if not token:
79
+ raise SubjectTokenError(f"{source} is empty.")
80
+ return token
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class EnvironmentSubjectToken:
85
+ """The subject token in an environment variable, read for every exchange."""
86
+
87
+ variable: str = WORKLOAD_IDENTITY_TOKEN_ENV
88
+
89
+ def __call__(self) -> str:
90
+ value = os.getenv(self.variable)
91
+ if value is None:
92
+ raise SubjectTokenError(f"{self.variable} is not set.")
93
+ return _non_empty(value, self.variable)
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class FileSubjectToken:
98
+ """The subject token in a file, read for every exchange."""
99
+
100
+ path: str
101
+
102
+ def __call__(self) -> str:
103
+ source = f"The workload identity token file {self.path}"
104
+ try:
105
+ with open(self.path, "rb") as token_file:
106
+ raw = token_file.read()
107
+ except FileNotFoundError:
108
+ raise SubjectTokenError(f"{source} does not exist.") from None
109
+ except OSError as exc:
110
+ raise SubjectTokenError(f"{source} could not be read ({type(exc).__name__}).") from None
111
+ try:
112
+ token = raw.decode("utf-8")
113
+ except UnicodeDecodeError:
114
+ # Raised below, outside this handler: the decode error holds the bytes.
115
+ token = None
116
+ if token is None:
117
+ raise SubjectTokenError(f"{source} does not hold a token.")
118
+ return _non_empty(token, source)
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class AzureManagedIdentitySubjectToken:
123
+ """
124
+ A token the host's Azure managed identity issues for ``audience``.
125
+
126
+ On Azure Container Apps, App Service and Functions the platform sets
127
+ ``IDENTITY_ENDPOINT`` and ``IDENTITY_HEADER`` and the token is requested
128
+ there; elsewhere, such as on a virtual machine, from the instance metadata
129
+ service. ``client_id`` selects a user-assigned managed identity; without it
130
+ the system-assigned identity answers. ``audience`` is the Application ID URI
131
+ the Main Sequence credential names, for example ``api://main-sequence``.
132
+
133
+ One request is made per exchange. Azure caches managed identity tokens, so
134
+ it is cheap. The request has no retry of its own: a failure fails the
135
+ exchange, and the next SDK request tries again.
136
+ """
137
+
138
+ audience: str
139
+ client_id: str | None = None
140
+ timeout: tuple[float, float] = DEFAULT_TIMEOUT
141
+
142
+ def _request(self) -> tuple[str, dict[str, str], dict[str, str]]:
143
+ endpoint = _environment_value(AZURE_IDENTITY_ENDPOINT_ENV)
144
+ identity_header = _environment_value(AZURE_IDENTITY_HEADER_ENV)
145
+ if endpoint and identity_header:
146
+ params = {"resource": self.audience, "api-version": AZURE_IDENTITY_ENDPOINT_API_VERSION}
147
+ headers = {"X-IDENTITY-HEADER": identity_header}
148
+ else:
149
+ endpoint = AZURE_IMDS_TOKEN_URL
150
+ params = {"resource": self.audience, "api-version": AZURE_IMDS_API_VERSION}
151
+ headers = {"Metadata": "true"}
152
+ if self.client_id:
153
+ params["client_id"] = self.client_id
154
+ return endpoint, params, headers
155
+
156
+ def __call__(self) -> str:
157
+ if not (self.audience or "").strip():
158
+ raise SubjectTokenError(
159
+ f"{WORKLOAD_IDENTITY_AUDIENCE_ENV} is required for the "
160
+ f"{SOURCE_AZURE_MANAGED_IDENTITY} source: it is the audience the "
161
+ "Main Sequence credential names."
162
+ )
163
+ endpoint, params, headers = self._request()
164
+ try:
165
+ response = requests.get(
166
+ endpoint,
167
+ params=params,
168
+ headers=headers,
169
+ timeout=remaining_timeout(self.timeout),
170
+ allow_redirects=False,
171
+ )
172
+ except requests.RequestException as exc:
173
+ # The exception text is not echoed: it can carry the request headers.
174
+ raise SubjectTokenError(
175
+ f"The Azure managed identity endpoint could not be reached ({type(exc).__name__})."
176
+ ) from None
177
+ if response.status_code != 200:
178
+ raise SubjectTokenError(
179
+ f"The Azure managed identity endpoint answered HTTP {response.status_code} "
180
+ f"for the audience {self.audience}."
181
+ )
182
+ try:
183
+ token = str(response.json().get("access_token") or "")
184
+ except (ValueError, AttributeError):
185
+ token = ""
186
+ return _non_empty(token, "The Azure managed identity endpoint's token")
187
+
188
+
189
+ def subject_token_source_from_environment() -> SubjectTokenSource:
190
+ """
191
+ Return the subject token source ``MAINSEQUENCE_WORKLOAD_IDENTITY_SOURCE`` selects.
192
+
193
+ Only the configuration is checked here; the token itself is obtained by
194
+ calling the source, once per exchange.
195
+ """
196
+ source = _environment_value(WORKLOAD_IDENTITY_SOURCE_ENV).lower()
197
+ if source == SOURCE_ENVIRONMENT:
198
+ return EnvironmentSubjectToken()
199
+ if source == SOURCE_FILE:
200
+ path = _environment_value(WORKLOAD_IDENTITY_TOKEN_FILE_ENV)
201
+ if not path:
202
+ raise SubjectTokenError(
203
+ f"{WORKLOAD_IDENTITY_TOKEN_FILE_ENV} is required when "
204
+ f"{WORKLOAD_IDENTITY_SOURCE_ENV}={SOURCE_FILE}."
205
+ )
206
+ return FileSubjectToken(path)
207
+ if source == SOURCE_AZURE_MANAGED_IDENTITY:
208
+ audience = _environment_value(WORKLOAD_IDENTITY_AUDIENCE_ENV)
209
+ if not audience:
210
+ raise SubjectTokenError(
211
+ f"{WORKLOAD_IDENTITY_AUDIENCE_ENV} is required when "
212
+ f"{WORKLOAD_IDENTITY_SOURCE_ENV}={SOURCE_AZURE_MANAGED_IDENTITY}."
213
+ )
214
+ client_id = _environment_value(WORKLOAD_IDENTITY_AZURE_CLIENT_ID_ENV) or None
215
+ return AzureManagedIdentitySubjectToken(audience=audience, client_id=client_id)
216
+ expected = ", ".join(SOURCES)
217
+ if not source:
218
+ raise SubjectTokenError(
219
+ f"{WORKLOAD_IDENTITY_SOURCE_ENV} is required when "
220
+ f"MAINSEQUENCE_AUTH_MODE={WORKLOAD_IDENTITY_AUTH_MODE}: one of {expected}."
221
+ )
222
+ raise SubjectTokenError(
223
+ f"{WORKLOAD_IDENTITY_SOURCE_ENV}={source} is not a subject token source: "
224
+ f"use one of {expected}."
225
+ )
226
+
227
+
228
+ def token_exchange_body(subject_token: str) -> dict[str, str]:
229
+ """Return the RFC 8693 form body that exchanges ``subject_token``."""
230
+ return {
231
+ "grant_type": TOKEN_EXCHANGE_GRANT_TYPE,
232
+ "subject_token": subject_token,
233
+ "subject_token_type": JWT_TOKEN_TYPE,
234
+ }
@@ -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.dev84
4
4
  Summary: Main Sequence SDK
5
5
  Author-email: Main Sequence GmbH <dev@main-sequence.io>
6
6
  License-Expression: MIT
@@ -7,20 +7,21 @@ agent_scaffold/skills/maintenance/metatables_transition/SKILL.md,sha256=Pisgpytc
7
7
  agent_scaffold/skills/platform_operations/access_control_and_sharing/SKILL.md,sha256=k3SYqiU-IuWm1IunlrAQY9NaCANlq6EjqCFN0gGcuiQ,29673
8
8
  agent_scaffold/skills/platform_operations/orchestration_and_releases/SKILL.md,sha256=hdGavnuDYYN8aBM3xWjOaKV3w7rc5rrLTRouRGnffc4,17670
9
9
  agent_scaffold/skills/sdk_code_repository_execution/SKILL.md,sha256=7hBAJuDOKdZUcGoqR7Y4nMHZ9kX5fuY6CMOcgdDaPWI,7046
10
- mainsequence/__init__.py,sha256=70CbIo7ZG1mzi5uwkqDtVESunBE0RanHjeFg4ptfsA0,385
10
+ mainsequence/__init__.py,sha256=lC_XotSSB3IBMjilFUUJpq_QGoaCoTN9AocNPapNkNo,563
11
11
  mainsequence/__main__.py,sha256=KuAP69uduS2ImrPIgNMzbGBRepZzjqvUONu5vFh4v4A,176
12
12
  mainsequence/_request_identity.py,sha256=suRjESLA_YY_TAxE2htWHd07gvPhJGr-1GtpFnjaVTc,5543
13
13
  mainsequence/_team_memberships.py,sha256=LQsn635Qw2VwhUQ4Ld8qa7utqXsAhO_0IFrf-kqzVk0,1771
14
- mainsequence/_transport.py,sha256=gFSw5bl4O2o3NwZOk-ueNnTQvySBecyhC2-7OPb-BPk,8425
15
- mainsequence/bootstrap.py,sha256=AvG55Y46RcshVqJZsyqvUDN62CJg4CDbHu0Bvsbwfzs,2910
14
+ mainsequence/_transport.py,sha256=K52a1AhOVLfSSR0C6k0rn2-VbF2VnAkfVBc3iSy8PM0,8742
15
+ mainsequence/bootstrap.py,sha256=TY1vsn4TYE_5HGDg2do6czZjauTMi1GoSA1kTEKS2gw,3209
16
16
  mainsequence/code_repository_context.py,sha256=JRrWjwpnUy8I-OjSd9hHlrcq8-Ow3Zeh_N6cYvmtA3o,28545
17
17
  mainsequence/code_repository_skills.py,sha256=AyC1HFAxQXHXNBGbarVUJS2cHd4X5HwDx6u8XBophbE,23611
18
18
  mainsequence/defaults.py,sha256=5r6s7AI-X40rpm1D3IgcNsWam7iJg4_lIxB3F_1u2z0,408
19
- mainsequence/logconf.py,sha256=q4aTXScwR3lW1nOB3KdamwUDRR7dNeKvmfFtp36msI0,20274
19
+ mainsequence/logconf.py,sha256=LosTSjilPpT5d3i4SOjtQkYOGzoB_AhqP6ImEJlEDvc,20436
20
20
  mainsequence/repository_identity_security.py,sha256=Cdywndhiy1zJFUPh-FfM90RjZ3Hg3tjhxBr64FRhmXs,1035
21
- mainsequence/runtime_credential_exchange.py,sha256=yYjeO8tkUeTi5tjfbXtHV5ekQw5Its4wBjPU38iBI2c,6152
21
+ mainsequence/runtime_credential_exchange.py,sha256=WxSj2qpWWsuSeaNpPgfJkhpmFdjdzLWSjEQDMpzq7Ic,6928
22
22
  mainsequence/runtime_flags.py,sha256=1eTM7VRRhnuZ_GXcmFhqAmdEKwyQYMyZcPsio88vJRQ,378
23
23
  mainsequence/scaffold_skills.py,sha256=k0V6eKC5AwbHr9wB9UGMJNF-8eJ0_1izF4-BU01KHrg,10606
24
+ mainsequence/workload_identity.py,sha256=L4EEwrD0JZBgPtulmhyWSAP81tIObbq-_ZP4k_QnmP8,9608
24
25
  mainsequence/cli/__init__.py,sha256=sMWTnomCaISjnureLuXFRqOzkH2Y77uYEivsd-M6_8Y,28
25
26
  mainsequence/cli/api.py,sha256=ExVKhvT99sXstS7aaL1Tx50_hbmf3X8X5aesOkTvXGo,128227
26
27
  mainsequence/cli/browser_auth.py,sha256=Vb5MBOnPC05HLZzVNUDODobJ_p5wEIzH_h8rIlpShlE,9984
@@ -43,26 +44,26 @@ mainsequence/client/client.py,sha256=Jaw9RYObdVDS5J2O0pln99-XpuW9e4vW-SsbJRNldfw
43
44
  mainsequence/client/compute_validation.py,sha256=ByeX0CkIE7qq06ggZFfN92U3Qp2e9cvo2RTIGWa5_Vw,6662
44
45
  mainsequence/client/exceptions.py,sha256=xx2L4l3OMNsTybbYkiTKK398ahnutEascM0It35tGr0,3815
45
46
  mainsequence/client/github_issues.py,sha256=pSTUw3UPrmE6wqnpoJctartTaNSq6iu6PQRrd8hip6I,14568
46
- mainsequence/client/inference.py,sha256=tYKHRxLR6mA5iLmgd3qURwweWc2OPQuw0__tD3LQgSI,7748
47
+ mainsequence/client/inference.py,sha256=BwwZSQ0auih58fQ0HmBeTAwIx8Od2uIsoRJrmyNN5PA,7938
47
48
  mainsequence/client/models_foundry.py,sha256=aHks-RcJtqNz-ZxZjxbd6x8B2Y79cV16G7GIEicYk-o,46397
48
49
  mainsequence/client/models_helpers.py,sha256=6we2XFTyp_G_EHXEcGiXHKgeDFplW135RFljgIN7v2o,52310
49
50
  mainsequence/client/models_user.py,sha256=txBjrW81jP1JvTwu_qMwiCgZZMaDc1X5C6SxBD9-zBw,53608
50
51
  mainsequence/client/object_access.py,sha256=OUZvhOQNfe3Q6sr4K9tz3X35Myp1LteIX8IiAvo1W_4,22900
51
52
  mainsequence/client/observability.py,sha256=_WrDKCaNk_TXmKElKCXC1inork6Exxxe8FRY4m1GI9s,16008
52
- mainsequence/client/utils.py,sha256=Rk2z-78swO6GepibLlQNdxL1eqYy8vHGrjiZdV3G5CM,31641
53
+ mainsequence/client/utils.py,sha256=BoCyp8g28MTYa4e7sHmBkE92-_B0UBtM9QCw-1-6eEc,38635
53
54
  mainsequence/client/value_sets.py,sha256=7TA-mpuAd3hOduNgO1WTQQTuNOGaFgue-VqCsDWKaC8,6181
54
55
  mainsequence/instrumentation/__init__.py,sha256=J_9XmfjprElvz0u2t9rTyJT0kFdyKpxdbkdQiaw28_U,316
55
- mainsequence/instrumentation/utils.py,sha256=b-ihjSioAepeLfMpudM2SqCtvnxMqIXileHx3klBCQU,3377
56
+ mainsequence/instrumentation/utils.py,sha256=Syn07w0LFV3XTMkElUetNt_uguQeB4t-rvAFxvivPmE,7351
56
57
  mainsequence/server/__init__.py,sha256=BHUAhtdWPDRdxX07NYO_6wrBv5mf0GsXflecO52PmUc,73
57
58
  mainsequence/server/caller_assertions.py,sha256=IUQ74UL3VqCAAuujTGk3DzCPogRYhWRD9rVoWezdWdU,11979
58
- mainsequence/server/fastapi.py,sha256=M5zDoFIu9MzuQZdLOXvQPU9Yyqyf_GyXWVn_aravHH4,20123
59
+ mainsequence/server/fastapi.py,sha256=uwdO67LltkKWKsdZ-pKvWWAdtJ-2hcgGSAmIZ6gVNTk,21174
59
60
  mainsequence/server/mcp_skills.py,sha256=-krRwAHCAMipScgGJ19uVkzznhTop1Nz4C_wRY1GUpw,16690
60
61
  mainsequence/server/_mcp_skills_upstream/__init__.py,sha256=px283qBMf3z1nxCfN3WHrH9v8Y8jOb1xoBqZMRZcaD8,2694
61
62
  mainsequence/server/_mcp_skills_upstream/server.py,sha256=laHsfpoaYX3LcwQ04-GN7r0_C63fG6CzyXDci2rmbHE,7695
62
63
  mainsequence/server/_mcp_skills_upstream/shared.py,sha256=JmnX9PoLoyi93nBYnUEPWCdPXor_nQHjHptQDXpFzPs,11978
63
- mainsequence-9.0.35.dev82.dist-info/licenses/LICENSE,sha256=b6Ecsk8wjsEby3lbSzdljR6hHiFGHBizt9iWV2p1c_I,1074
64
- mainsequence-9.0.35.dev82.dist-info/METADATA,sha256=zYx5Q7kCaJxcruBcX1wH5zlxBXA99IcEXrTHYXM0E9k,7867
65
- mainsequence-9.0.35.dev82.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
66
- mainsequence-9.0.35.dev82.dist-info/entry_points.txt,sha256=XGAOq3-mF2lWWpeRJvoaWyMarRcK167mH1g124aGdUs,88
67
- mainsequence-9.0.35.dev82.dist-info/top_level.txt,sha256=BFeblM_Q9q0cUWBvTxnfWcWQEHtf5XZi9nOS-Gdfwus,28
68
- mainsequence-9.0.35.dev82.dist-info/RECORD,,
64
+ mainsequence-9.0.36.dev84.dist-info/licenses/LICENSE,sha256=b6Ecsk8wjsEby3lbSzdljR6hHiFGHBizt9iWV2p1c_I,1074
65
+ mainsequence-9.0.36.dev84.dist-info/METADATA,sha256=CBsDj85rEHWrvuwTuyoRfI71budLJx57LoBWUEKTlEM,7867
66
+ mainsequence-9.0.36.dev84.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
67
+ mainsequence-9.0.36.dev84.dist-info/entry_points.txt,sha256=XGAOq3-mF2lWWpeRJvoaWyMarRcK167mH1g124aGdUs,88
68
+ mainsequence-9.0.36.dev84.dist-info/top_level.txt,sha256=BFeblM_Q9q0cUWBvTxnfWcWQEHtf5XZi9nOS-Gdfwus,28
69
+ mainsequence-9.0.36.dev84.dist-info/RECORD,,