mainsequence 9.0.36.dev85__tar.gz → 9.0.37__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 (121) hide show
  1. {mainsequence-9.0.36.dev85/mainsequence.egg-info → mainsequence-9.0.37}/PKG-INFO +1 -1
  2. mainsequence-9.0.37/mainsequence/_local_callers.py +121 -0
  3. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/server/fastapi.py +59 -19
  4. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37/mainsequence.egg-info}/PKG-INFO +1 -1
  5. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence.egg-info/SOURCES.txt +2 -0
  6. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/pyproject.toml +1 -1
  7. mainsequence-9.0.37/tests/test_local_caller_cache.py +370 -0
  8. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/LICENSE +0 -0
  9. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/README.md +0 -0
  10. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/a2a_sdk_execution/SKILL.md +0 -0
  11. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/application_surfaces/api_surfaces/SKILL.md +0 -0
  12. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/mainsequence-inference/SKILL.md +0 -0
  13. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/maintenance/bug_auditor/SKILL.md +0 -0
  14. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/maintenance/code_repository_maintenance/SKILL.md +0 -0
  15. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/maintenance/metatables_transition/SKILL.md +0 -0
  16. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/platform_operations/access_control_and_sharing/SKILL.md +0 -0
  17. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/platform_operations/orchestration_and_releases/SKILL.md +0 -0
  18. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/agent_scaffold/skills/sdk_code_repository_execution/SKILL.md +0 -0
  19. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/__init__.py +0 -0
  20. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/__main__.py +0 -0
  21. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/_request_identity.py +0 -0
  22. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/_team_memberships.py +0 -0
  23. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/_transport.py +0 -0
  24. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/bootstrap.py +0 -0
  25. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/__init__.py +0 -0
  26. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/api.py +0 -0
  27. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/browser_auth.py +0 -0
  28. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/cli.py +0 -0
  29. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/code_repository_status.py +0 -0
  30. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/config.py +0 -0
  31. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/docker_utils.py +0 -0
  32. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/doctor.py +0 -0
  33. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/local_ops.py +0 -0
  34. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/model_filters.py +0 -0
  35. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/pydantic_cli.py +0 -0
  36. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/sdk_utils.py +0 -0
  37. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/ssh_utils.py +0 -0
  38. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/cli/ui.py +0 -0
  39. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/__init__.py +0 -0
  40. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/access_catalog.py +0 -0
  41. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/agent_runtime_models.py +0 -0
  42. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/base.py +0 -0
  43. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/client.py +0 -0
  44. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/compute_validation.py +0 -0
  45. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/exceptions.py +0 -0
  46. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/github_issues.py +0 -0
  47. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/inference.py +0 -0
  48. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/models_foundry.py +0 -0
  49. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/models_helpers.py +0 -0
  50. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/models_user.py +0 -0
  51. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/object_access.py +0 -0
  52. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/observability.py +0 -0
  53. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/utils.py +0 -0
  54. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/client/value_sets.py +0 -0
  55. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/code_repository_context.py +0 -0
  56. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/code_repository_skills.py +0 -0
  57. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/defaults.py +0 -0
  58. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/instrumentation/__init__.py +0 -0
  59. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/instrumentation/utils.py +0 -0
  60. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/logconf.py +0 -0
  61. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/repository_identity_security.py +0 -0
  62. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/runtime_credential_exchange.py +0 -0
  63. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/runtime_flags.py +0 -0
  64. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/scaffold_skills.py +0 -0
  65. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/server/__init__.py +0 -0
  66. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/server/_mcp_skills_upstream/__init__.py +0 -0
  67. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/server/_mcp_skills_upstream/server.py +0 -0
  68. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/server/_mcp_skills_upstream/shared.py +0 -0
  69. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/server/caller_assertions.py +0 -0
  70. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/server/mcp_skills.py +0 -0
  71. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence/workload_identity.py +0 -0
  72. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence.egg-info/dependency_links.txt +0 -0
  73. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence.egg-info/entry_points.txt +0 -0
  74. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence.egg-info/requires.txt +0 -0
  75. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/mainsequence.egg-info/top_level.txt +0 -0
  76. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/setup.cfg +0 -0
  77. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_access_catalog_client.py +0 -0
  78. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_auth_bootstrap.py +0 -0
  79. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_auth_precedence.py +0 -0
  80. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_caller_assertions.py +0 -0
  81. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_caller_context.py +0 -0
  82. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_canonical_api_route_contract.py +0 -0
  83. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_cli_auth_contract.py +0 -0
  84. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_cli_browser_auth.py +0 -0
  85. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_cli_request_budget.py +0 -0
  86. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_cli_secure_storage.py +0 -0
  87. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_client.py +0 -0
  88. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_code_repository_branch_contract.py +0 -0
  89. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_code_repository_documentation_contract.py +0 -0
  90. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_code_repository_runtime_context.py +0 -0
  91. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_code_repository_skills.py +0 -0
  92. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_credential_repr.py +0 -0
  93. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_dependency_extras.py +0 -0
  94. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_dev_release_version.py +0 -0
  95. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_environment_resource_context.py +0 -0
  96. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_environment_response_contracts.py +0 -0
  97. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_fastapi_mcp.py +0 -0
  98. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_fastapi_request_identity.py +0 -0
  99. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_github_issues_client.py +0 -0
  100. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_http_retry_budget.py +0 -0
  101. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_independent_context.py +0 -0
  102. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_inference_client.py +0 -0
  103. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_instrumentation.py +0 -0
  104. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_job_client.py +0 -0
  105. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_local_ops.py +0 -0
  106. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_logconf.py +0 -0
  107. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_mcp_skills.py +0 -0
  108. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_models_user_request_bound_auth.py +0 -0
  109. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_notification_uid_contract.py +0 -0
  110. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_object_access_client.py +0 -0
  111. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_observability_client.py +0 -0
  112. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_runtime_credential_exchange.py +0 -0
  113. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_scaffold_skills.py +0 -0
  114. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_secret_client_model.py +0 -0
  115. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_source_ownership.py +0 -0
  116. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_ssh_utils.py +0 -0
  117. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_team_memberships.py +0 -0
  118. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_tolerant_response_reading.py +0 -0
  119. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_tolerant_value_sets.py +0 -0
  120. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_user_application_facts.py +0 -0
  121. {mainsequence-9.0.36.dev85 → mainsequence-9.0.37}/tests/test_workload_identity.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mainsequence
