mainsequence 9.0.8.dev43__py3-none-any.whl → 9.0.8.dev44__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.
@@ -92,46 +92,71 @@ Record:
92
92
  - whether the API uses backend transport or a contract-defined direct
93
93
  development transport
94
94
 
95
- Authenticated FastAPI routes receive the human caller from the Main Sequence
96
- platform through injected request state. No SDK authentication setup is
97
- required in repository code:
95
+ Install the SDK's request-identity integration once when creating the FastAPI
96
+ application. Inspect the existing application factory first: the generated
97
+ platform template already calls `install_request_identity(app)`, and a second
98
+ installation raises an error. For an application without that setup:
98
99
 
99
100
  ```python
100
- from fastapi import FastAPI, Request
101
+ from fastapi import FastAPI
102
+ from mainsequence.client import User
103
+ from mainsequence.server.fastapi import install_request_identity
101
104
 
102
105
 
103
106
  app = FastAPI()
107
+ install_request_identity(app)
104
108
 
105
109
 
106
110
  @app.get("/me")
107
- def get_me(request: Request) -> dict[str, str | None]:
108
- return {
109
- "uid": request.state.user_uid,
110
- "username": request.state.user.username,
111
- }
111
+ def get_me() -> dict[str, str | None]:
112
+ user = User.get_logged_user()
113
+ return {"uid": user.uid, "username": user.username}
112
114
  ```
113
115
 
114
- Protected route code must not detect local versus deployed execution, parse
115
- authentication headers, or resolve the request user itself. Consume the
116
- platform-injected human caller identity:
116
+ Use `User.get_logged_user()` in authenticated synchronous or asynchronous
117
+ handlers and their shared services. The middleware verifies the caller before
118
+ the handler, binds one isolated request context, and invalidates it on
119
+ completion, errors, or cancellation. Repeated getter calls do not perform
120
+ additional authentication requests.
117
121
 
118
- - `request.state.user` contains canonical `uid` and optional `username`
119
- - `request.state.user_uid` is the canonical public user UUID
120
- - `request.state.user_id` does not exist
122
+ The same installation handles both HTTP execution modes:
123
+
124
+ - Local execution without hosted deployment markers validates the incoming
125
+ Bearer token against `MAINSEQUENCE_ENDPOINT/api/v1/users/me/`.
126
+ - Platform-hosted execution verifies the gateway's signed caller assertion
127
+ using deployment-owned issuer, public-key, release, and Environment settings.
128
+ Hosted configuration cannot select local mode, and failed proof never falls
129
+ back to UID headers or the process's credentials.
130
+
131
+ Route code must not select the mode, parse authentication headers, or implement
132
+ another caller resolver. The launcher checks the application's installation
133
+ declaration before serving; it does not install the middleware itself.
134
+
135
+ The identity contains canonical `uid` and optional `username`; signed HTTP
136
+ proofs contain no username. `request.state.user` and `request.state.user_uid`
137
+ remain projections of the same identity, not a separate resolver. Outside an
138
+ authenticated request, including public routes, `User.get_logged_user()` raises
139
+ `RequestIdentityError`.
121
140
 
122
141
  On a protected route, this identity is the human making the current HTTP
123
142
  request. It is not the release creator, deployment owner, runtime workload
