graphharbor-runtime 0.13.0.post2__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 (46) hide show
  1. graphharbor_runtime-0.13.0.post2/.gitignore +15 -0
  2. graphharbor_runtime-0.13.0.post2/LICENSE +21 -0
  3. graphharbor_runtime-0.13.0.post2/PKG-INFO +50 -0
  4. graphharbor_runtime-0.13.0.post2/README.md +8 -0
  5. graphharbor_runtime-0.13.0.post2/pyproject.toml +90 -0
  6. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/__init__.py +45 -0
  7. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/auth.py +381 -0
  8. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/checkpoint.py +207 -0
  9. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/database.py +556 -0
  10. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/graph_executor.py +112 -0
  11. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/graph_registry.py +105 -0
  12. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/lifespan.py +201 -0
  13. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/metrics.py +66 -0
  14. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrate.py +109 -0
  15. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/__init__.py +1 -0
  16. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/env.py +53 -0
  17. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/script.py.mako +27 -0
  18. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/versions/001_initial_schema.py +331 -0
  19. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/versions/002_production_runtime.py +123 -0
  20. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/versions/003_cron_scope.py +29 -0
  21. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/versions/004_thread_event_seq.py +24 -0
  22. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/versions/005_run_retry_schedule.py +23 -0
  23. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/migrations/versions/__init__.py +1 -0
  24. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/models.py +294 -0
  25. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/ops.py +3925 -0
  26. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/production.py +96 -0
  27. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/production_worker.py +491 -0
  28. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/protocol.py +210 -0
  29. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/queue.py +383 -0
  30. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/redis_stream.py +1000 -0
  31. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/retry.py +39 -0
  32. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/routes.py +9 -0
  33. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/run_state.py +104 -0
  34. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/run_store.py +463 -0
  35. graphharbor_runtime-0.13.0.post2/src/langgraph_runtime_pg/store.py +187 -0
  36. graphharbor_runtime-0.13.0.post2/tests/conftest.py +183 -0
  37. graphharbor_runtime-0.13.0.post2/tests/test_e2e.py +250 -0
  38. graphharbor_runtime-0.13.0.post2/tests/test_interface.py +320 -0
  39. graphharbor_runtime-0.13.0.post2/tests/test_official_sdk_contract.py +423 -0
  40. graphharbor_runtime-0.13.0.post2/tests/test_ops_eager_iterators.py +249 -0
  41. graphharbor_runtime-0.13.0.post2/tests/test_persistence_contract.py +189 -0
  42. graphharbor_runtime-0.13.0.post2/tests/test_production_contract.py +1649 -0
  43. graphharbor_runtime-0.13.0.post2/tests/test_public_runtime.py +122 -0
  44. graphharbor_runtime-0.13.0.post2/tests/test_queue.py +695 -0
  45. graphharbor_runtime-0.13.0.post2/tests/test_rest_contract.py +165 -0
  46. graphharbor_runtime-0.13.0.post2/tests/test_runtime_service_p0_e2e.py +108 -0
