Skip to content

feat(D147): per-request perimeter; customer SQL connection target - #538

Merged
fazpu merged 4 commits into
mainfrom
feat/per-request-perimeter
Nov 6, 2026
Merged

fazpu merged 4 commits into
mainfrom
feat/per-request-perimeter

Conversation

@fazpu

@fazpu fazpu commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

These are the generic seams the UMC shared API needs: one app serving many deployments, on top of D147.

Public API

from rememberstack.surfaces.http_api import ApiDeployment, deployment_context, install_browser_origins

# 1. The perimeter is per request
ApiDeployment(..., auth=AuthPerimeterPort | None, direct_admission=DirectPathAdmission | None,
              spend_lease=SpendLeasePort | None)
app.dependency_overrides[deployment_context] = resolve   # resolve(request) -> ApiDeployment, sync or async
#   called ONCE per request by the perimeter gate, before authentication; may raise HTTPException (e.g. 401)
#   e.g. resolve returns dataclasses.replace(tenant_profile.api_deployment(), auth=..., spend_lease=...)
install_browser_origins(app=app, origins=("https://console.example",))   # public now (was _install_browser_origins)

# 2. Customer SQL connection target
SelfHostSettings(query_role_host="postgres.internal", query_role_port=5432)
#   env REMEMBERSTACK_SELFHOST_QUERY_ROLE_HOST / _PORT; default: the database URL's host/port

Behaviour

  • Order of the gate. The gate is pure ASGI and always installed. It resolves the request's deployment and stores it in request.state. Then it authenticates against that deployment, so a credential for another deployment gets 403, and admits under that deployment's limits. After that, the spend-lease middleware (now always installed, and a pass-through without a lease) applies that deployment's lease.
  • What reads the resolved deployment. Routes, the D74 barrier, the route scope check (_perimeter), ingest attribution and open-query principal forwarding all read the same resolved deployment. The override is called once per request, not once per dependency.
  • Without an override, the deployment build_api was composed with applies, so self-host behaviour is unchanged. build_api keyword arguments are unchanged, and the OpenAPI output is unchanged (verified by test_openapi_export).
  • Held routes. Every route is now built as a held route, because a request's deployment may bring admission limits that the composing deployment lacks. A held callable without a hold runs unchanged.
  • The profile's own deployment. SelfHostProfile.api_deployment() returns an empty perimeter; api() fills it from settings with dataclasses.replace.
  • /healthz still bypasses the gate.

Tests

  • New test_per_request_perimeter.py: one app, two deployments, chosen by a header resolver.
    • Each deployment's own credentials pass; the other deployment's are 403 and a missing one is 401.
    • Each deployment's spend lease is the only one called.
    • B's rate limit doesn't affect A.
    • The resolver's own 401 reaches the caller.
    • Without an override, the composed auth applies.
  • test_engine_settings.py: the query-role connection uses the configured host and port, and otherwise the URL's.
  • The existing direct-admission, CORS, ingest-principal, open-query and two-deployment tests pass. The one assertion that routes are not held without admission was removed: it is intentionally no longer true.

Checks

  • ruff, format, pyright (0), import-linter, unit lane (3097 passed), the DB tests above on PG 19 Beta 3, docs checks

  • CI (green)

  • Codex review: round 4 APPROVE (rounds 1-3 dispositions in comments: resolver called once for every router; held routes keep dependency overrides; cleared override returns to the composed deployment)

  • I have read and agree to the RememberStack Contributor License Agreement v1.0.

🤖 Generated with Claude Code

https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm

fazpu and others added 2 commits November 6, 2026 21:12
- ApiDeployment carries auth, direct_admission and spend_lease. The
  perimeter gate resolves the request's deployment through the app's
  deployment_context override (called once, with the request), then
  authenticates against it, admits under its limits, and the spend-lease
  middleware uses its lease. Without an override the composed deployment
  applies as before. Routes, the D74 barrier, the scope check, ingest
  attribution and open-query principal forwarding read the same resolved
  deployment; every route is built held.
- install_browser_origins is public.
- SelfHostSettings.query_role_host/query_role_port: where customer SQL
  connects as the query role; default the database URL's host and port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
…ployment

Codex round 1: held routes wrap sync dependencies, so a host route's
Depends(deployment_context) missed the override and returned the composed
deployment. The default now reads the gate's resolved deployment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Codex review round 1 (gpt-6.1-sol, max effort)

VERDICT: REQUEST_CHANGES

  • Blocker — the public deployment dependency can cross deployments. Always installing _HeldRoute (http_api.py:720) wraps synchronous dependencies, so FastAPI misses overrides keyed by the original deployment_context. That public function still returns the composed deployment (http_api.py:574). I reproduced a host-added route using Depends(deployment_context) returning 200, authenticated=B, served=A, with the resolver called once. Built-in routes avoid this through _request_deployment, but consumers of the public seam do not. Simplest fix: make public deployment_context read the gate’s cached request deployment, as _request_deployment does, and add this regression test.

365 focused tests passed, covering default authentication/scopes, admission and held slots, spend leases, CORS, healthz, OpenAPI, attribution, open-query principals, and two-deployment isolation. SQL overrides and configuration docs match; ingestion reuse keys are untouched.