124
- principal, or runtime target. Pass request state explicitly to shared services;
125
- do not use `User.get_logged_user()` as a FastAPI entry point. Platform-injected identity is
126
- not resource authorization; use `request.state.user_uid` when applying the
127
- endpoint's authorization policy.
143
+ principal, or the process account returned by `User.get_authenticated_user_details()`.
144
+ Caller authentication is not resource authorization; apply the endpoint's
145
+ application policy using the verified user UID.
146
+
147
+ WebSockets retain the platform's gateway ticket/header contract rather than
148
+ the HTTP Bearer/assertion flow; the getter is available while the authenticated
149
+ connection is active. See the version-matched
150
+ [FastAPI identity documentation](https://mainsequence-sdk.github.io/mainsequence-sdk/knowledge/fastapi/)
151
+ for the lifecycle and trust contract.
128
152
 
129
153
  ### Public provider callbacks and webhooks
130
154
 
131
155
  An external OAuth redirect or webhook cannot supply a Main Sequence Bearer token.
132
156
  For a FastAPI release that needs one, use the platform's exact `public_ingress`
133
157
  policy. CORS configuration and an app-declared route alone do not make a path
134
- public. Ordinary routes remain Bearer authenticated.
158
+ public. Ordinary routes still require an authenticated caller through the
159
+ request-identity integration.
135
160
 
136
161
  1. Implement the provider handler in the FastAPI app loaded by the workflow's
137
162
  `source_path`. Declare only its exact `GET` or `POST` method and literal
@@ -166,7 +191,9 @@ public. Ordinary routes remain Bearer authenticated.
166
191
  4. Send a provider-style request without a Main Sequence Bearer token to the
167
192
  exact public pair. Check that an unlisted path or wrong method is denied.
168
193
  An admitted request has `request.state.user` and `user_uid` set to `None`
169
- and `request.state.auth_outcome == "public_ingress"`. The handler must verify
194
+ and `request.state.auth_outcome == "public_ingress"`;
195
+ `User.get_logged_user()` raises `RequestIdentityError` in that anonymous
196
+ scope. The handler must verify
170
197
  OAuth state and exchange codes, or verify the webhook signature against the
171
198
  original body and reject replays. Public admission supplies no User or
172
199
  provider identity. Keep provider secrets and live codes out of workflow YAML,
@@ -37,6 +37,22 @@ class RequestUserIdentity(BaseModel):
37
37
  title="Username",
38
38
  description="Optional display name authenticated by the runtime gateway.",
39
39
  )
40
+ team_uids: tuple[str, ...] = Field(
41
+ (),
42
+ title="Team UIDs",
43
+ description=(
44
+ "Canonical UIDs of the caller's active teams, as signed by the platform "
45
+ "in the caller assertion. Empty when the request carries no such facts."
46
+ ),
47
+ )
48
+ is_organization_admin: bool = Field(
49
+ False,
50
+ title="Organization admin",
51
+ description=(
52
+ "Whether the platform signed the caller as an admin of the application's "
53
+ "Organization. False when the request carries no such facts."
54
+ ),
55
+ )
40
56
 
41
57
  @field_validator("uid", mode="before")
42
58
  @classmethod
@@ -46,6 +62,14 @@ class RequestUserIdentity(BaseModel):
46
62
  except (AttributeError, TypeError, ValueError) as exc:
47
63
  raise ValueError("Request user UID must be a valid UUID.") from exc
48
64
 
65
+ @field_validator("team_uids", mode="before")
66
+ @classmethod
67
+ def _canonicalize_team_uids(cls, value: Any) -> tuple[str, ...]:
68
+ try:
69
+ return tuple(str(UUID(str(item).strip())) for item in value or ())
70
+ except (AttributeError, TypeError, ValueError) as exc:
71
+ raise ValueError("Team UIDs must be valid UUIDs.") from exc
72
+
49
73
  @field_validator("username", mode="before")
50
74
  @classmethod
51
75
  def _normalize_username(cls, value: Any) -> str | None:
@@ -33,6 +33,10 @@ REQUIRED_CLAIMS = frozenset(
33
33
  "exp",
34
34
  }
35
35
  )
36
+ # What the platform states about the caller: active team UIDs and the
37
+ # Organization-admin flag. Sent together, or not at all by a platform that
38
+ # predates them; then the caller has no teams and is not an admin.
39
+ CALLER_FACT_CLAIMS = frozenset({"team_uids", "is_organization_admin"})
36
40
 
37
41
 
38
42
  class InvalidCallerAssertion(ValueError):
@@ -59,6 +63,25 @@ class AuthenticatedCaller:
59
63
  environment_uid: str
60
64
  issued_at: int
61
65
  expires_at: int
66
+ team_uids: tuple[str, ...] = ()
67
+ is_organization_admin: bool = False
68
+
69
+
70
+ def _caller_facts(payload: dict) -> tuple[tuple[str, ...], bool]:
71
+ facts = set(payload) & CALLER_FACT_CLAIMS
72
+ if set(payload) - facts != REQUIRED_CLAIMS or facts not in (set(), set(CALLER_FACT_CLAIMS)):
73
+ raise InvalidCallerAssertion("Caller assertion claims are invalid.")
74
+ if not facts:
75
+ return (), False
76
+ raw_team_uids = payload["team_uids"]
77
+ if not isinstance(raw_team_uids, list):
78
+ raise InvalidCallerAssertion("Caller team UIDs are invalid.")
79
+ team_uids = tuple(_canonical_uid(value) for value in raw_team_uids)
80
+ if list(team_uids) != sorted(set(team_uids)):
81
+ raise InvalidCallerAssertion("Caller team UIDs must be sorted and unique.")
82
+ if type(payload["is_organization_admin"]) is not bool:
83
+ raise InvalidCallerAssertion("Caller admin flag is invalid.")
84
+ return team_uids, payload["is_organization_admin"]
62
85
 
