Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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).
Expand Down
7 changes: 6 additions & 1 deletion src/rememberstack/profiles/selfhost.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()),
)

Expand Down
31 changes: 28 additions & 3 deletions src/rememberstack/surfaces/http_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -641,6 +642,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, ...] = (),
Expand Down Expand Up @@ -675,6 +677,12 @@ 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}")`` 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).
None — the self-host default — imposes no limit: caps are deployment
Expand Down Expand Up @@ -726,6 +734,9 @@ def build_api(
dependencies=dependencies,
)
app.state.api_deployment = deployment
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.
Expand Down Expand Up @@ -2483,7 +2494,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"
)
Expand All @@ -2499,7 +2510,21 @@ 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))
# 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.
Expand Down Expand Up @@ -2591,7 +2616,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
Expand Down
37 changes: 29 additions & 8 deletions src/rememberstack/workers/e0.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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_-]>"
Expand Down Expand Up @@ -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}"
)
Expand All @@ -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(
Expand Down
74 changes: 74 additions & 0 deletions src/tests/spine/test_managed_metering_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
2 changes: 1 addition & 1 deletion src/tests/surfaces/test_openapi_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
)


Expand Down
56 changes: 56 additions & 0 deletions src/tests/surfaces/test_per_request_perimeter.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,59 @@ 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"),),
)

# 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}

@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
# 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"}
).status_code
== 200
)
Loading