Repository navigation
§ 3.5: the openDox runtime — FastAPI + Postgres, identity and coordination, and nothing else (RULED Q1/Q2) - #25
Conversation
…ment package
RULED Q2 (openxFactory#656 comment 5542792997) puts the openDox runtime on the
`xFactory-Hermes-Install` pattern; RULED Q1 (comment 5542694957) fixes what its
database owns. This commit lands the ordered SQL, the `opendox.runtime`
subpackage and `deploy/{compose,kubernetes}/`, all at the root of this leg.
* `migrations/0001_identity_and_coordination.sql` — RULING Q1's six tables and
no seventh; pinned by `CANONICAL_MIGRATION_SHA256` and immutable thereafter.
`migrations/0002_migration_state.sql` — the ledger, additive.
* `src/opendox/runtime/` — `config` (every setting is an env var named in
`deploy/compose/.env.example`), `migrations` (the fail-closed runner),
`identity` (the six tables, one store), `db` (the pool), `oidc` (verify
against the broker; never issue), `app` (six collections behind a bearer
token), `cli` (`runtime init|migrate|serve|status|reset`).
* `deploy/compose/` + `deploy/kubernetes/` — separate migration and served
identities, no published host port, no committed credential.
* `pyproject.toml` — a NEW `[project.optional-dependencies] runtime` extra, so
the leg's existing `pip install -e ".[test]"` is unchanged, and
`[project.scripts] opendox-runtime`.
* `tests_runtime/` — the hermetic half: 68 assertions over the SQL, the closed
table set, the package's import weight and the deployment package.
Measured: `python -m pytest -q tests_runtime/test_migration_shape.py
tests_runtime/test_schema_shape.py tests_runtime/test_runtime_surface.py
tests_runtime/test_runtime_cli.py tests_runtime/test_deploy_shape.py
--noconftest` — 68 passed in 5.28s (python 3.12.3, pytest 8.4.2).
Lane: openxfactory-4
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* `docs/runtime.md` — the runbook: the three rulings quoted, the layout, the configuration, the five lifecycle verbs, the migration pin, compose and Kubernetes, what `reset` does and does not cover, and the residue this act records rather than resolves (design § D5's pre-governed scratch space; the Q-L5 (b′) narrowing, which this act lifts no part of). * `tests_runtime/conftest.py` — the DB-backed harness: one throwaway SCHEMA per test on a shared server (the Hermes install's shape), an in-fixture RSA key pair, a JWKS file and a token minter, so the OIDC suites run the REAL verifier and reach no network. No `OPENDOX_TEST_DATABASE_URL` is a SKIP with the reason printed, never a silent pass and never a red tree. * `tests_runtime/test_migrations_apply.py` (7), `test_oidc_verifier.py` (16), `test_api_endpoints.py` (20) — the runner against a real Postgres including both refusals, token verification against the local key pair including the `alg: none` and HS256 downgrades, and the six collections end to end. * `.github/workflows/validate.yml` — APPEND ONLY (`git diff --stat`: 99 insertions, 0 deletions, one hunk at `@@ -323,0 +324,99 @@`): a new `pytest (runtime, hermetic)` step in the required `validate` job, and a new `runtime` job with a `postgres:16` service for everything that needs a database, a token or a web framework. Nothing above line 323 is touched, so this cannot collide with #24, whose only hunk here is inside the comment block at lines 91-147. Two defects the suites found and this commit fixes, both in code this act introduces: * `oidc.CachingJwks._load_keyset` did not catch `jwt.PyJWKSetError`, which is NOT a subclass of `PyJWKError`. A broker serving `{"keys": []}` — a realm mid-rotation, a misconfigured proxy — would have escaped the typed `IdentityUnavailableError` and surfaced past `app.get_principal`'s 401 mapping as a 500. `test_an_empty_key_set_is_a_named_refusal_and_not_a_crash`. * `app`'s dependency callables annotated `request: Any`. FastAPI reads a dependency's annotations to decide where each argument comes from and takes `Any` for a QUERY PARAMETER, so every route answered 422 "missing query parameter: request" instead of authenticating — sixteen cases red on the first run. Now `request: Request`, with the reason recorded at the seam. Measured (python 3.12.3, pytest 8.4.2, postgres 16.15): hermetic, under the required job's own invocation .... 68 passed in 5.12s tests_runtime/test_migrations_apply.py ................ 7 passed in 1.94s tests_runtime/test_oidc_verifier.py ................... 16 passed in 1.08s tests_runtime/test_api_endpoints.py ................... 20 passed in 8.65s Lane: openxfactory-4 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
None of these change behaviour; all four were things a reviewer would have had to ask about, so they are answered in the source instead. * `tests_runtime/conftest.py` — two `pytest.importorskip(...)` calls followed by a `del` of the name they bound, and an `import jwt` bound only to be deleted. The `importorskip` is the guard; the binding was noise. * `tests_runtime/test_oidc_verifier.py`, `tests_runtime/test_runtime_cli.py` — three `open(...).read()` sites replaced with `Path.read_text`, so no file handle is left to the garbage collector. * `tests_runtime/test_runtime_cli.py` also now SAYS why it reads `parser._actions` and `argparse._SubParsersAction`: argparse publishes no way to ask a built parser which subcommands it declares, and asserting against the help text would pin formatting rather than structure and go red on a Python release that rewraps a line. * `src/opendox/runtime/app.py` — `del principal` in a read handler now carries its reason ONCE, at the first site: the `PrincipalDep` parameter is what makes the route authenticated at all (FastAPI resolves it, verifying the token and upserting the row, before the body runs), so a handler that does not then use the value has authorization "any signed-in principal may read this". `del` states that instead of leaving an argument that looks forgotten. Measured at this head: `python -m pyflakes src/opendox/runtime/*.py tests_runtime/*.py` clean; `python -m pytest -q tests_runtime/` 111 passed in 15.14s; the required job's own invocation 68 passed. Lane: openxfactory-4 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
|
@copilot review |
…measurement, and eight code smells
SonarCloud's Quality Gate on this PR failed one condition — "E Security Rating
on New Code (required ≥ A)" — over 32 issues. SonarCloud is ADVISORY on this
lane's gate, so nothing here is required; it is done because every one of these
is either a real improvement or a claim worth writing down.
TWO HARDENINGS (`githubactions:S8541`, `docker:S8541`) — `--only-binary :all:`
on both new pip installs, this act's CI job and the image build. Without it pip
may build a dependency from an sdist, which runs that project's `setup.py`
inside the job. MEASURED in a clean venv on 2026-09-16 before it was declared:
`pip install --only-binary :all: -e ".[runtime,test]"` resolves and installs,
and `import fastapi, psycopg, jwt, httpx, uvicorn, opendox.runtime` succeeds —
the local editable project is exempt from the flag, so `-e .` still works, and
`psycopg[binary]` is asked for by name precisely so libpq is never built.
`tests_runtime/test_deploy_shape.py` now asserts the Dockerfile carries it.
ONE SUPPRESSION BY MEASUREMENT (`secrets:S6698`, BLOCKER, the rating's cause) —
the `runtime` job's `POSTGRES_PASSWORD: opendox` is a throwaway credential for a
service container reachable only from that job's own network namespace and torn
down with it. `# NOSONAR`, on the estate's own precedent:
`xFactory-Hermes-Install/.github/workflows/ci.yml` marks its identical
`POSTGRES_PASSWORD: hermes` the same way. The runtime's real DSNs are Secret
references everywhere they appear and `test_deploy_shape.py` refuses a committed
credential value.
ONE MORE BY MEASUREMENT (`python:S5659`, CRITICAL) — "Don't use a JWT token
without verifying its signature" fires on `jwt.get_unverified_header`. Reading
the header first is the only possible order: it carries the `kid` that selects
the signing key and the `alg` the allow-list is applied to, and neither can be
known until it is read. Nothing from it is trusted — `alg` is checked against
the allow-list and the signature is verified in `_decode`, which runs with
`verify_signature: True` and a required-claim list. `# NOSONAR` with that
reason at the line.
EIGHT REAL SMELLS, fixed rather than argued with:
* `python:S5713` — `except (httpx.HTTPError, json.JSONDecodeError, ValueError)`
named a subclass beside its base: `json.JSONDecodeError` IS a `ValueError`
(measured), so the pair read as two different failures. Inherited from the
Hermes source this module was modelled on.
* `python:S3776` — `TokenVerifier.verify` was cognitive complexity 17 (limit
15). The seven-clause PyJWT-to-`OidcError` mapping is now `_decode`, which is
also the part a reader wants on its own.
* `python:S8415` — every authenticated router now declares `responses=REFUSALS`,
so the published OpenAPI schema states the 401/403/404/409 bodies a client
must handle instead of leaving them to be discovered.
* `python:S7632` — four `# noqa: BLE001 - prose` comments were not valid noqa
syntax; the prose moves to its own line and the marker is bare.
* `python:S1192` — "project repository" appeared as a literal three times in
`identity.py`; a module constant now, so a typo cannot make one refusal read
as a different failure.
* `python:S9083` ×5, `python:S9073` ×4, `python:S5778` ×6 in the suites — bare
`@pytest.fixture`, composite assertions split so a failure names which half
failed, and one throwing call per `pytest.raises` block so the block cannot
pass for the wrong reason.
RECORDED AND NOT DONE: `githubactions:S8544` / `docker:S8544` ("dependencies
without locking resolved versions"). That is the `--require-hashes` lockfile
`pyproject.toml` already names as the obvious successor and as a real act with
a real owner — the Hermes install carries a `uv.lock` for exactly that reason —
and a § 3.5 PR should not invent this leg's supply-chain pin. `S8541` at
`validate.yml:29` is the PRE-EXISTING install step this act must not edit.
Measured at this head: `python -m pyflakes src/opendox/runtime/*.py
tests_runtime/*.py` clean; the required job's own invocation 68 passed;
`python -m pytest -q tests_runtime/` 111 passed in 11.81s.
Lane: openxfactory-4
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate findings remain across authorization, migrations, deployment, CLI, OIDC, and test setup.
Get a fresh assessment by requesting another Copilot review.
Pull request overview
Adds the §3.5 openDox FastAPI/Postgres runtime with identity coordination, OIDC authentication, migrations, lifecycle CLI, deployment manifests, documentation, and CI coverage.
Changes:
- Adds the six-table coordination schema and migration runner.
- Implements API routes, database access, OIDC verification, and CLI operations.
- Adds Compose/Kubernetes deployment, documentation, and runtime tests.
File summaries
| File | Summary / final finding |
|---|---|
tests_runtime/test_schema_shape.py |
Validates schema boundaries. |
tests_runtime/test_runtime_surface.py |
Tests import weight and route closure. |
tests_runtime/test_runtime_cli.py |
Tests lifecycle CLI behavior and redaction. |
tests_runtime/test_oidc_verifier.py |
Tests OIDC token and JWKS verification. |
tests_runtime/test_migrations_apply.py |
Tests migrations against Postgres. |
tests_runtime/test_migration_shape.py |
Validates migration structure and pinning. |
tests_runtime/test_deploy_shape.py |
Validates deployment manifests. |
tests_runtime/test_api_endpoints.py |
Exercises API behavior. |
tests_runtime/conftest.py |
Provides fixtures; moderate, 2 votes: unreachable configured databases fail instead of being skipped. |
src/opendox/runtime/oidc.py |
Implements JWKS verification; critical, 1 vote: unknown-key requests bypass TTL and can serialize outbound refreshes. |
src/opendox/runtime/migrations.py |
Implements migrations; critical, 1 vote: migration execution lacks an advisory lock. |
src/opendox/runtime/identity.py |
Implements coordination persistence; moderate, 2 votes: concurrent duplicate slugs can return 500 instead of 409. |
src/opendox/runtime/db.py |
Provides pooled Postgres access. |
src/opendox/runtime/config.py |
Loads configuration; moderate, 1 vote: EdDSA normalization rejects the asymmetric algorithm. |
src/opendox/runtime/cli.py |
Implements lifecycle commands; moderate findings: closed-pool status introspection (3 votes), unsafe reset order (3 votes), and missing JSON error boundaries (1 and 1 votes). |
src/opendox/runtime/app.py |
Defines API routes; critical, 3 votes: draft reads lack membership checks. Moderate findings: unauthenticated documentation routes (2 votes) and incomplete migration-aware readiness (1 vote). |
src/opendox/runtime/__init__.py |
Declares runtime boundaries; moderate, 2 votes: promises a missing local_git_adapter.py. |
pyproject.toml |
Adds runtime dependencies and CLI entry point. |
migrations/0002_migration_state.sql |
Defines the migration ledger. |
migrations/0001_identity_and_coordination.sql |
Defines the canonical coordination schema. |
docs/runtime.md |
Documents runtime operation and deployment. |
deploy/kubernetes/overlays/dev/kustomization.yaml |
Provides development settings; moderate, 3 votes: uses a mutable tag instead of enforcing the reviewed digest. |
deploy/kubernetes/base/project-repositories-pvc.yaml |
Defines repository storage. |
deploy/kubernetes/base/postgres-statefulset.yaml |
Defines bundled Postgres; moderate, 2 votes: does not provision the least-privileged runtime role. |
deploy/kubernetes/base/postgres-service.yaml |
Defines the Postgres service. |
deploy/kubernetes/base/opendox-service.yaml |
Defines the runtime service. |
deploy/kubernetes/base/opendox-deployment.yaml |
Defines the runtime deployment; moderate, 1 vote: requires a database role absent from the base installation. |
deploy/kubernetes/base/namespace.yaml |
Defines the runtime namespace. |
deploy/kubernetes/base/migration-job.yaml |
Defines the migration job; moderate, 1 vote: exposes the privileged DSN as the served database setting. |
deploy/kubernetes/base/kustomization.yaml |
Defines Kubernetes base resources. |
deploy/compose/init-runtime-role.sh |
Creates the least-privileged database role. |
deploy/compose/Dockerfile |
Builds the runtime image. |
deploy/compose/docker-compose.yaml |
Defines Compose services; moderate findings: migration service lacks image build configuration (2 votes) and aliases the privileged DSN to the served setting (1 vote). |
deploy/compose/.env.example |
Provides Compose configuration defaults. |
.gitignore |
Ignores runtime-local state and secrets. |
.github/workflows/validate.yml |
Adds hermetic and database-backed runtime CI jobs. |
Review details
Suppressed comments (10)
deploy/compose/docker-compose.yaml:109
- The Compose migration service makes the same privileged DSN serve as both configuration fields. This defeats the claimed identity separation and makes any future path that reads
settings.database_urlin the migration container privileged; do not alias the migration credential to the served setting just to satisfyload_settings.
OPENDOX_DATABASE_URL: ${OPENDOX_MIGRATION_DATABASE_URL}
deploy/kubernetes/base/migration-job.yaml:50
- This migration job receives the privileged migration DSN in
OPENDOX_DATABASE_URLas well asOPENDOX_MIGRATION_DATABASE_URL. That is not a separate served identity: any accidental use ofsettings.database_urlin this pod runs with schema-changing privileges, contrary to the least-privilege boundary described above. Supply a distinct runtime DSN or let the migration command load configuration without requiring the served DSN.
- name: OPENDOX_DATABASE_URL
valueFrom:
secretKeyRef:
name: opendox-db-migration
deploy/kubernetes/base/opendox-deployment.yaml:75
- The Kubernetes base provisions a local Postgres with only the
opendoxrole, but unlike the Compose package it has no init script or job creating the least-privileged role used byopendox-db-runtime. On a fresh base install the Deployment's DSN secret therefore cannot authenticate. Add role bootstrap/pre-provisioning or make the base explicitly require an external database.
- name: OPENDOX_DATABASE_URL
valueFrom:
secretKeyRef:
name: opendox-db-runtime
key: dsn
src/opendox/runtime/app.py:486
/readyzis registered withoutPrincipalDepor any other authentication dependency, so it is another public route and returns database/broker availability to unauthenticated callers. This contradicts the PR's explicit “/livezis the only unauthenticated route” contract; either protect readiness and adapt the probes, or revise that contract and its security rationale consistently.
@app.get("/readyz")
def readyz() -> JSONResponse:
src/opendox/runtime/app.py:350
- The role check authorizes only
body.project_id;body.session_idis never loaded or checked. A caller can supply another user's session (or a session/project mismatch), and the store's(session_id, document_key)upsert can overwrite that session's draft, so this endpoint permits cross-user draft writes. Verify that the session belongs to the principal and the same project, or enforce that relationship in the schema.
_require_role(store, user=principal, project_id=body.project_id,
allowed=("owner", "member"))
return _draft_json(store.put_draft(
session_id=body.session_id, project_id=body.project_id,
document_key=body.document_key, body=body.body,
src/opendox/runtime/app.py:493
- Readiness marks the database healthy after
select 1only; it never checks the migration ledger or pending migrations. A fresh Postgres with no coordination tables therefore becomes Ready and traffic reaches endpoints that fail on missing relations. Check canonical/ledger state and keep readiness failed until the schema is applied.
try:
with app.state.context.database.connection() as conn:
conn.execute("select 1")
checks["database"] = "ok"
src/opendox/runtime/app.py:360
- Deletion authorizes only against
draft.project_id, so any owner/member of that project can delete another user's session draft. Check the draft's session owner (and the session/project consistency) before allowing discard.
draft = _found(lambda: store.get_draft(draft_id))
_require_role(store, user=principal, project_id=draft.project_id,
allowed=("owner", "member"))
store.delete_draft(draft_id)
src/opendox/runtime/cli.py:406
- The CLI entry point dispatches directly to the verb without a final refusal/error boundary. Database connectivity, pool, SQL, or filesystem failures from
migrate,reset,init, orservecan therefore emit a traceback and no JSON evidence, contrary to the lifecycle contract that every refusal/failure emits one redacted evidence object and a nonzero exit.
def main(argv: list[str] | None = None) -> int:
"""Parse and dispatch. `args.func(args)` — the core's own dispatch line."""
args = build_parser().parse_args(argv)
return int(args.func(args))
src/opendox/runtime/cli.py:193
- Only
MigrationErroris converted to_emit; connection/pool failures fromDatabaseor psycopg escape this block with a traceback and no JSON evidence, contrary to the lifecycle CLI contract. Map operational failures to a redacted refusal asstatusdoes.
except migrations.MigrationError as exc:
return _emit({"verb": "migrate", "refusal": type(exc).__name__,
"message": str(exc)}, ok=False)
src/opendox/runtime/config.py:250
- Algorithm names are normalized to uppercase above, but this tuple contains mixed-case
Ed. ConsequentlyEdDSAbecomesEDDSA, is classified as symmetric here, and would not match PyJWT's case-sensitive token algorithm name either. Preserve PyJWT's canonical spelling or canonicalizeEdDSAexplicitly so the asymmetric allow-list does not reject it.
symmetric = tuple(a for a in algorithms if not a.startswith(("RS", "ES", "PS", "Ed")))
- Files reviewed: 35/36 changed files
- Comments generated: 12
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
@copilot review |
…it unparseable
THE PREVIOUS HEAD RAN NO JOB AT ALL, and the PR page did not say so. Measured:
`gh api repos/opensoft/openDox-code/commits/4d3ce664.../check-runs` at that head
returns SonarCloud and the Copilot bot and NOTHING ELSE, and
`gh api .../actions/runs?head_sha=4d3ce664...` returns a run named
`.github/workflows/validate.yml` — GitHub's name for a file it could not parse —
with conclusion `failure`. Neither `validate` nor `runtime` started.
THE CAUSE. `run: python -m pip install --only-binary :all: -e ".[runtime,test]"`
as a PLAIN YAML scalar contains `: `, and a colon followed by a space is a
mapping indicator, so the document fails to scan:
`yaml.scanner.ScannerError: mapping values are not allowed here`, line 434
column 54. The flag was added in the previous commit to answer SonarCloud
`githubactions:S8541`; the flag is right and the scalar form was wrong. It is a
folded scalar (`>-`) now, which is the form the two steps above it already use.
AND THE ABSENCE OF A RUN LOOKS LIKE NOTHING, which is why this commit also adds
four suites to `tests_runtime/test_deploy_shape.py` rather than only fixing the
line:
* the workflow parses as YAML at all — the assertion whose failure this class of
defect is;
* both jobs are declared, this act's hermetic step is APPENDED after the
existing `pytest` step (reordering is an edit to what the required check
already ran), and the DB-backed step is the runtime job's last;
* the runtime job supplies a `postgres:` service, installs `.[runtime,test]`
with `--only-binary :all:`, and passes a `postgresql://` DSN;
* the REQUIRED job installs the test extra ALONE — if it ever installed
`.[runtime]` every assertion about what imports without the extra would still
pass and would stop meaning anything.
Two SonarCloud leftovers fixed in the same commit, both the same mistake:
`secrets:S6698` still fired because `xFactory-Hermes-Install`'s precedent marks
BOTH halves — its Postgres password AND its DSN — and this act had marked only
the first; and `python:S7632` fired on a PROSE comment that spelled the
suppression marker, which Sonar reads as a malformed suppression. The marker is
now written only at the end of the line it suppresses, in both files.
Measured at this head (python 3.12.3, pytest 8.4.2, postgres 16.15):
the required job's own invocation ............ 71 passed
python -m pytest -q tests_runtime/ ........... 114 passed
python -c "import yaml; yaml.safe_load(open('.github/workflows/validate.yml'))"
parses, and reports jobs ['validate', 'runtime']
Lane: openxfactory-4
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
The critical draft authorization issue and multiple moderate runtime, deployment, and CLI issues remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (21)
Previously missed (6) — in code that hasn't changed since the last review.
src/opendox/runtime/app.py:134
- FastAPI resolves the
get_storesubdependency before enteringget_principal, so every missing or invalid bearer request checks out a database connection and starts a transaction before the header is examined. If Postgres is unavailable, an unauthenticated collection request can therefore fail with a database error instead of the promised 401, and invalid traffic can consume the pool; authenticate first and only open the store after token verification.
src/opendox/runtime/app.py:508 readyzhas noPrincipalDep, so it is callable without a bearer token even though the PR defines/livezas the only unauthenticated route. It also lets any network caller trigger database and JWKS probes. Add an auth dependency, or explicitly narrow/update the health-check contract and its tests.
src/opendox/runtime/cli.py:188- Only
MigrationErroris caught below. A refused or unreachable Postgres raises a psycopg/pool exception from this context or fromrunner.apply(), so the lifecycle contract is violated: the command emits a traceback and no redacted JSON evidence. Catch the driver failure at this boundary and map it to_emitwithout including connection details.
src/opendox/runtime/cli.py:261 runneris used after thewith Database(...)block has exited, so its pool is already closed. On a reachable database,runner.applied()raises, the broad handler rewritesdatabasetounreachable, and status never reports migrations. Keep these runner queries inside the database context.
src/opendox/runtime/cli.py:314- The reset database context is also outside any error-to-evidence handling. If the privileged DSN is unreachable,
resetraises fromDatabase/transaction()and prints no JSON, despite the CLI's stated one-evidence-object-per-verb contract. Add the same redacted database-failure mapping used for other refusals.
src/opendox/runtime/config.py:244 - Algorithm identifiers are case-sensitive, but this uppercases
EdDSAtoEDDSA; the laterEdbranch then rejects it, and the resulting value would not match PyJWT'sEdDSAheader anyway. The code advertisesEdas an asymmetric family, so this makes that supported path unreachable.
deploy/compose/docker-compose.yaml:109
- This aliases the privileged migration DSN into
OPENDOX_DATABASE_URL, so the migration container does receive a value under the served-runtime setting andRuntimeSettings.database_urlcontains the privileged credential. That contradicts the two-identity separation described above; makemigrateload configuration without requiring the served DSN instead of copying the migration DSN into it.
OPENDOX_MIGRATION_DATABASE_URL: ${OPENDOX_MIGRATION_DATABASE_URL}
# `load_settings` requires these three before any verb runs; the
# migration job needs no broker and no served identity, so they are the
# compose file's own placeholders and reach no network.
OPENDOX_DATABASE_URL: ${OPENDOX_MIGRATION_DATABASE_URL}
deploy/compose/docker-compose.yaml:98
- The runbook tells a fresh user to run the
migrateservice beforeup -d, but this service has onlyimage: opendox-runtime:local; thebuildstanza exists only onopendox. With no pre-existing local image,docker compose ... run migratetries to pull that local tag and fails before migrations run. Givemigratethe same build definition or document an explicit build step.
# Privileged one-shot migration executor. Never the long-running application
# container, and it receives no runtime DSN.
# docker compose --profile migration run --rm migrate
migrate:
image: ${OPENDOX_IMAGE:-opendox-runtime:local}
deploy/compose/init-runtime-role.sh:42
- Granting DML on all current tables and on all future tables also grants the served role write access to
opendox_schema_migrationsonce the migration runner creates it. The API never needs that ledger, so a compromised runtime credential can delete or alter migration records and undermine the separate privileged migration identity. Grant only the six coordination tables, or explicitly revoke ledger access after it is created.
select format('grant select, insert, update, delete on all tables in schema '
'public to %I', :'runtime_user')
\gexec
select format('alter default privileges in schema public grant select, '
'insert, update, delete on tables to %I', :'runtime_user')
deploy/kubernetes/base/migration-job.yaml:50
- The Job repeats the privileged secret reference as
OPENDOX_DATABASE_URL, so this process has the migration credential in the setting intended for the served application. That defeats the declared separation of migration and served identities; make the migrate command work without requiringOPENDOX_DATABASE_URLrather than mapping it to the migration DSN.
- name: OPENDOX_DATABASE_URL
valueFrom:
secretKeyRef:
name: opendox-db-migration
deploy/kubernetes/base/postgres-statefulset.yaml:40
- This StatefulSet creates only the
opendoxdatabase role; unlike Compose it mounts no role-initialization SQL or grant step. The Deployment nevertheless consumesopendox-db-runtime/dsn, so a fresh install of the bundled Postgres has no runtime role/password/grants and the served pod cannot connect. Add a Kubernetes role/grant bootstrap, or make this base explicitly require an externally provisioned database.
env:
- name: POSTGRES_DB
value: opendox
- name: POSTGRES_USER
value: opendox
deploy/kubernetes/overlays/dev/kustomization.yaml:30
- This overlay claims to stamp the reviewed image “by digest”, but
newTag: "0.0.0"still selects a mutable tag. The resulting Deployment is not reproducible and can run an image different from the reviewed one; usenewDigestwith the reviewed SHA (or correct the claim and accept tag mutability).
# The reviewed image, by digest. A tag moves; a digest is the thing that was
# reviewed.
images:
- name: ghcr.io/opensoft/opendox-runtime
newName: ghcr.io/opensoft/opendox-runtime
newTag: "0.0.0"
src/opendox/runtime/app.py:492
FastAPI(...)leaves the default/docs,/redoc, and/openapi.jsonroutes enabled, and those routes have no bearer dependency. They are additional unauthenticated endpoints under the stated “only/livez” boundary; disable them or mount protected equivalents.
app = FastAPI(title="openDox runtime",
summary="identity and coordination (RULING Q1); "
"documents live in repositories",
lifespan=lifespan)
src/opendox/runtime/app.py:355
del principalmakes this endpoint bearer-authenticated only, so any signed-in user can list every draft body, including projects where they have no membership. Draft writes and deletes enforce project roles, so reads should be scoped through the caller's sessions/memberships rather than discarding the principal.
@drafts.get("")
def list_drafts(store: StoreDep, principal: PrincipalDep,
session_id: str | None = None,
project_id: str | None = None,
limit: LimitQuery = None,
after: str | None = None) -> list[dict[str, Any]]:
del principal
return [_draft_json(d) for d in store.list_drafts(
session_id=session_id, project_id=project_id, limit=limit, after=after)]
src/opendox/runtime/app.py:265
- A valid owner can submit a nonexistent target
user_id; the foreign-key violation fromcreate_membershipis not anidentity.ConflictError, so it escapes_conflictas an unstructured 500. Validate the target user first or translate the FK failure to the API's documented 404/409 refusal shape.
_require_role(store, user=principal, project_id=body.project_id,
allowed=("owner",))
return _membership_json(_conflict(lambda: store.create_membership(
user_id=body.user_id, project_id=body.project_id, role=body.role)))
src/opendox/runtime/app.py:514
- This readiness check only runs
select 1, so an empty or otherwise unmigrated database is reported as ready even though the module documentation says/readyzreports that state. Check the migration ledger/pending plan (and mark the database unavailable until the schema is applied) before returning a ready response.
try:
with app.state.context.database.connection() as conn:
conn.execute("select 1")
checks["database"] = "ok"
src/opendox/runtime/cli.py:318
reversed(identity.TABLES)is not a dependency order:TABLESputsmembershipsbeforeprojects, so this loop dropsprojectswhilemembershipsstill references it. A confirmed reset therefore fails with a foreign-key error instead of clearing the coordination tables. Use an explicit dependent-first order.
for table in (*reversed(identity.TABLES), migrations.LEDGER_TABLE):
src/opendox/runtime/identity.py:272
- The preflight
SELECTand subsequentINSERTare not atomic with respect to another request using the same slug. Two concurrent creates can both observe no row, then one gets an uncaught unique-violation from the database instead of the endpoint's documented 409; use anINSERT ... ON CONFLICT (slug) DO NOTHING RETURNING ...(or map the unique violation) to make the conflict deterministic.
row = self._conn.execute(
f"select {_PROJECT_COLUMNS} from projects where slug = %s", (slug,)
).fetchone()
if row is not None:
raise ConflictError(f"a project already exists at slug {slug!r}")
src/opendox/runtime/identity.py:344
- This repository-map preflight has the same check-then-insert race: concurrent requests for one
project_idcan both pass theSELECT, then one receives an uncaught unique-constraint error instead of the API's declared 409 conflict. Make the insert conflict-safe and translate the losing path toConflictError.
row = self._conn.execute(
f"select {_REPOSITORY_COLUMNS} from project_repositories "
"where project_id = %s", (project_id,)
).fetchone()
if row is not None:
src/opendox/runtime/migrations.py:282
apply()has no database lock around the ledger/bootstrap and migration loop. Two concurrent migrate jobs can both see an empty ledger and execute0001; the second then fails on the canonicalcreate tableor ledger insert instead of being an idempotent no-op. Serialize the runner with a PostgreSQL advisory/ledger lock held across discovery and application.
verify_canonical_digest(self._migrations_dir)
self.bootstrap_ledger()
recorded = {row.version: row.checksum for row in self.applied()}
applied_now: list[str] = []
tests_runtime/conftest.py:56
- This fixture skips only when
OPENDOX_TEST_DATABASE_URLis unset. If the variable is set but Postgres is unreachable,databaselater raises while openingadmin, so the DB suites fail instead of skipping with the promised reason. Probe the DSN here and convert connection failures topytest.skip, or change the documented behavior.
@pytest.fixture(scope="session")
def postgres_dsn() -> str:
dsn = os.environ.get(TEST_DSN_ENV, "").strip()
if not dsn:
pytest.skip(_SKIP_REASON)
- Files reviewed: 35/36 changed files
- Comments generated: 1
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical deployment and authorization issues block safe approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (26)
Previously missed (6) — in code that hasn't changed since the last review.
src/opendox/runtime/app.py:134
- Because
storeis a dependency ofget_principal, FastAPI entersget_storeand checks out a database transaction before line 141 checks theAuthorizationheader. An unauthenticated flood can therefore consume pool slots, and a database outage can turn a missing credential into a 5xx instead of 401. Verify the bearer token in a dependency that does not depend on the store, then open the store for the user upsert/route authorization.
src/opendox/runtime/app.py:508 /readyzhas noPrincipalDep, so it is publicly callable alongside/livezand exposes database/broker availability even though the application contract says/livezis the only unauthenticated route. Authenticate this endpoint and update the probe contract, or explicitly make both health endpoints unauthenticated instead of leaving the implementation and stated boundary inconsistent.
src/opendox/runtime/app.py:514- This readiness check only runs
select 1; it never inspects the migration ledger or pending files, even though the module contract says/readyzreports an unmigrated database. A fresh or partially migrated database will therefore be marked ready and route traffic into missing-table errors; include the migration state in readiness (without applying it) and return 503 when it is not current.
src/opendox/runtime/cli.py:193 - Only
MigrationErroris caught here. A refused or unreachable Postgres connection raises a driver/pool exception instead, so the lifecycle command emits a traceback and no JSON evidence, contrary to the CLI contract; catch the expected runtime failures and emit a redacted, nonzero refusal.
src/opendox/runtime/cli.py:314 - The reset connection and transaction are outside any error-to-evidence boundary. If the privileged database is unavailable or the drop fails, this verb likewise exits via an uncaught exception instead of printing one redacted refusal object as promised by the lifecycle CLI.
src/opendox/runtime/config.py:250 - The values are upper-cased on lines 240-242, but the EdDSA prefix here is still mixed-case. Therefore a valid asymmetric
EdDSAconfiguration becomesEDDSAand is rejected as “symmetric”, despite the documented asymmetric allow-list; compare against"ED"(or normalize the prefixes) after upper-casing.
deploy/compose/docker-compose.yaml:98
- The documented first-run command invokes
migratebeforeup, but this service has only animage:and nobuild:. On a fresh checkout there is noopendox-runtime:localimage yet, sodocker compose ... run migratetries to pull/fails instead of building the Dockerfile fromopendox; build the image before this command or give the migration service a shared build definition.
migrate:
image: ${OPENDOX_IMAGE:-opendox-runtime:local}
deploy/compose/docker-compose.yaml:109
- This compose migration service also assigns the privileged migration DSN to
OPENDOX_DATABASE_URL, the name reserved for the least-privileged served identity. That makes the two-identity separation only nominal inside the migration container and contradicts the comments above; do not alias the privileged secret to the served setting.
OPENDOX_MIGRATION_DATABASE_URL: ${OPENDOX_MIGRATION_DATABASE_URL}
# `load_settings` requires these three before any verb runs; the
# migration job needs no broker and no served identity, so they are the
# compose file's own placeholders and reach no network.
OPENDOX_DATABASE_URL: ${OPENDOX_MIGRATION_DATABASE_URL}
deploy/kubernetes/base/migration-job.yaml:14
- This fixed-name Job cannot be updated in place after it has run: Kubernetes treats the pod template as immutable. On the next migration/image release, applying the manifest will fail with an immutable-field error or leave the old image running, so the documented
kubectl applypath does not reliably execute later migrations. Use a versioned/generated Job or an explicit delete-and-recreate release step.
metadata:
name: opendox-migrate
namespace: opendox
spec:
backoffLimit: 2
deploy/kubernetes/base/migration-job.yaml:51
- This migration Job sets
OPENDOX_DATABASE_URL—the variable documented as the least-privileged served DSN—to the privileged migration secret. The Job then carries the same privileged credential under both identities, contradicting the separation this manifest is meant to enforce. Make migration mode not require a served DSN, or provide a non-credential placeholder instead of aliasing the migration secret.
- name: OPENDOX_DATABASE_URL
valueFrom:
secretKeyRef:
name: opendox-db-migration
key: dsn
deploy/kubernetes/overlays/dev/kustomization.yaml:30
- This overlay claims to stamp a reviewed image by digest, but
newTag: "0.0.0"is a mutable tag (and may not exist), not a digest. The resulting Kubernetes manifest is neither pinned nor the reviewed artifact; use Kustomize'sdigest: sha256:...with the actual reviewed image digest.
newTag: "0.0.0"
src/opendox/runtime/app.py:355
- This read path discards the principal and makes both filters optional, so any authenticated user can list every project's
drafts.body(including projects where they have no membership). Drafts are explicitly unsaved user work; require project/session authorization and reject or scope unqualified reads before serializing these rows.
del principal
return [_draft_json(d) for d in store.list_drafts(
session_id=session_id, project_id=project_id, limit=limit, after=after)]
src/opendox/runtime/app.py:371
- The role check covers
body.project_idonly;put_draftaccepts anysession_idand the schema stores the two foreign keys independently. A member who belongs to two projects can attach a draft for project B to a session from project A (and a caller can target another user's session), corrupting the coordination state; validate the session owner/project/open state or enforce that relationship in the schema.
_require_role(store, user=principal, project_id=body.project_id,
allowed=("owner", "member"))
return _draft_json(store.put_draft(
session_id=body.session_id, project_id=body.project_id,
document_key=body.document_key, body=body.body,
src/opendox/runtime/app.py:381
- Deleting a draft checks only membership in the draft's project, not ownership of the session that owns the draft. Any owner/member who learns another user's draft id can therefore discard that user's unsaved work; enforce the session ownership policy here instead of authorizing solely by project role.
draft = _found(lambda: store.get_draft(draft_id))
_require_role(store, user=principal, project_id=draft.project_id,
allowed=("owner", "member"))
store.delete_draft(draft_id)
src/opendox/runtime/app.py:492
- FastAPI enables
/docs,/redoc, and/openapi.jsonby default here. That creates three unauthenticated routes despite the runtime contract saying/livezis the only unauthenticated route; disable these endpoints or put them behind the same authentication boundary.
app = FastAPI(title="openDox runtime",
summary="identity and coordination (RULING Q1); "
"documents live in repositories",
lifespan=lifespan)
src/opendox/runtime/app.py:273
- This read enumerates every project for any valid bearer token and deliberately discards the principal without checking
memberships.role. With project-scoped roles and the stated rule that authorization is answered from the membership row, a user can discover projects they do not belong to; scope this and the analogous project/membership/repository reads by the principal or define an explicit directory policy.
def list_projects(store: StoreDep, principal: PrincipalDep,
limit: LimitQuery = None,
after: str | None = None) -> list[dict[str, Any]]:
del principal
return [_project_json(p) for p in store.list_projects(limit=limit, after=after)]
src/opendox/runtime/cli.py:261
Database(...)is closed when thiswithblock exits at line 258, sorunner.applied()andrunner.plan()then try to use a closed pool. A healthy database will therefore be reported as unreachable and its ledger state will never be included instatus; keep these reads inside the database context.
report["database"] = "reachable"
report["applied_migrations"] = [row.version for row in runner.applied()]
report["pending_migrations"] = [m.version for m in runner.plan()]
src/opendox/runtime/cli.py:318
- Reversing
identity.TABLESis not a valid dependency order: it dropsprojectsbeforememberships, which still has a foreign key to it. PostgreSQL will reject thatDROP TABLE, roll back the transaction, and makeresetunusable; use an explicit dependency-safe order (or drop only a dedicated coordination schema).
for table in (*reversed(identity.TABLES), migrations.LEDGER_TABLE):
src/opendox/runtime/cli.py:213
cmd_servenever calls_emit; a successful long-running invocation goes straight intouvicorn.runand emits no JSON evidence, contrary to the module and runbook statement that every lifecycle verb prints one. Emit a redacted startup result before serving, or explicitly exemptserveand update the contract and tests.
app = create_app(settings=settings)
uvicorn.run(app, host=settings.bind_host, port=settings.bind_port,
log_level=args.log_level)
return 0
src/opendox/runtime/cli.py:143
root.mkdirruns before any refusal handler. A permission error or invalidOPENDOX_PROJECT_REPOSITORY_ROOTtherefore produces a traceback and no JSON evidence, even thoughinitis one of the lifecycle verbs promised to report every refusal. Catch filesystem errors and route them through_emitwithout echoing sensitive configuration.
root = Path(settings.project_repository_root)
if not root.exists():
root.mkdir(parents=True, exist_ok=True)
created.append(str(root))
src/opendox/runtime/config.py:267
OPENDOX_OIDC_LEEWAY_SECONDS=0is a valid configuration for deployments that want no clock skew, but it is passed through_positive_int, which rejects zero. Use a non-negative validator for leeway while retaining the strictly-positive checks for TTL and port.
oidc_jwks_ttl_seconds=_positive_int(env, _by_name(PREFIX + "OIDC_JWKS_TTL_SECONDS")),
oidc_leeway_seconds=_positive_int(env, _by_name(PREFIX + "OIDC_LEEWAY_SECONDS")),
src/opendox/runtime/identity.py:272
- The check-then-insert sequence is racy: two concurrent requests can both observe no row, then one unique-index violation escapes as a raw Postgres error instead of the
409 coordination.conflictthis route promises. Make the insert itself conflict-safe (for exampleON CONFLICT (slug) DO NOTHING RETURNING) and raiseConflictErrorwhen it returns no row.
row = self._conn.execute(
f"select {_PROJECT_COLUMNS} from projects where slug = %s", (slug,)
).fetchone()
if row is not None:
raise ConflictError(f"a project already exists at slug {slug!r}")
src/opendox/runtime/identity.py:344
- The same check-then-insert race exists for the one-row project/repository map. Concurrent repository creation can hit the unique constraint at line 146 and leak a database exception instead of the declared conflict; use an
ON CONFLICT (project_id) DO NOTHING RETURNINGinsert and translate an empty result toConflictError.
row = self._conn.execute(
f"select {_REPOSITORY_COLUMNS} from project_repositories "
"where project_id = %s", (project_id,)
).fetchone()
if row is not None:
src/opendox/runtime/migrations.py:264
plan()only compares migration versions and never compares the recorded checksums with the current files. Consequentlyruntime migrate --planreturns success with an empty plan for an already-applied but edited migration, while the real apply path would refuse it; the read-only plan must perform the same drift check.
def plan(self) -> list[Migration]:
"""The pending migrations, in the order they would be applied."""
already = {row.version for row in self.applied()}
return [m for m in self.discover() if m.version not in already]
src/opendox/runtime/migrations.py:284
- The runner checks checksums only for files returned by
discover(). If a migration already recorded in the database is deleted or renamed from the image, it is absent from this loop and the runner proceeds as if the history were consistent, despite the fail-closed drift contract. Reject recorded versions that are missing from the discovered set before applying anything.
recorded = {row.version: row.checksum for row in self.applied()}
applied_now: list[str] = []
for migration in self.discover():
tests_runtime/conftest.py:56
- This fixture skips only when the variable is absent. If
OPENDOX_TEST_DATABASE_URLis set but stale or unreachable,Database(...)fails in thedatabasefixture and the runtime suites go red instead of skipping with the documented reason. Probe the DSN at session setup and convert connectivity failures topytest.skipwithout echoing credentials.
dsn = os.environ.get(TEST_DSN_ENV, "").strip()
if not dsn:
pytest.skip(_SKIP_REASON)
- Files reviewed: 35/36 changed files
- Comments generated: 4
- Review effort level: Lite
…he boundaries they exposed Copilot's review `5224556194` at `0a4969fe` — twelve threads and ten suppressed comments. Every finding is answered here, each with the assertion that would have caught it. THREE CRITICALS. * **Any signed-in principal could read every draft in the install.** `GET /api/v1/drafts` authenticated and then filtered by CALLER-SUPPLIED ids, and a draft is the one place this schema holds bytes (RULING Q1's "unsaved drafts"), so listing one is reading unwritten text. It filters by the PRINCIPAL'S OWN SESSIONS now. The write and the delete paths had the same hole one level down: both authorized `project_id` alone, and `drafts` is keyed by `(session_id, document_key)`, so a legitimate MEMBER who named another member's session id could overwrite or discard their unsaved text through the upsert. `_require_own_open_session` is where that is enforced, and five suites drive it. * **Two migration runs could both apply `0001`.** The gate, the ledger bootstrap, the ledger read and the per-migration transactions are four separate statements; two deploys, or a Job retry overlapping its predecessor, could both read an empty ledger. The run now holds `pg_advisory_lock` across all of it. `test_a_run_holds_the_advisory_lock_and_a_second_one_waits` holds that lock from another session and measures that `apply()` does not proceed — and that it creates nothing while it waits. * **An unknown `kid` was an amplifier.** Every miss forced an immediate JWKS fetch that bypassed the TTL, while the cache lock was held, so random `kid` headers turned one request into one outbound broker request and serialized every other verification. A miss still refreshes ONCE (rotation needs that) and at most once per cooldown: 50 unknown-kid lookups now cost one refresh, measured. TWO OUTRIGHT BUGS, both of the kind only a live dependency shows — every test that did not have one passed. * `opendox-runtime status` used `runner.applied()` and `runner.plan()` AFTER the `Database` context had closed its pool, so a perfectly reachable database was reported unreachable. * `reset` dropped in `reversed(identity.TABLES)`, which puts `projects` before `memberships` — and `memberships.project_id` references `projects.id`, so the first install with one membership failed the whole transaction and cleared nothing. `DROP_ORDER` is written out and topological, and the test asserts the PROPERTY (every table before each table it references), not the list. THE BOUNDARIES THE REVIEW EXPOSED. * **The migration container carried a served identity.** Both deployments set `OPENDOX_DATABASE_URL` to the PRIVILEGED DSN purely to satisfy `load_settings`, so any path reading `settings.database_url` there was schema-privileged — the separation those files exist to keep, undone by a loader requirement. `load_migration_settings` requires the migration DSN and nothing else; compose and the Job now carry that variable and `OPENDOX_MIGRATIONS_DIR` and no others, asserted. * **"`/livez` is the ONLY unauthenticated route" was wrong twice.** `/readyz` was already public, and FastAPI's defaults published `/docs`, `/redoc` and `/openapi.json`. The schema viewers are OFF unless `OPENDOX_PUBLISH_OPENAPI=true`; the two probes stay public and the docstring says WHY (a probe that needed a token could never report that the broker is down); and the suite ENUMERATES the running app's unauthenticated routes rather than trusting any of that. * **Readiness passed on an unmigrated database.** `select 1` succeeds against a schema with no tables in it, so a fresh install went READY and took traffic that failed on missing relations. `/readyz` reports the pending versions and is `not-ready` until they are applied. * **A slug race returned 500, not 409.** Check-then-insert is not atomic; the loser saw the driver's raw unique violation and `app.py` maps only `ConflictError`. Translated in the store by SQLSTATE `23505` — matched off the exception rather than by importing psycopg, because this module's import-weight contract forbids the import. Driven by two real connections whose pre-checks both pass. * **`EdDSA` could not be configured at all.** Names were upper-cased and then prefix-tested, so `EdDSA` became `EDDSA`, was classified symmetric, and would not have matched PyJWT's case-sensitive `alg` either. There is a declared `ASYMMETRIC_ALGORITHMS` set now and configured names canonicalize to PyJWT's spelling. * **The Kubernetes base could not authenticate.** It bundles a Postgres with the `opendox` role alone while the Deployment's Secret names a least-privileged one that nothing created. The base now mounts the SAME `deploy/compose/init-runtime-role.sh` through a `configMapGenerator` — one script, two deployments. * **The compose migration service could not run first.** It had `image:` and no `build:`, so the runbook's documented order (migrate, then up) tried to PULL an image that is in no registry. * **The dev overlay claimed a digest it did not pin.** `newTag:` is mutable; it is labelled an explicit non-production placeholder and shows the `digest:` form a real environment uses. * **The lifecycle contract leaked tracebacks.** `main()` now turns any escaped exception into one redacted evidence object and a nonzero exit, `migrate` maps operational failures the same way, and both emit AFTER their context has closed rather than inside it. * **An unreachable test database failed instead of skipping**, against the promise in the module, the runbook and the PR body. `conftest` probes with a bounded connect and skips naming the DSN and the error. * **`__init__` promised a module this branch does not carry.** `local_git_adapter` and `repository_act` arrive with § 3.6, stacked directly on this PR; the contract is stated as the one they land under, and `test_runtime_surface.py` measures whichever of the listed modules the tree actually has. AND ONE THIS ACT'S OWN SUITE FOUND while proving the advisory lock: a test `Database(schema=…)` whose schema does not exist writes into `public` instead of failing, because `search_path` is `<schema>,public`. That polluted the shared test database once. The `database` fixture now asserts `current_schema()` before it creates anything, and the lock test joins its worker before the schema is dropped. Measured at this head (python 3.12.3, pytest 8.4.2, postgres 16.15): the required job's own invocation ............ 84 passed in 5.09s python -m pytest -q tests_runtime/ ........... 141 passed in 18.40s python -m pyflakes src/opendox/runtime/*.py tests_runtime/*.py — clean Lane: openxfactory-4 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…and the served role could rewrite the ledger
Copilot's second pass at `bd109b7a` found two things the first did not, both
real and both of a class no test in this repository could have caught on its
own — so each lands with the assertion that can.
* **THE KUBERNETES PODS WOULD NOT HAVE STARTED.** Both the Deployment and the
migration Job declared `args: ["opendox-runtime", …]`, and the image has a
`CMD` and no `ENTRYPOINT`: Kubernetes `args` replaces CMD's ARGUMENTS and
leaves the entrypoint empty, so the container had no executable. `command:`
in both now — which is the form the compose file already used — and
`test_both_pods_declare_command_and_not_only_args` asserts it on the
manifest's shape, since nothing here runs a cluster.
* **THE SERVED ROLE COULD REWRITE THE MIGRATION LEDGER.**
`init-runtime-role.sh` sets `alter default privileges … grant select, insert,
update, delete on tables`, which covers `opendox_schema_migrations` the
moment `0002` creates it. A compromised API could then hide an applied
migration or manufacture one, and the fail-closed drift check would be
checking a story the API wrote.
THE NARROWING BELONGS IN THE RUNNER, and that is the part worth reading: the
bootstrap script runs on the database's FIRST START, before any migration
exists, so default privileges are all it can set. `opendox-runtime migrate`
is the process that owns the ledger and is already connected as the
privileged identity, so `MigrationRunner.protect_ledger` revokes
insert/update/delete/truncate and grants SELECT — kept, because `/readyz`
reads the ledger through the served DSN to report a pending schema. It is a
no-op when no role is named, so a single-role developer install stays legal.
The role NAME arrives as `OPENDOX_RUNTIME_PG_ROLE`, set in both deployments
as a plain literal — a name is not a credential, and the password for that
role never reaches the migration container. SQL takes an identifier as
SYNTAX and cannot take it as a parameter, so the name is validated against
`[A-Za-z_][A-Za-z0-9_]{0,62}` in the config loader AND again in the runner
(the method is public and a caller may not have come through the loader);
`test_the_ledger_narrowing_refuses_a_role_name_that_is_not_an_identifier`
hands it `evil"; drop table users; --` and measures the refusal.
`test_the_served_role_cannot_rewrite_the_ledger_after_a_run` creates a real
role with the bootstrap's own default privileges, runs the migration, and
reads `information_schema.table_privileges`: `{SELECT}` on the ledger, and
`{SELECT, INSERT, UPDATE, DELETE}` still on `users` — which is what makes it
a narrowing rather than a lockout.
Measured at this head (python 3.12.3, pytest 8.4.2, postgres 16.15):
the required job's own invocation ............ 87 passed in 4.98s
python -m pytest -q tests_runtime/ ........... 146 passed in 16.64s
python -m pyflakes src/opendox/runtime/*.py tests_runtime/*.py — clean
Lane: openxfactory-4
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
`test_status_reports_a_reachable_database_and_its_applied_migrations` runs the verb against the `runtime` job's real Postgres and asserts what the closed-pool defect made impossible: `database == reachable`, `applied_migrations == ["0001", "0002"]`, `pending_migrations == []`. Before the fix every one of those was a report of an unreachable database, and every UNREACHABLE-database test passed throughout — which is why the assertion has to be this one. The test schema travels IN the DSN (`options=-c search_path=…`), because `status` builds its own `Database` from `OPENDOX_DATABASE_URL` and the harness's `Database(schema=…)` never reaches it — the same libpq startup parameter, supplied the way a deployed install would supply it. Measured: `python -m pytest -q tests_runtime/` — 147 passed in 18.30s. Lane: openxfactory-4 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
WHAT HAPPENED, MEASURED. Requesting a review with `gh pr comment --body '@copilot review'` did not only request a review: on this repository it also started GitHub's Copilot CODING agent (`gh api .../actions/runs` shows a run named "Addressing comment on PR #25"), which pushed `86ab5fad` ("Fix repository adapter review issues", 359 insertions across 7 files) and `1bdedc24` ("Address validation follow-up comments") straight onto this branch. WHY THEY ARE REVERTED RATHER THAN KEPT. Nothing about them is reviewable as this act: they carry no `Lane:` trailer and no measurement, nobody ran their tests before they landed on the branch, and the act they modify is one this lane claimed (`#656` comment 5699629780) and is answerable for line by line. An act whose code arrived from an agent nobody asked and nobody measured is not an act this lane can put its name on, whatever the diff happens to say. THE FINDINGS THEY WERE ANSWERING ARE NOT DISMISSED. Copilot's review of this PR (`5224578194`) and of #25 (`5224556194`) are substantial and largely correct — the missing-executable normalization, the branch assumed to be `main`, the unborn-versus-unreadable HEAD, the per-process index name, the relative path persisted in the durable map, the adapter name ignored by `attach_remote` and `push_to_remote`, the CLI emitting success inside an open transaction, and the credential-bearing remote URL. Every one of them is answered in this lane's own commits, with the measurement each needs, in the commits that follow this one. This is a REVERT and not a force-push: the two commits stay in the history, which is what makes this note findable next to them. Reviews on this repository are requested through `gh api --method POST repos/<owner>/<repo>/pulls/<n>/requested_reviewers -f 'reviewers[]=Copilot'` from here on, never through an `@copilot` comment. `git diff a1e7dab` is empty at this commit — the tree is exactly what this lane last pushed. Lane: openxfactory-4 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
One or more issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (8)
deploy/compose/.env.example:19
- This copied first-start command has the same fresh-checkout failure:
docker compose runwill not build the image merely because the service declaresbuild:and can try to pull the local tag. Add--buildhere as well so the example actually works beforeuphas built the served service.
# -f deploy/compose/docker-compose.yaml --profile migration run --rm migrate
deploy/kubernetes/overlays/dev/kustomization.yaml:20
- These generated ConfigMaps have stable names, while the Deployment consumes their values through
configMapKeyRefenvironment variables. Updating the overlay's issuer/audience/JWKS values therefore updates the ConfigMap without changing the pod template, and Kubernetes does not refresh env vars or roll the Deployment; existing pods continue authenticating against the old broker configuration until a separate restart. Use a name hash/checksum annotation or otherwise make config changes trigger a rollout.
configMapGenerator:
- name: opendox-oidc
behavior: merge
options:
disableNameSuffixHash: true
docs/runtime.md:113
docker compose rundoes not build a declaredbuild:section unless--build(or a separate build) is requested. On a fresh checkout this first documented command can therefore try to pullopendox-runtime:localbefore the image exists, despite the compose file defining the build. Add--buildto this runbook command.
--profile migration run --rm migrate
src/opendox/runtime/cli.py:245
- The lifecycle contract says every verb emits one JSON evidence object, but the normal
servepath callsuvicorn.run()and returns without emitting anything. A successful long-running invocation therefore has no machine-readable start/outcome record, unlike the other verbs; emit an explicit startup/termination record or define howservereports its lifecycle outcome.
ok=False)
app = create_app(settings=settings)
uvicorn.run(app, host=settings.bind_host, port=settings.bind_port,
src/opendox/runtime/cli.py:479
- The last-resort error boundary copies
str(exc)directly into the JSON evidence. Driver/URL-parser failures are allowed to include connection info (and can echo a supplied DSN), so this does not enforce the CLI contract that no DSN or password is ever printed. Emit a safe error code/type or run all exception text through a redactor that removes the configured DSNs before_emit; the same pattern also appears in the migrate/reset handlers.
raise
except Exception as exc: # noqa: BLE001
return _emit({"verb": getattr(args, "verb", "unknown"),
"refusal": type(exc).__name__,
src/opendox/runtime/cli.py:358
- Reset has the same secret-disclosure path: a database exception is copied into
messagewithout redaction. A failed connection or malformed DSN must still produce evidence, but it must not echo arbitrary driver text containing connection details or credentials.
"message": str(exc)}, ok=False)
try:
with Database(dsn, application_name="opendox-runtime-reset",
checkout_timeout=args.connect_timeout) as db, \
db.transaction() as conn:
for table in DROP_ORDER:
conn.execute(f"drop table if exists {table}")
except Exception as exc: # noqa: BLE001
return _emit({"verb": "reset", "refusal": type(exc).__name__,
src/opendox/runtime/cli.py:306
- The status verb promises redacted evidence but includes the raw database exception here. This can expose connection details in the JSON output; report only the exception type/code or sanitize the message before emitting it.
report["pending_migrations"] = pending
# a status verb reports, never raises
except Exception as exc: # noqa: BLE001
report["database"] = f"unreachable: {type(exc).__name__}: {exc}"
tests_runtime/test_runtime_surface.py:32
- The test's prose and
__init__.pycontract includelocal_git_adapterandrepository_act, but neither module is inSTDLIB_ONLY_MODULES. As a result, themissingallow-list can never exercise those modules on the stacked § 3.6 branch, so a heavy import added there would pass this hermetic import-weight check. Add both dotted names to the tuple.
- Files reviewed: 35/36 changed files
- Comments generated: 13
- Review effort level: Lite
181 passed, 1 skipped hermetic and 298 for `pytest -q tests_runtime/`, both measured at bb84c6c6 — the commit that answered the two rounds, not this one. Seven tests added: four in the CLI (the two DSNs' schema invariant, the redacting log-record boundary around uvicorn, and the AST walk that forbids an unredacted exception in any handler) and three in the deployment (the healthcheck's bind host, the Secret subshell's `pipefail`, and the managed-database prerequisite's ON_ERROR_STOP and blank-password refusal). Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Critical privilege, schema parsing, and DSN-target validation findings remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (6)
.github/workflows/validate.yml:887
- This record is no longer synchronized with the PR description: the body calls
1c6cd9e/174 hermetic and 291 DB-backed current, while this workflow recordsbb84c6c6/181 and 298 as current. Please update the body or this measurement block so the same head/count pair is presented in both places.
# THE CURRENT FIGURE; the PR description states it at this
# same commit, and `pytest -q tests_runtime/` is 298 here.
deploy/compose/init-runtime-role.sh:94
- These grants are hard-coded to
public, but runtime DSNs may select a different schema viaoptions=-c search_path=...; the migration runner explicitly supports and validates that form. In that configuration the DDL lands in the selected schema while the served role gets no USAGE, default, or table grants there, soverify_runtime_accessfails and the deployment cannot start. Derive the selected schema from configuration or explicitly reject non-public schemas.
select format('grant usage on schema public to %I', :'runtime_user')
\gexec
deploy/kubernetes/base/init-runtime-role.sh:94
- These grants are hard-coded to
public, but runtime DSNs may select a different schema viaoptions=-c search_path=...; the migration runner explicitly supports and validates that form. In that configuration the DDL lands in the selected schema while the served role gets no USAGE, default, or table grants there, soverify_runtime_accessfails and the deployment cannot start. Derive the selected schema from configuration or explicitly reject non-public schemas.
select format('grant usage on schema public to %I', :'runtime_user')
\gexec
docs/runtime.md:429
- The managed-database prerequisite repeats the same broad default privilege: every future table created by
migration_ownerinpublicbecomes writable by the served role, including unrelated tables if that owner is reused. That contradicts the least-privilege/shared-database boundary described above; the instructions need either a dedicated-owner requirement or explicit grants tied to runtime tables/migrations.
select format('alter default privileges for role %I in schema public grant '
'select, insert, update, delete on tables to %I',
:'migration_owner', :'runtime_role')
\gexec
docs/runtime.md:404
- The managed-database prerequisite repeats the same
public-only grants. A DSN using a supported customsearch_pathcreates the coordination tables elsewhere, but this block grants the served role only onpublic, so the migration's runtime-access preflight rejects the install after provisioning. The prerequisite must handle the selected schema or state that non-public schemas are unsupported.
select format('grant usage on schema public to %I', :'runtime_role')
\gexec
src/opendox/runtime/app.py:1064
plan()anddrift()each callapplied(), so this readiness transaction can execute three queries per call plusselect 1, each with its own 3-secondstatement_timeout. A slow-but-healthy request can therefore take roughly 10s of checkout + 21s of database statements + 5s of JWKS work, exceeding the 20s Kubernetes timeout and causing probe overlap despite the budget assertion. Use a single total deadline/remaining timeout or consolidate the schema checks, then derive the probe budget from that total.
pending = [m.version for m in runner.plan(conn)]
drifted = runner.drift(conn)
- Files reviewed: 38/39 changed files
- Comments generated: 4
- Review effort level: Lite
Four threads and six suppressed comments; each case fails against the previous
head, and one of them is a defect round 34 introduced.
THE PREFLIGHT SPLIT `search_path` WITH `.split(",")[0]` while the runner it
feeds has had a quote-aware parser since round 26 — so the legal, distinct
schema names "tenant,blue" and "tenant,red" both reduced to `tenant` and two
DSNs selecting genuinely different schemas compared equal. `_path_entries` and
`_unquoted` move to `config` as `search_path_entries` and
`unquoted_identifier`, and `migrations` aliases them: ONE definition, so the
two cannot drift again. And the layer above them was wrong too — `shlex`
REMOVES double quotes, so the quoting that makes a comma part of a name was
gone before the parser saw it. libpq's `options` has no quote processing at
all: whitespace separates and a backslash escapes, which is what
`_libpq_option_words` now does. The conninfo layer above THAT does take single
quotes, and shlex is still right there.
AND THE SCHEMA COMPARISON MEANT NOTHING ACROSS TWO DATABASES. `public` in one
and `public` in another are different sets of tables, so a run could apply and
verify one while /readyz and the API read the other. `database_named_by` reads
the name out of both DSN forms — path or `dbname=`, no credential touched —
and the database is compared first. The host and port are deliberately NOT
compared: a served DSN through a pooler beside a migration DSN direct to the
server is the ordinary secure shape and nothing in a string tells a pooler
from a second server.
THE READINESS PROBE'S BOUND WAS PER-STATEMENT AND IT RUNS FOUR STATEMENTS —
`select 1`, then `plan()` and `drift()`, each asking the ledger — so the
derived budget was under a quarter of the worst case and a slow-but-healthy
request could pass the probe's own timeout, which is the overlap rounds 19 and
30 closed one term at a time. There is a deadline now: nothing is STARTED
after it and what starts is capped at the smaller of the ceiling and what is
left, so the bound is the budget plus one ceiling — 3.0 + 1.5 — and that is
the term `test_deploy_shape.py` adds. `timeoutSeconds` moves to 25.
AND THE BOOTSTRAP COULD NOT SERVE A SUPPORTED DSN. Every grant in it named
`public` while a runtime DSN may select a schema with `options=-c
search_path=…`, so the DDL landed in one schema and the served role's rights
in another and `verify_runtime_access` failed the migration. `OPENDOX_PG_SCHEMA`
carries it through compose, `.env.example`, the StatefulSet and the ConfigMap;
the schema is created (owned by the migration owner) before it is granted on.
Finally, `alter default privileges` follows the ROLE and not a table list, so
on a reused database a shared owner would hand the served role every table it
creates afterwards — the boundary replacing `grant … on all tables` was meant
to draw. The grant is refused when the owner already owns a table this runtime
did not create. MEASURED on postgres 16.15 against the shipped statement: no
row for an empty schema, no row for one holding only the seven coordination
tables, exactly one for an owner that also owns `invoices` — and that row's
`do` block raises naming both.
Lane: openxfactory-4 (openXfactory-4-openDox_extraction)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
184 passed, 1 skipped hermetic and 301 for `pytest -q tests_runtime/`, both measured at ad077e2f — the commit that answered the round, not this one. Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
A critical schema-selection issue and multiple moderate transaction, deployment, and grant-qualification findings remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (8)
.github/workflows/validate.yml:905
- The PR description says the current measurement is
c1414cbwith 181/298 tests, but this workflow marksad077e2fas CURRENT and reports 184/301. Please update either the description or this record so the claimed head and both measured counts are synchronized; otherwise the evidence is ambiguous.
# THE CURRENT FIGURE; the PR description states it at this
# same commit, and `pytest -q tests_runtime/` is 301 here.
deploy/compose/init-runtime-role.sh:131
- The generated
GRANTcontains onlyc.relname, so it is resolved through this psql session's defaultsearch_pathrather than the selectedOPENDOX_PG_SCHEMA. On a non-public schema with coordination tables already present, the prerequisite therefore grants the wrong table or errors instead of granting the table queried by the catalogue. Include:'schema'as a qualified identifier in the generated table name.
select format('grant select, insert, update, delete on table %I to %I',
c.relname, :'runtime_user')
deploy/kubernetes/base/init-runtime-role.sh:131
- The generated
GRANTcontains onlyc.relname, so it is resolved through this psql session's defaultsearch_pathrather than the selectedOPENDOX_PG_SCHEMA. On a non-public schema with coordination tables already present, the prerequisite therefore grants the wrong table or errors instead of granting the table queried by the catalogue. Include:'schema'as a qualified identifier in the generated table name.
select format('grant select, insert, update, delete on table %I to %I',
c.relname, :'runtime_user')
docs/runtime.md:433
- This managed-database prerequisite has the same qualification bug as the bundled bootstrap: the catalogue filters tables in
:'schema', but the generatedGRANTnames only%I/c.relname. Unless the operator's session happens to have that schema insearch_path, a non-public install grants a same-named table elsewhere or fails; generateschema.tablehere.
select format('grant select, insert, update, delete on table %I to %I',
c.relname, :'runtime_role')
docs/runtime.md:502
- This guard has the same fail-open pipeline: a failed
kustomize buildis hidden bygrep's status and theelsebranch can still apply the output of another failed build. Capture/check the build status before testing the placeholder, then apply the captured manifest only on success.
if kustomize build deploy/kubernetes/overlays/managed-database | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
else
kustomize build deploy/kubernetes/overlays/managed-database | kubectl apply -f -
docs/runtime.md:541
- The re-run guard also uses
kustomize build | grepwithout checking the build command's exit status, so a build failure can fall through tokubectl applyinstead of refusing the re-run. Check the build result before piping its manifest tokubectl.
if kustomize build deploy/kubernetes/overlays/dev | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
else
kustomize build deploy/kubernetes/overlays/dev | kubectl apply -f -
docs/runtime.md:268
- If
kustomize buildfails after emitting any YAML, this pipeline's status is taken fromgrep, so theelsebranch can run and pipe a second build's partial/empty output tokubectl apply; the guard is not fail-closed. Capture the build result (or enablepipefailin a Bash block) before checking the placeholder, and abort without applying when the build fails.
elif kustomize build deploy/kubernetes/overlays/dev | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
else
kustomize build deploy/kubernetes/overlays/dev | kubectl apply -f -
src/opendox/runtime/app.py:415
principal_for()inserts or updates the user through the same request transaction thatget_store()rolls back whenever the handler raises anHTTPException. Therefore a user's first authenticated request to an unauthorized endpoint (for example, a project they do not belong to) authenticates successfully but loses the new user row during dependency cleanup, contrary to the documented first-login durable-row contract; the next request creates a different identity again. Persist the identity in a transaction that is independent of the authorization/handler transaction, and cover a first login that receives a 403.
return oidc.principal_for(store, claims)
- Files reviewed: 37/39 changed files
- Comments generated: 1
- Review effort level: Lite
Five findings from a read-only opus-max review of `0860270f`, fixed in one
batch, each with a case that reproduces the reviewer's own input and fails
against the previous head.
A25-1, BLOCKING — A MALFORMED BROKER URL PRINTED ITS OWN PASSWORD. `_split_url`
interpolated the driver's message, and CPython's `_checknetloc` raises
`ValueError("netloc '<the whole netloc>' contains invalid characters under NFKC
normalization")` — userinfo and password included. A hostname that is not ASCII
is the ordinary case for an IDN broker, and `_split_url` runs BEFORE the
userinfo refusal, so the guard written to keep a password out of this very
message never ran: `OPENDOX_OIDC_ISSUER=https://svc:hunter2@brokerâ„€evil.example/realms/x`
put `hunter2` on stdout from `runtime status` and `runtime init`, in the JSON
the lifecycle contract calls redacted evidence. `_safe_message` did not catch it
either — the leaked run has no `://` and no `password=`. The exception type is
named now and the value is not, and the cause is dropped so the chain is clean
too.
A25-4, MINOR — AND THE SCAN THAT SHOULD HAVE CAUGHT IT READ ONE FILE. Round 35
made the no-credential contract a SHAPE and scoped the walk to `cli.py`;
`config.py`, `oidc.py`, `migrations.py`, `identity.py`, `app.py` and `db.py` all
compose messages an operator reads, and A25-1 lived in that gap for 36 rounds.
The scan is parameterized over every module in the package now, and the rule is
stated rather than allow-listed by line: a LIBRARY's exception text may not be
formatted into evidence, and this package's own may, because this package wrote
it. `traceback.format_exc()`, `print_exc()` and `sys.exc_info()` inside a
handler are flagged too.
A25-2, MAJOR — AN ANONYMOUS REQUEST WAS A 500. `_match` selected by `kid`
alone, so a token whose header names an EC key with `alg: RS256` passed the
allow-list, reached `RSAAlgorithm.prepare_key`, and got a plain `TypeError` —
not a `PyJWTError` — which escaped `_decode`'s seven clauses, `verify` and
`get_principal`. A realm publishing an RSA and an EC key is what Keycloak
publishes with an ES256 provider beside the default, and both `kid`s are public
facts from the unauthenticated JWKS endpoint. The key TYPE is bound to the
algorithm family at selection, and `_decode` grew a final `(TypeError,
ValueError)` clause so no future PyJWT shape can reopen it.
A25-3, MAJOR — THE TWO-DSN GUARD COULD NOT FIRE IN EITHER SHIPPED DEPLOYMENT.
No workload holds both DSNs: the Deployment has the served one, the Job the
migration one, compose splits them the same way, and `migrate` does not call
`load_settings` at all — `test_deploy_shape.py` PINS that split, because the
separation of the two identities is the point. `OPENDOX_SERVED_SCHEMA` is a
schema NAME and never a credential, so the migration container can be told
where the API reads; `MigrationRunner.refuse_a_schema_the_api_will_not_read`
refuses before the ledger is bootstrapped. Both deployments take it from the
same `pg_schema` value the first-start bootstrap grants in.
A25-5, MINOR — AN UNBOUNDED NUMBER SWITCHED OFF `exp`. PyJWT applies
`OPENDOX_OIDC_LEEWAY_SECONDS` as slack on expiry, so `999999999` was a legal
configuration under which no token expires. `MAXIMUM_BY_SETTING` bounds the
leeway, the JWKS TTL and the bind port; and `int()` takes Python's underscore
separators, so `3_0_0` silently meant 300 — digits only now.
Lane: openxfactory-4 (openXfactory-4-openDox_extraction)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
196 passed, 1 skipped hermetic and 317 for `pytest -q tests_runtime/`, both measured at 2e400a4 — the commit that answered A25-1 through A25-5, not this one. Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…s) into build/3-5-runtime Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> # Conflicts: # .github/workflows/validate.yml
There was a problem hiding this comment.
🟡 Changes recommended
Outstanding comments remain on database-name parsing, readiness budgeting, migration-plan preconditions, deployment guard failure handling, and stale coverage figures.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (5)
docs/runtime.md:267
- This guard is not fail-closed: a failed
kustomize buildon the left side of the pipeline is masked bygrep's status, so theelsecan send empty or partial output tokubectl apply; additionally, the secret-failure and placeholder branches only echo and leave a zero status. Capture the build result first and make every refusal path nonzero before applying its captured manifest.
if [ "${secrets_created:-1}" -ne 0 ]; then
echo 'a Secret was not created, so nothing is applied; fix it and re-run' >&2
elif kustomize build deploy/kubernetes/overlays/dev | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
else
docs/runtime.md:503
- The same pipeline masks a
kustomize buildfailure:grepdetermines the condition, so a failed or partial render can fall through tokubectl apply, while the placeholder branch returns success after only printing an error. Render once into a variable, check the render status, and return nonzero on both refusal paths before applying it.
if kustomize build deploy/kubernetes/overlays/managed-database | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
else
kustomize build deploy/kubernetes/overlays/managed-database | kubectl apply -f -
fi
docs/runtime.md:542
- This re-run guard has the same fail-open pipeline: a
kustomize builderror is hidden bygrep, and the placeholder branch ends with a successfulecho, so the block can report success without applying a valid manifest. Capture the build once, fail on render/placeholder, and only pipe the verified output tokubectl apply.
if kustomize build deploy/kubernetes/overlays/dev | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
else
kustomize build deploy/kubernetes/overlays/dev | kubectl apply -f -
fi
src/opendox/runtime/app.py:1064
- The readiness budget is not actually a total:
runner.plan(conn)andrunner.drift(conn)each callapplied(), which issues multiple SQL statements, but_bound_bysetsSET LOCAL statement_timeoutonly once before each phase. PostgreSQL applies that timeout per statement, so each query can consume the full 1.5 seconds and the endpoint can run past the 3-second database budget and the 25-second probe timeout, allowing overlapping probes. Re-check the deadline and set the remaining timeout for every execute (or otherwise enforce a true total budget).
# probe runs FOUR statements — `select 1`, then `plan()` and
# `drift()`, each asking the ledger — so a per-statement
# ceiling alone bounded the probe at four times that ceiling,
# which with the checkout wait and the JWKS timeout beside it
# exceeded the probe's own `timeoutSeconds` (Copilot review of
src/opendox/runtime/cli.py:434
migrate --plandoes not runrefuse_a_schema_the_api_will_not_read, even though the realapply()does. In the shipped split workload, a migration DSN selecting schema A withOPENDOX_SERVED_SCHEMAset to B therefore produces a successful plan while the subsequent real migration refuses before bootstrapping; the preview is not describing what would actually run. Check this guard on the same connection before callingrunner.plan(conn)(or explicitly make the preview report the precondition failure).
# The canonical gate has already run, above, for this path and
# for the real one.
evidence = {"verb": "migrate",
"planned": [m.version for m in runner.plan()],
"applied": []}
- Files reviewed: 37/39 changed files
- Comments generated: 2
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved credential exposure, probe deadline, pagination-bound, and OIDC error-handling findings remain.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (3)
src/opendox/runtime/identity.py:735
- The predicate only checks
bytes_before < budget, so it includes the row that crosses the budget. For example, two valid 600 KiB drafts are returned together even thoughMAX_PAGE_BODY_BYTESis 1 MiB; two maximum-size drafts can likewise make a page roughly 2 MiB, contradicting the stated page cap and weakening the memory bound. Enforce the cumulative size for subsequent rows (while retaining the special case for a first oversized row), or change the contract and test to describe a budget-plus-one-row bound.
" where page.bytes_before < %s order by d.id",
src/opendox/runtime/oidc.py:503
algcomes directly from the unverified JWT header and is only checked for tuple membership here. A header containing an array or number does not match the allow-list, then_key_can_carry()slices it and uses it as a dict key, raisingTypeError;get_principal()catches onlyOidcError, so an anonymous request can turn this into a 500 instead of a 401. Reject non-string algorithms before selecting the key.
if alg not in self._algorithms:
tests_runtime/conftest.py:11
- This heading says the fixture is “never failed”, but
_skip_or_fail()deliberately callspytest.fail()wheneverCIis set. That makes the module-level contract misleading for the required runtime job; state the developer-skip/CI-failure split here as the later docstring does.
- Files reviewed: 37/39 changed files
- Comments generated: 2
- Review effort level: Lite
…, remote_url Five unresolved threads, one batch, one regression each, every premise measured rather than argued. * `schema_selected_by` took the FIRST `-c search_path=` and libpq takes the LAST, so a DSN assembled by appending an override was read as saying what it overrode. Measured on postgres 16: `-csearch_path=old -csearch_path=new` then `show search_path` prints `new`. * `database_named_by` read the URI path alone, so `postgresql://h/?dbname=one` and `...?dbname=two` both answered `None` and the two-DSN preflight passed a pair naming two databases. Measured against `PQconninfoParse` itself (`psycopg.conninfo.conninfo_to_dict`): the query beats the path and a repeated key takes the last, in both DSN forms. * `/readyz` set `SET LOCAL statement_timeout` once per PHASE and called it a total. It is per statement, and a phase is several: driving the real `plan()`/`drift()` against a recording connection issues SEVEN statements under three bounds — 7 x 1.5s = 10.5s against a declared 3.0s budget, every bit of it inside the probe's own 25s `timeoutSeconds`, so nothing downstream would have reported it. `WithinTheDeadline` re-applies the bound before every statement from one deadline; the worst case is now the budget, and the probe is REFUSED partway rather than answering late. * `project_repositories.remote_url` was free text with nothing judging it, so `https://ci:hunter2@github.com/o/r.git` was a legal row — stored in the clear in a database RULING Q1 gives identity and coordination and not secrets, returned verbatim to every member of the project, and handed to `git` by § 3.6. Refused at the store, which is the column's only writer, and REDACTED at the JSON boundary and in the object's own `repr` for a row that got in some other way. `config.credential_in_a_remote_url` judges the two shapes git accepts and calls an ordinary `ssh://git@host/…` clean, because its userinfo is a username and not a secret. * The description's stale figures are already reconciled: it names `2e400a4a`/`b9bc316` with 196 and 317, which is what the workflow block says. The figure below moves them again, at this commit. Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`2c3e9bae` is the commit that was measured: 197 passed 1 skipped on the required job's own five modules with the runtime extra unimportable, and 320 on `pytest -q tests_runtime/` with a database. The PR description states the same two numbers at the same commit — a count here and a count there must not be two different heads' answers. Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate review findings remain, along with a coverage-count reconciliation issue.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (4)
.github/workflows/validate.yml:1061
- The workflow records the current full-suite figure as 320 here, while the PR description says the current head is 317 passed (and says the description and workflow carry the same head/count). Please reconcile the measured count and head before landing; otherwise the review record is internally inconsistent about which runtime coverage actually ran.
# THE CURRENT FIGURE; the PR description states it at this
# same commit, and `pytest -q tests_runtime/` is 320 here.
src/opendox/runtime/cli.py:434
cmd_migratepassesserved_schemainto the runner, butMigrationRunner.plan()only reads the ledger and does not callrefuse_a_schema_the_api_will_not_read; that guard is only reached byapply(). WithOPENDOX_SERVED_SCHEMAdifferent from the migration DSN's selected schema,runtime migrate --plantherefore reports a successful pending plan even though the actual migration will refuse. Run the same schema preflight before emitting the preview (or makeplan()enforce it) so--plandescribes an executable run.
evidence = {"verb": "migrate",
"planned": [m.version for m in runner.plan()],
"applied": []}
src/opendox/runtime/config.py:248
_SECRET_PARAMETERis a raw substring alternation, so a non-secret parameter such asmonkey=1matcheskeyand makes an otherwise valid explicit JWKS URL refuse as credential-bearing (the same false positive affects remote URLs). Match decoded parameter names against the declared credential names as whole names, rather than using.search()on substrings.
_SECRET_PARAMETER = re.compile("|".join(SECRET_PARAMETER_KEYS), re.IGNORECASE)
src/opendox/runtime/identity.py:795
bytes_before < budgettests only the sum of preceding rows, so it admits the current row even when that row pushes the response overMAX_PAGE_BODY_BYTES. For example, two legal 600 KiB drafts are both returned (the test explicitly expects that), producing about 1.2 MiB for a 1 MiB budget; two maximum-sized drafts can produce about 2 MiB. If this constant is intended to cap fetched response bytes, include the current row in the predicate while retaining an explicit first-row exception for oversized drafts; otherwise rename/document the actualbudget + one rowbound.
" select d.id, coalesce(sum(octet_length(d.body)) "
" over (order by d.id rows between unbounded preceding "
" and 1 preceding), 0) as bytes_before "
" from drafts d "
- Files reviewed: 37/39 changed files
- Comments generated: 1
- Review effort level: Lite
…d `key` matched `monkey`
The review submitted at this branch's own head, read after the five threads
were answered. Three findings, all FACT, all measured against `056d1597`.
* `runtime reset` — the one verb that cannot be undone — never asked the
served-schema declaration, and `runtime migrate --plan` did not either.
A25-3's guard was a METHOD reached from `apply()` alone. MEASURED at
`056d1597` with a migration DSN selecting `t_35e6…` and
`OPENDOX_SERVED_SCHEMA=somewhere-else`: `--plan` printed
`planned: ['0001','0002']` for a run `apply()` would refuse, and a confirmed
`reset` exited 0 having DROPPED the table in a schema the declaration says
the API does not read. The guard is module-level now, with one definition
and three callers, and its last clause reads "nothing has been changed"
because a refused reset has not applied anything either.
* `_SECRET_PARAMETER` was an alternation asked with `.search()`, so a
parameter name that merely CONTAINED a credential word matched. Measured at
`056d1597`: `monkey`, `sigma`, `tokenizer`, `authority`, `keyspace` and
`keyboard` all matched, and `redacted_url("…?monkey=1")` returned
`monkey=<redacted>` — a false refusal at the configuration boundary, where
the cost is an install that will not start for a reason that is not true.
The name is split into words (non-alphanumeric runs and camelCase
boundaries) and compared whole, so `access_token`, `X-Api-Key` and
`sessionToken` still match and the declared list is unchanged — the sibling
PR pins the two spellings of that list together.
* The 320-vs-317 reconciliation was already done: the description and this
workflow both name `2c3e9bae` with 197 and 320.
Left as it stands, with the reason: the drafts page budget bounds what
PRECEDES a row (`bytes_before < budget`), so a page can carry the budget plus
one row. That is deliberate and documented — the budget bounds what is
fetched before a row is decided on, the page stays a PREFIX so `after`
pagination is unchanged, and a draft larger than the whole budget is still
returned rather than being unreachable.
Lane: openxfactory-4 (openXfactory-4-openDox_extraction)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`61ab857c` is the commit that was measured: 198 passed 1 skipped on the required job's own five modules with the runtime extra unimportable, and 322 on `pytest -q tests_runtime/` with a database. The PR description states the same two numbers at the same commit. Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Critical database identity checks and additional moderate findings remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (10)
deploy/compose/init-runtime-role.sh:84
- When
OPENDOX_MIGRATION_PG_USERis set to an alternate owner, this is the only first-start hook in the bundled Compose database and it checks that role before creating the served role; a fresh volume therefore fails initialization because the alternate owner has no provisioning path in this stack. The setting is documented as usable in.env.example, so either provision that owner in an earlier init step or make this option explicitly managed-database-only and reject it for the bundled path.
if ! psql -tAqX --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \
-v owner="$migration_owner" \
-c "select 1 from pg_roles where rolname = :'owner'" | grep -q '^1$'; then
echo "init-runtime-role: OPENDOX_MIGRATION_PG_USER names '$migration_owner'," \
"which this database does not have. The bundled first start creates the" \
docs/runtime.md:542
- The re-run command is hard-coded to the
devoverlay even though this section has just instructed a managed-database install. Following it for that install reintroduces the bundled Postgres resources and loses the managed overlay's deletions/configuration, so a Job retry can change the deployment shape instead of merely recreating the migration Job. Make the re-run use the same overlay selected for the initial install, with separate dev and managed commands if necessary.
if kustomize build deploy/kubernetes/overlays/dev | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
else
kustomize build deploy/kubernetes/overlays/dev | kubectl apply -f -
fi
docs/runtime.md:266
- This branch only prints an error; because
echosucceeds, the pasted/automated block exits 0 even though it deliberately skippedkubectl apply. A caller can therefore record a successful install with no workload applied. Exit nonzero after the diagnostic so the placeholder guard is a refusal.
elif kustomize build deploy/kubernetes/overlays/dev | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
docs/runtime.md:500
- This branch only prints an error; because
echosucceeds, the pasted/automated block exits 0 even though it deliberately skippedkubectl apply. A caller can therefore record a successful install with no workload applied. Exit nonzero after the diagnostic so the placeholder guard is a refusal.
if kustomize build deploy/kubernetes/overlays/managed-database | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
docs/runtime.md:539
- This branch only prints an error; because
echosucceeds, the pasted/automated block exits 0 even though it deliberately skippedkubectl apply. A caller can therefore record a successful install with no workload applied. Exit nonzero after the diagnostic so the placeholder guard is a refusal.
if kustomize build deploy/kubernetes/overlays/dev | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
src/opendox/runtime/cli.py:719
runtime resetloadssettings.served_schemabut never invokesMigrationRunner.refuse_a_schema_the_api_will_not_read; it immediately selects the migration connection's schema and drops its tables. In a shipped deployment where the migration DSN selects a different schema than the served declaration, the confirmed reset can delete the wrong coordination state. Run the same served-schema guard onlockbefore selecting/dropping the schema.
# into DDL, and the schema is reported in the evidence so
src/opendox/runtime/cli.py:434
--planonly runs the canonical digest check; it does not apply theserved_schemaguard that the realapply()path runs before mutating anything. A migration DSN aimed at the wrong schema can therefore produce a successful plan that the immediately-followingmigratecommand will refuse, misleading the operator about what will be applied. Check the declaration and calculate the plan on that same connection before emitting it.
# AND THE SERVED-SCHEMA GUARD RUNS HERE TOO. It lived in
# `apply()` alone, so `--plan` printed a plan for a run that
src/opendox/runtime/config.py:620
str.isdigit()accepts non-ASCII code points such as², butint("²")raises a rawValueError. Consequently a malformed integer setting can escape_positive_intwithout the promisedConfigurationErrornaming the setting (andload_settingscallers that handle onlyConfigurationErrorbreak). Restrict this check to ASCII digits and add a regression for a Unicode digit.
#: would make the setting meaningless rather than merely large.
src/opendox/runtime/migrations.py:484
unquoted_identifier()has already erased whether this entry was a quoted identifier, so a real schema named$useris treated as PostgreSQL's special$usertoken. If that literal schema iscurrent_schema()while the role-named schema exists but lacksUSAGE, this branch adds the role schema toskippedand can reject a valid connection even though the literal entry answered; preserve the token-versus-identifier distinction before applying this exemption.
(_unquoted(entry) for entry in _path_entries(path)) if entry]
skipped: list[str] = []
user_entry: int | None = None # `"$user"`'s position in `skipped`
for entry in configured:
if entry == "$user":
tests_runtime/test_runtime_surface.py:56
EXTRA_TOP_LEVEL_NAMESis not the runtime extra's complete import closure; it omits transitive top-level modules such asanyio,starlette, andtyping_extensions. If a stdlib-only runtime module imports one of those, both the AST and subprocess checks remain green because they intersect only this hand-curated subset, so the advertised stdlib-only contract can regress undetected. Check all non-stdlib modules or derive the runtime dependency closure instead.
- Files reviewed: 37/39 changed files
- Comments generated: 2
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
One or more issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (6)
deploy/kubernetes/base/migration-job.yaml:18
- The manifest repeats a re-run command hard-coded to
overlays/dev. That is wrong for the shipped managed-database overlay: deleting and recreating this Job withdevcan bring back the bundled Postgres and use different connection/configuration resources. The re-run instructions need to preserve whichever overlay created the Job.
# kubectl -n opendox delete job opendox-migrate --ignore-not-found
# kustomize build deploy/kubernetes/overlays/dev | kubectl apply -f -
docs/runtime.md:542
- This re-run recipe is always built from
overlays/dev, even though the preceding section explicitly supportsoverlays/managed-database. Following it for a managed install recreates the bundled Postgres/OIDC resources and can point the migration Job at the wrong database. The command must use the same overlay selected for the initial install, not a hard-codeddevpath.
if kustomize build deploy/kubernetes/overlays/dev | grep -q 'opendox-runtime:0\.0\.0'; then
echo 'the image is still the placeholder 0.0.0; this apply would ImagePullBackOff' >&2
else
kustomize build deploy/kubernetes/overlays/dev | kubectl apply -f -
fi
docs/runtime.md:195
read -rssucceeds for an empty line, so this accepts an empty superuser password. The official Postgres image refuses to initialize without a non-empty superuser password, meaning the Secret creation can succeed and the StatefulSet then fail on a clean install. Reject empty input here as well as failed input.
if ! read -rs -p 'postgres superuser password: ' pw; then
echo 'no superuser password was read; nothing is created' >&2; exit 1
fi
docs/runtime.md:199
read -rsalso succeeds for an empty line here, so the block writes a zero-byteruntime-password.init-runtime-role.shexplicitly refuses an emptyOPENDOX_RUNTIME_PG_PASSWORD, leaving this install with a successfully-created Secret but no served role; the prompt must reject empty input before writing the file.
if ! read -rs -p 'served role password: ' rpw; then
echo 'no served-role password was read; nothing is created' >&2; exit 1
fi
src/opendox/runtime/config.py:649
str.isdigit()accepts characters such as²thatint()cannot parse. WithOPENDOX_*set to such a value, line 649 raises a rawValueErrorinstead of the promisedConfigurationErrornaming the setting, so the lifecycle commands lose their normal configuration refusal; use a decimal-digit check or catch the conversion error.
if not raw.isdigit():
raise ConfigurationError(
f"{setting.name} must be a whole number written in digits, not "
f"{raw!r}: {setting.purpose}")
value = int(raw)
src/opendox/runtime/config.py:1008
database_named_by()returnsNonewhen no explicitdbnameis present, but libpq can derive the database from the connection user (or aserviceprofile). Thus served and migration DSNs such asruntime@.../andmigrator@.../compare asNone == Noneeven though they may connect to different databases, allowing migrations/readiness and API traffic to split across databases. Resolve the effective database or reject indirect/unknown database selection before accepting this pair.
mine, yours = database_named_by(served), database_named_by(migration)
if mine != yours:
- Files reviewed: 37/39 changed files
- Comments generated: 2
- Review effort level: Lite
My own defect, from the batch two commits ago, and the review at `0968ff8b` found it. `credential_in_a_remote_url`'s scp branch read the text before the FIRST `/` — the shape of an scp-like authority — so a password holding one fell outside the window: measured at `0968ff8b`, `ci:hun/ter2@github.com:o/r.git` was called clean, the store accepted it and `redacted_remote_url` returned it unchanged, which is the API handing a password to every member of the project. It is round 29's shape on the sibling PR — a bound that excluded `/` defeated by a password holding one — and it takes the same answer: the last `@` in the WHOLE value, with the over-detection stated rather than hidden. A local path that really contains `:`…`@` before its last component is refused with its own name; a value carrying WHITESPACE is left alone, so this cannot start eating prose. `_scp_like_userinfo` is one definition and the predicate and the redactor both ask it, which is what keeps them agreeing. The figures do not move: the shape is a new carrier in the existing case, not a new case. 198 passed 1 skipped hermetic and 322 full, the same two numbers `61ab857c` recorded. Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
One or more issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (9)
Previously missed (1) — in code that hasn't changed since the last review.
src/opendox/runtime/identity.py:796
- This running window is evaluated before the inner
LIMIT, so the row cap bounds the response but not the database work: a user with many matching drafts can still make PostgreSQL scan and size the entire candidate set on every page. Select the ordered candidate IDs with the row limit first, then calculate the byte budget and join bodies for those rows; otherwise this page can become an unbounded cost despite the advertised cap.
deploy/compose/docker-compose.yaml:141
- Changing
OPENDOX_PROJECT_REPOSITORY_ROOTto any non-default absolute path makes this named volume target a directory the image never creates or chowns. The container runs asopendox, so on a clean volume repository creation cannot write there even though the environment setting and mount both follow the custom value; either constrain this setting to the pre-created path or initialize/chown the configured mount before serving.
- project_repositories:${OPENDOX_PROJECT_REPOSITORY_ROOT:-/var/lib/opendox/projects}
deploy/kubernetes/base/migration-job.yaml:206
- This migration workload declares only the served schema, so the served database is still unchecked. The Job receives only
OPENDOX_MIGRATION_DATABASE_URLwhile the Deployment receives onlyOPENDOX_DATABASE_URL; if those Secrets name different databases but the same schema, the Job applies and verifies one database while the API and readiness use the other. Add a non-secret served-database declaration and compare it before bootstrapping, wiring the same setting through configuration and the other deployment shape.
- name: OPENDOX_SERVED_SCHEMA
valueFrom:
configMapKeyRef:
name: opendox-runtime-config
key: pg_schema
src/opendox/runtime/app.py:445
- Using a plain
Header()dependency authenticates requests at runtime but does not declare an HTTP bearer security scheme in FastAPI's OpenAPI document. WhenOPENDOX_PUBLISH_OPENAPI=true, generated clients will see these operations as unauthenticated and omitAuthorization, even though every collection returns 401 without it. Use a bearer security dependency (while preserving the custom 401 shape) or explicitly add the security requirement to the generated schema.
def get_principal(
request: Request,
store: Annotated[Any, Depends(get_store)],
authorization: Annotated[str | None, Header()] = None,
) -> identity.User:
src/opendox/runtime/config.py:950
- When neither DSN includes an explicit database name, this helper returns
Noneand_refuse_two_dsns_that_select_different_schemastreats the pair as agreeing. Libpq's default database is derived from the connection user, so distinct served and migration users can validly land in different databases while both values compare asNone; migrations can then verify one database while the API reads another. Resolve the effective database (or require explicit names) before accepting the pair, and add a regression test.
def database_named_by(dsn: str) -> str | None:
"""The DATABASE a DSN names, or `None` where it leaves it to the default.
src/opendox/runtime/config.py:945
$useris a dynamicsearch_pathtoken, not a literal schema name. Returning it here makes served and migration DSNs with different users compare equal even though PostgreSQL expands the token to different user schemas, bypassing the schema-split guard. Treat dynamic entries as unresolved and fail closed (or require an explicit first schema) rather than comparing the token as a schema name, with a regression test.
entries = search_path_entries(setting.split("=", 1)[1])
effective = unquoted_identifier(entries[0]) or None
return effective
src/opendox/runtime/config.py:670
str.isdigit()accepts characters such as the superscript², butint("²")raisesValueError; that bypasses the promisedConfigurationErrorboundary and makes an invalid environment value escape as a traceback/evidence failure. Validate ASCII decimal digits (or catch the conversion) before callingint().
if not raw.isdigit():
src/opendox/runtime/migrations.py:839
- The ledger bootstrap is committed before the initial
protect_ledgercall. If narrowing fails (for example because the configured runtime role owns the ledger or is otherwise impossible to revoke), the protection transaction rolls back but the already-committedopendox_schema_migrationstable remains in a run that the comment says applies nothing. Keep bootstrap and the precondition narrowing in one atomic unit, or otherwise remove the ledger on this refusal, and add a fresh-schema regression.
self.bootstrap_ledger(lock)
lock.commit()
# THE LEDGER IS NARROWED BEFORE ANY MIGRATION RUNS, not after. When
# this came last, a misconfigured `runtime_role` failed the run only
src/opendox/runtime/migrations.py:957
- The access preflight checks schema and table privileges but never checks
CONNECTon the database. A managed-database setup can therefore pass this check after granting schema/table rights while the served role still cannot open a connection; the migration succeeds and/readyz/API fail later. Include the database-level connect privilege in the preflight or make that prerequisite an enforced check.
usable = conn.execute("select has_schema_privilege(%s, %s, 'usage')",
(self._runtime_role, schema)).fetchone()
if not usable or not usable[0]:
raise RuntimeAccessMissingError(
f"{self._runtime_role!r} has no USAGE on schema {schema!r}, so "
- Files reviewed: 37/39 changed files
- Comments generated: 2
- Review effort level: Lite
| # (independent adversarial review of openDox-code#25, A25-3). The SAME | ||
| # `.env` value the Postgres service grants in, so one edit moves the | ||
| # schema, its grants and this refusal together. | ||
| OPENDOX_SERVED_SCHEMA: ${OPENDOX_PG_SCHEMA:-} |
| - name: OPENDOX_DATABASE_URL | ||
| valueFrom: | ||
| secretKeyRef: | ||
| name: opendox-db-runtime | ||
| key: dsn |
…"$user"` token The third mini-batch, RULED by Brett Heap ~17:55Z on openxFactory#656: the two security-relevant findings of the round at `0968ff8b`, one test each, every premise measured on postgres 16 and through `PQconninfoParse` rather than argued. * TWO DSNs THAT NAME NO DATABASE DID NOT NAME THE SAME ONE. `database_named_by` reports what the STRING says, so a pair that both leave the database out both answered `None` and the preflight read that as agreement. libpq defaults `dbname` to the CONNECTION USER, and this deployment's two DSNs carry deliberately different users — the privileged migration identity and the least-privileged served one, which is the whole point of the split. MEASURED: `postgresql://opendox:…@host:5432/` connects and `select current_database()` answers `opendox`. `effective_database` resolves `dbname`, else the user; and with NEITHER in the string the answer is UNRESOLVED and the pair is refused, because libpq then falls back to the operating-system user of whichever process connects and the two DSNs are used by two different containers. That is the contract the guard already has — it answers before anything connects, so a comparison it cannot make is a refusal, exactly as for a broker URL it cannot parse. Resolving it AFTER connecting was the alternative and is not available to a configuration-time check without a network. * `"$user"` IS A TOKEN AND WAS COMPARED AS A LITERAL, so two roles' DSNs both selecting `"$user",public` agreed on the string while PostgreSQL resolved them to two different schemas. `effective_schema` substitutes the DSN's own user, as the server does, and the token with no user in the string is UNRESOLVED rather than "names no schema" — reading it as the latter would have compared equal to a DSN that really names none, which is the same false agreement one step along. MEASURED on postgres 16, three ways: `search_path = "$user", public` with no matching schema gives `current_schema() = public`; WITH A SCHEMA LITERALLY NAMED `$user` it is STILL `public`; and with a schema named for the session user it is that schema. PostgreSQL never reads `"$user"` as a schema NAME, even when one exists — which also measures FALSE the suppressed finding at `migrations.py:484` that a real `$user` schema is mistaken for the token. (`set search_path = $user` unquoted is a syntax error; the token is always written quoted.) At `68ebea49` the guard ACCEPTED three of the four shapes these cases forbid; the fourth was refused for the wrong reason. `user_named_by` is new and reads a NAME, never a credential: the user name is in every server log line, in `pg_stat_activity` and in a committed ConfigMap, and nothing here touches the password. REGISTERED, NOT BUILT — a follow-up act under the same claim: the served DATABASE has no non-secret declaration, only the served schema (`deploy/kubernetes/base/migration-job.yaml:206`). `OPENDOX_SERVED_DATABASE` on A25-3's precedent, checked against `current_database()` before the ledger is bootstrapped, plus four manifest edits. Ruled a separate act, not this one. Erratum, carried from the sibling PR: the commit recording openDox-code#26's `7ed5ee26` figure names it `7ed5ee2b` in its own message. The workflow block and that PR's description both say `7ed5ee26`, which is the number that matters. Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`3d587ae8` is the commit that was measured: 200 passed 1 skipped on the required job's own five modules with the runtime extra unimportable, and 324 on `pytest -q tests_runtime/` with a database. The PR description states the same two numbers at the same commit. Lane: openxfactory-4 (openXfactory-4-openDox_extraction) Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
There was a problem hiding this comment.
🔵 Needs a closer look
Two moderate findings remain in migration planning and numeric validation; a documentation nit also remains.
Review details
Suppressed comments (3)
docs/runtime.md:541
- This re-run block is below the managed-database instructions but hard-codes the
devoverlay. Following it for a managed install reintroduces the bundled Postgres resources and dev broker settings instead of reapplyingmanaged-database, so a failed/updated managed migration cannot be safely retried. Make the command use the same overlay selected during the initial install, or provide separate guarded re-run commands for both overlays.
kustomize build deploy/kubernetes/overlays/dev | kubectl apply -f -
src/opendox/runtime/cli.py:443
--planonly runsrunner.plan(), which discovers filenames and consults the ledger but never decodes the migration bytes. A pending0002_*.sqlcontaining invalid UTF-8 is therefore reported inplanned, while the realapply()refuses it insnapshot_run()before any mutation; the preview is not an executable plan. Preflight the samesnapshot_run()/decode validation before emitting the plan (and surface itsMigrationErroras the refusal).
planned = [m.version for m in runner.plan(conn)]
src/opendox/runtime/config.py:670
str.isdigit()accepts characters such as the superscript², butint("²")raisesValueError. That lets an invalid numeric environment value escape_positive_intas a raw exception instead of the promisedConfigurationError, so configuration loading/CLI handling is inconsistent. Restrict this check to ASCII digits before callingint().
if not raw.isdigit():
- Files reviewed: 36/39 changed files
- Comments generated: 0 new
- Review effort level: Lite
Registered, not taken — the review at the landed-candidate head
|
|
Lane: openxfactory-4 (openXfactory-4-openDox_extraction) LANDED — lane openxfactory-4, 2026-09-18T18:15:46Z, PR #25 → aca94ec (opensoft/openDox-code main; plain gate) § 3.5 runtime: config guard + served-schema declaration; adversarial rounds A25-1..5, batches 1–3 (absent-dbname refusal, $user expansion); three suppressed Copilot findings registered for the follow-up |




Lane: openxfactory-4 (openXfactory-4-openDox_extraction)
CLAIM: 5699629780
Refs #656 (stays OPEN).
§ 3.5 — the openDox runtime: FastAPI + Postgres, identity and coordination, and nothing else
openspec/changes/split-opendox-two-layer-product/tasks.md§ 3.5 at openxFactorymain.The two rulings this realizes, in their own words
What this PR does
migrations/, at the root of this leg — § 3.5's own sentence is "all at the root ofopenDox-code, not of the assembly root", andtests_runtime/test_migration_shape.pyasserts it.0001_identity_and_coordination.sql— RULING Q1's six tables, in the ruling's own list, CLOSED:users,memberships,projects,project_repositories,sessions,drafts. It is byte-pinned:opendox.runtime.migrations.CANONICAL_MIGRATION_SHA256declares its digest, the runner verifies it before any mutation and refuses the whole run on a mismatch, and a test hashes the file against the constant on everyvalidate. Changing the schema is an additive0002_…file; moving the pin is a two-file act somebody has to mean.0002_migration_state.sql— the ledger, additive, and the reviewable copy of the DDL the runner bootstraps (create table if not exists, because the ledger has to exist before 0001 can be recorded). A test asserts the two texts are identical.src/opendox/runtime/— one new subpackage, eight modules.config(every setting an env var named indeploy/compose/.env.example; no credential default; a redacting__repr__),migrations(the fail-closed runner),identity(the six tables, one store, SQL composed only from module-level constants with every runtime value a%sparameter),db(the psycopg pool and the unit of work),oidc(verify against the broker's JWKS; issue nothing),app(the six collections),cli(the lifecycle verbs).The API.
/api/v1/{users,memberships,projects,project-repositories,sessions,drafts}— the closedCOLLECTIONStuple, read against the routersbuild_v1_routeractually mounts. The unauthenticated surface is/livezand/readyz, and it is exactly those two — both orchestrator probes, because a liveness probe that needed a bearer token would need the broker to be up in order to discover that the broker is down, and a readiness probe that needed one could never report an unreachable database. They return no row, no id and no document. FastAPI's defaults would have published/docs,/redocand/openapi.jsonas well; those are OFF unlessOPENDOX_PUBLISH_OPENAPIsays otherwise, andtests_runtime/test_api_endpoints.pyENUMERATES the running app's unauthenticated routes against that list rather than trusting this sentence. Everything else resolves a bearer token to anidentity.Userrow and then asksmemberships.roleabout that row — and the store is opened LAZILY, so a request refused at the header touches no database connection at all.Design § D5's inversion is where the act is largest, and it is executed rather than described. "Two current requirements say in terms that the dashboard authorizes nothing on the hosted actor and that identity presence changes no capability verdict — write authority today is a property of WHERE the request came from (a loopback console verdict), not WHO sent it. Q1 and Q2 together invert that: an account is a durable row, authentication delegates to the Keycloak broker, and authorization stops being a property of the request's origin. This is the largest conceptual change in the rulings and the easiest to under-read." So: a first login WRITES the user row; there is no loopback exemption and no header that stands in for a token; and
test_every_collection_refuses_an_unauthenticated_requestruns an in-process client — the loopback case — and is refused 401 like any other.One lifecycle CLI.
opendox-runtime runtime init | migrate | serve | status | reset. Every verb prints one redacted JSON evidence object and exits nonzero on a refusal; no DSN, token or password is ever printed.resetneeds the spelled phrase--confirm yes-drop-the-coordination-database, and it can exist at all only because of RULING Q1's last sentence.deploy/compose/anddeploy/kubernetes/, on the Hermes install's shapes. The migration identity and the served identity are separate in both, andconfig.migration_database_urlrefuses to fall back from one to the other, so the separation is enforced in code as well as declared. No service publishes a host port. Every Secret is committed by name and key and never by value;tests_runtime/test_deploy_shape.pyrefuses akind: Secretanywhere underdeploy/kubernetes/.docs/runtime.md— the runbook, including a table of which suite runs where and why.Why the seam decision is what it is (this is the one choice a reviewer should check)
The verbs are not registered in
opendox.cli.build_parser, and the tree points three ways about that, sosrc/opendox/runtime/cli.py's header writes it down:src/subcommand_extension.pyis for a layer above contributing a subcommand — that is openXdox, and the runtime is not that layer;src/opendox/cli_project.pystates the counter-rule for openDox's own verbs in terms: "FIXED CORE, NOT AN EXTENSION … these verbs are registered bybuild_parserdirectly";src/opendox/cli.pyis a CARVED file with a row in openxFactory's manifest, so a line added to it is a declared edit that lands at openxFactory first — a different act with a different claim. Andopendox.clicannot be imported at this leg at all: it reachesopendox.serve, whose line 192from ideation_dashboard import serve_openxfactory_lanesexists at neither carve destination, whichtests/test_consumer_reach.py::STILL_REACHINGrecords by name and RULED Q-L5 (b′) leaves to the BUILD arc.So this act ships both spellings and neither is a fork:
[project.scripts] opendox-runtimeruns the verbs today, andRuntimeSubcommandwraps the same registration function in an object that structurally conforms tosubcommand_extension.SubcommandExtension(asserted withisinstance). The dayopendox.cliimports, wiring them into the core parser is one line at the assembly point and no verb is re-authored.What this PR does NOT do — residue, by name
opendox.servestill cannot import at this leg. Nothing inopendox.runtimedepends on that being repaired: the runtime imports no part ofopendox.serve, and the two are joined only by the project-to-repository map row.GET /project-repositories/{id}→ 404), which is the shape § 3.6's act fills.draftsis the draft of a document and is not that scratch space. Recorded indocs/runtime.md§ 9 and here.runtimeCI job is not a required check. Making one required is a repository setting (docs/branch-protection.md), a separate act with a separate owner; the gap is named in the workflow rather than assumed away.xFactory-Hermes-Install, each for a reason (all four recorded at the seam that would have carried them): its three-layer Subject/Tenant/Domain topology and itslayertoken claim — openDox is single-layer, so that would be a shape without a meaning; its worker-readiness surface; its correlated backup job; and itsuv.locksupply-chain pin, whichpyproject.tomlalready records as a real act with a real owner rather than something a § 3.5 PR should invent.The arrival floor
Measured:
scripts/verify-carve-arrival.py::declared_rootsoverrows_for(manifest, "opendox_code")(119 effective rows) returns exactly['src/opendox', 'tests']. Somigrations/,deploy/,docs/runtime.md,pyproject.toml,.gitignore,.github/and the newtests_runtime/tree need no admission (under_rootsis segment-aware — "tests_helpers/x.pyis not undertests"), and the eight files undersrc/opendox/runtime/each need one. Those rows are openxFactory PR opensoft/openxFactory#1067, which lands first per RULED Q-L1.CI, and why it is split
.github/workflows/validate.ymlis append-only againstmain—git diff --stat: 99 insertions, 0 deletions, one hunk at@@ -323,0 +324,99 @@. Nothing above line 323 is touched, so this cannot collide with openDox-code #24, whose only hunk in this file is inside the comment block at lines 91–147.validatejob runs the hermetic suites under that job's existingpip install -e ".[test]"— no FastAPI, no psycopg, no PyJWT. That is the package's declared import-weight contract, andtests_runtime/test_runtime_surface.pymeasures it two ways: an AST walk for module-level imports, and a fresh interpreter that imports the stdlib-only modules and reports any extra distribution that ended up insys.modules.runtimecarries apostgres:16service (the Hermes install's own CI shape) andpip install -e ".[runtime,test]"for everything that needs a database, a token or a web framework. WhereOPENDOX_TEST_DATABASE_URLis unreachable a developer's tree skips with the reason printed — never a silent pass, never a red tree for somebody without Postgres — and in CI the same absence FAILS: pytest exits 0 when every collected case is skipped, so a job whosepostgres:16service failed to start reported green having made no database-backed assertion at all. The job supplies the service, so its absence there is the job's own defect (conftest._skip_or_fail, round 5).Measured (python 3.12.3, pytest 8.4.2, postgres 16.15)
Every figure below was measured at
3d587ae8— with theruntimeextra made UNIMPORTABLE, which is the required job's own install — and holds at the current headabc7f634, which adds only the workflow's record of it and names the command that produced it. A count in this table and a count in the workflow's own comment block must not be two different heads' answers — Copilot's review of #26 was right about that, and both places now say which head they mean.validatejob's own invocation (--noconftest, the five hermetic modules that job names)python -m pytest -q tests_runtime/withOPENDOX_TEST_DATABASE_URLset (theruntimejob's invocation)python -m pyflakes src/opendox/runtime/*.py tests_runtime/*.pyyaml.safe_loadover.github/workflows/validate.yml['validate', 'runtime']The one skip, named rather than left to be found. It is the live reproducer for round 26's credential leak: it needs
psycopgto make libpq quote an unparsable DSN back, and the required job installs.[test]alone. The property it proves — that the probe never interpolates the exception's text — is measured beside it against a stub driver that raises with the DSN in its message, and that case runs in the required job. A suite that skipped a contract silently is the thing this act refuses; a skip that names the driver it wants and points at the case that covers it anyway is not that.The figures moved with every review round, which is why they are stated with a head.
72 → 93 → 97 → 101 → 102 → 106 → 108 → 109 → 111 → 111 → 118 → 122 → 126 → 128 → 130 → 132 → 132 → 132 → 132 → 135 → 138 → 139 → 141 → 142 → 144 → 145 → 153 → 162 → 167 → 167 → 167 → 171 → 173 → 173 → 174 → 181 → 184 → 196 → 197 → 198 → 200on the required invocation and115 → 160 → 173 → 180 → 184 → 189 → 192 → 194 → 196 → 197 → 211 → 216 → 223 → 227 → 230 → 232 → 235 → 236 → 236 → 240 → 245 → 246 → 248 → 249 → 251 → 252 → 262 → 272 → 277 → 279 → 280 → 286 → 288 → 289 → 291 → 298 → 301 → 317 → 320 → 322 → 324on the full suite: each rise is assertions added to answer a finding, never a suite widened to look busier.Review round 4 (Copilot review
5225498056at45bb29c5) — eight findings, all fixedGET /users,GET /memberships,GET /projectsand both project-repository reads authenticated and then returned the whole install, so any signed-in account could enumerate every user's issuer/subject/email and every project's repositorylocationandremote_url. The scope is now the MEMBERSHIP ROW, applied in SQL; a row the caller may not see is 404 for a user and 403authz.not_a_memberfor a project — which is also what an id that exists nowhere gets, so the pair is not an existence oracle.apply()heldMIGRATION_LOCK_KEYon one connection and did the bootstrap, the ledger read and every migration through another; a pool of one deadlocked. Every statement now goes through the lock's own connection, measured withmax_size=1.runtime resethad the identical shape.runtime_rolefailed the run only once everything had committed — and/readyzasks about schema and drift, never grants.defaultMode: 0o555is a string in YAML 1.1 and the API server rejects the StatefulSet before Postgres starts.backoffLimit: 2.list_draftscollected the principal's sessions with one capped query, so a user with more thanMAX_PAGE_SIZEsittings lost the later ones' drafts and was refused its own session by name.POST /membershipscarriedon conflict … do update set role, so a repeat silently changed a role and still answered 201.initreported a valid install when the repository root existed as a file;servewas the one lifecycle verb that printed no evidence on an ordinary shutdown;STDLIB_ONLY_MODULESomitted § 3.6's two modules, so on that branch the import-weight contract skipped exactly the files it exists for.Each fix carries an assertion; the seven suppressed comments of that round are answered one by one in this comment.
Two defects the suites found in this act's own code, both fixed here and both recorded at the seam:
oidc.CachingJwks._load_keysetdid not catchjwt.PyJWKSetError, which is not a subclass ofPyJWKError. A broker serving{"keys": []}— a realm mid-rotation, a misconfigured proxy — would have escaped the typedIdentityUnavailableErrorand surfaced pastapp.get_principal's 401 mapping as a 500.app's dependency callables annotatedrequest: Any. FastAPI reads a dependency's annotations to decide where each argument comes from and takesAnyfor a query parameter, so every route answered422 missing query parameter: requestinstead of authenticating — sixteen cases red on the first run.Review round 6 (Copilot review
5226506490ate9bec395) — four threads and nine suppressed comments, every one answered.env.exampledeclaredOPENDOX_RUNTIME_PG_USER(which created the role) andOPENDOX_RUNTIME_PG_ROLE(which the runtime reads and the migration narrows), and the compose file read only the first — so setting the documented one changed nothing, and setting both differently created one role and narrowed another. One declaration now, and both services interpolate it.revokesucceeds and changes nothing for the ledger's owner, a superuser, or a role holding the write through another grant._narrow_ledgeraskshas_table_privilegefor each of the four writes and raisesLedgerNarrowingIneffectiveErrorwhen one survives; the narrowing is a precondition of the run, so nothing is applied./readyzverifies the pinned0001BEFORE it calculates a plan.discover()returns[]for a directory that exists and is empty, so an image that lost the canonical file madeplan()anddrift()both empty on a fresh database and readiness reportedschema: applied.BodySizeLimitis a pure ASGI middleware: a declaredContent-Lengthover one MiB is refused unread, a chunked body is counted and refused the moment it passes. The cap is declared in the runtime rather than imported, becauseopendox.serve*cannot be imported at this leg (RULED Q-L5 (b′)).timeoutSeconds, a foreign-key race that escaped as a 500 instead of the documented 404, a discovery regex broader than the filename contract, and animportorskipthat let theruntimejob pass without exercising a single OIDC or API case.Residue this act records rather than resolves (round 6)
current_user. The runner now refuses a narrowing that changed nothing, and creation, narrowing and the served DSN derive from one.envdeclaration — but a served container that is handed a DSN for some other role is still only caught by the operator's own care. Asserting it in the process needs the role name configured on the served container too, which is a new setting and a separate declared act.Review round 7 (Copilot review
5226856961at51cfff71) — three threads and nine suppressed comments, every one answeredapply()run and COMMIT the first and fail on the ledger's key for the second — the partially applied run the runner exists to prevent.discover_migrationsrefuses the directory by name, before anything is mutated, for every caller.opendox_runtimewhile the Job readruntime_pg_role. Both read the same ConfigMap key now — the Kubernetes half of the one-name rule the compose package got in round 6.%I, so a configuredMyRolehad its revoke and grant folded tomyrole: a different role, or none. Quoted here, and measured against a genuinely mixed-case role.migrate --planskipping the canonical gateapply()runs first,statusreporting pending migrations and staying healthy (and now running that same gate, because an empty directory otherwise reads as "nothing pending"),statusblaming the database for a failure of the TREE, animportorskipthat let the API suite skip in CI, and a filename assertion broader than the runner's own regex.Review round 8 (Copilot review at
392fd143) — two threads, both fixedservecould not tell "served and stopped" from "never started".uvicorn.rundoes not propagate a lifespan startup failure — uvicorn logs it and the loop returns — so the verb emittedok: trueand exited 0 for a process that never served a request. An explicituvicorn.Server(uvicorn.Config(...))runs, andserver.starteddecides which evidence is emitted.0000_*.sqland discovery only ordered and de-duplicated, so such a file ran BEFORE the pinned0001— mutating the database after the digest gate passed and before the schema that digest pins existed.And a rule this round proved twice. Round 7's preview test passed in a developer's tree and went RED in the required job, because the gate it asserted sat behind the deferred driver import. The gate moved ahead of that import (asking about the TREE needs no driver), and the hermetic figure is now measured with
psycopg,psycopg_pool,fastapi,uvicornandjwtmade unimportable — the required job's own install. A figure measured with the extras present is not that job's figure.Review round 9 (Copilot review at
392fd143) — three threads, all fixedkeysettook in round 5, in the method beside it. A caller queued behind a forced refresh — which holds the lock for a whole fetch — was refused a refresh the cooldown had already allowed, so a real key rotation went unseen until the next miss.CachingJwks(ttl_seconds=...)is annotatedfloat: the arithmetic is float throughout and the suites cross TTL boundaries on purpose.DROP_ORDERnames the ledger throughmigrations.LEDGER_TABLErather than spelling it twice — the one moment two spellings differ is a rename, after whichresetwould drop six of seven tables and report all seven.Review round 10 (Copilot reviews
5227436293atab7f2110and5227525961at6e09fbe5) — twelve findings: eleven fixed, one answered by citationClassified before anything was touched, as this act now does every round — FIX (a real defect here: fix plus a test that fails against the old shape), REPEAT (already answered on this PR: cite, resolve, change nothing), OUT OF SCOPE (a behaviour no ruling ordered: answer by measurement, register, resolve). This round: 11 FIX, 1 REPEAT, 0 out of scope.
Three writes that could lose a race, each a claim the code did not keep:
require_open=Trueis a promise about the WRITE, and the route's check and the upsert were two statements — aDELETE /sessions/{id}committing between them wrote the draft anyway. The session-open predicate now travels IN the insert (insert … select … where exists (… ended_at is null)), so the promise is kept by one atomic act rather than by the interval between two. The ordinary refusal is unchanged (409coordination.session_closedfrom the pre-check, which still gives the better message); the raced one is 404coordination.not_found.DELETE /drafts/{id}calleddelete_draftdirectly, so a second discard by the owner — or a row gone between the read and the statement — escaped as a 500 instead of the documented coordination 404. Wrapped in_found, like the session-close path beside it.POST /sessionsinserted outside both translations. A project deleted between the membership check and the insert made a raw foreign-key violation escape as a 500.identity.open_sessiongoes through_conflict_if_duplicatenow (SQLSTATE →NotFoundError) and the route through_conflict(→ 404), which is what every other referencing write in this API already did.The existence oracle one step out from the one round 7 closed. Round 7 made "unknown draft" and "another member's draft" one answer — for a member of the project. A caller who was NOT a member still got
authz.not_a_memberfor a draft that exists andauthz.not_your_sessionfor an id that does not, so the id space stayed walkable by anyone with an account. Ownership is asked FIRST now, before authorization is consulted at all, and both questions have one refusal. Asserted byte-for-byte, the way the hidden-user pair already is.The lifecycle contract's loud half. Round 8 closed the silent failure
servecould not report (uvicorn swallows a lifespan error).Server.run()also RAISES —SystemExitfrom uvicorn's ownsys.exit(1)on an occupied port,OSErrorfor an address that is not this host's — and that call sat outside every exception-to-evidence handler, so the verb an operator runs longest answered a misconfigured port with a traceback and no JSON.SystemExitis named explicitly becauseexcept Exceptiondoes not reach aBaseException, and the refusal names the host and port it tried and is redacted like every other message this CLI emits.statusno longer rewrites an answer it already has. Onceselect 1has succeeded the database IS reachable, and a later failure — a served role withoutselecton the ledger, a search path that misses the schema — was reported asdatabase: unreachable, pointing an operator at the network for a privilege problem. It isdatabase: reachableplusschema_queries: failed: …now. Round 7 made exactly this distinction for the runner's ownMigrationErrorand left it unmade in the handler one line below.The managed-database path had no role provisioning at all. The bundled Postgres creates and grants the served role on its first start (
deploy/compose/init-runtime-role.sh); a managed database runs no init script, so the migration owner created the six tables and the served role had no privilege on any of them — the Job succeeded,/readyzreported an applied schema, and every request then failed withpermission denied. Of Copilot's two remedies this took the second, because that role is created out of band with its password anyway and half a provisioning story is worse than a stated one:docs/runtime.mdstates it as an explicit PREREQUISITE with the four statements the bundled script performs, andtests_runtime/test_deploy_shape.pyDERIVES the required list from that script, so the two paths cannot drift apart silently. The narrowing the migration run then applies to the ledger is named there too, so an operator granting everything knows the one exception.Two declared surfaces that were narrower than the code:
migrations's documented connection contract. The docstring promised.execute(...)and the runner also calls.transaction(),.commit()and.rollback()— so a double or an alternative driver written to the documented contract failed withAttributeError. The contract is stated in full (four members), and two hermetic tests hold it: one drives a wholeapply()through a double implementing exactly those four, the other shows the old shorter list raising.CachingJwks(source=…)was annotated as a union of the two sources this module ships, while the cache and the suites only ever ask forload()— the rotation and counting sources intest_oidc_verifier.pyare third implementations already.JwksSourceis aruntime_checkableProtocol now, so the annotation andisinstanceask the same question.The readiness probe's timeout was EXACTLY the sum of the endpoint's budgets (10s database checkout + 5s JWKS) while the comment beside it called that "longer than both budgets together". A worst-case-but-valid request had nothing left for scheduling, latency or writing the response. It is 20s now with
periodSecondsat 30 so a probe still cannot overlap itself, and the test reads BOTH budgets out of the modules that declare them rather than restating them.And two prose defects, fixed rather than argued (both are false statements in landed text, which is the class this act fixes): the deployment's service-account comment was a malformed sentence, and three
tests_runtimedocstrings claimed a narrower import list than their own import block — a hermeticity claim a reader cannot check is the opposite of what those files are for.REPEAT: the JWKS miss cooldown's clock read outside the lock (suppressed at
ab7f2110) was fixed one head earlier, at6e09fbe5— answered on its thread by citation, not re-argued.Erratum, recorded here because this act records them: the commit that recorded the new figure (
cd22da4d) says "eighteen more hermetic cases"; it is seven (111 → 118). The figure itself — 118 atf9c72341— is the same in the workflow block and in the table above, which is the number that matters.Review round 11 (Copilot review
5228860529atcd22da4d) — nine findings: eight fixed, one answered by measurementClassified first, as every round is now: 8 FIX, 0 REPEAT, 1 answered by measurement (a finding whose premise is a description this PR no longer has).
psql -v runtime_password=…puts it in argv, wherepsand a world-readable/proc/<pid>/cmdlinecan read it for the life of the command — the Secret copied out of the Secret store and into a process table, in both copies of the bootstrap.\getenvreads it from psql's own environment now; the role NAME stays an argument, because a name is not a secret. Measured against psql 16 in a live container before it was written:\getenvsets the variable,%Lquotes it, andpg_rolesshows the role created with login.apply()read0001three times — the gate,checksum(), thenread_sql()to execute — so a migrations directory that can change under the process could pass the pin and run something else, with the ledger recording the digest of bytes that did not run. Each migration is read ONCE into a snapshot now: that is what is hashed, what the canonical pin is re-checked against immediately before execution, and what executes.except Exceptionand turns anything it catches into400 "There was an error parsing the body"— so a chunked request over the cap stopped reading at the limit (the memory bound held) and then answered 400 instead of the documented413 request.too_large, unmeasured because the only cap test sent a declaredContent-Length._BodyTooLargeis aBaseExceptionnow, which passes that handler and reaches the middleware — the only frame that can answer for a request whose body it refused..env.example, and the compose file's own inline runbook).docker compose rundoes not build by policy — it is the only one ofrun,upandcreatewith no--no-buildflag, because it has nothing to suppress — and the defaultOPENDOX_IMAGEis the local tagopendox-runtime:local, which no registry has.--buildon that one command;up -dneeds none, and the comment says why.backoffLimit2 → 6, about ten minutes under Kubernetes' exponential backoff.Answered by measurement, no change. The review reports that this description "identifies
6e09fbe5as the current head and reports197 passed" while the workflow saysf9c72341/211. The description saidf9c72341,118and211at the time of that review and says5d86d8b8,132and236now; the sentences naming6e09fbe5are in the round-10 SECTION, where they name the head the reviews under discussion ran at and the head the JWKS cooldown was fixed at. History and current figure are different claims, and the block that carries the figures says in one line which is which.Review round 12 (Copilot review
5229072217at3e524f08) — five findings, all fixedClassified first, as every round is now: 5 FIX, 0 REPEAT, 0 out of scope — three threads and two suppressed comments, every one a real defect in this act's own code, each answered with a test that fails against the shape it forbids.
alter default privilegesis recorded FOR the current role, the first-start script runs as$POSTGRES_USER, and the migration service's DSN is configured separately — so pointing it at another owner (a valid configuration this base documents) meant0001created the six tables with no privilege for the served role at all: the Job succeeded,/readyzreported a reachable database and an applied schema, and every API request failedpermission denied for table …. The grant now names the owner —OPENDOX_MIGRATION_PG_USERin compose, themigration_pg_userConfigMap key in Kubernetes, both defaulting to$POSTGRES_USER, which is today's bundled shape unchanged. Measured on psql 16.15 in a live container, both ways: with the fix, a table created bymig_ownerleaves the served role holdingSELECT|t INSERT|t UPDATE|t DELETE|t; against the old script,f f f f.MigrationRunner.verify_runtime_accessis the last act of every run:has_table_privilege— which counts ownership and group membership, so a role granted through a group passes — for the four rights on every table in the schema but the ledger, andRuntimeAccessMissingErrornaming the missingtable:privilegepairs otherwise. It is the sibling of the narrowing check beside it (LedgerNarrowingIneffectiveError), and it closes the MANAGED path's own version of this finding — an operator who skipped the documented prerequisite — with the same answer. This act does not claim privilege work it did not do.verify_canonical_digest()hashed0001;bootstrap_ledger()andprotect_ledger()then COMMITTED the ledger table and its privilege changes; and only the loop's re-read raisedCanonicalDigestMismatchError. For a migrations directory that changes under the process — which this runner supports by design, and which is why round 11's per-file snapshot exists — "a tree carrying the wrong0001changes nothing at all" was therefore false by two changes.snapshot_run()reads every migration's bytes and runs the gate BEFORE the first statement, and the loop drives off that snapshot with nothing left to re-check: round 11's rule ("one read, one digest, one execution") widened from a file to a run.MAX_REQUEST_BODY_BYTES(1 MiB) on the way in andMAX_PAGE_SIZEis 500, so one authenticated request could force roughly 500 MiB of database fetches, JSON serialization and worker memory, and a few concurrent ones an outage — out of entirely legitimate drafts.identity.MAX_PAGE_BODY_BYTESis the SAME NUMBER as the request cap (a page carries no more body bytes than one draft may, and a test asserts the two are one number), and it is applied in the query as a running sum over the rows BEFORE each row: the bytes are never fetched, the page is always a prefix soafterpagination is unchanged, and a draft larger than the whole budget is still returned — the budget bounds what precedes a row, so the first row of a page is never excluded and pagination can always advance. Measured: three 600 KiB drafts were 3 rows / 1,843,200 body bytes and are now 2 + 1 across two pages.'is a syntax error — or, worse, silently a different password — while the bundled script it is derived from has read it through\getenvand quoted it with%Lsince round 11. Same shape now, so the secret never enters the SQL, this runbook, or~/.psql_history. Measured in the same live container:pa'ss w0rdcreates the role and logs in.Every new case was run against the shape it forbids before it was committed — the four hermetic ones fail on the old tree, and the three DB-backed ones fail as DID NOT RAISE, CanonicalDigestMismatchError, and the page returned 3 drafts and 1843200 body bytes. One new case,
test_the_whole_run_is_read_before_the_ledger_is_bootstrapped, passes against BOTH shapes and its docstring says so: it is not this round's regression (its sibling is), it pins the other half of the promise — that a refusal's whole footprint is the advisory lock — so no later round can satisfy the sibling by moving a mutation earlier instead of moving the reads.Review round 13 (Copilot review
5235999257at84cbe14e) — one thread and five suppressed commentsClassified first, as every round is now: 4 FIX, 0 REPEAT, 0 out of scope, 2 answered by measurement (of which one is the description-versus-workflow figure pair, and one is a behaviour that was measured and found to be the decision).
existssubquery reads the snapshot the statement began with, so aclose_sessioncommitting AFTER that snapshot and BEFORE this transaction commits still left the draft written into a sitting that had ended — which is exactly whatrequire_open=Truepromises cannot happen.for updatemakes the subquery WAIT on a close that is in flight and re-evaluate against the committed row, so the two acts are ordered rather than overlapping. Measured with two real connections, both ways: with the close updated and not committed, the new shape's write is still running after three seconds and then raisesNotFoundErrorwhen the close commits; the old shape's had already returnedsaved, with the draft in the database before the session was closed.get_store's docstring promised that "a request that only reads still gets one consistent snapshot", which READ COMMITTED does not give (every statement takes a new snapshot); the atomicity beside it is real and is what the transaction is for, and asking for the stronger guarantee is a declared act with its own cost — a serialization failure is a retry this API does not have. Andupsert_user's said the display fields are "refreshed on every login" while the SQLcoalesces: this runtime sees ONE TOKEN PER REQUEST, not a profile event, and whether a token carriesemaildepends on the scopes it was issued for, so assigningexcluded.emaildirectly would make the stored value FLAP between requests made with different tokens by the same person. The docstring now says what the code does and states the consequence the review named — a value removed at the broker is not cleared until a token arrives with a different one — and both halves have a case.'<runtime role>',"<database>"and"<migration owner>", so an operator who pasted it got a role and a database named after the placeholders and the real served role with no access at all. Every name now arrives through psql's\getenvand is quoted byformat's%I; the password by%L. Measured against postgres 16.15 by running the block verbatim: it created a role whose name contains a SPACE (Svc Role) with a password containing a quote, that role logged in with it, andpg_default_aclshows the grantor is the migration owner and the grantee"Svc Role".var/projects— right for a developer runningopendox-runtimedirectly — and the compose file uses the configured root as theproject_repositoriesvolume's container mount target. Measured on Docker Compose v5.5.1:docker compose configACCEPTS a relative target and the daemon refuses at container creation withinvalid mount path: 'var/projects' mount path must be absolute. The failure is loud, names the path and happens before anything runs, which is why this stays ONE expression rather than becoming a fixed literal that would make the documented setting mean nothing here again; the new case is labelled a guard rather than a regression, because the value that can be relative lives in an operator's own.env.Answered by measurement, no change: the description/workflow figure pair. The review quotes this description at
4bf054ec/122/216, which is what it said before round twelve's update; both places have named2052e1e6/126/223 since, and both name5d86d8b8/132/236 now.Review round 14 (Copilot review
5236637540atf6b7a19c) — two threads and five suppressed commentsClassified first: 3 FIX (one of them two call sites, one of them six), 0 REPEAT, 0 out of scope, 0 answered by measurement. Two threads and five suppressed comments.
current_schema()IS the search-path fallback this module's qualification was defending against. Round 5 qualifiedruntime reset's drops and round 6 qualified the ledger read precisely so that nothing resolves throughsearch_path— and the qualification itself resolved throughsearch_path, becausecurrent_schema()answers the first existing schema on the path and never the first configured one. Measured on postgres 16.15 with notenantschema:set search_path = tenant, publicgivescurrent_schema()=public,current_schemas(false)={public}, andshow search_path=tenant, public. So a DSN selecting a schema that was dropped, renamed or never created read and WROTE another one in silence —MigrationRunner.applied()reportedpublic's ledger as the selected schema's, after whichplan()calls a fresh schema migrated and/readyzcalls it ready, andruntime resetqualified every drop aspublic.*and deleted another install's coordination tables under a promise that it would not.migrations.selected_schema(conn)asks both questions in one statement and refuses when they disagree, naming both schemas; the same answer replacescurrent_schema()in_check_runtime_access's predicate one method along, where measuringpublic's tables would have reported on tables the run did not create. Only the first configured entry is compared, and"$user"is not compared at all — it is not a schema name but the first entry of PostgreSQL's own defaultsearch_path, where an absent user schema is skipped by design, so a plain install is not refused for having one. Two cases, both failing against the previous head: a hermetic pair through a connection that answers the two columns, and a DB-backed one the way the defect appears — auserstable inpublic, a schema that is never created, and a DSN that selects it; the reset refuses with nothing dropped andpublic.usersintact.The command this service PRINTS was not a command.
register()nests every verb under theruntimegroup, so the shortened spelling — the console script followed straight by a verb — exits 2 with argparse's usage error. Measured through the parser:['migrate']raisesSystemExit(2)withinvalid choice: 'migrate' (choose from 'runtime'), and['runtime', 'migrate']is the verb. It was whatruntime init's evidence emitted as itsnext, what/readyztold an operator to run while migrations are pending, what the runbook's transcript showed, and what a case intest_api_endpoints.pypinned — so an operator who copied the answer the service itself gave them could not make the service ready, and the suite agreed with the broken spelling. Every occurrence insrc/,docs/,deploy/andtests_runtime/names the group now, and a new hermetic case sweeps all four trees for the console script followed by a verb, so the next one cannot be written silently.The managed-database prerequisite accepted a served role this runtime refuses. Round 13 made every name in that block arrive through
\getenvand be quoted by%I, and measured it by creating a role namedSvc Role— which works, in the block. It does not work in the runtime:config.load_migration_settingsrefuses a served role that is not a plain SQL identifier beforemigrateconnects, andMigrationRunner.protect_ledgerrefuses it again, because the ledger narrowing interpolates a role name into arevokeas syntax. A prerequisite an operator can complete and still not start is the same defect as a command they cannot run. The runbook states the grammar now —[A-Za-z_][A-Za-z0-9_]{0,62}, with the reason — and says why%Iis still not redundant under it: the migration owner and the database are under no such constraint, and a served role that IS a plain identifier can still collide with an SQL keyword. The new case pins the statement and both refusals to one spelling.Review round 15 (Copilot review
5237498282atf86439b1) — one thread, fixedClassified: 4 FIX, 0 REPEAT, 0 out of scope, 1 answered by measurement. One thread and four suppressed comments.
The schema guard ran one call too late. Round 14 made
applied()andruntime resetaskselected_schema, andbootstrap_ledgerruns BEFOREapplied()in_apply_locked. Itscreate tableis unqualified — which is right, it must land where the connection'ssearch_pathselects — so on a connection configured for a schema that no longer exists it created the ledger inpublicand committed it, and the refusal arrived one call later: a fail-closed run that had already mutated another schema. The guard is asked before the DDL now, on both ofbootstrap_ledger's paths, and the DB-backed case measures the whole run rather than the reader alone — the tables inpublicbefore and after, with the refusedapply()in between. Against the previous head it fails with "the refused run created tables inpublic".A concurrent rotation refused a valid token. The miss-refresh cooldown bounds fetches, and it was being used as a bound on answers: the thread it denies is precisely the one waiting for another thread's fetch, so a request whose
kidhad already arrived in the new key set raisedInvalidSignatureErroragainst the old one it was still holding. A denied thread re-reads throughkeyset()now — which takes the same lock the refresh holds, so it waits for the fetch in flight and reads its result, and fetches nothing itself, leaving the amplification bound exactly where it was. The case forces the order rather than racing it: the denied thread is held between its read of the old key set and its cooldown question, which is the only window in which the defect exists (an unordered version passes against the previous head, and the docstring says so).The access preflight asked about every table, and not about the schema. It scanned
relkind = 'r'across the whole selected schema, so a table that has nothing to do with this runtime — another application sharing the schema, an operator's scratch table — failed the migration run for a privilege the served role was never meant to hold. Andhas_table_privilegealone is not the question: withoutusageon the schema a role cannot name those tables at all, so a run could pass the check and every request still failpermission denied for schema. The list is RULING Q1's own, imported fromidentityrather than retyped; the schema'susageis asked first and named in its own refusal. Both halves measured in one schema against a real role.The page budget bounded what the application received, not what Postgres read. The inner query selected every
bodyand carried it through the window function and the sort before the outer predicate dropped it, so a page of 500 one-megabyte drafts still made the database read and move ~500 MB to return a short prefix. The inner query selects ids and sizes; the bodies are joined back on the ids that survive. Which rows come back — and that at least one always does — is unchanged, and is measured by round 12's own case.Answered by measurement, no change: the description/workflow figure pair, quoted one head apart. Both name
541b0329/132/235 now, and both say which head they mean.Review round 16 (Copilot review
5238724938at6c613232) — two windows left half-closed, both closedClassified: 2 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. Both are refinements of round 15's own fixes, and both are right.
The whole configured
search_pathis walked, not only its first entry. Round 15 compared the head of the path and exempted"$user"— sosearch_path = "$user", tenant, publicwith neither the role's schema nortenantpresent stopped the walk at the exempt entry and acceptedpublic: the same silent fallback one position along. Every named entry ahead of the one PostgreSQL resolved must now exist — "nothing this connection asked for was skipped"."$user"stays exempt and only it, because an absent user schema is skipped by design; it is resolved againstcurrent_user, so a session whose own schema is the answer stops the walk there, which is what that path means. The hermetic fake grew the second questionselected_schemanow asks, because a fake that answered only the first would let the whole walk pass vacuously.The cooldown claim and the refresh are one lock acquisition. Round 15 made a denied thread re-read, which narrowed the window and did not close it: the claim and the fetch were two acquisitions, so a denied thread could leave the lock and read the cache before the claiming thread had taken it to fetch, and reject a valid token carrying the newly rotated
kid.keyset_after_missholds the lock across the claim and the fetch. The cooldown still bounds fetches — one per cooldown, asserted by the load count — which is the property it exists for; what it no longer bounds is answers. The case drives the window itself (the claiming thread paused between its claim and its fetch, the denied thread running during the pause) and hooks whichever method the shape under test claims the cooldown in, so it runs against both heads — and against the previous one the denied thread is refused.And a gap this round itself opened: a dropped coordination table was not reported missing. The preflight is driven by
pg_class, so a required table that is not there produces no row and was never added tomissing— a rerun afteruserswas removed reported success and the API failed on the relation later. Restricting the scan toSERVED_TABLES(round 15) is what turned "every table in the schema" into a set that can have a hole in it, so the set is compared now and every absent one of RULING Q1's six is named.The JWKS setting promised a discovery this runtime does not make. "derived from the issuer's discovery document when unset" — nothing reads
.well-known/openid-configuration;jwks_url()appends the fixed Keycloak path. A broker publishing a differentjwks_uriwould have followed the documented configuration and failed readiness. The contract is narrowed to what the code does and says what to set when that is not enough; bounded discovery is a change with its own failure modes and its own tests, and is not smuggled in under a docstring.0002_migration_state.sql's comment also named a test that does not exist, and now names the one that does.Registered, not done.
/readyzcompares ledger versions and migration checksums and does not ask whether the six relations are still there, so an operator who dropsuserswhile leaving the ledger intact gets a 200. It is the same question the preflight now answers at the END of a run, one surface over, andverify_runtime_accessis the call readiness would make.Review round 19 (Copilot review at
2c56b65) — three findings, all measured, all realClassified: 3 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. Each fix carries a case that fails against the previous head.
_DSN_SHAPED'spassword\s*=\s*\S+ends at whitespace, and libpq documents that a value containing spaces is written in single quotes, with\'and\\escaped inside. So the valid conninfopassword='secret value'matched onlypassword='secret, and this CLI printed<redacted> value'— half the password in the evidence, beside the marker that says it was removed. psycopg accepts an arbitrary conninfo and its driver errors quote it back, which is how a real failure arrives here. The pattern reads the quoted forms now; the closing quote is optional and neither quoted form crosses a newline, because a truncated message must redact more rather than less and must not swallow the next line of a multi-line error.sslpasswordis named too —\bbeforepassworddoes not reach it, and a private key's passphrase is the same secret. The case also pins the non-over-match:password=simplestill ends at whitespace andpasswordless=fineis untouched.search_pathresolution asks whether THIS ROLE may use a schema, not whether it exists. Round 16 walked the whole configured path and probed the skipped entries againstpg_namespace— which proves the schema is there. PostgreSQL skips an entry the session lacksusageon exactly as it skips an absent one, so an existing but unauthorizedtenantleftmissingempty, the fallbackpublicwas accepted, and every statement of the run went topublic. In a multi-tenant install the grant is the isolation. Measured on postgres 16.15 as a role holding no grant on a schema that exists:pg_namespacecount 1,has_schema_privilege(current_user, …, 'usage')false,current_schema()public. The probe askshas_schema_privilegenow, and the refusal names which of the two it is because the remedy differs — create the schema, or grant usage. Against the previous head the DB-backed case does not refuse at all: it proceeds intopublicand is stopped only by an accident of that role's grants..envto the docker daemon.context: ../..is right — the Dockerfile installs this package from source — and the context is uploaded before any instruction runs.deploy/compose/.envis git-ignored, which is not a build-context rule, so its DSN and password travelled with everydocker compose … --buildeven though the Dockerfile never copies it into the image..dockerignoreis an allowlist, so the property is structural rather than a list somebody has to extend: everything excluded, the Dockerfile's ownCOPYsources named back in, and the guard derives that list from the Dockerfile so the two cannot drift. Measured with docker server 29.6.2 by copying the context into abusyboximage — before,/ctx/deploy/compose/held.env; after,/ctxis exactlyREADME.md,migrations,pyproject.toml,src— and the real image still builds and runsopendox-runtime --help.And the figure block says which entries are history. Round 18 on the sibling PR read a superseded entry as that branch's claim about its own head, and it had every reason to: each entry asserted currency in its own words, so only the note at the top of the block said otherwise. Every superseded entry says SUPERSEDED now, in the entry.
And its six suppressed comments: four real, two false and measured so.
The readiness probe made three pool checkouts under a budget for one.
test_deploy_shape.pyderives the probe'stimeoutSecondsfrom ONEDEFAULT_CHECKOUT_TIMEOUT_SECONDSplus the JWKS timeout and holds it strictly over both — and/readyzchecked out forselect 1, again insideplan()and again insidedrift(), each of which callsapplied(). A contended pool therefore made the probe wait three of those, kubelet cut the probe off mid-flight and the next one overlapped it.plan()anddrift()take the connectionapplied()already accepted, and the probe holds one across every database question. The case counts checkouts, and against the previous head it says "this probe checked out 3 pooled connections".120 attempts is not 240 seconds.
socket.create_connection(..., timeout=2)can spend its whole two seconds before thesleep(2)that follows, so the migration Job's counted wait ran for up to 480s while the line it ends with — and the runbook that quotes it — said 240s. Measured against a non-routable address with the counts scaled down by 40: three attempts claiming 6s took 12.1s, exactly twice. It is atime.monotonic()deadline now, and the case asserts both the shape and one real bounded run.A documented command carried a password in its own argv.
--from-literalputs the value in the shell's history file and in/proc/<pid>/cmdlinefor as long askubectlruns — the same exposure the managed-database block one page down already avoided withread -rs, so two paths said different things about one secret. The install block reads into files underumask 077, passes--from-file, and removes them; measured with akubectlon PATH that prints its own argv. The guard greps the runbook for any--from-literalwhose key is secret-shaped.The managed-database path now ships the overlay it requires. Pointing both DSNs at a managed database does not remove
postgres-statefulset.yamlfrom the base, so that path started a second database nobody uses and failed on theopendox-postgresSecret it never creates. An overlay is the only place kustomize can remove a base resource. Measured with kustomize v5.4.3:deploy/kubernetes/overlays/managed-databaserenders the Namespace, both ConfigMaps, the runtime Service, the PVC, the Deployment and the Job — and none ofStatefulSet/opendox-postgres,Service/opendox-postgresorConfigMap/opendox-postgres-init— withmigration_wait_hostempty.False against the code.
STDLIB_ONLY_MODULESis reported to omitopendox.runtime.identity. It is line 43 of that tuple and has been since the module was added.False against PostgreSQL, and this is the second report of it.
octet_length(d.body)is held to detoast every candidate body, so that a 500-draft page still makes the database process ~500 MB.textoctetlentakes the raw length out of the varlena header —toast_raw_datum_sizereads a TOAST pointer, not the chunks it points at. Measured on postgres 16.15 over 200 rows of 1 MiB of incompressible ASCII, a 208 MB relation, best of three:sum(octet_length(body))count(*)sum(length(body))(counts characters)max(md5(body))(reads the bytes)Sizing costs what counting costs; reading is three orders of magnitude more. A DB-backed case drives the same shapes at a size a test can afford and asserts the ratio, with the measured ratio at that size ~36x against a 4x bar.
Review round 20 (Copilot review at
2c56b65) — one finding, and round 19's own fix is what left itClassified: 1 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.
"$user"is exempt for being ABSENT, not for being unreachable. Round 19 made every named entry ahead of the answer prove it is usable and left"$user"skipped unconditionally — and PostgreSQL skips an existing schema the role lacksusageon exactly as it skips an absent one. So a schema named for the role, present and denied, still fell through topublic: the same silent fallback this function exists to refuse, wearing the default path's name. It goes through the same probe now, under the role's own name, and is forgiven only for not existing. The refusal says the entry came from"$user", because that is not a name an operator can grep the DSN for, and the exemption is positional rather than by name, so a role whose name also appears as a later named entry does not get that entry forgiven with it. The case covers all four states — denied, absent, answering, and an entry after it judged on its own — and against the previous head the first DID NOT RAISE.Review round 22 (Copilot review at
a10bd08) — two findings, one of them reported twiceClassified: 2 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.
oidc_issuerand an explicitoidc_jwks_urlare public endpoints — the issuer is what a token'sissis compared against, the key set is fetched unauthenticated — andload_settingsaccepted any string. Measured against the previous head withOPENDOX_OIDC_ISSUER=https://svc:pw@broker/realms/x:load_settingsaccepted it,repr(settings)printed it,statusprinted the derivedOPENDOX_OIDC_JWKS_URLwith it, andstatusprintedbroker_discoverywith it — three printed credentials from a value that had never been a DSN, which is why the DSN-shaped redaction saw nothing. It is refused at the door, because redaction alone would make the evidence safe and leavejwks_url()— which the verifier actually fetches — pointing at a URL with a credential in it; and redacted at both printing boundaries anyway, because aRuntimeSettingsbuilt by hand does not go through that door. The host survives the redaction, for the same reason a push refusal keeps the host it could not reach.oidc_issuerandoidc_audienceempty on purpose — they are an environment's facts — so an overlay the runbook tells an operator to build must supply them or it renders a Deployment that failsload_settingsbefore it serves.overlays/devcarries a worked example for exactly that reason; round 19's new overlay had none. The guard is derived from the base: everyoidc_*the base declares empty must be supplied by every overlay, and every overlay must be named in the runbook, so one added later is covered by the rule instead of by somebody remembering.Review round 23 (Copilot review at
334b9b6) — two findings, one defectClassified: 2 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. Compose interpolates
${VAR}before the container sees the string, so both healthchecks turned an operator's.envvalue into code.CMD-SHELLmade it shell source.OPENDOX_PG_USER=x; touch /tmp/pwnedran in the Postgres container on every probe, and a value with a space silently became two arguments long before anything hostile was needed. It is exec-formCMDnow — the interpolation stays, because the probe must follow the configured values, but each one is a single argumentexecpasses with no shell between.config.load_settingshad looked at the port. The script is fixed and reads the value fromos.environ— the container already has the variable, set from the same.envby theenvironment:block — so it holds no interpolated text. Measured withOPENDOX_BIND_PORT="8080'),None) or __import__('os').system('touch /tmp/PWNED')#": exit 1 with aValueError, and no marker.int()is the same validationload_settingsapplies, so probe and service now refuse a malformed port in the same direction.The guard is over every service rather than these two: exec form, and no
${in any argument that follows a-c. The round-6 assertion that the probe follows the configured port is kept and re-derived — it asserts the probe and theenvironment:block name the same variable.Review round 24 (Copilot review at
5cb4922) — three findings, two of them round 22's own guardClassified: 3 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.
netlocand nothing else, andredacted_urlpreserved the query — sohttps://broker/certs?token=…was accepted and then printed by bothrepr(settings)andstatus. Both halves read the query and the fragment now, against a list of credential-shaped parameter names (local_git_adapter.SECRET_PARAMETER_KEYSholds the same list for the remote rule on the sibling PR; this branch has no such module). The redaction replaces the value and keeps the rest —?token=<redacted>&format=jwk— because an operator has to see which endpoint was configured.urlsplitraises, from inside the function that owes a named refusal. Measured on python 3.12:urlsplit("https://[::1/x")raisesValueError("Invalid IPv6 URL"), so a malformedOPENDOX_OIDC_ISSUERescaped as a traceback where this module promises aConfigurationErrornaming the variable. The parse is inside the boundary, andredacted_urlanswers<redacted-url>for a value it cannot parse.runtime_pg_roleis an edit the managed-database overlay cannot make. The base's value is the role the bundled Postgres creates on first start; a managed database runs no init script, so the served role is whichever one the operator provisioned. If the two differ the migration Job narrowsopendox_runtime— or fails because it does not exist — while the role actually serving keeps the right to rewrite the ledger. The overlay cannot know that name, so the required edit is stated: the literal is in the overlay commented with its exact form, and the runbook makes it a step of the managed-database path, tied toOPENDOX_RUNTIME_PG_ROLE— one name, now in four places.Review round 25 (Copilot review at
5700d56) — one finding, and it is the sharpest form of round 22'sClassified: 1 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.
HttpJwksSourcefetches it, and the keys it returns are what every token is verified against — so overhttp://anyone on the path replaces the key set and mints tokens whoseissandaudstill pass: verification reduced to whoever controls the network. It ishttps, or a loopback host, and only those. The exception is for a developer running a broker on127.0.0.1, where there is no network for anyone to be on, and it is exact rather than name-shaped —ipaddressjudges a literal, so127.5.5.5and[::1]are one answer and127.0.0.1.evil.testis not one at all. The explicitOPENDOX_OIDC_JWKS_URLgoes through the same rule, since it is the URL actually fetched.Review round 26 (Copilot review at
99c2118) — five findings: three fixed, two answered by measurementClassified: 3 FIX, 0 REPEAT, 0 out of scope, 2 answered by measurement.
kubectl applyreached a clean cluster with a placeholder image. True, and measured against kustomize v5.4.3:kustomize build deploy/kubernetes/overlays/devemitsghcr.io/opensoft/opendox-runtime:0.0.0at three container sites (the Deployment and the migration Job's two containers), and this repository publishes no image, so the install the runbook documents reachesImagePullBackOffbefore the runtime or the migration can start. The reviewer offered two dispositions and this takes the second — require the replacement — because the first (build a local image) would make the runbook's happy path a development shortcut rather than the install it documents. Every documented apply is now preceded, in its own pasteable block, bykustomize edit set image …@sha256:<the reviewed digest>(measured: it replacesnewTag:withdigest:, keeps the overlay's comments, and the build then emits the digest at all three sites) and by a guard that greps the build's output for the placeholder and does not apply while it is there. The new case reads the tag out of the manifests instead of restating it, so the guard's pattern, the base's tag and each overlay'snewTagcannot drift apart; against an unguarded apply and against an overlay tag the guard would miss, it fails.ProgrammingError: end of string reached when looking for matching "]" in IPv6 host address in URI: "postgresql://opendox:hunter2@[::1/x". An unbracketed IPv6 host is the ordinary way to mis-set this variable, so the leak is one typo away in a job whose DSN carries a password. The reason now names the exception type and a destination rebuilt by a small stdlib-only helper — scheme, host and port for a URI (brackets kept for an IPv6 literal),host=/port=/hostaddr=for the keyword/value form,<the configured DSN>when there is no destination to name. Two cases, both of which printhunter2against the previous head: one stubs the driver so the contract is measured in the required job, one is the live reproducer.rm -rf "$secrets"was reached only when everykubectl create secretsucceeded, so a failed create — or a Ctrl-C at the second prompt — left four files holding passwords and DSNs on disk, under the no-leak contract that block exists to keep. A trap follows themktemp -dimmediately, onEXITand onINT/TERM, and the signal handlers re-raise so the shell's own exit status is still the truth.LEDGER_DDLcannot reuse apublicledger. The finding's mechanism is thatCREATE TABLE IF NOT EXISTS"sees the public relation and skips creation in the selected schema". On postgres 16.15 it does not:IF NOT EXISTSis tested against the relation the statement would create — the first schema insearch_paththe role can create in — and not against what the name resolves to for a read. Driven directly, withpublic.opendox_schema_migrationsalready present and holding a row, the bootstrap created a second ledger in the selected schema and the unqualified insert landed there;public's row count never moved. The finding's second half needs the creation target to diverge fromselected_schema(), and it cannot: a role with no USAGE on the firstsearch_pathentry has its unqualifiedCREATEskip that schema to the next one — the same entryhas_schema_privilegewalks to (measured on anosuperuserrole). The regression the reviewer asked for is added anyway, DB-backed, with the decoy built from the runner's own DDL so it cannot drift into a shape the run would reject for some other reason; against a bootstrap that writes topublicit fails on the tenant ledger's rows.8779a776 / 142 / 249from the description against65376475 / 144 / 251in the workflow, and both were two rounds stale by the time the review was posted: ata4d0eddfthe description and the workflow both said 145 and 252, at the same commit, which is the invariant the finding asks for. They say 153 (1 skipped) and 262 atc21b8b97now, in both places, and the rule that keeps them together is the one written above the table: a count here and a count in the workflow's comment block must name the same head.The same round's suppressed comments — two more, and both were defects.
urlsplit("https:///realms/x")yields the schemehttpsand hostnameNone, so round 25's check — which read only the scheme — passed it: measured before the fix,OPENDOX_OIDC_ISSUER=https:///realms/xproduced settings carrying that issuer, and the install would have discovered it when the key-set fetch made/readyzandstatusfail. That is configuration found at serve time, which is the boundaryload_settingsexists to hold. A missing hostname is refused before the scheme check now, and the refusal does not echo the value:https://user:pw@/realms/xhas no hostname either, so the hostless shape and the credential-carrying shape overlap exactly and a message quoting the value would print the password this function keeps out ofstatusand the logs.broker/realms/xmoves to this rule from the scheme rule's list — it has no scheme and no host, and "names no HOST" is the more accurate of the two diagnoses for a value that is not a URL.search_pathwas split withstr.split(","), which is not a parser. A schema whose name contains a comma is legal and PostgreSQL quotes it, so"tenant,blue", publicbecame"tenantandblue"andselected_schemarefused a valid connection — one whosecurrent_schema()was exactly the schema it had asked for — naming'"tenant'as the thing that did not exist. Measured on postgres 16.15 against a schema created as"tenant,blue"._path_entriessplits on commas outside double quotes and leaves each entry raw, so_unquotedstill reads it: seven parametrized cases including a doubled quote ("a""b") and a quoted name whose own spaces are part of it, the finding's case throughselected_schema, and a DB-backed end-to-end run that creates the schema, sets the path on the connection and bootstraps the ledger into it. The guard still refuses such a name when it really is skipped — the fix widens the parser, not the rule.octet_lengthdetoast (answered by measurement, round 19), the migration Job's wall-clock deadline, the runbook's--from-literalsecrets, the managed-database overlay,/readyzholding one connection, andidentityinSTDLIB_ONLY_MODULES— which is in that tuple already.Review round 27 (Copilot review
5246688086at9df2661) — three threads and seven suppressed commentsClassified: 4 FIX, 0 REPEAT, 0 out of scope, 1 answered by measurement, 5 registered and not taken. Two of the four fixes are defects in the code that answered round 26 an hour earlier.
urlsplit("postgresql://u:pw@host:not-a-port/db")succeeds and defers the error to.port, a property that parses on read — and that access sat outside theValueErrorboundary, so_redacted_dsnraised from inside the handler that was reporting a connection failure. Measured before the fix:ValueError: Port could not be cast to integer value as 'not-a-port'. The finding stops there; the sharper half is the chain.pytest.skipraised insideexceptcarries the psycopg error as__context__, and libpq quotes a conninfo it cannot parse — so onpostgresql://opendox:hunter2@[::1:not-a-port/dbthe password was in the formatted traceback while the reason was clean, and a crash is exactly what makes pytest print one. Both measured, both ways: before,password in reason: False | in full traceback: True; after, bothFalseand__context__isNone, because the reason is now raised outside the handler. Every access is inside the boundary and the fallback is<the configured DSN>.https://broker:not-a-port/realmpassed it, because the checks read the scheme and the hostname, and theValueErrorwould have surfaced inside the JWKS fetch — neither aConfigurationErrornor a named setting. Refused now, with the value unechoed for round 26's reason;https://broker:99999/realmis refused by the same access.opendox_runtime— the bundled database's role — so the migration Job narrowed a role nobody serves as, or failed because a managed database runs no init script to create it, while the role actually serving kept the right to rewrite the ledger. That is round 24's defect reached by ordering rather than by a missing edit. The apply block now sits after theruntime_pg_roleinstruction and after the role-provisioning block, and the new case measures positions in the document, which is the whole claim._load_keyset()raises,_keysetis never assigned and_loaded_monotonicis unchanged, so every authenticated request re-entered the refresh branch and fetched again — each waiting the source's whole timeout with the cache lock held, so every other verification queued behind it and a broker outage spent the worker pool waiting on a broker already down. The miss cooldown does not bound it: that one is claimed on akidmiss. A failure is remembered for a cooldown now, and the cooldown never serves a key set — every call inside it still raises, so a stale set is not used past its TTL and verification stays fail-closed; only the traffic is bounded. A success clears it. Against the previous head the first assertion reads 5 fetches, not 1.948cf056now, in both places.Registered and not taken, with reasons — each is a change to serving behaviour or a new suite rather than a correction to this act's own work, and each is named here rather than left silent:
get_principaldeclares no bearer security scheme, so a client generated from the published OpenAPI omits credentials;document_keyandbasis_revisionare outside the page budget that boundsbody; the access preflight does not checkCONNECTon the database;HttpJwksSourcehas no mocked-transport coverage (every verifier fixture usesFileJwksSourceor an in-test fake); and the secret block does not abort on a failedkubectl— a pasted block that ranset -ewould exit the operator's own shell, so the disposition there is a choice and not an oversight.Review round 28 (Copilot review
5246781523atd250fd9) — one finding, and it is about this act's own headline promiseClassified: 1 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.
snapshot_run()takes every migration's bytes and runs the canonical gate before the ledger is bootstrapped, which is what makes "a tree carrying the wrong0001changes nothing at all" true against a directory that changes under the process. Butraw.decode("utf-8")sat inside the per-migration loop — after the bootstrap, afterprotect_ledger, and after earlier migrations had committed — so a later file holding invalid UTF-8 aborted the run with an untypedUnicodeDecodeErroron a database this runner had already changed. A partial migration, from the method whose whole job is that there are none. One read of every file, and now one decode of every file, before the firstcommit; the refusal is aMigrationErrornaming the file and the byte. The case puts the bad bytes in a third migration so the run has real work to commit before it reaches them, and asserts the strictest form of "nothing at all" — the schema holds no tables, not even the ledger, whose bootstrap alone would have left one behind. Against the previous head it raisesUnicodeDecodeErrorand leaves the six tables and the ledger.Review round 29 (Copilot reviews
5246781523at9df2661and5246859442atd250fd9) — nine suppressed comments, seven still liveClassified: 6 FIX, 0 REPEAT, 0 out of scope, 1 answered by measurement (two of the nine were already fixed by round 27 before the bodies were written).
jwks_url()anddiscovery_url()append their paths to the issuer, and a URL's query and fragment come after its path. Measured, both components accepted:https://broker/realms/x?tenant=aderived…/realms/x?tenant=a/protocol/openid-connect/certsand…/realms/x?tenant=a/.well-known/openid-configuration. Refused now — and the rule is the issuer's alone: an explicitOPENDOX_OIDC_JWKS_URLis fetched as given and a broker behind a rewriting proxy may need a query on it, which is the whole reason that variable exists. The case pins the derivation on a value that passes, too.ftp://localhost/realms/xandfile://127.0.0.1/realms/xthrough (both measured accepted), andHttpJwksSourcefetches withhttpx.get, which can use neither. It ishttpsanywhere, orhttpon a loopback host, and nothing else.UnicodeDecodeErroris aValueErrorand not ajson.JSONDecodeError, so the air-gapped path's malformed key set surfaced as a 500 instead of the typed refusalFileJwksSourceexists to produce.ValueErroris the base of both — the ruleHttpJwksSourcealready states one class below._open()assignedself._exitand then called__enter__(), so a checkout that raised left a non-None_exitwhose__enter__had never completed, andget_store's cleanup callsclose()— which calls__exit__on it. Whatever that raises replaces the database error that is the real answer. The manager is held in a local until__enter__returns.\S*stops at the first whitespace, so a driver quoting backpostgresql://opendox:hunter 2@db.internal/xwas redacted to<redacted> 2@db.internal/x— the tail of the password and the whole host, beside the marker that says the credential was removed. Userinfo ends at the first@and cannot contain/, which is what lets the pattern absorb the space and not run away down the line: onpostgresql://host/db for user a@bthe@branch cannot cross the/, so the unrelated@is not swallowed. Both bounds are cases.set -e, inside a subshell so a paste cannot close the operator's own shell, and the status taken by$?on its own line — because measured with akubectlstub that refuses the first create,) && ok=yes || ok=nosuppressesset -einside the subshell (bash disables errexit in an operand of&&/||, and the subshell inherits it): all three creates ran and the status was 0. Withsecrets_created=$?the block stops at the first failure, the EXIT trap removes the files, and the status is 1. The signal trapsexitrather than re-raising, because$$in a subshell is still the parent's pid — the round-26 form would have signalled the operator's shell. The apply is guarded on that status. The same block's claim that "neither the password nor a mistyped placeholder can reach the database" was false and is rewritten:create role … password %Lis the statement that sends it; what this block keeps the password out of is the operator's shell, and what%Lkeeps out of the database is a mistyped placeholder.read -r -sis already what the DSN prompts use. The finding asks forread -r -swhere the line readsread -rs -p, and those are the same flags. Measured on bash 5.2:printf 'a\b\n' | read -rs vkeepsa\b; with-salone it becomesab.Review round 30 (Copilot review
5246951266atb2c8056) — two threads and five suppressed commentsClassified: 4 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. The two threads are the same finding on the two byte-identical copies of the bootstrap script.
grant select, insert, update, delete on all tables in schema publichands the API role another application's data on a reused or managed database — which the migration preflight explicitly tolerates being there — and it was not even doing the job it looked like it was doing: at first start the coordination tables do not exist yet, so that grant could only ever reach tables this install did not create. Two narrow halves replace it, both measured on postgres 16.15:alter default privileges for role <migration owner>covers every table that owner creates from then on (measured: a table the owner creates afterwards carriesDELETE, INSERT, SELECT, UPDATEfor the served role; a table created by anybody else carries none), and a JOIN against the catalogue grants the coordination tables that already exist — the case the broad grant's own comment named. Measured withprojectsandunrelated_appboth present, it emitted exactlygrant … on table projects …and left the unrelated table with zero grants; on a fresh database it emits nothing. The names are Q1's six plus the ledger, derived in the case fromidentity.TABLESandmigrations.LEDGER_TABLEso a seventh coordination table cannot be added and left out — which is the failure the broad grant was hiding. The reviewer's fifth suppressed comment asked for exactly that, since the old case made the over-broad grant part of the contract.OPENDOX_MIGRATION_PG_USERis documented as an alternate owner andalter default privileges for role %Inames it, so setting it to a role nobody had provisioned failed underON_ERROR_STOP=1on a fresh volume — the stack could not initialize, with PostgreSQL's message rather than one naming the variable. The script refuses first now, and says what the bundled path does and does not provision.bash, which is a prerequisite and not a label. They prompt withread -rs -p, and neither-snor-pis in POSIXread: under/bin/shas dash the prompt is consumed as the variable name and the block fails before a Secret file holds anything. The fenced-block scanner intest_deploy_shape.pyreadsshorbashnow, so correcting the fence did not blind the guard that reads those blocks.select 1pasttimeoutSecondsand kubelet would start an overlapping probe.SET LOCALin an explicit transaction, and that shape is measured: a session-levelset statement_timeouton a pooled connection survived the checkout it was made in (a later checkout of the same connection still read1234ms), so the bound would have leaked onto whatever request borrowed it next. The value is interpolated becauseSETtakes no bind parameter —set local statement_timeout = %sis aSyntaxErrorfrom PostgreSQL, measured. The deployment'stimeoutSecondsassertion takes the new term from the module that declares it.Review round 31 (Copilot review
5247062148atdbc704f6) — two threads, neither mechanism holdsClassified: 1 FIX, 0 REPEAT, 0 out of scope, 2 answered by measurement.
selected_schema()proves USAGE, the ledger DDL creates, and PostgreSQL would therefore choose "a latersearch_pathentry where the migration role has CREATE (for examplepublic) as the object-creation target". Measured on postgres 16.15 as anosuperuserrole with USAGE and no CREATE on the first entry and CREATE onpublic:current_schema()is still the selected schema and the unqualifiedcreate tableraisesInsufficientPrivilege: permission denied for schema sel. It does not fall through — the second time this act has measured that resolution rule against a finding that assumed otherwise (round 26 was the USAGE case). What was worth taking is the message: that refusal is PostgreSQL's, it arrives from inside acreate tableafter the guard that exists to answer this question has passed, and it names no remedy. The guard asks for CREATE before the DDL now and refuses in this act's own words. The reviewer asked for the usage-without-create case to be covered and it is, DB-backed:MigrationErrorand notInsufficientPrivilege, the schema and the grant named, and nothing created in either schema.SyntaxErrordoes not exist. The quoted line isassert "--from-file=password=" in runbook: a string whose last character is=, followed by its closing quote. Three measurements at the commit the review names (dbc704f6):py_compileon that exact blob compiles clean; the hermetic five collect and run 171 passed 1 skipped; and the requiredvalidatejob at that commit is green, which a collection-timeSyntaxErrorwould have made impossible. No change.Review round 32 (Copilot review
5247180700at7fd2e2a0) — two threads and three suppressed commentsClassified: 4 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement, 1 registered.
verify_runtime_access's message told an operator to rungrant select, insert, update, delete on all tables in schema … to <runtime role>— the exact grant the bootstrap was narrowed away from, and following it would have put back what round 30 took out. The message names the coordination tables (RULING Q1's own list, imported rather than retyped), keeps the default-privilege guidance separate for the tables a later migration adds, and says in terms what it no longer tells anyone to do.has_table_privilegedoes not see it. Measured on postgres 16.15: withINSERT (version)andUPDATE (checksum)held, all four table-level answers areFalse.update <ledger> set checksum = …needs nothing more than that second grant, so the run reported a narrowed ledger the served identity could still rewrite — the one propertyprotect_ledgerexists to establish. And the revoke does not always clear them, which is why this is a check and not a second revoke: measured both ways, a column grant from the same grantor is removed by the table-level revoke this method already issues, and one made by a third party (another role with grant option) survives it, withhas_table_privilegefalse throughout.has_column_privilegeover the ledger's own attributes is asked after the revoke, where any true is column-level by construction, and the refusal names the column and the privilege. The case builds the third-party grant and asserts the four table-level answers are false first, so it cannot pass vacuously.set -edoes not abort on the left operand of&&. The runbook's prompts wereread -rs -p … && printf …, and measured with EOF on stdin the block kept running with the variable unset — "second command ran", status 0 — so a Secret could be created from a file that was never written. Each prompt is its ownif ! read …; then … exit 1; fi; the same measurement on that form stops at the failed read with status 1. Second instance in this act of one rule; the first was round 29's subshell.createcalls meant a failure in the second or third left the earlier Secrets in the cluster and the re-run failed withAlreadyExists— an install half configured and a cleanup by hand.create --dry-run=client -o yaml | kubectl apply -f -renders the same object and applies it: created once, updated thereafter. The value still never reaches a command line, and the case asserts that too, since an idempotent form built on--from-literalwould trade one defect for a worse one.LIMIT. PostgreSQL computes the runningoctet_lengthwindow over the whole filtered set and then applies the limit, soMAX_PAGE_SIZEbounds the response and not the scan. It is real, and it is a query rewrite — a candidate subquery carrying the order and the limit, the bodies joined back after — which is a change to the read path rather than a correction to this round's own work.Review round 33 (Copilot review
5247313926at3517222e) — two threadsClassified: 2 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. Three of that review's five suppressed comments are round 32's and were already fixed at
05e13af9before it was written./from the URI branch's userinfo so the match could not run away to an unrelated later@. A password holding both a/and a space defeats it:postgresql://opendox:pa/ss word@db.internal/opendoxfalls to the plain branch, which stops at the space, and the message keepsword@db.internal/opendox— the tail of the password and the whole destination. Two spaces did the same to that form. There is no pattern that both absorbs arbitrary userinfo and stops before an unrelated later@, so this takes the act's own rule — round 19's "a truncated message must redact MORE rather than less" — and over-redacts: the DSN branch runs to the last@on the line. The price is stated in the case rather than hidden (postgresql://host/db for user a@bnow loses the text between),[^\n]*never crosses a newline, and a line with no@is untouched past the URI.readsucceeds on an empty line, and the managed-database prerequisite rancreate role … password %Lwith whatever it got — where the bundled bootstrap refuses exactly that case by name. One path's refusal is not the other's. The block refuses a failed read and an empty value together, and the whole prerequisite sits inside theelse, so nothing downstream runs on a password that was never given.Review rounds 34 and 35 (Copilot reviews
5247428924at1faa18d3and5247510939at1c6cd9e6) — three threads and five suppressed commentsClassified: 7 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. Every case below fails against the previous head.
OPENDOX_MIGRATION_DATABASE_URLand the servedDatabasefromOPENDOX_DATABASE_URL. Two DSNs at one database with differentsearch_pathoptions let a run apply and verify schema A while/readyzand the API read schema B — including a pre-existing fully migrated schema, which is another install's coordination data, reported ready by a runtime that migrated nothing in it.config.schema_selected_byreads the selection out of the string in every form libpq accepts — the URI query percent-encoded (options=-c%20search_path%3Dtenant), the attached-csearch_path=x, and the keyword/value conninfo where libpq quotes a value holding a space (options='-c search_path=tenant', which astr.split()read missed) — and only the first entry, because that is where an unqualifiedcreate tablelands, which is the questionmigrations.selected_schemaasks of a live connection.load_settingsrefuses a split before anything connects, and the refusal names the two schemas and neither DSN: this is the one refusal holding two passwords. Residue, stated: a schema that comes from a role's defaultsearch_pathon the server is not in either string, andselected_schemais the guard there.servelends the process to uvicorn, and uvicorn's log was outside the redaction contract. A failed lifespan is logged by uvicorn itself, withexc_info, beforecmd_servereaches its own handler, and psycopg names the whole conninfo in the text of an exception raised for an unparsable DSN — so a malformedOPENDOX_DATABASE_URLprinted its password to stderr in a traceback while the JSON beside it was scrupulously redacted. The boundary islogging.setLogRecordFactory, not a filter on the handlers uvicorn happens to install: a logger's filter runs only for records created on it, a handler's covers only that handler, and uvicorn's owndictConfigreplaces the handlers onuvicorn.erroranduvicorn.accesswhenConfigis constructed — every per-handler answer is a list of the loggers somebody remembered. The factory is the one hook every record in the process goes through. Each record is redacted in three places, because a formatter can reach the exception three ways: the message and its%-arguments (a number stays a number), the stack text, and the traceback — which is rendered here, redacted, cached inexc_textwherelogging.Formatteruses it instead of formattingexc_infoagain, after whichexc_infois dropped so a formatter that ignoresexc_textprints nothing rather than the raw exception. The global is restored on every path, including an exception. The case measures the same record both ways: with the boundary down it carrieshunter2, with it up it does not andRuntimeError: could not connectsurvives.discover_migrations()names the configuredOPENDOX_MIGRATIONS_DIRin its error text, so a directory path holding a DSN orpassword=…was printed raw byinit,migrate --plan,migrateandstatus— under a module docstring promising that no DSN, token or password is ever printed. Reading the file for the five named sites would have left eight, and would go stale at the next handler added, so the test is an AST walk: inside everyexcept … as exc, the name may be reached only by_safe_message(exc)ortype(exc), which reads a class name and cannot reach the message. The walk is run against the shape it forbids as well as against the file.localhostwhile the bind host is a setting (suppressed).OPENDOX_BIND_HOSTis interpolated into the service's environment as${OPENDOX_BIND_HOST:-0.0.0.0}, so a container told to bind its own address served every request while the probe gotconnection refused, marked it unhealthy and had the orchestrator restart a working server — the defect the port line fixed, one setting over. A wildcard is mapped, not dialled (nothing connects to0.0.0.0): the two wildcards become the loopback address of their own family, an IPv6 literal is bracketed, and every other value is used verbatim. The script still reads the value from the environment rather than having it interpolated into its own source, which is round 23's rule. The case runs the shipped script under five environments and asserts the URL it opens, and runs the previous spelling to show it dialledlocalhostfor all of them.set -edid not see a failed left side of a pipeline (suppressed). Every create in it iskubectl create … --dry-run=client -o yaml | kubectl apply -f -, and a shell reports a pipeline's status as its right side's. Measured, bash 5.2:set -e; (exit 3) | cat; echo reachedprintsreachedand exits 0;set -e -o pipefailstops the block with status 3. The block is bash already —read -rs -pis not POSIX — sopipefailcosts it no portability it had, and the test measures both shells rather than asserting the claim.create rolefail while the grants below it still ran — a prerequisite that ended looking successful with the identity it exists to create never made.\set ON_ERROR_STOP onis the same settingdeploy/*/init-runtime-role.shspellpsql -v ON_ERROR_STOP=1, in the form a pasted session takes.\getenvto see anything, so it cannot run in a subshell, andexit 1in it would close the operator's shell — which is why the Secret block two sections up is a subshell in the first place. An operator who pasted the SQL anyway reachedcreate role … password %Lwith nothing. So the guard is now where the act is: an unset variable (\if :{?runtime_password}— not the same thing as an empty one in psql, which substitutes an undefined variable as its own literal text) and an empty one both raise before the role is created, and withON_ERROR_STOPa raised exception is what gives psql a nonzero exit. Not measured against a server: there is nopsqlbinary in thevalidatejob, which installs.[test]and nothing else — so what the case asserts is the order, every guard ahead of the first act, which is the property that was wrong.Review round 36 (Copilot review
5248010092atc1414cbb) — four threads and six suppressed commentsClassified: 9 FIX, 0 REPEAT, 0 out of scope, 1 answered by measurement. One of the fixes is a defect round 34 introduced, which is stated as such.
search_pathwith.split(",")[0], one layer from the parser that exists to prevent exactly that. A schema whose name contains a comma is legal and PostgreSQL quotes it, so"tenant,blue"and"tenant,red"both reduced totenantand two DSNs selecting genuinely different schemas passed round 34's comparison._path_entriesand_unquotedmove toconfigassearch_path_entriesandunquoted_identifierandmigrationsaliases them — one definition, asserted withis, so the string answer and the live-connection answer cannot diverge again.shlexstrips double quotes, so-c search_path="tenant,blue",publicarrived assearch_path=tenant,blue,public. libpq'soptionshas no quote processing at all: whitespace separates arguments and a backslash escapes the next character, which is what_libpq_option_wordsdoes — the double quotes belong to PostgreSQL's identifier syntax and survive. The conninfo layer above that does take single quotes, andshlexis still right there. A space inside a schema name is therefore the backslash form (search_path="a\ b"), because an unescaped space is not one argument to libpq either; round 34's case asserted the unescaped form and is corrected.publicin one database andpublicin another are two different sets of tables.database_named_byreads the name from the URI path or thedbname=token — no credential touched — and it is compared first. The host and port are deliberately not compared, and that is a judgement stated rather than hidden: a served DSN through a pooler beside a migration DSN direct to the server is the ordinary secure shape, the same database reached two ways, and nothing in a string tells a pooler from a second server. What catches a genuinely different server is the ledger — its schema is not the one this install migrated, so/readyzreports not-applied rather than ready.select 1, thenplan()anddrift(), each asking the ledger: the derived budget was under a quarter of the worst case, and with one checkout wait and the JWKS timeout beside it a slow-but-healthy request could pass the probe's owntimeoutSeconds— the overlap rounds 19 and 30 closed one term at a time. It is a deadline now: nothing is STARTED after it and what starts is capped at the smaller of the per-statement ceiling and what is left, so the bound is the budget plus one ceiling (3.0 + 1.5), and that is the termtest_deploy_shape.pyadds to the checkout and JWKS budgets.timeoutSecondsmoves to 25. The test that held the old shape by source proximity is now an AST check, because the bound is set by a closure the transaction calls: all three calls must be insidewith conn.transaction():, sinceSET LOCALoutside one is a no-op with a warning and a session-level SET leaks onto the next borrower of a pooled connection.publicwhile a DSN may select a schema (suppressed, three places).options=-c search_path=<schema>is a form the runner supports and validates, and in that configuration the DDL landed in the selected schema while the served role got no USAGE, no table grants and no default privilege there —verify_runtime_accessthen failed the migration and the install could not start.OPENDOX_PG_SCHEMAcarries it through both bootstrap scripts, compose,.env.example, the StatefulSet and the ConfigMap, and the schema is created, owned by the migration owner, before it is granted on. The bootstrap cannot read a DSN — it is the database container's environment and a DSN carries a password — so the runbook states that it must be the same schema, and a mismatch is a failed migration rather than a failed first request.alter default privilegesfollows the ROLE, so a shared migration owner widens it silently (two threads and one suppressed). Every table that owner creates from here on becomes readable and writable by the served role; on a reused database that is another application's data, which is the boundary replacinggrant … on all tables in schema publicwas meant to draw. The grant is now refused when the owner already owns a table this runtime did not create, which is what "a dedicated migration owner" means at the moment it becomes load-bearing. MEASURED on postgres 16.15 against the shipped statement: no row for an empty schema, no row for one holding only the seven coordination tables, exactly one row for an owner that also ownsinvoices— and that row'sdoblock raises naming both.\gexecruns nothing when there is no row, so thehaving count(*) > 0is the whole conditional and the fresh volume the script runs on sees no statement at all. Explicit per-table grants are not available here: at first start the tables do not exist yet, which is why the default privilege is the whole grant.1c6cd9e/174/291 against the workflow'sbb84c6c6/181/298. The body was updated tobb84c6c6, 181 and 298 before that review was written, and both places said the same head and the same counts at that moment; they sayad077e2f, 184 and 301 now. This is the third time that comparison has been made against a stale copy of this description, and the rule above the table is what keeps the two together.Independent adversarial review (opus-max, read-only, at
0860270f) — five findings, all fixedNot a Copilot round. A second reviewer with no history on this PR read the head in a fresh clone, reproduced the workflow's two invocations exactly (
101 passedhermetic,301 passedDB-backed — the figures this branch records), and produced one findings list. Classified: 5 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. Each case reproduces the reviewer's own input and fails against0860270f.OPENDOX_OIDC_ISSUERprinted its own password.config._split_urlinterpolated the driver's message, and CPython's_checknetlocraisesValueError("netloc '<the whole netloc>' contains invalid characters under NFKC normalization")— userinfo and password included. A hostname that is not ASCII is the ordinary case for an IDN broker, and_split_urlruns before the userinfo refusal, so the guard written to keep a password out of this very message never got to run. Measured:OPENDOX_OIDC_ISSUER='https://svc:hunter2@broker℀evil.example/realms/x'puthunter2on stdout fromopendox-runtime runtime statusand... runtime init, inside the JSON the lifecycle contract calls redacted evidence — andcli._safe_messagepassed it through untouched, because the leaked run isnetloc 'svc:hunter2@…', with no://and nopassword=. The exception TYPE is named now and the value is not; the cause is dropped withfrom None, so the chain a traceback would print is clean too. The case asserts the password is absent from the refusal, from_safe_message, from the exception chain, and from the verb's stdout.Path(cli.__file__)and nothing else, whileconfig.py,oidc.py,migrations.py,identity.py,app.pyanddb.pyall compose messages an operator reads. A25-1 lived in that gap for thirty-six review rounds. The scan is parameterized over every module in the package now, and the rule is stated rather than allow-listed by line: a library's exception text may not be formatted into evidence, and this package's own may, because this package wrote it — which is precisely what separatesapp._found'sstr(exc)on anidentity.NotFoundErrorfrom_split_url's{exc}on a CPythonValueError. A benign-attribute table (reason,start,code,sqlstate, …) covers the data reads,raise … from excis allowed, andtraceback.format_exc()/print_exc()/sys.exc_info()inside a handler are newly flagged. A bareraiseis deliberately not flagged, with the reason given. The scan is run against four shapes it must flag and six it must not.CachingJwks._matchselected bykidalone and never asked whether the selected key's TYPE could carry the token'salg, and PyJWT'sRSAAlgorithm.prepare_keyanswers an EC key with a plainTypeError("Expecting a PEM-formatted key.")— not aPyJWTError— so it escaped_decode's seven typed clauses, escapedverify, and escapedget_principal, which catchesOidcError. A realm publishing an RSA and an EC signing key is what Keycloak publishes the moment it has an ES256 provider beside the default RS256 one, and bothkids are public facts from the unauthenticated JWKS endpoint: any anonymous caller could sendBearer <RS256-shaped token, kid=ec-1>— the payload need not verify or even be well-formed past the header. The key type is bound to the algorithm family at selection, so the cryptography backend never sees the wrong key;_decodegrew a final(TypeError, ValueError)clause so no future PyJWT shape reopens it. A bonus the binding buys: akid-less token is now unambiguous where the algorithm picks one key out of a two-type key set. Measured at the library and at the HTTP boundary —GET /api/v1/users/meis 401, not 500./readyzand the API read schema B" — and no shipped workload holds both DSNs: the Deployment carriesOPENDOX_DATABASE_URL, the migration Job carriesOPENDOX_MIGRATION_DATABASE_URL, compose splits them the same way,migrateandresetdo not callload_settingsat all, and this suite's own cases pin that split because the separation of the privileged and the served identity is the point. So the control existed and could only fire in a developer's shell.OPENDOX_SERVED_SCHEMAis a schema name and never a credential, which is exactly why the workload that must not hold the served DSN can be told it:MigrationRunner.refuse_a_schema_the_api_will_not_readrefuses before the ledger is bootstrapped, and both deployments take the value from the samepg_schemathe first-start bootstrap grants in, so one edit moves the schema, its grants and this refusal together. Declared-and-unset is the bundled single-schema install, not an error.exp. PyJWT appliesOPENDOX_OIDC_LEEWAY_SECONDSas slack on expiry, so999999999was a legal configuration under which no token ever expires — a security property turned off by a number, with nothing saying so.MAXIMUM_BY_SETTINGbounds the leeway (300s, generous for clock skew), the JWKS TTL and the bind port, and the case is driven from that table so a bound that moves moves the case with it. The same helper handed the string straight toint(), which takes Python's underscore separators:3_0_0was silently 300. Digits only now.Confirmed clean by the same review, and recorded so it is not re-audited: migration discovery/ordering/de-duplication (the zero-padding bypass is closed by the four-digit filename shape),
snapshot_run's decode-before-mutate atomicity, thesearch_path/optionsparsing,redacted_url,FileJwksSource's typed errors,CachingJwks's locking (no self-deadlock, no stale serve, fail-closed cooldown), the Kubernetes runbook's secret sequence, the dev overlay's image pin,load_migration_settings, and the algorithm allow-list itself.Review rounds 37, 38 and 39 (Copilot reviews
5248370624at0860270f,5248856351atb9bc3167,5248961642at48de5833) — five threads, one batchAnswered as ONE batch and not five rounds, on the holder's ruling after thirty-six consecutive rounds each produced a real finding: every open thread fixed together, one regression apiece, each premise measured rather than argued. Three pushes carried these three reviews' worth of work (
2e400a4a/b9bc316, the52b237ebase merge into48de5833, and2c3e9bae/056d1597here), and two merges ofmainare in that history —52b237e(§ 3.4 S7 residue) and the retired intent-feed suites — so the figures above are stated against the head that produced them and not against the branch point.schema_selected_bytook the FIRST-c search_path=where libpq takes the LAST.optionsis a list of arguments and a repeated assignment is an override, which is exactly how an operator ends up with one: a base DSN plus an appended-csearch_path=<tenant>. Measured on postgres 16:psql "…?options=-csearch_path%3Dold -csearch_path%3Dnew"thenshow search_pathprintsnew. So the preflight read a DSN as saying what it overrode, and two DSNs that genuinely select different schemas could compare equal — the same class of false agreement round 36's comma fix closed one layer down. The scan keeps going and returns the last assignment; five cases, including "a later-cfor a different setting is not an override" (the error the fix could have made in the other direction) and the interaction with the first-entry reduction.database_named_byread the URI path and ignoreddbnamein the query.postgresql://host/?dbname=oneand...?dbname=twoboth answeredNone, so the two-DSN guard passed a pair naming two different databases — and a path-and-query pair answered with the path, which is not what connects. Measured againstPQconninfoParseitself (psycopg.conninfo.conninfo_to_dict, the parser that actually decides):postgresql://h/frompath?dbname=fromquery→fromquery,…?dbname=one&dbname=two→two,host=h dbname=one dbname=two→two. The query beats the path and the last assignment wins, in both DSN forms; the preflight now refuses the two-URI pair it used to pass, and the refusal still carries no credential./readyzbounded each PHASE and called it a total.SET LOCAL statement_timeoutis per statement, and a phase is several: driving the realMigrationRunner.plan()and.drift()against a recording connection issues seven statements under three bounds (selected_schema, theto_regclassledger probe and the ledger read, twice over, plusselect 1) — a worst case of 7 × 1.5s = 10.5s against a declared 3.0s budget, all of it inside the probe's own 25stimeoutSeconds, so nothing downstream would have reported it and probes would simply have overlapped.WithinTheDeadlinewraps the connection and re-applies the bound before every statement from one deadline, capped at the smaller of the ceiling and what remains. The test drives the real phases twice: with every statement taking all it may, the budget is spent and the probe is refused partway (which is the point — not ready rather than late); at 10ms a statement all seven run well inside it. A hermetic AST case pins the shape so no future edit re-introduces a rawconn.executeinside the readiness transaction.project_repositories.remote_urlwas free text with nothing judging it. The migration argues only the column's NULLABILITY, sohttps://ci:hunter2@github.com/o/r.gitwas a legal row: stored in the clear in a database RULING Q1 gives identity and coordination and not secrets, returned verbatim byGET /api/v1/project-repositoriesto every member of the project, in every backup, and handed togitby § 3.6. Both layers, because either alone is half:identity.refuse_a_remote_url_that_carries_a_credentialrefuses at the store — the column's only writer, and both of its writers — and_repository_jsonplusProjectRepository.__repr__redact a row that got in some other way (an earlier build, a restore,psql).config.credential_in_a_remote_urljudges the two shapes git accepts — the URL authority and the scp-like[user[:password]@]host:path, whichurlsplitreads as a bare path — and calls an ordinaryssh://git@host/…clean, because that userinfo is a username and not a secret. The refusal names the shape and never the value, and the redactor changes nothing the predicate calls clean, which is a property the case asserts over every shape at once. Measured at the previous head: the store accepted it,reprprinted it and the API returned it.0860270/184/301 in this description while the workflow recorded2e400a4a/196/317; the description had already been updated to2e400a4aandb9bc316with 196 and 317 by the time the review was submitted, and both places have named the same head since. The table above and the workflow's comment block now both say2c3e9bae, 197 and 320.Review round 40 (Copilot review
5249443180at056d1597) — one thread, four suppressed, three FACTSubmitted at this branch's own head while the five threads above were being answered, and read before it was replied to. Classified: 3 FIX, 1 answered-and-left, 1 already reconciled.
runtime resetnever asked the served-schema declaration, andmigrate --plandid not either. A25-3's guard was a METHOD reached fromapply()alone, so of the three acts that change or preview a schema, two did not ask. Measured at056d1597with a migration DSN selectingt_35e62eb47603andOPENDOX_SERVED_SCHEMA=somewhere-else:migrate --planexited 0 printingplanned: ['0001', '0002']— a preview of a runapply()would refuse, which is the answer an operator checks before committing to the real one — and a confirmedresetexited 0 having dropped the coordination table in a schema the declaration says the API does not read (tables left: []). The guard is module-level now, one definition and three callers, and it is asked before the firstDROPand before the plan is printed; its last clause reads "nothing has been changed", because a refused reset has not applied anything either. DB-backed regression drives both verbs against a real schema, refused with the table still there, then re-runs both with the declaration agreeing so the guard is a refusal of a mismatch and not of the feature;test_deploy_shape.pypins all three call sites by position, matching the DDL and not the paragraph that quotes it._SECRET_PARAMETERwasre.compile("|".join(SECRET_PARAMETER_KEYS))asked with.search(), so any name merely containing one of the words matched. Measured at056d1597:monkey,sigma,tokenizer,authority,keyspaceandkeyboardall matched, andredacted_url("https://broker/certs?monkey=1")returnedmonkey=<redacted>. A valid explicit JWKS URL or git remote carrying such a parameter was refused as credential-bearing — a false refusal at the configuration boundary, where the cost is an install that will not start for a reason that is not true, and the reviewer was right that my own remote-URL predicate had just inherited it. The decoded name is split into words — every non-alphanumeric run and each camelCase boundary — and each word compared whole, soaccess_token,X-Api-KeyandsessionTokenstill match; the declared list is untouched, because the sibling PR pins the two spellings of it together. The case drives nine benign names, nine carriers, every declared word, and all three callers.61ab857c, 198 and 322.bytes_before < budgetbounds what PRECEDES a row, so a page can carry the budget plus one row, and the reviewer is right about the arithmetic. It is deliberate and documented: the budget bounds what is fetched before a row is decided on, the page stays a prefix soafterpagination is unchanged, and a draft larger than the whole budget is still returned rather than being permanently unreachable. Including the current row in the predicate with a first-row exception is the same bound with an extra branch.Review round 41 (Copilot review at
0968ff8b) — one FIX taken here; three findings remain and are named/walked through the scp branch, and it was this batch's own defect.credential_in_a_remote_urlread the text before the FIRST/, which is the shape of an scp-like authority — soci:hun/ter2@github.com:o/r.gitwas reduced toci:hun, read as a username with no password and called clean. Measured at0968ff8b: the predicate answeredNone, the store accepted the row, andredacted_remote_urlreturned it unchanged, which is the API handing a password to every member of the project. It is round 29's shape on the sibling PR — a bound that excluded/defeated by a password holding one — and takes the same answer: the last@in the whole value, with the over-detection stated rather than hidden (a local path that really contains:…@before its last component is refused by name; a value carrying whitespace is left alone, so this cannot start eating prose)._scp_like_userinfois one definition and both the predicate and the redactor ask it. The carrier joins the existing case, so the figures do not move.THREE FINDINGS FROM THIS ROUND ARE OPEN AND ARE NOT SILENTLY DROPPED, because each is a decision rather than a repair, and this act does not make a decision of that size inside a review round:
config.py:983— when both DSNs omit an explicitdbname,database_named_byanswersNonefor both and the guard accepts the pair; libpq then defaults the database to the connection user, and the migration and served users are different by design. The remedy is to resolve the effective name (dbname, else the user) and refuse a pair that differs, or to require an explicit name.config.py:920—"$user"is a search-path token, not a schema; two DSNs for different users withsearch_path="$user",publiccompare equal while PostgreSQL resolves them to different schemas. The remedy is to treat that entry as unresolved rather than as a literal.deploy/kubernetes/base/migration-job.yaml:206— the served-database identity has no non-secret declaration, only the served schema.OPENDOX_SERVED_SCHEMAis the precedent (A25-3): a name, never a credential, so the workload that must not hold the served DSN can be told it. The same shape for the database would close this, and it is a new setting plus four manifest edits — a declared act, not a fix inside a round.The third mini-batch (RULED by Brett Heap on openxFactory#656, ~2026-09-18 17:55Z) — the two security-relevant findings, taken
Both premises measured on postgres 16 and through
PQconninfoParse, one regression each. At68ebea49the guard ACCEPTED three of the four shapes these cases forbid, and refused the fourth for the wrong reason.database_named_byreports what the STRING says, so a pair that both leave the database out both answeredNoneand the preflight read that as agreement. libpq defaultsdbnameto the connection user, and this deployment's two DSNs carry deliberately different users — the privileged migration identity and the least-privileged served one, which is the whole point of the split. Measured:postgresql://opendox:…@host:5432/— no database anywhere in the string — connects andselect current_database()answersopendox;PQconninfoParsedoes not fill the default in, so it is invisible in the parse and applied at connect.effective_databaseresolvesdbname, else the user. With neither in the string the answer is UNRESOLVED and the pair is refused: libpq then falls back to the operating-system user of whichever process connects, and the two DSNs are used by two different containers. That is the contract this guard already has — it answers before anything connects, so a comparison it cannot make is a refusal, exactly as for a broker URL it cannot parse; resolving the database after connecting was the alternative and is not available to a configuration-time check without a network. The refusal says where the name came from, because it is nowhere in the operator's own DSN."$user"is a token and was compared as a literal. Two roles' DSNs both selecting"$user",publicagreed on the string while PostgreSQL resolved them to two different schemas. Measured on postgres 16, three ways:set search_path = "$user", publicwith no matching schema givescurrent_schema() = public; with a schema literally named$usercreated it is stillpublic; and with a schema named for the session user it is that schema. So PostgreSQL never reads"$user"as a schema NAME even when one exists — which is why substituting the DSN's own user here matches the server, and which also measures FALSE the suppressed finding atmigrations.py:484that a real$userschema is mistaken for the token. (set search_path = $userunquoted is a syntax error; the token is always written quoted.) The token with no user in the string is UNRESOLVED rather than "names no schema" — reading it as the latter would have compared equal to a DSN that really names none, the same false agreement one step along.user_named_byis new and reads a name, never a credential: the user name is in every server log line, inpg_stat_activityand in a committed ConfigMap; nothing here touches the password. Its precedence is measured through libpq — the query beats the userinfo, the last repeat wins, and the userinfo is percent-decoded.REGISTERED AS A FOLLOW-UP ACT, under the same claim — not built here
The served DATABASE has no non-secret declaration, only the served schema (
deploy/kubernetes/base/migration-job.yaml:206).OPENDOX_SERVED_SCHEMAis the precedent (A25-3): a name, never a credential, so the workload that must not hold the served DSN can be told it. The same shape for the database —OPENDOX_SERVED_DATABASE, checked againstcurrent_database()before the ledger is bootstrapped — closes it without giving either workload the other's DSN. That is a new setting plus four manifest edits and a guard, ruled a separate act and deliberately not taken in this batch.SonarCloud — answered in full, and it is advisory on this lane's gate
The first analysis of this PR failed one Quality Gate condition, "E Security Rating on New Code", over 32 issues. Twenty-nine are fixed and three are answered:
Fixed —
--only-binary :all:on both installs this act adds (a real hardening: without it pip may build a dependency from an sdist and run itssetup.pyin the job; measured in a clean venv before it was declared); the CI Postgres password and its DSN both marked, onxFactory-Hermes-Install's own precedent, which marks both halves;jwt.get_unverified_headermarked with the reason that reading the header is the only possible order and nothing in it is trusted; and eight real smells — a subclass named beside its base in anexcepttuple,verify's cognitive complexity (the seven-clause PyJWT mapping is now_decode),responses=REFUSALSon every authenticated router, four invalid# noqacomments, one duplicated literal, and fifteen test-file nits (bare@pytest.fixture, composite assertions split so a failure names which half failed, one throwing call perpytest.raisesblock).Answered, not fixed, and each is recorded rather than argued away:
githubactions:S8544/docker:S8544— "dependencies without locking resolved versions". This is the--require-hasheslockfilepyproject.tomlalready names as the obvious successor and as a real act with a real owner;xFactory-Hermes-Installcarries auv.lockfor exactly that reason and this leg carries none. A § 3.5 PR should not invent this leg's supply-chain pin, and inventing one would also be the only route to a green Sonar gate — which is precisely the wrong reason to do it.githubactions:S8541atvalidate.yml:29— the pre-existing install step of the required job, unchanged by this act and outside its declared edit surface.python:S8415×5 — four of the five sites are helper functions (_require_role,_found,_conflict), not routes, so the rule cannot see theresponses=REFUSALSthe routers do declare. The published OpenAPI schema is correct; the finding is about where the raise textually sits.And one defect SonarCloud's own answer introduced, caught by measurement rather than by a review: adding
--only-binary :all:as a plain YAML scalar madevalidate.ymlunparseable (:is a mapping indicator), so at head4d3ce664GitHub ran no job at all —gh api .../actions/runs?head_sha=…returns a run named for the file itself, and neithervalidatenorruntimeappears in the check list. The absence of a run looks like nothing on a PR page, so the repair commit also adds four suites totests_runtime/test_deploy_shape.py: the workflow parses, both jobs are declared with this act's step appended after the existing one, the runtime job supplies its Postgres service and installs with the flag, and the required job installs the test extra alone — because if it ever installed.[runtime], every assertion about what imports without the extra would still pass and would stop meaning anything.The lifecycle, run end to end as a process (2026-09-16)
Not a test: the installed
opendox-runtimeconsole script, a real Postgres, a real socket.docs/runtime.md§ 8a carries the transcript.runtime init["0001","0002"]on diskruntime migrate0001and0002runtime statusok: falseGET /livez{"status":"live"}GET /readyz{"database":"ok","schema":"applied","broker_keys":"unavailable: …"}GET /docsOPENDOX_PUBLISH_OPENAPIGET /api/v1/projectsruntime reset --confirm …statusand/readyzare deliberately not healthy there: that environment has no Keycloak broker, and both surfaces say so by name rather than reporting green. The database half is green in both, the schema is applied and nothing has drifted — which is the whole of what this act can prove without a broker, and it proves it rather than asserting it.Four decisions, RULED
RULED openxFactory#656 comment
5701772032(Brett Heap, 2026-09-16, by interactive multi-choice). All four answers are what this PR already did, so the ruling cost no re-authoring — it cost a citation, which ise9bec39on this branch and the matching commit on #26:repository_act.)write_backRECORDSbasis_revisionas a commit trailer; the compare-and-swap ref move is what decides staleness. (§ 3.6: openDox creates a repository as a first-class act, with RULING C3's conformant local-git adapter #26'slocal_git_adapter.)runtimeCI job stays ADVISORY now and is made required in a separate declared act. Cited in.github/workflows/validate.yml's own block, beside the sentence that records the gap.opendox.cliin the BUILD-arc act that repairsopendox.serve;opendox-runtimeis the spelling until then. Cited inopendox/runtime/cli.py's header, where the two spellings are explained.Review round 5 (Copilot review
5225958167at7213b0a4) — every finding fixed, each with an assertionGET /users/{id}were not the same answer. The row was read first, so a missing user came back asno user with id=…and a hidden one as a visibility message: one status, two bodies, the same enumeration oracle wearing a different hat. Visibility is asked FIRST and both refusals are one_NO_SUCH_USERconstant that names no id at all.protect_ledgernarrows. The served DSN is an out-of-band Secret, so an overlay serving as another role left the REAL served role able to rewrite the migration ledger.runtime_pg_roleis now a literal in theopendox-runtime-configConfigMap, read throughconfigMapKeyRef, and the runbook says beside the Secret that the two are one role.OPENDOX_PUBLISH_OPENAPIreached no container..env.exampledeclared it,config.SETTINGSread it, the runbook's boundary table named it, and neither the compose service nor the Deployment passed it — so the documented switch changed nothing and/docsstayed 404 with no way to tell why. Both deployments pass it now, default OFF.nowwas read BEFORE the lock, so a caller arriving while another fetched re-evaluated staleness against a pre-fetch clock and refreshed in turn. The clock is read inside the lock and stamped after the fetch. Measured with staggered arrivals: 6 refreshes for one TTL boundary before, 1 after — and the stagger is the test, because eight threads sharing one instant cannot tell the two shapes apart.runtimejob whosepostgres:16service failed to start went green while running no database-backed assertion. In CI that absence is now a failure; a developer still skips.runtime resetdropped through the search path.drop table if exists usersin a schema that has nousersresolves topublic.users— one tenant's confirmed reset taking another tenant's table, under a verb whose promise is "this schema's coordination state and nothing else". The drops are qualified withcurrent_schema()throughpsycopg.sql.Identifier, no-current-schema is a refusal, and the evidence reports the schema. The test fails naming the lost column against the unqualified shape.COPY srcorder does not give it. Both are fixed in the only direction that is true, and the comment names the--require-hasheslockfile act where the split belongs.