@@ -0,0 +1,15 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .mypy_cache/
7
+ *.egg-info/
8
+ dist/
9
+ build/
10
+ .langgraph_api/
11
+ .cache/
12
+ .tests/
13
+ .DS_Store
14
+ .env
15
+ *.pckl
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohankumar Ramachandran
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.5
2
+ Name: graphharbor-runtime
3
+ Version: 0.13.0.post2
4
+ Summary: GraphHarbor PostgreSQL and Redis runtime for the LangGraph Agent Server
5
+ Project-URL: Homepage, https://github.com/ljxpython/graphharbor
6
+ Project-URL: Repository, https://github.com/ljxpython/graphharbor
7
+ Project-URL: Issues, https://github.com/ljxpython/graphharbor/issues
8
+ Project-URL: Changelog, https://github.com/ljxpython/graphharbor/releases
9
+ Author-email: Mohankumar Ramachandran <mail@mohanram.dev>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agent-protocol,agent-server,agents,ai-agents,asgi,checkpoint,langchain,langgraph,langgraph-api,langgraph-checkpoint,langgraph-sdk,langsmith,langsmith-deployments,llm,multi-agent,open-source,postgres,postgresql,redis,runtime,self-hosted,uvicorn
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Database
24
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.11
28
+ Requires-Dist: alembic>=1.14
29
+ Requires-Dist: asyncpg>=0.29
30
+ Requires-Dist: croniter>=1.0
31
+ Requires-Dist: langgraph-checkpoint-postgres==3.1.2
32
+ Requires-Dist: orjson>=3.9
33
+ Requires-Dist: psycopg[binary]>=3.3.4
34
+ Requires-Dist: pyjwt[crypto]>=2.8
35
+ Requires-Dist: redis>=5.0
36
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.51
37
+ Requires-Dist: starlette>=0.37
38
+ Requires-Dist: structlog>=24.0
39
+ Provides-Extra: compatibility
40
+ Requires-Dist: langgraph-api==0.13.0; extra == 'compatibility'
41
+ Description-Content-Type: text/markdown
42
+
43
+ # graphharbor-runtime
44
+
45
+ MIT PostgreSQL + Redis runtime (`LANGGRAPH_RUNTIME_EDITION=pg`) for the
46
+ self-hosted GraphHarbor Agent Server. `langgraph-api` is optional and only
47
+ used by the internal compatibility profile.
48
+
49
+ See the [repository README](https://github.com/ljxpython/graphharbor)
50
+ for setup, CLI (`graphharbor`), and architecture.
@@ -0,0 +1,8 @@
1
+ # graphharbor-runtime
2
+
3
+ MIT PostgreSQL + Redis runtime (`LANGGRAPH_RUNTIME_EDITION=pg`) for the
4
+ self-hosted GraphHarbor Agent Server. `langgraph-api` is optional and only
5
+ used by the internal compatibility profile.
6
+
7
+ See the [repository README](https://github.com/ljxpython/graphharbor)
8
+ for setup, CLI (`graphharbor`), and architecture.
@@ -0,0 +1,90 @@
1
+ [project]
2
+ name = "graphharbor-runtime"
3
+ # GraphHarbor has its own release line; langgraph-api is compatibility-spike-only.
4
+ version = "0.13.0.post2"
5
+ description = "GraphHarbor PostgreSQL and Redis runtime for the LangGraph Agent Server"
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ requires-python = ">=3.11"
10
+ authors = [{ name = "Mohankumar Ramachandran", email = "mail@mohanram.dev" }]
11
+ keywords = [
12
+ "langgraph",
13
+ "langsmith",
14
+ "langsmith-deployments",
15
+ "langchain",
16
+ "langgraph-api",
17
+ "langgraph-sdk",
18
+ "langgraph-checkpoint",
19
+ "agent-server",
20
+ "agent-protocol",
21
+ "ai-agents",
22
+ "agents",
23
+ "multi-agent",
24
+ "llm",
25
+ "self-hosted",
26
+ "open-source",
27
+ "postgres",
28
+ "postgresql",
29
+ "redis",
30
+ "checkpoint",
31
+ "runtime",
32
+ "uvicorn",
33
+ "asgi",
34
+ ]
35
+ classifiers = [
36
+ "Development Status :: 4 - Beta",
37
+ "Intended Audience :: Developers",
38
+ "License :: OSI Approved :: MIT License",
39
+ "Operating System :: OS Independent",
40
+ "Programming Language :: Python",
41
+ "Programming Language :: Python :: 3",
42
+ "Programming Language :: Python :: 3 :: Only",
43
+ "Programming Language :: Python :: 3.11",
44
+ "Programming Language :: Python :: 3.12",
45
+ "Programming Language :: Python :: 3.13",
46
+ "Topic :: Database",
47
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
48
+ "Topic :: Software Development :: Libraries :: Python Modules",
49
+ "Typing :: Typed",
50
+ ]
51
+ dependencies = [
52
+ "sqlalchemy[asyncio]>=2.0.51",
53
+ "asyncpg>=0.29",
54
+ "redis>=5.0",
55
+ "alembic>=1.14",
56
+ "psycopg[binary]>=3.3.4",
57
+ "structlog>=24.0",
58
+ "croniter>=1.0",
59
+ "orjson>=3.9",
60
+ "PyJWT[crypto]>=2.8",
61
+ "starlette>=0.37",
62
+ "langgraph-checkpoint-postgres==3.1.2",
63
+ ]
64
+
65
+ [project.optional-dependencies]
66
+ # Keep the old server available for comparison tests, never for the production profile.
67
+ compatibility = ["langgraph-api==0.13.0"]
68
+
69
+ [dependency-groups]
70
+ compatibility = ["langgraph-api==0.13.0"]
71
+
72
+ [project.urls]
73
+ Homepage = "https://github.com/ljxpython/graphharbor"
74
+ Repository = "https://github.com/ljxpython/graphharbor"
75
+ Issues = "https://github.com/ljxpython/graphharbor/issues"
76
+ Changelog = "https://github.com/ljxpython/graphharbor/releases"
77
+
78
+ [project.scripts]
79
+ graphharbor-runtime-migrate = "langgraph_runtime_pg.migrate:main"
80
+
81
+ [build-system]
82
+ requires = ["hatchling"]
83
+ build-backend = "hatchling.build"
84
+
85
+ [tool.hatch.build.targets.wheel]
86
+ packages = ["src/langgraph_runtime_pg"]
87
+
88
+ # Keep Alembic templates / non-.py migration assets in the wheel.
89
+ [tool.hatch.build.targets.wheel.force-include]
90
+ "src/langgraph_runtime_pg/migrations/script.py.mako" = "langgraph_runtime_pg/migrations/script.py.mako"
@@ -0,0 +1,45 @@
1
+ """Postgres+Redis LangGraph runtime (``LANGGRAPH_RUNTIME_EDITION=pg``).
2
+
3
+ The package entry point stays dependency-light. Production graph discovery only
4
+ needs ``graph_registry`` and must not import the legacy compatibility modules (or
5
+ their optional ``langgraph-api``/migration dependencies) as a side effect.
6
+ """
7
+
8
+ from importlib import import_module
9
+ from importlib.metadata import PackageNotFoundError, version
10
+ from typing import Any
11
+
12
+ try:
13
+ __version__ = version("graphharbor-runtime")
14
+ except PackageNotFoundError: # pragma: no cover - editable / source tree edge
15
+ __version__ = "0.0.0"
16
+ _MODULES = {
17
+ "auth",
18
+ "checkpoint",
19
+ "database",
20
+ "lifespan",
21
+ "metrics",
22
+ "migrate",
23
+ "models",
24
+ "ops",
25
+ "production",
26
+ "protocol",
27
+ "queue",
28
+ "redis_stream",
29
+ "retry",
30
+ "routes",
31
+ "run_state",
32
+ "run_store",
33
+ "store",
34
+ }
35
+
36
+
37
+ def __getattr__(name: str) -> Any:
38
+ if name in _MODULES:
39
+ module = import_module(f"{__name__}.{name}")
40
+ globals()[name] = module
41
+ return module
42
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
43
+
44
+
45
+ __all__ = ["__version__", *_MODULES]
@@ -0,0 +1,381 @@
1
+ """Platform delegation JWT validation and the shared request Principal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import json
7
+ import os
8
+ import time
9
+ import urllib.request
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ import jwt
15
+ from starlette.types import ASGIApp, Receive, Scope, Send
16
+
17
+
18
+ class AuthenticationError(ValueError):
19
+ pass
20
+
21
+
22
+ class AuthorizationError(ValueError):
23
+ pass
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class Principal:
28
+ subject: str
29
+ tenant_id: str
30
+ project_id: str
31
+ roles: frozenset[str]
32
+ scopes: frozenset[str]
33
+ credential_type: str
34
+ jti: str
35
+ claims: dict[str, Any]
36
+
37
+ @property
38
+ def sub(self) -> str:
39
+ return self.subject
40
+
41
+ def can(self, scope: str) -> bool:
42
+ return scope in self.scopes or "*" in self.scopes
43
+
44
+ def scope_filter(self) -> dict[str, str]:
45
+ return {"tenant_id": self.tenant_id, "project_id": self.project_id}
46
+
47
+ @classmethod
48
+ def from_claims(cls, claims: dict[str, Any]) -> Principal:
49
+ def claim_text(*names: str) -> str:
50
+ for name in names:
51
+ value = claims.get(name)
52
+ if value is not None and str(value).strip():
53
+ return str(value)
54
+ return ""
55
+
56
+ subject = claim_text("sub")
57
+ tenant_id = claim_text("tenant_id", "tenant")
58
+ project_id = claim_text("project_id", "project")
59
+ jti = claim_text("jti")
60
+ if not subject or not tenant_id or not project_id or not jti:
61
+ raise AuthenticationError("delegation JWT requires sub, tenant_id, project_id, and jti")
62
+
63
+ def claim_set(*names: str) -> frozenset[str]:
64
+ for name in names:
65
+ value = claims.get(name)
66
+ if isinstance(value, str):
67
+ return frozenset(item for item in value.split() if item)
68
+ if isinstance(value, (list, tuple, set)):
69
+ return frozenset(str(item) for item in value)
70
+ return frozenset()
71
+
72
+ return cls(
73
+ subject=subject,
74
+ tenant_id=tenant_id,
75
+ project_id=project_id,
76
+ roles=claim_set("roles", "role"),
77
+ scopes=claim_set("scope", "scopes"),
78
+ credential_type="delegation",
79
+ jti=jti,
80
+ claims=dict(claims),
81
+ )
82
+
83
+ @classmethod
84
+ def from_auth_user(cls, user: Any) -> Principal:
85
+ """Normalize a ``langgraph_sdk.Auth`` user into the runtime Principal."""
86
+
87
+ def value(name: str, default: Any = None) -> Any:
88
+ if isinstance(user, Mapping):
89
+ return user.get(name, default)
90
+ try:
91
+ return user[name]
92
+ except (KeyError, TypeError, AttributeError):
93
+ return getattr(user, name, default)
94
+
95
+ subject = str(value("identity", value("sub", "")) or "").strip()
96
+ if not subject:
97
+ raise AuthenticationError("custom auth user must contain identity")
98
+ tenant_id = str(value("tenant_id", "__default") or "__default").strip()
99
+ project_id = str(value("project_id", "__default") or "__default").strip()
100
+ raw_roles = value("roles", value("role", []))
101
+ raw_scopes = value("scopes", value("permissions", []))
102
+
103
+ def normalize(value_: Any) -> frozenset[str]:
104
+ if isinstance(value_, str):
105
+ return frozenset(item for item in value_.split() if item)
106
+ if isinstance(value_, (list, tuple, set, frozenset)):
107
+ return frozenset(str(item) for item in value_ if str(item).strip())
108
+ return frozenset()
109
+
110
+ jti = str(value("jti", value("delegation_id", subject)) or subject).strip()
111
+ return cls(
112
+ subject=subject,
113
+ tenant_id=tenant_id,
114
+ project_id=project_id,
115
+ roles=normalize(raw_roles),
116
+ scopes=normalize(raw_scopes),
117
+ credential_type=str(value("credential_type", "custom_auth")),
118
+ jti=jti,
119
+ claims=dict(user) if isinstance(user, Mapping) else {"identity": subject},
120
+ )
121
+
122
+
123
+ class JWKSCache:
124
+ """Tiny TTL cache; unknown ``kid`` forces one refresh for key rotation."""
125
+
126
+ def __init__(self, url: str, *, ttl_seconds: int = 300, timeout_seconds: float = 3.0) -> None:
127
+ self.url = url
128
+ self.ttl_seconds = max(ttl_seconds, 1)
129
+ self.timeout_seconds = timeout_seconds
130
+ self._expires_at = 0.0
131
+ self._keys: dict[str, dict[str, Any]] = {}
132
+
133
+ def _fetch(self) -> dict[str, dict[str, Any]]:
134
+ with urllib.request.urlopen(self.url, timeout=self.timeout_seconds) as response:
135
+ payload = json.load(response)
136
+ keys = payload.get("keys")
137
+ if not isinstance(keys, list):
138
+ raise AuthenticationError("JWKS response does not contain a keys array")
139
+ self._keys = {str(item["kid"]): item for item in keys if item.get("kid")}
140
+ self._expires_at = time.monotonic() + self.ttl_seconds
141
+ return self._keys
142
+
143
+ def get(self, kid: str) -> dict[str, Any]:
144
+ if time.monotonic() >= self._expires_at:
145
+ self._fetch()
146
+ key = self._keys.get(kid)
147
+ if key is None:
148
+ key = self._fetch().get(kid)
149
+ if key is None:
150
+ raise AuthenticationError(f"unknown delegation JWT kid: {kid}")
151
+ return key
152
+
153
+
154
+ class DelegationJWTValidator:
155
+ def __init__(
156
+ self,
157
+ *,
158
+ issuer: str,
159
+ audience: str,
160
+ jwks_url: str | None = None,
161
+ shared_secret: str | None = None,
162
+ algorithms: tuple[str, ...] = ("RS256",),
163
+ leeway_seconds: int = 30,
164
+ jwks_ttl_seconds: int = 300,
165
+ ) -> None:
166
+ if not jwks_url and not shared_secret:
167
+ raise ValueError("either jwks_url or shared_secret is required")
168
+ self.issuer = issuer
169
+ self.audience = audience
170
+ self.jwks = JWKSCache(jwks_url, ttl_seconds=jwks_ttl_seconds) if jwks_url else None
171
+ self.shared_secret = shared_secret
172
+ self.algorithms = algorithms
173
+ self.leeway_seconds = leeway_seconds
174
+
175
+ def validate(self, token: str) -> Principal:
176
+ try:
177
+ header = jwt.get_unverified_header(token)
178
+ algorithm = str(header.get("alg", ""))
179
+ if algorithm not in self.algorithms:
180
+ raise AuthenticationError("delegation JWT algorithm is not allowed")
181
+ if self.shared_secret:
182
+ key: Any = self.shared_secret
183
+ else:
184
+ if self.jwks is None:
185
+ raise AuthenticationError("JWKS validator is not configured")
186
+ try:
187
+ jwk = self.jwks.get(str(header["kid"]))
188
+ except (KeyError, TypeError, OSError, ValueError) as exc:
189
+ raise AuthenticationError(
190
+ "unable to resolve delegation JWT signing key"
191
+ ) from exc
192
+ key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk))
193
+ claims = jwt.decode(
194
+ token,
195
+ key=key,
196
+ algorithms=list(self.algorithms),
197
+ issuer=self.issuer,
198
+ audience=self.audience,
199
+ leeway=self.leeway_seconds,
200
+ options={"require": ["exp", "iat", "iss", "aud", "sub", "jti"]},
201
+ )
202
+ return Principal.from_claims(claims)
203
+ except AuthenticationError:
204
+ raise
205
+ except jwt.PyJWTError as exc:
206
+ raise AuthenticationError("invalid delegation JWT") from exc
207
+ except (KeyError, TypeError, OSError, ValueError) as exc:
208
+ raise AuthenticationError("invalid delegation JWT") from exc
209
+
210
+ @classmethod
211
+ def from_env(cls) -> DelegationJWTValidator:
212
+ issuer = os.environ.get("GRAPHHARBOR_JWT_ISSUER")
213
+ audience = os.environ.get("GRAPHHARBOR_JWT_AUDIENCE")
214
+ if not issuer or not audience:
215
+ raise ValueError("GRAPHHARBOR_JWT_ISSUER and GRAPHHARBOR_JWT_AUDIENCE are required")
216
+ algorithms = tuple(
217
+ item.strip()
218
+ for item in os.environ.get("GRAPHHARBOR_JWT_ALGORITHMS", "RS256").split(",")
219
+ if item.strip()
220
+ )
221
+ if not algorithms:
222
+ raise ValueError("GRAPHHARBOR_JWT_ALGORITHMS must contain at least one algorithm")
223
+ return cls(
224
+ issuer=issuer,
225
+ audience=audience,
226
+ jwks_url=os.environ.get("GRAPHHARBOR_JWT_JWKS_URL"),
227
+ shared_secret=os.environ.get("GRAPHHARBOR_JWT_SHARED_SECRET"),
228
+ algorithms=algorithms,
229
+ leeway_seconds=int(os.environ.get("GRAPHHARBOR_JWT_LEEWAY_SECONDS", "30")),
230
+ )
231
+
232
+
233
+ def principal_from_scope(scope: Scope) -> Principal | None:
234
+ value = scope.get("principal")
235
+ return value if isinstance(value, Principal) else None
236
+
237
+
238
+ def scope_override_error(payload: dict[str, Any], principal: Principal | None) -> str | None:
239
+ """Reject tenant/project values supplied by a client when a Principal exists."""
240
+ if principal is None:
241
+ return None
242
+ for claim, expected in principal.scope_filter().items():
243
+ if claim in payload and payload[claim] != expected:
244
+ return f"{claim} is owned by the authenticated Principal"
245
+ return None
246
+
247
+
248
+ def in_principal_scope(resource: Any, principal: Principal | None) -> bool:
249
+ """Return whether a persisted resource belongs to the request Principal."""
250
+ if principal is None:
251
+ return True
252
+ return all(
253
+ getattr(resource, key, None) == value for key, value in principal.scope_filter().items()
254
+ )
255
+
256
+
257
+ class PrincipalMiddleware:
258
+ """ASGI middleware; health/discovery are public, all other paths fail closed in prod."""
259
+
260
+ def __init__(
261
+ self,
262
+ app: ASGIApp,
263
+ validator: DelegationJWTValidator | None,
264
+ *,
265
+ auth_handler: Any | None = None,
266
+ allow_anonymous: bool,
267
+ ) -> None:
268
+ self.app = app
269
+ self.validator = validator
270
+ self.auth_handler = auth_handler
271
+ self.allow_anonymous = allow_anonymous
272
+
273
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
274
+ if scope["type"] != "http" or scope.get("path") in {
275
+ "/ok",
276
+ "/live",
277
+ "/ready",
278
+ "/info",
279
+ "/openapi.json",
280
+ "/metrics",
281
+ }:
282
+ await self.app(scope, receive, send)
283
+ return
284
+ headers = {key.lower(): value for key, value in scope.get("headers", [])}
285
+ auth_header = headers.get(b"authorization", b"").decode("latin-1")
286
+ management_header = headers.get(b"x-graphharbor-management-key", b"").decode("latin-1")
287
+ if management_header:
288
+ # Management credentials are deliberately not a data-plane credential.
289
+ # There are no management routes in the Core profile yet, so fail closed.
290
+ await _json_error(
291
+ send, 403, "management credentials cannot access data-plane resources"
292
+ )
293
+ return
294
+ if not auth_header and self.auth_handler is None:
295
+ if self.allow_anonymous:
296
+ await self.app(scope, receive, send)
297
+ return
298
+ await _json_error(send, 401, "missing delegation token")
299
+ return
300
+ try:
301
+ if self.auth_handler is not None:
302
+ user = await authenticate_with_auth_handler(
303
+ self.auth_handler,
304
+ scope=scope,
305
+ receive=receive,
306
+ authorization=auth_header or None,
307
+ )
308
+ scope["principal"] = Principal.from_auth_user(user)
309
+ else:
310
+ if not auth_header.startswith("Bearer ") or self.validator is None:
311
+ await _json_error(send, 401, "invalid authorization header")
312
+ return
313
+ scope["principal"] = self.validator.validate(auth_header[7:].strip())
314
+ except AuthorizationError as exc:
315
+ await _json_error(send, 403, str(exc))
316
+ return
317
+ except AuthenticationError as exc:
318
+ await _json_error(send, 401, str(exc))
319
+ return
320
+ await self.app(scope, receive, send)
321
+
322
+
323
+ async def authenticate_with_auth_handler(
324
+ auth_handler: Any,
325
+ *,
326
+ scope: Scope,
327
+ receive: Receive,
328
+ authorization: str | None,
329
+ ) -> Any:
330
+ """Call the public custom-auth shape without consuming the request body."""
331
+ handler = getattr(auth_handler, "_authenticate_handler", None)
332
+ if not callable(handler):
333
+ if callable(auth_handler):
334
+ handler = auth_handler
335
+ else:
336
+ raise AuthenticationError("configured auth handler has no authenticate function")
337
+ headers = {key.lower(): value for key, value in scope.get("headers", [])}
338
+ path_params = scope.get("path_params", {})
339
+ query_string = scope.get("query_string", b"").decode("latin-1")
340
+ query_params = dict(
341
+ item.split("=", 1) if "=" in item else (item, "")
342
+ for item in query_string.split("&")
343
+ if item
344
+ )
345
+ values = {
346
+ "path": scope.get("path", ""),
347
+ "method": scope.get("method", "GET"),
348
+ "headers": headers,
349
+ "authorization": authorization,
350
+ "path_params": path_params,
351
+ "query_params": query_params,
352
+ }
353
+ signature = inspect.signature(handler)
354
+ kwargs = {name: values[name] for name in signature.parameters if name in values}
355
+ try:
356
+ result = handler(**kwargs)
357
+ if inspect.isawaitable(result):
358
+ result = await result
359
+ except Exception as exc:
360
+ status = getattr(exc, "status_code", None)
361
+ detail = str(getattr(exc, "detail", exc))
362
+ if status is not None and int(status) < 500:
363
+ if int(status) == 403:
364
+ raise AuthorizationError(detail) from exc
365
+ raise AuthenticationError(detail) from exc
366
+ raise AuthenticationError(detail) from exc
367
+ if result is None or result is False:
368
+ raise AuthenticationError("custom authentication rejected the request")
369
+ return result
370
+
371
+
372
+ async def _json_error(send: Send, status: int, detail: str) -> None:
373
+ body = json.dumps({"detail": detail}, separators=(",", ":")).encode()
374
+ await send(
375
+ {
376
+ "type": "http.response.start",
377
+ "status": status,
378
+ "headers": [(b"content-type", b"application/json")],
379
+ }
380
+ )
381
+ await send({"type": "http.response.body", "body": body})