63
86
 
64
87
  class CallerAssertionVerifier:
@@ -206,8 +229,7 @@ class CallerAssertionVerifier:
206
229
  audience=f"urn:mainsequence:fapi:{self.release_uid}",
207
230
  options={"require": list(REQUIRED_CLAIMS)},
208
231
  )
209
- if set(payload) != REQUIRED_CLAIMS:
210
- raise InvalidCallerAssertion("Caller assertion claims are invalid.")
232
+ team_uids, is_organization_admin = _caller_facts(payload)
211
233
  if (
212
234
  payload["aud"] != f"urn:mainsequence:fapi:{self.release_uid}"
213
235
  or _canonical_uid(payload["resource_release_uid"]) != self.release_uid
@@ -226,6 +248,8 @@ class CallerAssertionVerifier:
226
248
  environment_uid=self.environment_uid,
227
249
  issued_at=iat,
228
250
  expires_at=exp,
251
+ team_uids=team_uids,
252
+ is_organization_admin=is_organization_admin,
229
253
  )
230
254
  except (InvalidTokenError, KeyError, TypeError, ValueError) as exc:
231
255
  raise InvalidCallerAssertion("Caller assertion is invalid.") from exc
@@ -213,7 +213,11 @@ class _RequestIdentityMiddleware:
213
213
  elif self.mode == "assertion":
214
214
  assertion = _header(scope, ASSERTION_HEADER.lower().encode()) or ""
215
215
  caller = await asyncio.to_thread(self.verifier.verify, assertion)
216
- user = RequestUserIdentity(uid=caller.user_uid)
216
+ user = RequestUserIdentity(
217
+ uid=caller.user_uid,
218
+ team_uids=caller.team_uids,
219
+ is_organization_admin=caller.is_organization_admin,
220
+ )
217
221
  state["resource_release_uid"] = caller.release_uid
218
222
  state["organization_environment_uid"] = caller.environment_uid
219
223
  else:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mainsequence
3
- Version: 9.0.8.dev43
3
+ Version: 9.0.8.dev44
4
4
  Summary: Main Sequence SDK
5
5
  Author-email: Main Sequence GmbH <dev@main-sequence.io>
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  agent_scaffold/AGENTS.md,sha256=W91rpnyQuoQIa-3dsebIYyuwnbGLvkmuq_8X5k2hTAw,6399
2
2
  agent_scaffold/skills/a2a_sdk_execution/SKILL.md,sha256=NKtcXibE8TxZzKzz1KzJ2cVZ_EeuJJkb660U6wLvZ3s,11809
3
- agent_scaffold/skills/application_surfaces/api_surfaces/SKILL.md,sha256=EEU3eZGgOmY0KOWTgDZ5RJIrLtM8p6yqK894jM7-ySg,14357
3
+ agent_scaffold/skills/application_surfaces/api_surfaces/SKILL.md,sha256=GdbPjIf4xMs5Pz6VrjAwBBePkc7rC3P57s70PNjYZWU,15997
4
4
  agent_scaffold/skills/mainsequence-inference/SKILL.md,sha256=IrVnpuzFMZ3_x5oSH4OiPZsZ5jFf_aKdxEynrQhnRZE,11627
5
5
  agent_scaffold/skills/maintenance/bug_auditor/SKILL.md,sha256=CCKs7edyZ9RK-WtAgXJXucokJFXZxk8sRUe0_imFtu8,8610
6
6
  agent_scaffold/skills/maintenance/code_repository_maintenance/SKILL.md,sha256=pPsZaERlfokSJ6b6vLjpA5U0KuKxbOFzzcxOVW_ikiI,17935
@@ -44,18 +44,18 @@ mainsequence/client/github_issues.py,sha256=pSTUw3UPrmE6wqnpoJctartTaNSq6iu6PQRr
44
44
  mainsequence/client/inference.py,sha256=g24H9LWumMRABIevho8FS7BBOuyYvf80pRwCmJZpLeY,7353