3
- Version: 9.0.36.dev85
3
+ Version: 9.0.37
4
4
  Summary: Main Sequence SDK
5
5
  Author-email: Main Sequence GmbH <dev@main-sequence.io>
6
6
  License-Expression: MIT
@@ -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)"
@@ -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 _local_user(scope):
124
- authorization = _header(scope, b"authorization") or ""
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.strip()},
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
- user = RequestUserIdentity(uid=payload["uid"], username=payload.get("username"))
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, app, *, mode, verifier, public_ingress, routes, team_membership_cache_seconds=0
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(_local_user, scope)
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
- if (
309
- isinstance(team_membership_cache_seconds, bool)
310
- or not isinstance(team_membership_cache_seconds, (int, float))
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
- raise ValueError("team_membership_cache_seconds must be a non-negative number.")
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,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mainsequence
3
- Version: 9.0.36.dev85
3
+ Version: 9.0.37
4
4
  Summary: Main Sequence SDK
5
5
  Author-email: Main Sequence GmbH <dev@main-sequence.io>
6
6
  License-Expression: MIT
@@ -12,6 +12,7 @@ agent_scaffold/skills/platform_operations/orchestration_and_releases/SKILL.md
12
12
  agent_scaffold/skills/sdk_code_repository_execution/SKILL.md
13
13
  mainsequence/__init__.py
14
14
  mainsequence/__main__.py
15
+ mainsequence/_local_callers.py
15
16
  mainsequence/_request_identity.py
16
17
  mainsequence/_team_memberships.py
17
18
  mainsequence/_transport.py
@@ -98,6 +99,7 @@ tests/test_independent_context.py
98
99
  tests/test_inference_client.py
99
100
  tests/test_instrumentation.py
100
101
  tests/test_job_client.py
102
+ tests/test_local_caller_cache.py
101
103
  tests/test_local_ops.py
102
104
  tests/test_logconf.py
103
105
  tests/test_mcp_skills.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "mainsequence"
7
- version = "9.0.36.dev85"
7
+ version = "9.0.37"
8
8
  description = "Main Sequence SDK"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.13"
@@ -0,0 +1,370 @@
1
+ """Local-mode callers reused across requests (#251)."""
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import hmac
6
+ import logging
7
+ import threading
8
+ import time
9
+ from unittest.mock import Mock
10
+ from uuid import uuid4
11
+
12
+ import jwt
13
+ import pytest
14
+ import requests
15
+ from fastapi import FastAPI
16
+ from fastapi.testclient import TestClient
17
+
18
+ import mainsequence._local_callers as local_callers
19
+ from mainsequence._local_callers import LocalCallerCache
20
+ from mainsequence.client import User
21
+ from mainsequence.server.fastapi import _RequestIdentityMiddleware, install_request_identity
22
+
23
+ USER = str(uuid4())
24
+ OTHER = str(uuid4())
25
+ ENDPOINT = "https://platform.example.test"
26
+
27
+
28
+ @pytest.fixture(autouse=True)
29
+ def local_mode(monkeypatch):
30
+ for name in (
31
+ "APP_NAME",
32
+ "FASTAPI_PUBLIC_BASE_URL",
33
+ "MAINSEQUENCE_CALLER_AUTH_MODE",
34
+ "MAINSEQUENCE_CALLER_ASSERTION_ISSUER",
35
+ "MAINSEQUENCE_CALLER_ASSERTION_JWKS_URL",
36
+ "FASTAPI_PUBLIC_INGRESS",
37
+ ):
38
+ monkeypatch.delenv(name, raising=False)
39
+ monkeypatch.setenv("MAINSEQUENCE_ENDPOINT", ENDPOINT)
40
+
41
+
42
+ @pytest.fixture
43
+ def clock(monkeypatch):
44
+ """The cache's monotonic clock, moved by the test."""
45
+ now = [1_000.0]
46
+ monkeypatch.setattr(local_callers, "_now", lambda: now[0])
47
+ return now
48
+
49
+
50
+ def answering(*statuses, uid=USER):
51
+ """A fake ``requests.get`` for users/me answering ``statuses`` in turn, then 200."""
52
+ queue = list(statuses)
53
+
54
+ def get(url, **kwargs):
55
+ status = queue.pop(0) if queue else 200
56
+ if isinstance(status, BaseException):
57
+ raise status
58
+ response = Mock(status_code=status)
59
+ response.json.return_value = {"uid": uid, "username": "local"}
60
+ return response
61
+
62
+ return Mock(side_effect=get)
63
+
64
+
65
+ def app_for(**options):
66
+ app = FastAPI()
67
+
68
+ @app.get("/me")
69
+ def me():
70
+ return {"uid": User.get_logged_user().uid}
71
+
72
+ install_request_identity(app, **options)
73
+ return app
74
+
75
+
76
+ def bearer(token="local-token"):
77
+ return {"Authorization": "Bearer " + token}
78
+
79
+
80
+ def test_repeated_requests_with_one_token_ask_the_platform_once(monkeypatch):
81
+ get = answering()
82
+ monkeypatch.setattr("mainsequence.server.fastapi.requests.get", get)
83
+
84
+ with TestClient(app_for(local_caller_cache_seconds=60)) as client:
85
+ answers = [client.get("/me", headers=bearer()).json() for _ in range(5)]
86
+
87
+ assert answers == [{"uid": USER}] * 5
88
+ assert get.call_count == 1
89
+ assert get.call_args.kwargs["headers"] == bearer()
90
+
91
+
92
+ def test_without_a_period_every_request_asks_the_platform(monkeypatch):
93
+ get = answering()
94
+ monkeypatch.setattr("mainsequence.server.fastapi.requests.get", get)
95
+
96
+ with TestClient(app_for()) as client:
97
+ for _ in range(3):
98
+ assert client.get("/me", headers=bearer()).json() == {"uid": USER}
99
+
100
+ assert get.call_count == 3
101
+
102
+
103
+ def _concurrent_first_requests(monkeypatch, *, count, outcome, period=60, gate=None):
104
+ """``count`` simultaneous first requests with one token.
105
+
106
+ Each platform check runs ``gate`` first; by default it ends once every other
107
+ request waits for it.
108
+ """
109
+ runtime = None
110
+ calls = 0
111
+
112
+ def all_others_wait():
113
+ deadline = time.monotonic() + 5
114
+ while time.monotonic() < deadline:
115
+ if sum(check.waiters for check in runtime.local_callers._checks.values()) == count - 1:
116
+ return
117
+ time.sleep(0.005)
118
+
119
+ def get(url, **kwargs):
120
+ nonlocal calls
121
+ calls += 1
122
+ (gate or all_others_wait)()
123
+ if isinstance(outcome, BaseException):
124
+ raise outcome
125
+ response = Mock(status_code=outcome)
126
+ response.json.return_value = {"uid": USER, "username": "local"}
127
+ return response
128
+
129
+ monkeypatch.setattr("mainsequence.server.fastapi.requests.get", get)
130
+
131
+ async def application(scope, receive, send):
132
+ await send({"type": "http.response.start", "status": 200, "headers": []})
133
+ await send({"type": "http.response.body", "body": User.get_logged_user().uid.encode()})
134
+
135
+ runtime = _RequestIdentityMiddleware(
136
+ application,
137
+ mode="local",
138
+ verifier=None,
139
+ public_ingress=(),
140
+ routes=(),
141
+ local_caller_cache_seconds=period,
142
+ )
143
+
144
+ async def request():
145
+ sent = []
146
+ scope = {
147
+ "type": "http",
148
+ "method": "GET",
149
+ "path": "/",
150
+ "headers": [(b"authorization", b"Bearer shared-token")],
151
+ }
152
+
153
+ async def receive():
154
+ return {"type": "http.request", "body": b""}
155
+
156
+ async def send(message):
157
+ sent.append(message)
158
+
159
+ await runtime(scope, receive, send)
160
+ return sent[0]["status"], sent[1]["body"]
161
+
162
+ async def all_at_once():
163
+ return await asyncio.gather(*(request() for _ in range(count)))
164
+
165
+ return asyncio.run(all_at_once()), calls, runtime
166
+
167
+
168
+ def test_concurrent_first_requests_share_one_check(monkeypatch):
169
+ answers, calls, _ = _concurrent_first_requests(monkeypatch, count=6, outcome=200)
170
+
171
+ assert calls == 1
172
+ assert answers == [(200, USER.encode())] * 6
173
+
174
+
175
+ def test_without_a_period_concurrent_requests_each_ask_the_platform(monkeypatch):
176
+ together = threading.Barrier(6, timeout=5)
177
+
178
+ def all_checks_at_once():
179
+ try:
180
+ together.wait()
181
+ except threading.BrokenBarrierError:
182
+ pass
183
+
184
+ answers, calls, _ = _concurrent_first_requests(
185
+ monkeypatch, count=6, outcome=200, period=0, gate=all_checks_at_once
186
+ )
187
+
188
+ assert calls == 6
189
+ assert answers == [(200, USER.encode())] * 6
190
+
191
+
192
+ def test_concurrent_first_requests_share_a_failed_check_and_the_next_asks_again(monkeypatch):
193
+ answers, calls, runtime = _concurrent_first_requests(
194
+ monkeypatch, count=6, outcome=requests.Timeout("users/me timed out")
195
+ )
196
+
197
+ assert calls == 1
198
+ assert [status for status, _ in answers] == [503] * 6
199
+ assert len(runtime.local_callers) == 0
200
+
201
+
202
+ @pytest.mark.parametrize(
203
+ "refusal, status",
204
+ [
205
+ (401, 401),
206
+ (500, 503),
207
+ (requests.Timeout("timed out"), 503),
208
+ (requests.ConnectionError("unreachable"), 503),
209
+ ],
210
+ ids=["refused", "server-error", "timeout", "network-error"],
211
+ )
212
+ def test_a_refusal_is_not_kept(monkeypatch, refusal, status):
213
+ get = answering(refusal)
214
+ monkeypatch.setattr("mainsequence.server.fastapi.requests.get", get)
215
+
216
+ with TestClient(app_for(local_caller_cache_seconds=60)) as client:
217
+ assert client.get("/me", headers=bearer()).status_code == status
218
+ assert client.get("/me", headers=bearer()).json() == {"uid": USER}
219
+ assert client.get("/me", headers=bearer()).json() == {"uid": USER}
220
+
221
+ assert get.call_count == 2
222
+
223
+
224
+ def test_an_answer_expires_after_the_period(monkeypatch, clock):
225
+ get = answering()
226
+ monkeypatch.setattr("mainsequence.server.fastapi.requests.get", get)
227
+
228
+ with TestClient(app_for(local_caller_cache_seconds=60)) as client:
229
+ client.get("/me", headers=bearer())
230
+ clock[0] += 59
231
+ client.get("/me", headers=bearer())
232
+ assert get.call_count == 1
233
+ clock[0] += 1
234
+ client.get("/me", headers=bearer())
235
+
236
+ assert get.call_count == 2
237
+
238
+
239
+ def test_an_answer_never_outlives_the_token(monkeypatch, clock):
240
+ get = answering()
241
+ monkeypatch.setattr("mainsequence.server.fastapi.requests.get", get)
242
+ key = "k" * 32 # the cache reads exp without verifying the signature
243
+ soon = jwt.encode({"exp": int(time.time()) + 10}, key, algorithm="HS256")
244
+ expired = jwt.encode({"exp": int(time.time()) - 1}, key, algorithm="HS256")
245
+
246
+ with TestClient(app_for(local_caller_cache_seconds=60)) as client:
247
+ client.get("/me", headers=bearer(soon))
248
+ clock[0] += 5
249
+ client.get("/me", headers=bearer(soon))
250
+ assert get.call_count == 1
251
+ clock[0] += 6 # past the token's exp, well within the period
252
+ client.get("/me", headers=bearer(soon))
253
+ assert get.call_count == 2
254
+ # A token already past its exp is never kept.
255
+ client.get("/me", headers=bearer(expired))
256
+ client.get("/me", headers=bearer(expired))
257
+
258
+ assert get.call_count == 4
259
+
260
+
261
+ def test_each_token_and_endpoint_is_its_own_entry(monkeypatch):
262
+ get = answering()
263
+ monkeypatch.setattr("mainsequence.server.fastapi.requests.get", get)
264
+ app = app_for(local_caller_cache_seconds=60)
265
+
266
+ with TestClient(app) as client:
267
+ client.get("/me", headers=bearer("first-token"))
268
+ client.get("/me", headers=bearer("second-token"))
269
+ client.get("/me", headers=bearer("first-token"))
270
+ assert get.call_count == 2
271
+ monkeypatch.setenv("MAINSEQUENCE_ENDPOINT", "https://other.example.test")
272
+ client.get("/me", headers=bearer("first-token"))
273
+
274
+ assert get.call_count == 3
275
+ assert get.call_args.args[0] == "https://other.example.test/api/v1/users/me/"
276
+
277
+
278
+ def test_the_identity_header_is_checked_on_every_request(monkeypatch):
279
+ get = answering()
280
+ monkeypatch.setattr("mainsequence.server.fastapi.requests.get", get)
281
+
282
+ with TestClient(app_for(local_caller_cache_seconds=60)) as client:
283
+ assert client.get("/me", headers={**bearer(), "X-User-UID": USER}).status_code == 200
284
+ conflicting = client.get("/me", headers={**bearer(), "X-User-UID": OTHER})
285
+ assert client.get("/me", headers=bearer()).status_code == 200
286
+
287
+ assert conflicting.status_code == 401
288
+ assert get.call_count == 1
289
+
290
+
291
+ def test_no_token_key_or_hash_is_logged_or_shown(monkeypatch, caplog):
292
+ caplog.set_level(logging.DEBUG)
293
+ token = "secret-local-token"
294
+ monkeypatch.setattr(
295
+ "mainsequence.server.fastapi.requests.get", answering(requests.Timeout("timed out"))
296
+ )
297
+ app = app_for(local_caller_cache_seconds=60)
298
+
299
+ with TestClient(app) as client:
300
+ refused = client.get("/me", headers=bearer(token))
301
+ accepted = client.get("/me", headers=bearer(token))
302
+ conflicting = client.get("/me", headers={**bearer(token), "X-User-UID": OTHER})
303
+ cache = app.middleware_stack
304
+ while not isinstance(cache, _RequestIdentityMiddleware):
305
+ cache = cache.app
306
+ cache = cache.local_callers
307
+
308
+ digest = hmac.new(cache._hmac_key, token.encode(), hashlib.sha256)
309
+ secrets = (token, cache._hmac_key.hex(), digest.hexdigest())
310
+ shown = [caplog.text, repr(cache), refused.text, accepted.text, conflicting.text]
311
+ assert repr(cache) == "LocalCallerCache(1 callers)"
312
+ assert not [secret for secret in secrets for text in shown if secret in text]
313
+
314
+
315
+ def test_the_cache_keeps_the_newest_callers():
316
+ cache = LocalCallerCache(max_callers=2)
317
+ checks = []
318
+
319
+ def check(token):
320
+ checks.append(token)
321
+ return token
322
+
323
+ for token in ("a", "b", "c", "a"):
324
+ cache.caller(ENDPOINT, token, lifetime=60, check=lambda token=token: check(token))
325
+
326
+ # "a" was the oldest when "c" arrived, so it was asked again.
327
+ assert checks == ["a", "b", "c", "a"]
328
+ assert len(cache) == 2
329
+
330
+
331
+ def _wait_until(condition):
332
+ deadline = time.monotonic() + 5
333
+ while not condition():
334
+ assert time.monotonic() < deadline, "timed out"
335
+ time.sleep(0.005)
336
+
337
+
338
+ def test_a_waiter_gets_the_check_s_failure():
339
+ cache = LocalCallerCache()
340
+ release = threading.Event()
341
+ results = {}
342
+
343
+ def failing():
344
+ release.wait(5)
345
+ raise RuntimeError("refused")
346
+
347
+ def ask(name, check):
348
+ try:
349
+ results[name] = cache.caller(ENDPOINT, "token", lifetime=60, check=check)
350
+ except RuntimeError as exc:
351
+ results[name] = f"raised {exc}"
352
+
353
+ leader = threading.Thread(target=ask, args=("leader", failing))
354
+ leader.start()
355
+ _wait_until(lambda: cache._checks)
356
+ waiter = threading.Thread(target=ask, args=("waiter", Mock(return_value="never")))
357
+ waiter.start()
358
+ _wait_until(lambda: any(check.waiters for check in cache._checks.values()))
359
+ release.set()
360
+ leader.join(5)
361
+ waiter.join(5)
362
+
363
+ assert results == {"leader": "raised refused", "waiter": "raised refused"}
364
+ assert len(cache) == 0
365
+
366
+
367
+ @pytest.mark.parametrize("value", [-1, float("inf"), float("nan"), True, "60"])
368
+ def test_the_period_must_be_a_non_negative_number(value):
369
+ with pytest.raises(ValueError, match="local_caller_cache_seconds"):
370
+ install_request_identity(FastAPI(), local_caller_cache_seconds=value)