From e8592e67df546245bed138ef47956f0e663e067b Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 12:45:00 +0100 Subject: [PATCH 1/2] feat(D147): meter stored objects; host routes in the ingest scope; mounted scopes - ingest_stored measures a metered deployment's object exactly as ingest does (the managed text profile: native text up to 10 MB). A larger object is refused before it is read into memory; an accepted one is measured from the spooled copy and released to the raw store on approval. - build_api(ingest_scope_routes=...) / SelfHostProfile.api(...) let an ingest credential reach a host's own routes mounted in the app. - Route scopes and the healthz exemption are matched on the router's own path, so an app mounted under a prefix keeps its narrow credentials working (they all needed write before). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 12 ++- src/rememberstack/profiles/selfhost.py | 7 +- src/rememberstack/surfaces/http_api.py | 20 ++++- src/rememberstack/surfaces/route_scope.py | 29 +++++++- src/rememberstack/workers/e0.py | 37 ++++++++-- src/tests/spine/test_managed_metering_sql.py | 74 +++++++++++++++++++ src/tests/surfaces/test_openapi_export.py | 2 +- .../surfaces/test_per_request_perimeter.py | 47 ++++++++++++ 8 files changed, 211 insertions(+), 17 deletions(-) diff --git a/decisions.md b/decisions.md index d2cae63e2..38e63c128 100644 --- a/decisions.md +++ b/decisions.md @@ -7438,8 +7438,11 @@ deployment's values into another's work. bytes are already stored under another key, that version answers and every ingest path (`ingest`, `ingest_observed`, `ingest_stored`) deletes the copy it wrote or was given. Callers never delete registered objects. The declared size must - match, the uploader chooses the storage class (D51 routing is not applied), and a - deployment with managed ingest metering (which needs the bytes) refuses this path. + match, and the uploader chooses the storage class (D51 routing is not applied). A + deployment with managed text metering measures the object exactly as `ingest` does; + that profile accepts only native text up to 10 MB, so a larger object is refused + before it is read into memory, and an accepted one is measured from the spooled copy + and released to the raw store on approval, where it already is. - *No deployment state on local disk.* `SelfHostSettings.forget_manifest_bucket_name` keeps D74 hard-forget manifests as immutable objects in that dedicated bucket (`ObjectStoreForgetManifestStore`, same contract as the local root) instead of @@ -7466,6 +7469,11 @@ deployment's values into another's work. open-query principal forwarding all read the same resolved deployment, and every route is built held so per-request admission keeps its slot accounting. `install_browser_origins(app=…, origins=…)` is public for a host composing its own app. + `build_api(ingest_scope_routes=[("POST", "/uploads/{id}/complete"), …])` (and + `SelfHostProfile.api(ingest_scope_routes=…)`) lets a narrow ingest credential reach a + host's own routes mounted in the app, as it reaches `POST /ingest`; every other host + route needs write. Route scopes are matched on the router's own path, so an app + mounted under a prefix classifies its routes exactly as an unmounted one. `SelfHostSettings.query_role_host` / `query_role_port` send customer SQL straight to PostgreSQL when the database URL points at a pooler, and `query_role_sslmode` / `query_role_sslrootcert` set that connection's TLS (unset: libpq defaults). diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index a95d9fc9a..d720d16d5 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -4,6 +4,7 @@ import argparse from collections.abc import AsyncIterator +from collections.abc import Collection from collections.abc import Mapping from contextlib import asynccontextmanager from dataclasses import dataclass @@ -1242,11 +1243,14 @@ def setup(self) -> None: # for the previous served set. self.run_projection(plane="p3") - def api(self) -> FastAPI: + def api(self, *, ingest_scope_routes: Collection[tuple[str, str]] = ()) -> FastAPI: """Build the existing HTTP surface over this self-host dependency graph. Every route reads this profile's :meth:`api_deployment` through the overridable ``deployment_context`` dependency (D147). + ``ingest_scope_routes`` are a host's own routes, mounted in the + returned app, that an ingest-scoped credential may call (see + ``build_api``). """ from rememberstack.spine.perimeter_state import PerimeterStateCatalog from rememberstack.surfaces import build_api @@ -1277,6 +1281,7 @@ def api(self) -> FastAPI: ingest_body_max_bytes=self._settings.ingest_body_max_bytes, trusted_principal_source=self._settings.trusted_principal_source, browser_origins=_browser_origins(self._settings.browser_origins), + ingest_scope_routes=ingest_scope_routes, readiness=_FreshDeploymentReadiness(store=self._forget_manifest_store()), ) diff --git a/src/rememberstack/surfaces/http_api.py b/src/rememberstack/surfaces/http_api.py index 58d8ab56b..560be3926 100644 --- a/src/rememberstack/surfaces/http_api.py +++ b/src/rememberstack/surfaces/http_api.py @@ -19,6 +19,7 @@ from collections.abc import AsyncIterator from collections.abc import Callable +from collections.abc import Collection from collections.abc import Iterator from contextlib import contextmanager from contextvars import ContextVar @@ -161,6 +162,7 @@ from rememberstack.surfaces.query_sandbox.errors import SandboxRejection from rememberstack.surfaces.query_sandbox.open_query import OpenQueryFacade from rememberstack.surfaces.query_sandbox.result import QueryResult +from rememberstack.surfaces.route_scope import ingest_route_patterns from rememberstack.surfaces.route_scope import operation_scope from rememberstack.surfaces.route_scope import required_scope @@ -641,6 +643,7 @@ def build_api( build_info: BuildInfoPort | None = None, processing_layers: ProcessingLayersPort | None = None, task_queue: TaskQueuePort | None = None, + ingest_scope_routes: Collection[tuple[str, str]] = (), ingest_body_max_bytes: int | None = None, trusted_principal_source: bool = False, browser_origins: tuple[str, ...] = (), @@ -675,6 +678,10 @@ def build_api( pair is **ignored, never rejected** — metadata must not be able to fail an otherwise valid ingest. + `ingest_scope_routes` names a host's own routes mounted in this app, as + ``(METHOD, "/path/{param}")``, that a narrow ingest credential may reach + as it may reach `POST /ingest` (D147); every other host route needs WRITE. + `ingest_body_max_bytes` bounds `POST /ingest` request bodies before they are buffered (413 over the cap; 411 when no Content-Length is declared). None — the self-host default — imposes no limit: caps are deployment @@ -726,6 +733,7 @@ def build_api( dependencies=dependencies, ) app.state.api_deployment = deployment + app.state.ingest_scope_routes = ingest_route_patterns(ingest_scope_routes) # Before any route is declared, so every one is built held: a request's # deployment may bring admission limits even when this one has none. A # held callable without a hold runs unchanged. @@ -2483,7 +2491,7 @@ def _perimeter( request.state, "perimeter_context", None ) if context is None: - if _is_healthz(method=request.method, path=request.url.path): + if _is_healthz(method=request.method, path=get_route_path(request.scope)): return AuthenticatedContext( deployment_id=deployment.deployment_id, principal="healthz" ) @@ -2499,7 +2507,13 @@ def _perimeter( # never sees the request — and because the method alone cannot tell a # read from a write on this API (`POST /graph/path` reads, # `POST /ingest` does not). See ``route_scope``. - required = required_scope(method=request.method, path=request.url.path) + # The router's own path: relative to any mount and decoded, so a mounted + # app classifies its routes exactly as an unmounted one. + required = required_scope( + method=request.method, + path=get_route_path(request.scope), + extra_ingest_routes=request.app.state.ingest_scope_routes, + ) # ``None`` means the route decides for itself, because its authority is # a property of registry data rather than of the path. Today that is # only ``POST /operations/{name}``, whose handler asks the descriptor. @@ -2591,7 +2605,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await _send_json_error(send=send, status=400, detail="invalid_path") return if scope["type"] != "http" or _is_healthz( - method=scope["method"], path=scope["path"] + method=scope["method"], path=get_route_path(scope) ): await self._app(scope, receive, send) return diff --git a/src/rememberstack/surfaces/route_scope.py b/src/rememberstack/surfaces/route_scope.py index 4aa992b13..5bfe374ec 100644 --- a/src/rememberstack/surfaces/route_scope.py +++ b/src/rememberstack/surfaces/route_scope.py @@ -29,6 +29,7 @@ from __future__ import annotations +from collections.abc import Collection import re from remember.http_routes import _READ_ROUTES @@ -56,7 +57,12 @@ ) -def required_scope(*, method: str, path: str) -> PerimeterScope | None: +def required_scope( + *, + method: str, + path: str, + extra_ingest_routes: tuple[tuple[str, re.Pattern[str]], ...] = (), +) -> PerimeterScope | None: """The scope a caller needs for this route. ``None`` means the route decides for itself (see :data:`_ROUTE_DECIDES`); @@ -70,7 +76,7 @@ def required_scope(*, method: str, path: str) -> PerimeterScope | None: for route_method, pattern in _ROUTE_DECIDES: if route_method == upper and pattern.match(normalised): return None - for route_method, pattern in _INGEST_ROUTES: + for route_method, pattern in (*_INGEST_ROUTES, *extra_ingest_routes): if route_method == upper and pattern.match(normalised): return PerimeterScope.INGEST for route_method, pattern in _READ_ROUTES: @@ -79,6 +85,25 @@ def required_scope(*, method: str, path: str) -> PerimeterScope | None: return PerimeterScope.WRITE +def ingest_route_patterns( + routes: Collection[tuple[str, str]], +) -> tuple[tuple[str, re.Pattern[str]], ...]: + """Compile host routes ``(METHOD, "/path/{param}")`` that ingest scope may reach. + + For a host that mounts its own upload routes in the engine app (D147): a + narrow ingest credential may then call them as it may call + ``POST /ingest``. Each ``{param}`` matches one non-empty path segment. + """ + compiled = [] + for method, template in routes: + parts = re.split(r"(\{[^{}/]+\})", template.rstrip("/") or "/") + body = "".join( + "[^/]+" if part.startswith("{") else re.escape(part) for part in parts + ) + compiled.append((method.upper(), re.compile(f"^{body}$"))) + return tuple(compiled) + + def routes_that_decide_for_themselves() -> tuple[tuple[str, str], ...]: """The deferring routes, for tests that pin the set to exactly what is intended.""" return tuple((method, pattern.pattern) for method, pattern in _ROUTE_DECIDES) diff --git a/src/rememberstack/workers/e0.py b/src/rememberstack/workers/e0.py index c0eb8f984..c8a76c2b8 100644 --- a/src/rememberstack/workers/e0.py +++ b/src/rememberstack/workers/e0.py @@ -71,6 +71,7 @@ from rememberstack.core.storage_routing import storage_class_for_derived from rememberstack.core.text_metering import classify_doc_text from rememberstack.core.text_metering import DOC_TEXT_CLASSIFIER_VERSION +from rememberstack.core.text_metering import DOC_TEXT_MAX_SOURCE_BYTES from rememberstack.core.text_metering import DOC_TEXT_MEASUREMENT_ALGORITHM_VERSION from rememberstack.model import Block from rememberstack.model import ClaimedWork @@ -109,6 +110,7 @@ from rememberstack.model import UnroutableMimeError from rememberstack.model import UploadRecord from rememberstack.model.metering import ManagedMeterScope +from rememberstack.model.metering import ManagedTextClassificationError from rememberstack.model.metering import ManagedTextMeasurementDraft from rememberstack.model.occurrence_provenance import ( parse_persisted_conversion_manifest, @@ -342,14 +344,15 @@ def ingest_stored( key in every store, so a key outside this namespace could name another object, and file names would enter the immutable forget manifests. ``size`` must match the stored object. The uploader - chooses the storage class (D51 routing is not applied). Managed text - metering needs the whole bytes, so a deployment that meters ingest - refuses this path; use :meth:`ingest`. + chooses the storage class (D51 routing is not applied). + + A deployment with managed text metering measures the object exactly + as :meth:`ingest` does. That profile accepts only native text of at + most ``DOC_TEXT_MAX_SOURCE_BYTES`` (10 MB), so a larger object is + refused before anything is read into memory, and an accepted one is + measured from the spooled copy; its staged bytes are released to the + raw store on approval, where the object already is. """ - if self._meter_scope is not None: - raise ValueError( - "managed ingest metering needs the bytes; register through ingest" - ) if _STORED_KEY.fullmatch(key.root) is None: raise ValueError( "a stored object's key must be uploads/<16-128 of [A-Za-z0-9_-]>" @@ -390,6 +393,24 @@ def ingest_stored( detected = self._detected_mime( content=mapped, filename=filename, mime=mime ) + metering: ManagedTextMeasurementDraft | None = None + if self._meter_scope is not None: + if received > DOC_TEXT_MAX_SOURCE_BYTES: + raise ManagedTextClassificationError( + code="source_bytes_limit_exceeded" + ) + spool.seek(0) + measured, metering = self._prepare_managed_text( + deployment_id=deployment_id, + upload=DocumentUpload( + filename=filename, + mime=detected, + content=spool.read(), + title=title, + source_path=source_path, + ), + ) + detected = measured.mime doc_id = uuid5( NAMESPACE_URL, f"rememberstack:upload:{deployment_id}:{content_hash}" ) @@ -415,7 +436,7 @@ def ingest_stored( ), convert_component_version=E0_CONVERT_VERSION, lane=lane, - metering=None, + metering=metering, routable_mimes=routable, ) self._release_unretained( diff --git a/src/tests/spine/test_managed_metering_sql.py b/src/tests/spine/test_managed_metering_sql.py index 88585f82f..d1697020c 100644 --- a/src/tests/spine/test_managed_metering_sql.py +++ b/src/tests/spine/test_managed_metering_sql.py @@ -23,12 +23,15 @@ from sqlalchemy.engine import Engine from rememberstack.adapters.selfhost import LocalFSObjectStore +from rememberstack.core.text_metering import classify_doc_text +from rememberstack.core.text_metering import DOC_TEXT_MAX_SOURCE_BYTES from rememberstack.model import DeploymentBootstrapInput from rememberstack.model import DocumentUpload from rememberstack.model import ObjectKey from rememberstack.model.metering import ManagedDocumentVersionOutcomeV2 from rememberstack.model.metering import ManagedIngestMeasurementV2 from rememberstack.model.metering import ManagedMeterScope +from rememberstack.model.metering import ManagedTextClassificationError from rememberstack.model.metering import MeterAdmissionResult from rememberstack.model.metering import MeterReceiptConflict from rememberstack.ports.metering import MeterReceiptPort @@ -585,3 +588,74 @@ def test_missing_managed_text_route_parks_only_after_meter_approval( == "converting" ) assert receipts.outcomes == [] + + +def test_a_stored_object_is_metered_like_an_upload( + database_engine: Engine, tmp_path: Path +) -> None: + """D147: a directly uploaded text is measured, held and released as ingest is.""" + receipts = ControlledReceipts() + readiness = ControlledReadiness() + raw_store = LocalFSObjectStore(root=tmp_path / "raw") + meter = ManagedMeterCatalog( + engine=database_engine, + receipts=receipts, + readiness=cast(PipelineReadinessCatalog, readiness), + raw_store=raw_store, + ) + ingestor = UploadIngestor( + catalog=DocumentCatalog(engine=database_engine), + raw_store=raw_store, + admission=AllowIngest(), + routable_mimes=frozenset({"text/markdown", "text/plain"}), + meter_scope=ManagedMeterScope( + org_id=_ORG_ID, + project_id=_PROJECT_ID, + identity_key=SecretStr("umc_mik_abcdefghijklmnopqrstuvwxyz0123456789ABCD"), + ), + ) + content = b"stored hello\n\nworld" + key = ObjectKey("uploads/meteredmetered0001") + raw_store.write_bytes(key=key, content=content, storage_class="cold") + + version = ingestor.ingest_stored( + deployment_id=_DEPLOYMENT_ID, + key=key, + size=len(content), + mime="text/plain", + filename="stored.txt", + ) + assert version.created is True and version.processing_admission == "pending" + assert _work_count(engine=database_engine, version_id=version.version_id) == 0 + with database_engine.connect() as connection: + measured = connection.execute( + text( + "SELECT normalized_character_count, canonical_source_bytes" + " FROM managed_ingest_measurements WHERE version_id = :version_id" + ), + {"version_id": version.version_id}, + ).one() + assert tuple(measured) == ( + classify_doc_text( + content=content, declared_mime="text/plain" + ).normalized_character_count, + len(content), + ) + approved = meter.drain_once() + assert approved.measurements_accepted == 1 + # Released to convert, with the raw object still where the client put it. + assert _work_count(engine=database_engine, version_id=version.version_id) == 1 + assert raw_store.read_bytes(key=key) == content + + too_large = ObjectKey("uploads/meteredmetered0002") + big = b"x" * (DOC_TEXT_MAX_SOURCE_BYTES + 1) + raw_store.write_bytes(key=too_large, content=big, storage_class="cold") + with pytest.raises(ManagedTextClassificationError) as refused: + ingestor.ingest_stored( + deployment_id=_DEPLOYMENT_ID, + key=too_large, + size=len(big), + mime="text/plain", + filename="big.txt", + ) + assert refused.value.code == "source_bytes_limit_exceeded" diff --git a/src/tests/surfaces/test_openapi_export.py b/src/tests/surfaces/test_openapi_export.py index 2522bae85..20215697b 100644 --- a/src/tests/surfaces/test_openapi_export.py +++ b/src/tests/surfaces/test_openapi_export.py @@ -188,7 +188,7 @@ def test_the_checked_in_schema_matches_the_app() -> None: #: A task queue only announces the work a request created (D147); it mounts #: no route. _POLICY_PARAMETERS = frozenset( - {"ingest_body_max_bytes", "direct_admission", "task_queue"} + {"ingest_body_max_bytes", "direct_admission", "task_queue", "ingest_scope_routes"} ) diff --git a/src/tests/surfaces/test_per_request_perimeter.py b/src/tests/surfaces/test_per_request_perimeter.py index 354c0268b..8ad4355c3 100644 --- a/src/tests/surfaces/test_per_request_perimeter.py +++ b/src/tests/surfaces/test_per_request_perimeter.py @@ -262,3 +262,50 @@ def whoami( app.dependency_overrides.clear() # type: ignore[union-attr] # No resolver any more: the composed deployment (no perimeter) serves it. assert client.get("/whoami").json() == {"deployment": str(_A)} + + +class _ScopedAuth: + """``Bearer ingest`` may only ingest; ``Bearer write`` may do anything.""" + + def authenticate(self, *, credential: PerimeterCredential) -> AuthenticatedContext: + from rememberstack.model.auth import PerimeterScope + + value = credential.value.get_secret_value().decode() + scope = {"ingest": PerimeterScope.INGEST, "write": PerimeterScope.WRITE}[value] + return AuthenticatedContext(deployment_id=_A, principal=value, scope=scope) + + +def test_a_host_route_can_be_opened_to_ingest_credentials() -> None: + """D147: host upload routes listed at build time take the ingest scope.""" + from fastapi import FastAPI + + app = build_api( + engine=cast(QueryEngine, object()), + deployment_id=_A, + admission=_Open(), + readiness=_Ready(), + auth=_ScopedAuth(), + ingest_scope_routes=(("POST", "/uploads/{upload_id}/complete"),), + ) + + @app.post("/uploads/{upload_id}/complete") + def complete(upload_id: str) -> dict[str, str]: + return {"completed": upload_id} + + @app.post("/uploads/{upload_id}/share") + def share(upload_id: str) -> dict[str, str]: + return {"shared": upload_id} + + # Mounted under a prefix, as a host serving many deployments may do. + host = FastAPI() + host.mount("/d/one", app) + client = TestClient(host) + ingest = {"Authorization": "Bearer ingest"} + assert client.post("/d/one/uploads/u1/complete", headers=ingest).status_code == 200 + assert client.post("/d/one/uploads/u1/share", headers=ingest).status_code == 403 + assert ( + client.post( + "/d/one/uploads/u1/share", headers={"Authorization": "Bearer write"} + ).status_code + == 200 + ) From 3b17a6c7c787a9f9aea401e2d6e6bc7aeb1d19be Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 12:56:14 +0100 Subject: [PATCH 2/2] fix(D147): grant host ingest scope by the selected route, never by pattern Codex round 1: a listed template also matched other handlers (a static /uploads/admin/complete) and could override the built-in read table. The grant now compares the route FastAPI selected (method and declared template) and applies only to routes the table leaves at WRITE. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- src/rememberstack/surfaces/http_api.py | 29 +++++++++++++------ src/rememberstack/surfaces/route_scope.py | 29 ++----------------- .../surfaces/test_per_request_perimeter.py | 9 ++++++ 3 files changed, 31 insertions(+), 36 deletions(-) diff --git a/src/rememberstack/surfaces/http_api.py b/src/rememberstack/surfaces/http_api.py index 560be3926..527c4df20 100644 --- a/src/rememberstack/surfaces/http_api.py +++ b/src/rememberstack/surfaces/http_api.py @@ -162,7 +162,6 @@ from rememberstack.surfaces.query_sandbox.errors import SandboxRejection from rememberstack.surfaces.query_sandbox.open_query import OpenQueryFacade from rememberstack.surfaces.query_sandbox.result import QueryResult -from rememberstack.surfaces.route_scope import ingest_route_patterns from rememberstack.surfaces.route_scope import operation_scope from rememberstack.surfaces.route_scope import required_scope @@ -679,8 +678,10 @@ def build_api( otherwise valid ingest. `ingest_scope_routes` names a host's own routes mounted in this app, as - ``(METHOD, "/path/{param}")``, that a narrow ingest credential may reach - as it may reach `POST /ingest` (D147); every other host route needs WRITE. + ``(METHOD, "/path/{param}")`` exactly as the route is declared, that a + narrow ingest credential may reach as it may reach `POST /ingest` (D147). + A grant applies to the declared route only, never to a route the scope + table already classifies; every other host route needs WRITE. `ingest_body_max_bytes` bounds `POST /ingest` request bodies before they are buffered (413 over the cap; 411 when no Content-Length is declared). @@ -733,7 +734,9 @@ def build_api( dependencies=dependencies, ) app.state.api_deployment = deployment - app.state.ingest_scope_routes = ingest_route_patterns(ingest_scope_routes) + app.state.ingest_scope_routes = frozenset( + (method.upper(), path) for method, path in ingest_scope_routes + ) # Before any route is declared, so every one is built held: a request's # deployment may bring admission limits even when this one has none. A # held callable without a hold runs unchanged. @@ -2509,11 +2512,19 @@ def _perimeter( # `POST /ingest` does not). See ``route_scope``. # The router's own path: relative to any mount and decoded, so a mounted # app classifies its routes exactly as an unmounted one. - required = required_scope( - method=request.method, - path=get_route_path(request.scope), - extra_ingest_routes=request.app.state.ingest_scope_routes, - ) + required = required_scope(method=request.method, path=get_route_path(request.scope)) + # D147: a host route the app was built to open to ingest credentials, + # matched by the route FastAPI selected (its method and template), so a + # listed template never covers another handler. Only routes the table + # leaves at WRITE can be opened this way. + route = request.scope.get("route") + if ( + required is PerimeterScope.WRITE + and isinstance(route, APIRoute) + and (request.method.upper(), route.path) + in request.app.state.ingest_scope_routes + ): + required = PerimeterScope.INGEST # ``None`` means the route decides for itself, because its authority is # a property of registry data rather than of the path. Today that is # only ``POST /operations/{name}``, whose handler asks the descriptor. diff --git a/src/rememberstack/surfaces/route_scope.py b/src/rememberstack/surfaces/route_scope.py index 5bfe374ec..4aa992b13 100644 --- a/src/rememberstack/surfaces/route_scope.py +++ b/src/rememberstack/surfaces/route_scope.py @@ -29,7 +29,6 @@ from __future__ import annotations -from collections.abc import Collection import re from remember.http_routes import _READ_ROUTES @@ -57,12 +56,7 @@ ) -def required_scope( - *, - method: str, - path: str, - extra_ingest_routes: tuple[tuple[str, re.Pattern[str]], ...] = (), -) -> PerimeterScope | None: +def required_scope(*, method: str, path: str) -> PerimeterScope | None: """The scope a caller needs for this route. ``None`` means the route decides for itself (see :data:`_ROUTE_DECIDES`); @@ -76,7 +70,7 @@ def required_scope( for route_method, pattern in _ROUTE_DECIDES: if route_method == upper and pattern.match(normalised): return None - for route_method, pattern in (*_INGEST_ROUTES, *extra_ingest_routes): + for route_method, pattern in _INGEST_ROUTES: if route_method == upper and pattern.match(normalised): return PerimeterScope.INGEST for route_method, pattern in _READ_ROUTES: @@ -85,25 +79,6 @@ def required_scope( return PerimeterScope.WRITE -def ingest_route_patterns( - routes: Collection[tuple[str, str]], -) -> tuple[tuple[str, re.Pattern[str]], ...]: - """Compile host routes ``(METHOD, "/path/{param}")`` that ingest scope may reach. - - For a host that mounts its own upload routes in the engine app (D147): a - narrow ingest credential may then call them as it may call - ``POST /ingest``. Each ``{param}`` matches one non-empty path segment. - """ - compiled = [] - for method, template in routes: - parts = re.split(r"(\{[^{}/]+\})", template.rstrip("/") or "/") - body = "".join( - "[^/]+" if part.startswith("{") else re.escape(part) for part in parts - ) - compiled.append((method.upper(), re.compile(f"^{body}$"))) - return tuple(compiled) - - def routes_that_decide_for_themselves() -> tuple[tuple[str, str], ...]: """The deferring routes, for tests that pin the set to exactly what is intended.""" return tuple((method, pattern.pattern) for method, pattern in _ROUTE_DECIDES) diff --git a/src/tests/surfaces/test_per_request_perimeter.py b/src/tests/surfaces/test_per_request_perimeter.py index 8ad4355c3..beca6e87c 100644 --- a/src/tests/surfaces/test_per_request_perimeter.py +++ b/src/tests/surfaces/test_per_request_perimeter.py @@ -288,6 +288,11 @@ def test_a_host_route_can_be_opened_to_ingest_credentials() -> None: ingest_scope_routes=(("POST", "/uploads/{upload_id}/complete"),), ) + # Declared first, so it wins for /uploads/admin/complete; it is not listed. + @app.post("/uploads/admin/complete") + def admin_complete() -> dict[str, str]: + return {"admin": "yes"} + @app.post("/uploads/{upload_id}/complete") def complete(upload_id: str) -> dict[str, str]: return {"completed": upload_id} @@ -303,6 +308,10 @@ def share(upload_id: str) -> dict[str, str]: ingest = {"Authorization": "Bearer ingest"} assert client.post("/d/one/uploads/u1/complete", headers=ingest).status_code == 200 assert client.post("/d/one/uploads/u1/share", headers=ingest).status_code == 403 + # The listed template never covers another handler matching its pattern. + assert ( + client.post("/d/one/uploads/admin/complete", headers=ingest).status_code == 403 + ) assert ( client.post( "/d/one/uploads/u1/share", headers={"Authorization": "Bearer write"}