45
45
  mainsequence/client/models_foundry.py,sha256=iN1jJzDokfniEQF0Ac5eepAB7L5pVjJnKavaHLP7BHA,36310
46
46
  mainsequence/client/models_helpers.py,sha256=y7cgcsH8yO3dfIWPhRdcYam7ItWHw3Ps63-WYDe4YHE,46262
47
- mainsequence/client/models_user.py,sha256=BU_hfn4-4KqYz3nsaPlXuYZmUG6_-7YM892mkM92Zyo,37613
47
+ mainsequence/client/models_user.py,sha256=co9uhe-LKkt7Kw5u8-wDMWcp0yL_lS2LuUOyauW5KF0,38557
48
48
  mainsequence/client/observability.py,sha256=_WrDKCaNk_TXmKElKCXC1inork6Exxxe8FRY4m1GI9s,16008
49
49
  mainsequence/client/utils.py,sha256=c4JjMIqKfwSz8DdkwLGmGtQ9lSmVn_KEw9KWGDwz_T0,30133
50
50
  mainsequence/client/value_sets.py,sha256=7TA-mpuAd3hOduNgO1WTQQTuNOGaFgue-VqCsDWKaC8,6181
51
51
  mainsequence/instrumentation/__init__.py,sha256=J_9XmfjprElvz0u2t9rTyJT0kFdyKpxdbkdQiaw28_U,316
52
52
  mainsequence/instrumentation/utils.py,sha256=b-ihjSioAepeLfMpudM2SqCtvnxMqIXileHx3klBCQU,3377
53
53
  mainsequence/server/__init__.py,sha256=BHUAhtdWPDRdxX07NYO_6wrBv5mf0GsXflecO52PmUc,73
54
- mainsequence/server/caller_assertions.py,sha256=hZW1pkkvQ9gaFL075bxUbbctTRrgMMQRTSc2Da0vKCM,9705
55
- mainsequence/server/fastapi.py,sha256=tD1aVuJOgoBTu7H8bs9IldPNYRT4fhkr1leN3KZP1pI,10521
56
- mainsequence-9.0.8.dev43.dist-info/licenses/LICENSE,sha256=b6Ecsk8wjsEby3lbSzdljR6hHiFGHBizt9iWV2p1c_I,1074
57
- mainsequence-9.0.8.dev43.dist-info/METADATA,sha256=1GLtjggEXh4UZaisPIBKffjPsaqgkW5LeX7pambJX60,7402
58
- mainsequence-9.0.8.dev43.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
59
- mainsequence-9.0.8.dev43.dist-info/entry_points.txt,sha256=XGAOq3-mF2lWWpeRJvoaWyMarRcK167mH1g124aGdUs,88
60
- mainsequence-9.0.8.dev43.dist-info/top_level.txt,sha256=BFeblM_Q9q0cUWBvTxnfWcWQEHtf5XZi9nOS-Gdfwus,28
61
- mainsequence-9.0.8.dev43.dist-info/RECORD,,
54
+ mainsequence/server/caller_assertions.py,sha256=f9jHhVeoFK1ScDCmW8h3lEIU5V7zKw70SUSVV2P7wUI,10975
55
+ mainsequence/server/fastapi.py,sha256=Y5QB51CRVbuUVRUcWh5GKQ5b5vMPjbs9scioTt684oQ,10712
56
+ mainsequence-9.0.8.dev44.dist-info/licenses/LICENSE,sha256=b6Ecsk8wjsEby3lbSzdljR6hHiFGHBizt9iWV2p1c_I,1074
57
+ mainsequence-9.0.8.dev44.dist-info/METADATA,sha256=2cyUFtw68GftzC-tFiPNUwc3ZV7Vqg4hpptgihrgOX0,7402
58
+ mainsequence-9.0.8.dev44.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
59
+ mainsequence-9.0.8.dev44.dist-info/entry_points.txt,sha256=XGAOq3-mF2lWWpeRJvoaWyMarRcK167mH1g124aGdUs,88
60
+ mainsequence-9.0.8.dev44.dist-info/top_level.txt,sha256=BFeblM_Q9q0cUWBvTxnfWcWQEHtf5XZi9nOS-Gdfwus,28
61
+ mainsequence-9.0.8.dev44.dist-info/RECORD,,