mainsequence 9.0.36.dev85__py3-none-any.whl → 9.0.37.dev86__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/_local_callers.py +121 -0
- mainsequence/server/fastapi.py +59 -19
- {mainsequence-9.0.36.dev85.dist-info → mainsequence-9.0.37.dev86.dist-info}/METADATA +1 -1
- {mainsequence-9.0.36.dev85.dist-info → mainsequence-9.0.37.dev86.dist-info}/RECORD +8 -7
- {mainsequence-9.0.36.dev85.dist-info → mainsequence-9.0.37.dev86.dist-info}/WHEEL +0 -0
- {mainsequence-9.0.36.dev85.dist-info → mainsequence-9.0.37.dev86.dist-info}/entry_points.txt +0 -0
- {mainsequence-9.0.36.dev85.dist-info → mainsequence-9.0.37.dev86.dist-info}/licenses/LICENSE +0 -0
- {mainsequence-9.0.36.dev85.dist-info → mainsequence-9.0.37.dev86.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Local-mode callers an application may reuse across requests (#251)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import math
|
|
8
|
+
import secrets
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from collections import OrderedDict
|
|
12
|
+
|
|
13
|
+
import jwt
|
|
14
|
+
|
|
15
|
+
# At most this many callers per process, as for team membership answers.
|
|
16
|
+
MAX_CACHED_CALLERS = 10_000
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _now() -> float:
|
|
20
|
+
return time.monotonic()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _seconds_until_expiry(token: str) -> float | None:
|
|
24
|
+
"""Seconds until the token's ``exp``, read unverified only to shorten a lifetime.
|
|
25
|
+
|
|
26
|
+
The platform has already verified the token; None when it is not a JWT or
|
|
27
|
+
carries no usable ``exp``.
|
|
28
|
+
"""
|
|
29
|
+
try:
|
|
30
|
+
expiry = jwt.decode(token, options={"verify_signature": False}).get("exp")
|
|
31
|
+
except (jwt.PyJWTError, AttributeError):
|
|
32
|
+
return None
|
|
33
|
+
if isinstance(expiry, bool) or not isinstance(expiry, (int, float)):
|
|
34
|
+
return None
|
|
35
|
+
if not math.isfinite(expiry):
|
|
36
|
+
return None
|
|
37
|
+
return expiry - time.time()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Check:
|
|
41
|
+
"""One platform check that requests for the same token wait for."""
|
|
42
|
+
|
|
43
|
+
def __init__(self):
|
|
44
|
+
self.done = threading.Event()
|
|
45
|
+
self.outcome = None
|
|
46
|
+
self.waiters = 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class LocalCallerCache:
|
|
50
|
+
"""Who holds a Bearer token, as the platform answered, oldest dropped first.
|
|
51
|
+
|
|
52
|
+
An entry is keyed by the endpoint and an HMAC-SHA256 of the token under a
|
|
53
|
+
key generated for this cache, so the token is never stored and the key
|
|
54
|
+
means nothing outside the process. Only successful answers are kept, for
|
|
55
|
+
at most ``lifetime`` seconds and never past the token's ``exp``. Requests
|
|
56
|
+
for the same token while its check is in flight wait for that check and
|
|
57
|
+
share its result, success or failure.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, max_callers: int = MAX_CACHED_CALLERS):
|
|
61
|
+
self._hmac_key = secrets.token_bytes(32)
|
|
62
|
+
self._callers: OrderedDict[tuple[str, bytes], tuple[object, float]] = OrderedDict()
|
|
63
|
+
self._checks: dict[tuple[str, bytes], _Check] = {}
|
|
64
|
+
self._max_callers = max_callers
|
|
65
|
+
self._lock = threading.Lock()
|
|
66
|
+
|
|
67
|
+
def caller(self, endpoint: str, token: str, *, lifetime: float, check):
|
|
68
|
+
"""The caller ``check()`` answers for ``token``, reused while it is fresh.
|
|
69
|
+
|
|
70
|
+
``check`` asks the platform and raises when it refuses or cannot answer.
|
|
71
|
+
"""
|
|
72
|
+
key = (endpoint, hmac.new(self._hmac_key, token.encode(), hashlib.sha256).digest())
|
|
73
|
+
with self._lock:
|
|
74
|
+
stored = self._callers.get(key)
|
|
75
|
+
if stored is not None:
|
|
76
|
+
caller, expires_at = stored
|
|
77
|
+
if _now() < expires_at:
|
|
78
|
+
return caller
|
|
79
|
+
del self._callers[key]
|
|
80
|
+
pending = self._checks.get(key)
|
|
81
|
+
leader = pending is None
|
|
82
|
+
if leader:
|
|
83
|
+
pending = self._checks[key] = _Check()
|
|
84
|
+
else:
|
|
85
|
+
pending.waiters += 1
|
|
86
|
+
if not leader:
|
|
87
|
+
pending.done.wait()
|
|
88
|
+
if isinstance(pending.outcome, BaseException):
|
|
89
|
+
raise pending.outcome
|
|
90
|
+
return pending.outcome
|
|
91
|
+
try:
|
|
92
|
+
pending.outcome = check()
|
|
93
|
+
except BaseException as exc:
|
|
94
|
+
pending.outcome = exc
|
|
95
|
+
raise
|
|
96
|
+
finally:
|
|
97
|
+
refused = isinstance(pending.outcome, BaseException)
|
|
98
|
+
if not refused:
|
|
99
|
+
remaining = _seconds_until_expiry(token)
|
|
100
|
+
lifetime = lifetime if remaining is None else min(lifetime, remaining)
|
|
101
|
+
with self._lock:
|
|
102
|
+
if not refused:
|
|
103
|
+
self._store(key, pending.outcome, lifetime)
|
|
104
|
+
del self._checks[key]
|
|
105
|
+
pending.done.set()
|
|
106
|
+
return pending.outcome
|
|
107
|
+
|
|
108
|
+
def _store(self, key, caller, lifetime: float) -> None:
|
|
109
|
+
if lifetime <= 0:
|
|
110
|
+
return
|
|
111
|
+
self._callers[key] = (caller, _now() + lifetime)
|
|
112
|
+
self._callers.move_to_end(key)
|
|
113
|
+
while len(self._callers) > self._max_callers:
|
|
114
|
+
self._callers.popitem(last=False)
|
|
115
|
+
|
|
116
|
+
def __len__(self) -> int:
|
|
117
|
+
with self._lock:
|
|
118
|
+
return len(self._callers)
|
|
119
|
+
|
|
120
|
+
def __repr__(self) -> str:
|
|
121
|
+
return f"LocalCallerCache({len(self)} callers)"
|
mainsequence/server/fastapi.py
CHANGED
|
@@ -14,6 +14,7 @@ from uuid import UUID
|
|
|
14
14
|
import requests
|
|
15
15
|
from opentelemetry import context as otel_context
|
|
16
16
|
|
|
17
|
+
from mainsequence._local_callers import LocalCallerCache
|
|
17
18
|
from mainsequence._request_identity import (
|
|
18
19
|
RequestIdentityError,
|
|
19
20
|
_get_request_identity,
|
|
@@ -120,18 +121,12 @@ def _trace_carrier(scope):
|
|
|
120
121
|
return carrier
|
|
121
122
|
|
|
122
123
|
|
|
123
|
-
def
|
|
124
|
-
|
|
125
|
-
scheme, separator, token = authorization.partition(" ")
|
|
126
|
-
if scheme.lower() != "bearer" or not separator or not token.strip():
|
|
127
|
-
raise _AdmissionError(401, "Authenticated request user could not be resolved.")
|
|
128
|
-
endpoint = os.environ.get("MAINSEQUENCE_ENDPOINT", "").strip().rstrip("/")
|
|
129
|
-
if not endpoint:
|
|
130
|
-
raise _AdmissionError(503, "Local caller authentication is unavailable.")
|
|
124
|
+
def _users_me(endpoint, token):
|
|
125
|
+
"""Who holds ``token``, as the platform answers ``users/me``."""
|
|
131
126
|
try:
|
|
132
127
|
response = requests.get(
|
|
133
128
|
endpoint + "/api/v1/users/me/",
|
|
134
|
-
headers={"Authorization": "Bearer " + token
|
|
129
|
+
headers={"Authorization": "Bearer " + token},
|
|
135
130
|
timeout=10,
|
|
136
131
|
allow_redirects=False,
|
|
137
132
|
)
|
|
@@ -140,11 +135,29 @@ def _local_user(scope):
|
|
|
140
135
|
if response.status_code != 200:
|
|
141
136
|
raise _AdmissionError(401, "Authenticated request user could not be resolved.")
|
|
142
137
|
payload = response.json()
|
|
143
|
-
|
|
138
|
+
return RequestUserIdentity(uid=payload["uid"], username=payload.get("username"))
|
|
144
139
|
except requests.RequestException as exc:
|
|
145
140
|
raise _AdmissionError(503, "Caller authentication is unavailable.") from exc
|
|
146
141
|
except (ValueError, TypeError, KeyError) as exc:
|
|
147
142
|
raise _AdmissionError(401, "Authenticated request user could not be resolved.") from exc
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _local_user(scope, callers=None, cache_seconds=0):
|
|
146
|
+
authorization = _header(scope, b"authorization") or ""
|
|
147
|
+
scheme, separator, token = authorization.partition(" ")
|
|
148
|
+
token = token.strip()
|
|
149
|
+
if scheme.lower() != "bearer" or not separator or not token:
|
|
150
|
+
raise _AdmissionError(401, "Authenticated request user could not be resolved.")
|
|
151
|
+
endpoint = os.environ.get("MAINSEQUENCE_ENDPOINT", "").strip().rstrip("/")
|
|
152
|
+
if not endpoint:
|
|
153
|
+
raise _AdmissionError(503, "Local caller authentication is unavailable.")
|
|
154
|
+
if callers is not None and cache_seconds > 0:
|
|
155
|
+
# Only who holds the token is reused; the identity header is checked below (#251).
|
|
156
|
+
user = callers.caller(
|
|
157
|
+
endpoint, token, lifetime=cache_seconds, check=lambda: _users_me(endpoint, token)
|
|
158
|
+
)
|
|
159
|
+
else:
|
|
160
|
+
user = _users_me(endpoint, token)
|
|
148
161
|
uid_header = _header(scope, b"x-user-uid")
|
|
149
162
|
if uid_header:
|
|
150
163
|
try:
|
|
@@ -191,7 +204,15 @@ async def _deny(scope, receive, send, error):
|
|
|
191
204
|
|
|
192
205
|
class _RequestIdentityMiddleware:
|
|
193
206
|
def __init__(
|
|
194
|
-
self,
|
|
207
|
+
self,
|
|
208
|
+
app,
|
|
209
|
+
*,
|
|
210
|
+
mode,
|
|
211
|
+
verifier,
|
|
212
|
+
public_ingress,
|
|
213
|
+
routes,
|
|
214
|
+
team_membership_cache_seconds=0,
|
|
215
|
+
local_caller_cache_seconds=0,
|
|
195
216
|
):
|
|
196
217
|
self.app = app
|
|
197
218
|
self.mode = mode
|
|
@@ -200,6 +221,9 @@ class _RequestIdentityMiddleware:
|
|
|
200
221
|
# Membership answers reused across this application's requests (#225).
|
|
201
222
|
self.team_memberships = TeamMembershipCache()
|
|
202
223
|
self.team_membership_cache_seconds = team_membership_cache_seconds
|
|
224
|
+
# Local-mode callers reused across this application's requests (#251).
|
|
225
|
+
self.local_callers = LocalCallerCache()
|
|
226
|
+
self.local_caller_cache_seconds = local_caller_cache_seconds
|
|
203
227
|
for method, path in public_ingress:
|
|
204
228
|
if not any(
|
|
205
229
|
getattr(route, "path", None) == path
|
|
@@ -260,7 +284,12 @@ class _RequestIdentityMiddleware:
|
|
|
260
284
|
is_organization_admin=caller._requester.is_organization_admin,
|
|
261
285
|
)
|
|
262
286
|
else:
|
|
263
|
-
user = await asyncio.to_thread(
|
|
287
|
+
user = await asyncio.to_thread(
|
|
288
|
+
_local_user,
|
|
289
|
+
scope,
|
|
290
|
+
self.local_callers,
|
|
291
|
+
self.local_caller_cache_seconds,
|
|
292
|
+
)
|
|
264
293
|
context.user = user
|
|
265
294
|
caller_verified = True
|
|
266
295
|
state.update(user=user, user_uid=user.uid, auth_outcome="authenticated")
|
|
@@ -290,7 +319,7 @@ class _RequestIdentityMiddleware:
|
|
|
290
319
|
otel_context.detach(context_token)
|
|
291
320
|
|
|
292
321
|
|
|
293
|
-
def install_request_identity(app, *, team_membership_cache_seconds=0):
|
|
322
|
+
def install_request_identity(app, *, team_membership_cache_seconds=0, local_caller_cache_seconds=0):
|
|
294
323
|
"""Install once at application creation.
|
|
295
324
|
|
|
296
325
|
Handlers use User.get_logged_user() for the caller and, on a
|
|
@@ -302,16 +331,26 @@ def install_request_identity(app, *, team_membership_cache_seconds=0):
|
|
|
302
331
|
answer only within the same request. A longer lifetime means fewer calls
|
|
303
332
|
and a membership change seen up to that much later; the choice belongs to
|
|
304
333
|
the application (ADR 0036, #225).
|
|
334
|
+
|
|
335
|
+
``local_caller_cache_seconds`` is how long, in local mode, the platform's
|
|
336
|
+
answer to who holds a Bearer token may be reused across requests, never
|
|
337
|
+
past the token's ``exp``. ``0``, the default, asks the platform on every
|
|
338
|
+
request. A revoked token stays accepted for up to that long; the choice
|
|
339
|
+
belongs to the application (ADR 0036, #251).
|
|
305
340
|
"""
|
|
306
341
|
if getattr(app.state, _INSTALLATION, None) is not None:
|
|
307
342
|
raise RuntimeError("Request identity is already installed.")
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
or not math.isfinite(team_membership_cache_seconds)
|
|
312
|
-
or team_membership_cache_seconds < 0
|
|
343
|
+
for name, value in (
|
|
344
|
+
("team_membership_cache_seconds", team_membership_cache_seconds),
|
|
345
|
+
("local_caller_cache_seconds", local_caller_cache_seconds),
|
|
313
346
|
):
|
|
314
|
-
|
|
347
|
+
if (
|
|
348
|
+
isinstance(value, bool)
|
|
349
|
+
or not isinstance(value, (int, float))
|
|
350
|
+
or not math.isfinite(value)
|
|
351
|
+
or value < 0
|
|
352
|
+
):
|
|
353
|
+
raise ValueError(f"{name} must be a non-negative number.")
|
|
315
354
|
mode = _mode()
|
|
316
355
|
public_ingress = _public_routes()
|
|
317
356
|
verifier = CallerAssertionVerifier.from_environment() if mode == "assertion" else None
|
|
@@ -322,6 +361,7 @@ def install_request_identity(app, *, team_membership_cache_seconds=0):
|
|
|
322
361
|
public_ingress=public_ingress,
|
|
323
362
|
routes=app.routes,
|
|
324
363
|
team_membership_cache_seconds=team_membership_cache_seconds,
|
|
364
|
+
local_caller_cache_seconds=local_caller_cache_seconds,
|
|
325
365
|
)
|
|
326
366
|
setattr(
|
|
327
367
|
app.state,
|
|
@@ -9,6 +9,7 @@ agent_scaffold/skills/platform_operations/orchestration_and_releases/SKILL.md,sh
|
|
|
9
9
|
agent_scaffold/skills/sdk_code_repository_execution/SKILL.md,sha256=7hBAJuDOKdZUcGoqR7Y4nMHZ9kX5fuY6CMOcgdDaPWI,7046
|
|
10
10
|
mainsequence/__init__.py,sha256=lC_XotSSB3IBMjilFUUJpq_QGoaCoTN9AocNPapNkNo,563
|
|
11
11
|
mainsequence/__main__.py,sha256=KuAP69uduS2ImrPIgNMzbGBRepZzjqvUONu5vFh4v4A,176
|
|
12
|
+
mainsequence/_local_callers.py,sha256=6cgAcfTwHH0JPcRIuU9y1i7E-kZaiJpzoI9RvqpnrUw,4191
|
|
12
13
|
mainsequence/_request_identity.py,sha256=suRjESLA_YY_TAxE2htWHd07gvPhJGr-1GtpFnjaVTc,5543
|
|
13
14
|
mainsequence/_team_memberships.py,sha256=LQsn635Qw2VwhUQ4Ld8qa7utqXsAhO_0IFrf-kqzVk0,1771
|
|
14
15
|
mainsequence/_transport.py,sha256=K52a1AhOVLfSSR0C6k0rn2-VbF2VnAkfVBc3iSy8PM0,8742
|
|
@@ -56,14 +57,14 @@ mainsequence/instrumentation/__init__.py,sha256=J_9XmfjprElvz0u2t9rTyJT0kFdyKpxd
|
|
|
56
57
|
mainsequence/instrumentation/utils.py,sha256=Syn07w0LFV3XTMkElUetNt_uguQeB4t-rvAFxvivPmE,7351
|
|
57
58
|
mainsequence/server/__init__.py,sha256=BHUAhtdWPDRdxX07NYO_6wrBv5mf0GsXflecO52PmUc,73
|
|
58
59
|
mainsequence/server/caller_assertions.py,sha256=IUQ74UL3VqCAAuujTGk3DzCPogRYhWRD9rVoWezdWdU,11979
|
|
59
|
-
mainsequence/server/fastapi.py,sha256=
|
|
60
|
+
mainsequence/server/fastapi.py,sha256=_GXt-PFbEh2i_YDExP0ecfEEgHp87EHPqYLmNfErARc,22720
|
|
60
61
|
mainsequence/server/mcp_skills.py,sha256=-krRwAHCAMipScgGJ19uVkzznhTop1Nz4C_wRY1GUpw,16690
|
|
61
62
|
mainsequence/server/_mcp_skills_upstream/__init__.py,sha256=px283qBMf3z1nxCfN3WHrH9v8Y8jOb1xoBqZMRZcaD8,2694
|
|
62
63
|
mainsequence/server/_mcp_skills_upstream/server.py,sha256=laHsfpoaYX3LcwQ04-GN7r0_C63fG6CzyXDci2rmbHE,7695
|
|
63
64
|
mainsequence/server/_mcp_skills_upstream/shared.py,sha256=JmnX9PoLoyi93nBYnUEPWCdPXor_nQHjHptQDXpFzPs,11978
|
|
64
|
-
mainsequence-9.0.
|
|
65
|
-
mainsequence-9.0.
|
|
66
|
-
mainsequence-9.0.
|
|
67
|
-
mainsequence-9.0.
|
|
68
|
-
mainsequence-9.0.
|
|
69
|
-
mainsequence-9.0.
|
|
65
|
+
mainsequence-9.0.37.dev86.dist-info/licenses/LICENSE,sha256=b6Ecsk8wjsEby3lbSzdljR6hHiFGHBizt9iWV2p1c_I,1074
|
|
66
|
+
mainsequence-9.0.37.dev86.dist-info/METADATA,sha256=_K5vBEc5IP8JRNfYXCI30CBErf0TtnESTH4iU5bVyw0,7867
|
|
67
|
+
mainsequence-9.0.37.dev86.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
68
|
+
mainsequence-9.0.37.dev86.dist-info/entry_points.txt,sha256=XGAOq3-mF2lWWpeRJvoaWyMarRcK167mH1g124aGdUs,88
|
|
69
|
+
mainsequence-9.0.37.dev86.dist-info/top_level.txt,sha256=BFeblM_Q9q0cUWBvTxnfWcWQEHtf5XZi9nOS-Gdfwus,28
|
|
70
|
+
mainsequence-9.0.37.dev86.dist-info/RECORD,,
|
|
File without changes
|
{mainsequence-9.0.36.dev85.dist-info → mainsequence-9.0.37.dev86.dist-info}/entry_points.txt
RENAMED
|
File without changes
|
{mainsequence-9.0.36.dev85.dist-info → mainsequence-9.0.37.dev86.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|
|
File without changes
|