The dedicated PG 19 Beta 3 container was removed. No files changed.

Disposition (Claude): accepted, fixed in 02fa01a

The public deployment_context default now returns the deployment the gate resolved for the request; it falls back to the composed one only when nothing was resolved (healthz). A host route that uses Depends(deployment_context) therefore sees the request's deployment whether or not FastAPI applies the override. Regression test added: test_a_hosts_own_route_sees_the_resolved_deployment.

…router

Codex round 2: an included router's Depends(deployment_context) called the
host's override again. The gate now keeps the override as the app's
resolver and points the override at the resolved value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Codex review round 2 (gpt-6.1-sol, max effort)

VERDICT: REQUEST_CHANGES

  • Blocker — included routers can resolve a different deployment after authentication. The gate calls the override at http_api.py:582. The round-1 fix at http_api.py:576 works for directly declared held routes, whose wrappers suppress FastAPI’s override lookup. However, app.include_router(APIRouter(...)) uses normal dependency resolution: Depends(deployment_context) calls the override again, bypassing the cached getter. With a resolver returning B then A, I reproduced 200, authenticated=B, served=A, resolver calls=2, with both synchronous and asynchronous resolvers. Simplest fix: make subsequent FastAPI calls to the registered resolver reuse the gate’s cached deployment, including on included routers. Extend the regression test with include_router and assert one resolver call.

The direct-route round-1 regression passes. 423 focused tests passed, covering default authentication/scopes, admission and held slots, lease accounting, CORS ordering, healthz, OpenAPI, attribution, principal forwarding, SQL connection overrides, and database isolation. No other findings; reuse keys are untouched.

The dedicated PostgreSQL 19 Beta 3 container was removed. No repository files changed.

Disposition (Claude): accepted, fixed in cc87fc9

On the first request it handles, the gate stores the host's deployment_context override as the app's resolver (app.state.deployment_resolver) and repoints the override at the request's resolved value. FastAPI's own dependency resolution therefore never calls the host's resolver again: not on directly declared routes, held routes or included routers. If a host re-registers an override, the next request takes it over the same way. Regression test: test_included_routers_reuse_the_one_resolution (async resolver, include_router, exactly one resolver call, served deployment = authenticated deployment).

… an override

Codex round 3:
- Held routes replace a dependency's callable with a wrapper, which hid
  overrides keyed by the original. _HeldOverrides answers FastAPI's lookup
  by wrapper with the original's override, held when synchronous.
- Clearing the deployment_context override returns to the composed
  deployment instead of reusing the saved resolver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Codex review round 3 (gpt-6.1-sol, max effort)

VERDICT: REQUEST_CHANGES

  • Major — Default apps ignore synchronous dependency overrides. Unconditionally installing _HeldRoute at http_api.py:730 replaces dependency identities with wrappers at http_api.py:2677. FastAPI consequently misses overrides keyed by the original function. Reproduced with admission disabled: a host dependency override raising 403 produces 403 on origin/main, 200 on HEAD. This can skip a host authorization check. Simplest fix: preserve override lookup by the original dependency, then hold the selected synchronous callable.

  • Minor — Removing the deployment override leaves its resolver active. http_api.py:590 retrieves the saved resolver even when no override remains. Reproduced: resolve B, call app.dependency_overrides.clear(), then request again; B’s resolver runs and B is served instead of composed A. Simplest fix: return the composed deployment when the override is absent; reuse the saved resolver only while the cached-getter override remains registered.

The round-2 regression passes. 479 focused tests passed; 40 concurrent requests also confirmed consistent deployment resolution, authentication, D74 checks and lease selection. SQL overrides and configuration docs match; ingestion reuse keys are untouched.

The dedicated PostgreSQL 19 Beta 3 container was removed. No repository files changed.

Disposition (Claude): both accepted, fixed in 9e6d8a6

  • Major: _HeldRoute now gives FastAPI a _HeldOverrides provider. When FastAPI looks up an override by a held wrapper, the provider returns the override registered for the original callable, held when it is a synchronous plain function. Overrides are therefore honoured on every held route. This also fixes the same gap that existed before this PR whenever direct_admission was configured. Test: test_a_hosts_dependency_override_still_applies_on_held_routes (403 from the override).
  • Minor: with no deployment_context override registered, the gate serves the composed deployment. The saved resolver is reused only while the gate's own cached getter is the registered override. Test: test_removing_the_override_returns_to_the_composed_deployment.

@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Codex review round 4 (gpt-6.1-sol, max effort)

VERDICT: APPROVE

No blocker, major, or minor findings.

The latest fixes preserve dependency overrides and restore the composed deployment when its override is removed. Resolution remains once per request and consistent across authentication, admission, leases, routes, D74, scope checks, attribution, and principal forwarding.

Default behavior, CORS ordering, healthz, and OpenAPI remain intact. SQL target overrides and docs match. Ingestion reuse keys are untouched.

541 focused tests passed, plus 30 dependency-override comparisons and cancellation probes.

The dedicated PostgreSQL 19 Beta 3 container was removed. No repository files changed.

@fazpu
fazpu marked this pull request as ready for review November 6, 2026 20:51
@fazpu
fazpu merged commit 860c757 into main Nov 6, 2026
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant