Skip to content

§ 3.5: the openDox runtime — FastAPI + Postgres, identity and coordination, and nothing else (RULED Q1/Q2) - #25

Merged
brettheap merged 102 commits into
mainfrom
build/3-5-runtime
Sep 18, 2026
Merged

brettheap merged 102 commits into
mainfrom
build/3-5-runtime

Conversation

@brettheap

@brettheap brettheap commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

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 openxFactory main.

The two rulings this realizes, in their own words

RULING Q2 — #656 comment 5542792997, Brett Heap, 2026-09-04T15:31Z: "reuse the Hermes install pattern — FastAPI + Postgres, deployed the way xFactory-Hermes-Install is (live on AKS since 2026-07-19), OIDC through the Keycloak broker being adopted in QA". Rejected there: "bolting a database onto today's stdlib serve.py monolith; a new full-stack platform."

RULING Q1 — #656 comment 5542694957: "the database owns identity and coordination; git owns governed artifacts. Users, memberships, projects, the project-to-repository mapping, sessions and unsaved drafts live in the openDox database. Specs, changes, ideation documents and contracts stay in git, read from repositories and written back only through the apply lane. … the database is disposable relative to the corpus." Rejected: "documents in the database with git as an export; and the hybrid (ideas in the DB until promoted)."

What this PR does

migrations/, at the root of this leg — § 3.5's own sentence is "all at the root of openDox-code, not of the assembly root", and tests_runtime/test_migration_shape.py asserts 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_SHA256 declares 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 every validate. Changing the schema is an additive 0002_… 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 in deploy/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 %s parameter), 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 closed COLLECTIONS tuple, read against the routers build_v1_router actually mounts. The unauthenticated surface is /livez and /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, /redoc and /openapi.json as well; those are OFF unless OPENDOX_PUBLISH_OPENAPI says otherwise, and tests_runtime/test_api_endpoints.py ENUMERATES the running app's unauthenticated routes against that list rather than trusting this sentence. Everything else resolves a bearer token to an identity.User row and then asks memberships.role about 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_request runs 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. reset needs 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/ and deploy/kubernetes/, on the Hermes install's shapes. The migration identity and the served identity are separate in both, and config.migration_database_url refuses 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.py refuses a kind: Secret anywhere under deploy/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, so src/opendox/runtime/cli.py's header writes it down:

  • src/subcommand_extension.py is for a layer above contributing a subcommand — that is openXdox, and the runtime is not that layer;
  • src/opendox/cli_project.py states the counter-rule for openDox's own verbs in terms: "FIXED CORE, NOT AN EXTENSION … these verbs are registered by build_parser directly";
  • and they cannot go there in this act, for two measured reasons. src/opendox/cli.py is 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. And opendox.cli cannot be imported at this leg at all: it reaches opendox.serve, whose line 192 from ideation_dashboard import serve_openxfactory_lanes exists at neither carve destination, which tests/test_consumer_reach.py::STILL_REACHING records 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-runtime runs the verbs today, and RuntimeSubcommand wraps the same registration function in an object that structurally conforms to subcommand_extension.SubcommandExtension (asserted with isinstance). The day opendox.cli imports, 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

  • It lifts no part of RULED Q-L5 (b′). opendox.serve still cannot import at this leg. Nothing in opendox.runtime depends on that being repaired: the runtime imports no part of opendox.serve, and the two are joined only by the project-to-repository map row.
  • It creates no repository. That is § 3.6, the PR stacked on this branch. A project with no repository is a visible state here (GET /project-repositories/{id} → 404), which is the shape § 3.6's act fills.
  • Design § D5's unresolved residual stands, unresolved: "The hybrid where ideas live in the database until promoted was REJECTED, so an idea is a governed document in git from its first save — consistent, and heavier than a lab assistant may want. Whether openDox needs a pre-governed scratch space that is NOT 'a draft of a document' is a real residual, it is not one of the open questions." drafts is the draft of a document and is not that scratch space. Recorded in docs/runtime.md § 9 and here.
  • The runtime CI 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.
  • Not taken from 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 its layer token claim — openDox is single-layer, so that would be a shape without a meaning; its worker-readiness surface; its correlated backup job; and its uv.lock supply-chain pin, which pyproject.toml already 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_roots over rows_for(manifest, "opendox_code") (119 effective rows) returns exactly ['src/opendox', 'tests']. So migrations/, deploy/, docs/runtime.md, pyproject.toml, .gitignore, .github/ and the new tests_runtime/ tree need no admission (under_roots is segment-aware — "tests_helpers/x.py is not under tests"), and the eight files under src/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.yml is append-only against main — 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.

  • A new step in the required validate job runs the hermetic suites under that job's existing pip install -e ".[test]" — no FastAPI, no psycopg, no PyJWT. That is the package's declared import-weight contract, and tests_runtime/test_runtime_surface.py measures 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 in sys.modules.
  • A new job runtime carries a postgres:16 service (the Hermes install's own CI shape) and pip install -e ".[runtime,test]" for everything that needs a database, a token or a web framework. Where OPENDOX_TEST_DATABASE_URL is 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 whose postgres:16 service 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 the runtime extra made UNIMPORTABLE, which is the required job's own install — and holds at the current head abc7f634, 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.

run result
the required validate job's own invocation (--noconftest, the five hermetic modules that job names) 200 passed, 1 skipped
python -m pytest -q tests_runtime/ with OPENDOX_TEST_DATABASE_URL set (the runtime job's invocation) 324 passed
python -m pyflakes src/opendox/runtime/*.py tests_runtime/*.py clean
yaml.safe_load over .github/workflows/validate.yml parses; jobs ['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 psycopg to 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 → 200 on the required invocation and 115 → 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 → 324 on the full suite: each rise is assertions added to answer a finding, never a suite widened to look busier.

Review round 4 (Copilot review 5225498056 at 45bb29c5) — eight findings, all fixed

  • The read routes did not ask the question this module's contract said they did. GET /users, GET /memberships, GET /projects and 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 repository location and remote_url. The scope is now the MEMBERSHIP ROW, applied in SQL; a row the caller may not see is 404 for a user and 403 authz.not_a_member for a project — which is also what an id that exists nowhere gets, so the pair is not an existence oracle.
  • The migration run's advisory lock did not cover the work it named. apply() held MIGRATION_LOCK_KEY on 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 with max_size=1. runtime reset had the identical shape.
  • The ledger was narrowed after the migrations, not before, so a wrong runtime_role failed the run only once everything had committed — and /readyz asks about schema and drift, never grants.
  • defaultMode: 0o555 is a string in YAML 1.1 and the API server rejects the StatefulSet before Postgres starts.
  • The migration Job raced the Postgres StatefulSet on a clean install and could retire itself inside backoffLimit: 2.
  • list_drafts collected the principal's sessions with one capped query, so a user with more than MAX_PAGE_SIZE sittings lost the later ones' drafts and was refused its own session by name.
  • POST /memberships carried on conflict … do update set role, so a repeat silently changed a role and still answered 201.
  • init reported a valid install when the repository root existed as a file; serve was the one lifecycle verb that printed no evidence on an ordinary shutdown; STDLIB_ONLY_MODULES omitted § 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:

  1. 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.
  2. 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.

Review round 6 (Copilot review 5226506490 at e9bec395) — four threads and nine suppressed comments, every one answered

  • ONE NAME FOR THE SERVED ROLE. .env.example declared OPENDOX_RUNTIME_PG_USER (which created the role) and OPENDOX_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.
  • AND THE NARROWING IS MEASURED. revoke succeeds and changes nothing for the ledger's owner, a superuser, or a role holding the write through another grant. _narrow_ledger asks has_table_privilege for each of the four writes and raises LedgerNarrowingIneffectiveError when one survives; the narrowing is a precondition of the run, so nothing is applied.
  • /readyz verifies the pinned 0001 BEFORE it calculates a plan. discover() returns [] for a directory that exists and is empty, so an image that lost the canonical file made plan() and drift() both empty on a fresh database and readiness reported schema: applied.
  • A request body is bounded. BodySizeLimit is a pure ASGI middleware: a declared Content-Length over 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, because opendox.serve* cannot be imported at this leg (RULED Q-L5 (b′)).
  • The nine suppressed comments are answered one by one in this comment: the compose healthcheck's literal port and the repositories volume's literal path (both now follow their settings), the Kubernetes root held EQUAL to the mountPath it is claimed at, the readiness probe's missing timeoutSeconds, a foreign-key race that escaped as a 500 instead of the documented 404, a discovery regex broader than the filename contract, and an importorskip that let the runtime job pass without exercising a single OIDC or API case.

Residue this act records rather than resolves (round 6)

  • The served process does not assert its own current_user. The runner now refuses a narrowing that changed nothing, and creation, narrowing and the served DSN derive from one .env declaration — 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 5226856961 at 51cfff71) — three threads and nine suppressed comments, every one answered

  • Two files claiming one version made apply() 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_migrations refuses the directory by name, before anything is mutated, for every caller.
  • The Kubernetes bootstrap created a role the migration did not narrow: the StatefulSet hard-coded opendox_runtime while the Job read runtime_pg_role. Both read the same ConfigMap key now — the Kubernetes half of the one-name rule the compose package got in round 6.
  • The narrowing interpolated an UNQUOTED identifier while the bootstrap creates the role with %I, so a configured MyRole had its revoke and grant folded to myrole: a different role, or none. Quoted here, and measured against a genuinely mixed-case role.
  • The nine suppressed comments: two existence oracles (a session and a draft read by id, each answering 404 for an unknown and 403 for another user's — one refusal each now, naming no id), migrate --plan skipping the canonical gate apply() runs first, status reporting pending migrations and staying healthy (and now running that same gate, because an empty directory otherwise reads as "nothing pending"), status blaming the database for a failure of the TREE, an importorskip that 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 fixed

  • serve could not tell "served and stopped" from "never started". uvicorn.run does not propagate a lifespan startup failure — uvicorn logs it and the loop returns — so the verb emitted ok: true and exited 0 for a process that never served a request. An explicit uvicorn.Server(uvicorn.Config(...)) runs, and server.started decides which evidence is emitted.
  • Nothing below the canonical version is a migration. The filename shape accepts 0000_*.sql and discovery only ordered and de-duplicated, so such a file ran BEFORE the pinned 0001 — 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, uvicorn and jwt made 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 fixed

  • The miss cooldown's clock was read before the lock, which is the same correction keyset took 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 annotated float: the arithmetic is float throughout and the suites cross TTL boundaries on purpose.
  • DROP_ORDER names the ledger through migrations.LEDGER_TABLE rather than spelling it twice — the one moment two spellings differ is a rename, after which reset would drop six of seven tables and report all seven.

Review round 10 (Copilot reviews 5227436293 at ab7f2110 and 5227525961 at 6e09fbe5) — twelve findings: eleven fixed, one answered by citation

Classified 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:

  • A draft could be written into a session that had ENDED. require_open=True is a promise about the WRITE, and the route's check and the upsert were two statements — a DELETE /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 (409 coordination.session_closed from the pre-check, which still gives the better message); the raced one is 404 coordination.not_found.
  • DELETE /drafts/{id} called delete_draft directly, 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 /sessions inserted 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_session goes through _conflict_if_duplicate now (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_member for a draft that exists and authz.not_your_session for 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 serve could not report (uvicorn swallows a lifespan error). Server.run() also RAISES — SystemExit from uvicorn's own sys.exit(1) on an occupied port, OSError for 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. SystemExit is named explicitly because except Exception does not reach a BaseException, and the refusal names the host and port it tried and is redacted like every other message this CLI emits.

status no longer rewrites an answer it already has. Once select 1 has succeeded the database IS reachable, and a later failure — a served role without select on the ledger, a search path that misses the schema — was reported as database: unreachable, pointing an operator at the network for a privilege problem. It is database: reachable plus schema_queries: failed: … now. Round 7 made exactly this distinction for the runner's own MigrationError and 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, /readyz reported an applied schema, and every request then failed with permission 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.md states it as an explicit PREREQUISITE with the four statements the bundled script performs, and tests_runtime/test_deploy_shape.py DERIVES 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 with AttributeError. The contract is stated in full (four members), and two hermetic tests hold it: one drives a whole apply() 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 for load() — the rotation and counting sources in test_oidc_verifier.py are third implementations already. JwksSource is a runtime_checkable Protocol now, so the annotation and isinstance ask 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 periodSeconds at 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_runtime docstrings 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, at 6e09fbe5 — 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 at f9c72341 — is the same in the workflow block and in the table above, which is the number that matters.

Review round 11 (Copilot review 5228860529 at cd22da4d) — nine findings: eight fixed, one answered by measurement

Classified 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).

  • The role password was in a process argument. psql -v runtime_password=… puts it in argv, where ps and a world-readable /proc/<pid>/cmdline can 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. \getenv reads 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: \getenv sets the variable, %L quotes it, and pg_roles shows the role created with login.
  • The byte pin did not cover the bytes that ran. apply() read 0001 three times — the gate, checksum(), then read_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.
  • The streamed half of the body cap answered the wrong refusal, and Copilot asked for the test that found it. FastAPI's body parser wraps its read in except Exception and turns anything it catches into 400 "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 documented 413 request.too_large, unmeasured because the only cap test sent a declared Content-Length. _BodyTooLarge is a BaseException now, which passes that handler and reaches the middleware — the only frame that can answer for a request whose body it refused.
  • The documented first command could not run on a clean checkout, in all three places that document it (the runbook, .env.example, and the compose file's own inline runbook). docker compose run does not build by policy — it is the only one of run, up and create with no --no-build flag, because it has nothing to suppress — and the default OPENDOX_IMAGE is the local tag opendox-runtime:local, which no registry has. --build on that one command; up -d needs none, and the comment says why.
  • The migration Job could exhaust itself while Postgres was still recovering. The initContainer proves a LISTENER, and a database replaying a crash recovery listens while answering "the database system is starting up"; the wait carries no credential — deliberately — so it cannot tell that from ready. The honest probe for that case is the migration container itself, which opens a real session, and the Job's retry budget is what makes that a wait rather than a failure: backoffLimit 2 → 6, about ten minutes under Kubernetes' exponential backoff.

Answered by measurement, no change. The review reports that this description "identifies 6e09fbe5 as the current head and reports 197 passed" while the workflow says f9c72341/211. The description said f9c72341, 118 and 211 at the time of that review and says 5d86d8b8, 132 and 236 now; the sentences naming 6e09fbe5 are 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 5229072217 at 3e524f08) — five findings, all fixed

Classified 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.

  • The bootstrap's default privileges belonged to whoever ran the script, not to the role that creates the tables. alter default privileges is 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) meant 0001 created the six tables with no privilege for the served role at all: the Job succeeded, /readyz reported a reachable database and an applied schema, and every API request failed permission denied for table …. The grant now names the owner — OPENDOX_MIGRATION_PG_USER in compose, the migration_pg_user ConfigMap 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 by mig_owner leaves the served role holding SELECT|t INSERT|t UPDATE|t DELETE|t; against the old script, f f f f.
  • And the run now MEASURES that, because a grant that was never made is invisible until a request fails. MigrationRunner.verify_runtime_access is 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, and RuntimeAccessMissingError naming the missing table:privilege pairs 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.
  • The canonical gate covered the first read, not the run. verify_canonical_digest() hashed 0001; bootstrap_ledger() and protect_ledger() then COMMITTED the ledger table and its privilege changes; and only the loop's re-read raised CanonicalDigestMismatchError. 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 wrong 0001 changes 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.
  • The drafts listing was bounded in rows and not in bytes, and a row is a document here. Each body is capped at MAX_REQUEST_BODY_BYTES (1 MiB) on the way in and MAX_PAGE_SIZE is 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_BYTES is 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 so after pagination 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.
  • The managed-database prerequisite typed the password into SQL. It asked an operator to substitute a value inside a single-quoted literal, where a ' is a syntax error — or, worse, silently a different password — while the bundled script it is derived from has read it through \getenv and quoted it with %L since 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 w0rd creates 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 5235999257 at 84cbe14e) — one thread and five suppressed comments

Classified 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).

  • A close in flight raced the draft write. Round 10 put the session-open predicate INTO the insert, which closed the interval between the route's check and the write; it did not close the one inside the statement. Under READ COMMITTED the exists subquery reads the snapshot the statement began with, so a close_session committing AFTER that snapshot and BEFORE this transaction commits still left the draft written into a sitting that had ended — which is exactly what require_open=True promises cannot happen. for update makes 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 raises NotFoundError when the close commits; the old shape's had already returned saved, with the draft in the database before the session was closed.
  • Two claims the code does not keep, corrected in the text — because in both cases the behaviour is the decision. 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. And upsert_user's said the display fields are "refreshed on every login" while the SQL coalesces: this runtime sees ONE TOKEN PER REQUEST, not a profile event, and whether a token carries email depends on the scopes it was issued for, so assigning excluded.email directly 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.
  • The managed-database prerequisite substitutes nothing by hand. It still carried '<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 \getenv and is quoted by format'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, and pg_default_acl shows the grantor is the migration owner and the grantee "Svc Role".
  • The compose package's repository root must be absolute, and now says so where it is set. The application's own default is the relative var/projects — right for a developer running opendox-runtime directly — and the compose file uses the configured root as the project_repositories volume's container mount target. Measured on Docker Compose v5.5.1: docker compose config ACCEPTS a relative target and the daemon refuses at container creation with invalid 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 named 2052e1e6/126/223 since, and both name 5d86d8b8/132/236 now.

Review round 14 (Copilot review 5236637540 at f6b7a19c) — two threads and five suppressed comments

Classified 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 qualified runtime reset's drops and round 6 qualified the ledger read precisely so that nothing resolves through search_path — and the qualification itself resolved through search_path, because current_schema() answers the first existing schema on the path and never the first configured one. Measured on postgres 16.15 with no tenant schema: set search_path = tenant, public gives current_schema() = public, current_schemas(false) = {public}, and show 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() reported public's ledger as the selected schema's, after which plan() calls a fresh schema migrated and /readyz calls it ready, and runtime reset qualified every drop as public.* 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 replaces current_schema() in _check_runtime_access's predicate one method along, where measuring public'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 default search_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 — a users table in public, a schema that is never created, and a DSN that selects it; the reset refuses with nothing dropped and public.users intact.

  • The command this service PRINTS was not a command. register() nests every verb under the runtime group, so the shortened spelling — the console script followed straight by a verb — exits 2 with argparse's usage error. Measured through the parser: ['migrate'] raises SystemExit(2) with invalid choice: 'migrate' (choose from 'runtime'), and ['runtime', 'migrate'] is the verb. It was what runtime init's evidence emitted as its next, what /readyz told an operator to run while migrations are pending, what the runbook's transcript showed, and what a case in test_api_endpoints.py pinned — 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 in src/, docs/, deploy/ and tests_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 \getenv and be quoted by %I, and measured it by creating a role named Svc Role — which works, in the block. It does not work in the runtime: config.load_migration_settings refuses a served role that is not a plain SQL identifier before migrate connects, and MigrationRunner.protect_ledger refuses it again, because the ledger narrowing interpolates a role name into a revoke as 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 %I is 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 5237498282 at f86439b1) — one thread, fixed

Classified: 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() and runtime reset ask selected_schema, and bootstrap_ledger runs BEFORE applied() in _apply_locked. Its create table is unqualified — which is right, it must land where the connection's search_path selects — so on a connection configured for a schema that no longer exists it created the ledger in public and 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 of bootstrap_ledger's paths, and the DB-backed case measures the whole run rather than the reader alone — the tables in public before and after, with the refused apply() in between. Against the previous head it fails with "the refused run created tables in public".

  • 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 kid had already arrived in the new key set raised InvalidSignatureError against the old one it was still holding. A denied thread re-reads through keyset() 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. And has_table_privilege alone is not the question: without usage on the schema a role cannot name those tables at all, so a run could pass the check and every request still fail permission denied for schema. The list is RULING Q1's own, imported from identity rather than retyped; the schema's usage is 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 body and 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 5238724938 at 6c613232) — two windows left half-closed, both closed

Classified: 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_path is walked, not only its first entry. Round 15 compared the head of the path and exempted "$user" — so search_path = "$user", tenant, public with neither the role's schema nor tenant present stopped the walk at the exempt entry and accepted public: 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 against current_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 question selected_schema now 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_miss holds 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 to missing — a rerun after users was removed reported success and the API failed on the relation later. Restricting the scan to SERVED_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 different jwks_uri would 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. /readyz compares ledger versions and migration checksums and does not ask whether the six relations are still there, so an operator who drops users while 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, and verify_runtime_access is the call readiness would make.

Review round 19 (Copilot review at 2c56b65) — three findings, all measured, all real

Classified: 3 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. Each fix carries a case that fails against the previous head.

  • A libpq password holding a space was cut in half by the redactor. _DSN_SHAPED's password\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 conninfo password='secret value' matched only password='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. sslpassword is named too — \b before password does not reach it, and a private key's passphrase is the same secret. The case also pins the non-over-match: password=simple still ends at whitespace and passwordless=fine is untouched.
  • search_path resolution asks whether THIS ROLE may use a schema, not whether it exists. Round 16 walked the whole configured path and probed the skipped entries against pg_namespace — which proves the schema is there. PostgreSQL skips an entry the session lacks usage on exactly as it skips an absent one, so an existing but unauthorized tenant left missing empty, the fallback public was accepted, and every statement of the run went to public. 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_namespace count 1, has_schema_privilege(current_user, …, 'usage') false, current_schema() public. The probe asks has_schema_privilege now, 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 into public and is stopped only by an accident of that role's grants.
  • The compose build context uploaded a filled-in .env to the docker daemon. context: ../.. is right — the Dockerfile installs this package from source — and the context is uploaded before any instruction runs. deploy/compose/.env is git-ignored, which is not a build-context rule, so its DSN and password travelled with every docker compose … --build even though the Dockerfile never copies it into the image. .dockerignore is an allowlist, so the property is structural rather than a list somebody has to extend: everything excluded, the Dockerfile's own COPY sources 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 a busybox image — before, /ctx/deploy/compose/ held .env; after, /ctx is exactly README.md, migrations, pyproject.toml, src — and the real image still builds and runs opendox-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.py derives the probe's timeoutSeconds from ONE DEFAULT_CHECKOUT_TIMEOUT_SECONDS plus the JWKS timeout and holds it strictly over both — and /readyz checked out for select 1, again inside plan() and again inside drift(), each of which calls applied(). 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() and drift() take the connection applied() 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 the sleep(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 a time.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-literal puts the value in the shell's history file and in /proc/<pid>/cmdline for as long as kubectl runs — the same exposure the managed-database block one page down already avoided with read -rs, so two paths said different things about one secret. The install block reads into files under umask 077, passes --from-file, and removes them; measured with a kubectl on PATH that prints its own argv. The guard greps the runbook for any --from-literal whose 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.yaml from the base, so that path started a second database nobody uses and failed on the opendox-postgres Secret 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-database renders the Namespace, both ConfigMaps, the runtime Service, the PVC, the Deployment and the Job — and none of StatefulSet/opendox-postgres, Service/opendox-postgres or ConfigMap/opendox-postgres-init — with migration_wait_host empty.

  • False against the code. STDLIB_ONLY_MODULES is reported to omit opendox.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. textoctetlen takes the raw length out of the varlena header — toast_raw_datum_size reads 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:

    query time
    sum(octet_length(body)) 0.3 ms
    count(*) 0.3 ms
    this act's windowed inner query 0.7 ms
    sum(length(body)) (counts characters) 463.5 ms
    max(md5(body)) (reads the bytes) 381.9 ms

    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 it

Classified: 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 lacks usage on exactly as it skips an absent one. So a schema named for the role, present and denied, still fell through to public: 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 twice

Classified: 2 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.

  • No broker URL this runtime prints can carry a credential. oidc_issuer and an explicit oidc_jwks_url are public endpoints — the issuer is what a token's iss is compared against, the key set is fetched unauthenticated — and load_settings accepted any string. Measured against the previous head with OPENDOX_OIDC_ISSUER=https://svc:pw@broker/realms/x: load_settings accepted it, repr(settings) printed it, status printed the derived OPENDOX_OIDC_JWKS_URL with it, and status printed broker_discovery with 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 leave jwks_url() — which the verifier actually fetches — pointing at a URL with a credential in it; and redacted at both printing boundaries anyway, because a RuntimeSettings built 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.
  • The managed-database overlay supplies the broker. The base leaves oidc_issuer and oidc_audience empty 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 fails load_settings before it serves. overlays/dev carries a worked example for exactly that reason; round 19's new overlay had none. The guard is derived from the base: every oidc_* 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 defect

Classified: 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 .env value into code.

  • CMD-SHELL made it shell source. OPENDOX_PG_USER=x; touch /tmp/pwned ran 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-form CMD now — the interpolation stays, because the probe must follow the configured values, but each one is a single argument exec passes with no shell between.
  • The application probe made it python source, evaluated on every probe and before config.load_settings had looked at the port. The script is fixed and reads the value from os.environ — the container already has the variable, set from the same .env by the environment: block — so it holds no interpolated text. Measured with OPENDOX_BIND_PORT="8080'),None) or __import__('os').system('touch /tmp/PWNED')#": exit 1 with a ValueError, and no marker. int() is the same validation load_settings applies, 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 the environment: block name the same variable.

Review round 24 (Copilot review at 5cb4922) — three findings, two of them round 22's own guard

Classified: 3 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.

  • A credential in the broker URL's QUERY is refused like one in its userinfo. Round 22's guard read netloc and nothing else, and redacted_url preserved the query — so https://broker/certs?token=… was accepted and then printed by both repr(settings) and status. Both halves read the query and the fragment now, against a list of credential-shaped parameter names (local_git_adapter.SECRET_PARAMETER_KEYS holds 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.
  • urlsplit raises, from inside the function that owes a named refusal. Measured on python 3.12: urlsplit("https://[::1/x") raises ValueError("Invalid IPv6 URL"), so a malformed OPENDOX_OIDC_ISSUER escaped as a traceback where this module promises a ConfigurationError naming the variable. The parse is inside the boundary, and redacted_url answers <redacted-url> for a value it cannot parse.
  • runtime_pg_role is 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 narrows opendox_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 to OPENDOX_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's

Classified: 1 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.

  • The broker URL is a trust anchor, and its scheme was unchecked. Round 22 refused a credential in the URL and said nothing about how it is reached. HttpJwksSource fetches it, and the keys it returns are what every token is verified against — so over http:// anyone on the path replaces the key set and mints tokens whose iss and aud still pass: verification reduced to whoever controls the network. It is https, or a loopback host, and only those. The exception is for a developer running a broker on 127.0.0.1, where there is no network for anyone to be on, and it is exact rather than name-shaped — ipaddress judges a literal, so 127.5.5.5 and [::1] are one answer and 127.0.0.1.evil.test is not one at all. The explicit OPENDOX_OIDC_JWKS_URL goes 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 measurement

Classified: 3 FIX, 0 REPEAT, 0 out of scope, 2 answered by measurement.

  • FIX — the documented kubectl apply reached a clean cluster with a placeholder image. True, and measured against kustomize v5.4.3: kustomize build deploy/kubernetes/overlays/dev emits ghcr.io/opensoft/opendox-runtime:0.0.0 at three container sites (the Deployment and the migration Job's two containers), and this repository publishes no image, so the install the runbook documents reaches ImagePullBackOff before 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, by kustomize edit set image …@sha256:<the reviewed digest> (measured: it replaces newTag: with digest:, 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's newTag cannot drift apart; against an unguarded apply and against an overlay tag the guard would miss, it fails.
  • FIX — the DB probe printed the DSN, and "can include" is understated. Five shapes measured against psycopg 3: a refused connection, an unknown URI parameter, an unknown keyword/value option and the refused keyword/value form all report without the password, because libpq's message is about the connection. The fifth — a URI libpq cannot parse — quotes the whole string back: 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 print hunter2 against the previous head: one stubs the driver so the contract is measured in the required job, one is the live reproducer.
  • FIX — the runbook's plaintext secret files survived a failure. rm -rf "$secrets" was reached only when every kubectl create secret succeeded, 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 the mktemp -d immediately, on EXIT and on INT/TERM, and the signal handlers re-raise so the shell's own exit status is still the truth.
  • Answered by measurement — LEDGER_DDL cannot reuse a public ledger. The finding's mechanism is that CREATE TABLE IF NOT EXISTS "sees the public relation and skips creation in the selected schema". On postgres 16.15 it does not: IF NOT EXISTS is tested against the relation the statement would create — the first schema in search_path the role can create in — and not against what the name resolves to for a read. Driven directly, with public.opendox_schema_migrations already 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 from selected_schema(), and it cannot: a role with no USAGE on the first search_path entry has its unqualified CREATE skip that schema to the next one — the same entry has_schema_privilege walks to (measured on a nosuperuser role). 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 to public it fails on the tenant ledger's rows.
  • Answered by measurement — the figure pair was already reconciled. The comparison names 8779a776 / 142 / 249 from the description against 65376475 / 144 / 251 in the workflow, and both were two rounds stale by the time the review was posted: at a4d0eddf the 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 at c21b8b97 now, 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.

  • FIX — a broker URL that names no host was accepted. urlsplit("https:///realms/x") yields the scheme https and hostname None, so round 25's check — which read only the scheme — passed it: measured before the fix, OPENDOX_OIDC_ISSUER=https:///realms/x produced settings carrying that issuer, and the install would have discovered it when the key-set fetch made /readyz and status fail. That is configuration found at serve time, which is the boundary load_settings exists to hold. A missing hostname is refused before the scheme check now, and the refusal does not echo the value: https://user:pw@/realms/x has 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 of status and the logs. broker/realms/x moves 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.
  • FIX — search_path was split with str.split(","), which is not a parser. A schema whose name contains a comma is legal and PostgreSQL quotes it, so "tenant,blue", public became "tenant and blue" and selected_schema refused a valid connection — one whose current_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_entries splits on commas outside double quotes and leaves each entry raw, so _unquoted still 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 through selected_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.
  • The other suppressed comments on those reviews are earlier rounds' and were already answered: the octet_length detoast (answered by measurement, round 19), the migration Job's wall-clock deadline, the runbook's --from-literal secrets, the managed-database overlay, /readyz holding one connection, and identity in STDLIB_ONLY_MODULES — which is in that tuple already.

Review round 27 (Copilot review 5246688086 at 9df2661) — three threads and seven suppressed comments

Classified: 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.

  • FIX — the DSN redaction crashed on a port that is not a number, and the crash is what printed the password. 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 the ValueError boundary, so _redacted_dsn raised 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.skip raised inside except carries the psycopg error as __context__, and libpq quotes a conninfo it cannot parse — so on postgresql://opendox:hunter2@[::1:not-a-port/db the 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, both False and __context__ is None, because the reason is now raised outside the handler. Every access is inside the boundary and the fallback is <the configured DSN>.
  • FIX — a broker URL's port was never evaluated. The same property at the configuration boundary: https://broker:not-a-port/realm passed it, because the checks read the scheme and the hostname, and the ValueError would have surfaced inside the JWKS fetch — neither a ConfigurationError nor a named setting. Refused now, with the value unechoed for round 26's reason; https://broker:99999/realm is refused by the same access.
  • FIX — the managed-database apply stood above its own prerequisites. An operator working top to bottom applied the overlay carrying the base's inherited 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 the runtime_pg_role instruction and after the role-provisioning block, and the new case measures positions in the document, which is the whole claim.
  • FIX — a failed JWKS refresh cost one outbound fetch per inbound request. When _load_keyset() raises, _keyset is never assigned and _loaded_monotonic is 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 a kid miss. 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.
  • Answered by measurement — the figure pair, again, and stale again. The comparison is against figures two commits old; the description and the workflow both name the same head and the same counts, which is the invariant the finding asks for. They say 167 (1 skipped) and 279 at 948cf056 now, 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_principal declares no bearer security scheme, so a client generated from the published OpenAPI omits credentials; document_key and basis_revision are outside the page budget that bounds body; the access preflight does not check CONNECT on the database; HttpJwksSource has no mocked-transport coverage (every verifier fixture uses FileJwksSource or an in-test fake); and the secret block does not abort on a failed kubectl — a pasted block that ran set -e would exit the operator's own shell, so the disposition there is a choice and not an oversight.

Review round 28 (Copilot review 5246781523 at d250fd9) — one finding, and it is about this act's own headline promise

Classified: 1 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement.

  • FIX — the whole-run promise covered the digest and not the decode. 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 wrong 0001 changes nothing at all" true against a directory that changes under the process. But raw.decode("utf-8") sat inside the per-migration loop — after the bootstrap, after protect_ledger, and after earlier migrations had committed — so a later file holding invalid UTF-8 aborted the run with an untyped UnicodeDecodeError on 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 first commit; the refusal is a MigrationError naming 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 raises UnicodeDecodeError and leaves the six tables and the ledger.

Review round 29 (Copilot reviews 5246781523 at 9df2661 and 5246859442 at d250fd9) — nine suppressed comments, seven still live

Classified: 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).

  • FIX — an issuer with a query or fragment derived a URL nothing serves. jwks_url() and discovery_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=a derived …/realms/x?tenant=a/protocol/openid-connect/certs and …/realms/x?tenant=a/.well-known/openid-configuration. Refused now — and the rule is the issuer's alone: an explicit OPENDOX_OIDC_JWKS_URL is 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.
  • FIX — the loopback exception accepted every non-https scheme. Written as "not https AND not loopback", it let ftp://localhost/realms/x and file://127.0.0.1/realms/x through (both measured accepted), and HttpJwksSource fetches with httpx.get, which can use neither. It is https anywhere, or http on a loopback host, and nothing else.
  • FIX — a non-UTF-8 JWKS file escaped its own handler. UnicodeDecodeError is a ValueError and not a json.JSONDecodeError, so the air-gapped path's malformed key set surfaced as a 500 instead of the typed refusal FileJwksSource exists to produce. ValueError is the base of both — the rule HttpJwksSource already states one class below.
  • FIX — a failed pool checkout was masked by the store's own teardown. _open() assigned self._exit and then called __enter__(), so a checkout that raised left a non-None _exit whose __enter__ had never completed, and get_store's cleanup calls close() — 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.
  • FIX — a URI password holding a space was half-printed. Round 19's finding in its URI form: \S* stops at the first whitespace, so a driver quoting back postgresql://opendox:hunter 2@db.internal/x was 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: on postgresql://host/db for user a@b the @ branch cannot cross the /, so the unrelated @ is not swallowed. Both bounds are cases.
  • FIX — the secret block had no fail-fast (reported twice). 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 a kubectl stub that refuses the first create, ) && ok=yes || ok=no suppresses set -e inside the subshell (bash disables errexit in an operand of &&/||, and the subshell inherits it): all three creates ran and the status was 0. With secrets_created=$? the block stops at the first failure, the EXIT trap removes the files, and the status is 1. The signal traps exit rather 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 %L is the statement that sends it; what this block keeps the password out of is the operator's shell, and what %L keeps out of the database is a mistyped placeholder.
  • Answered by measurement — read -r -s is already what the DSN prompts use. The finding asks for read -r -s where the line reads read -rs -p, and those are the same flags. Measured on bash 5.2: printf 'a\b\n' | read -rs v keeps a\b; with -s alone it becomes ab.

Review round 30 (Copilot review 5246951266 at b2c8056) — two threads and five suppressed comments

Classified: 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.

  • FIX — the served role was granted every table in the schema. grant select, insert, update, delete on all tables in schema public hands 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 carries DELETE, INSERT, SELECT, UPDATE for 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 with projects and unrelated_app both present, it emitted exactly grant … 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 from identity.TABLES and migrations.LEDGER_TABLE so 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.
  • FIX — the bundled script never created an alternate migration owner. OPENDOX_MIGRATION_PG_USER is documented as an alternate owner and alter default privileges for role %I names it, so setting it to a role nobody had provisioned failed under ON_ERROR_STOP=1 on 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.
  • FIX — the install blocks are fenced bash, which is a prerequisite and not a label. They prompt with read -rs -p, and neither -s nor -p is in POSIX read: under /bin/sh as dash the prompt is consumed as the variable name and the block fails before a Secret file holds anything. The fenced-block scanner in test_deploy_shape.py reads sh or bash now, so correcting the fence did not blind the guard that reads those blocks.
  • FIX — the readiness probe now bounds its own statements. The budget covered the pool checkout and the JWKS fetch — how long it waits to get a connection — and said nothing about how long a statement may then take, so a lock or a stalled server could hold select 1 past timeoutSeconds and kubelet would start an overlapping probe. SET LOCAL in an explicit transaction, and that shape is measured: a session-level set statement_timeout on a pooled connection survived the checkout it was made in (a later checkout of the same connection still read 1234ms), so the bound would have leaked onto whatever request borrowed it next. The value is interpolated because SET takes no bind parameter — set local statement_timeout = %s is a SyntaxError from PostgreSQL, measured. The deployment's timeoutSeconds assertion takes the new term from the module that declares it.

Review round 31 (Copilot review 5247062148 at dbc704f6) — two threads, neither mechanism holds

Classified: 1 FIX, 0 REPEAT, 0 out of scope, 2 answered by measurement.

  • Answered by measurement, with one half taken — USAGE without CREATE does not fall through. The finding: selected_schema() proves USAGE, the ledger DDL creates, and PostgreSQL would therefore choose "a later search_path entry where the migration role has CREATE (for example public) as the object-creation target". Measured on postgres 16.15 as a nosuperuser role with USAGE and no CREATE on the first entry and CREATE on public: current_schema() is still the selected schema and the unqualified create table raises InsufficientPrivilege: 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 a create table after 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: MigrationError and not InsufficientPrivilege, the schema and the grant named, and nothing created in either schema.
  • Answered by measurement — the claimed SyntaxError does not exist. The quoted line is assert "--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_compile on that exact blob compiles clean; the hermetic five collect and run 171 passed 1 skipped; and the required validate job at that commit is green, which a collection-time SyntaxError would have made impossible. No change.

Review round 32 (Copilot review 5247180700 at 7fd2e2a0) — two threads and three suppressed comments

Classified: 4 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement, 1 registered.

  • FIX — a refusal was still teaching the grant round 30 removed. verify_runtime_access's message told an operator to run grant 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.
  • FIX — a column-level grant is a write, and has_table_privilege does not see it. Measured on postgres 16.15: with INSERT (version) and UPDATE (checksum) held, all four table-level answers are False. 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 property protect_ledger exists 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, with has_table_privilege false throughout. has_column_privilege over 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.
  • FIX — set -e does not abort on the left operand of &&. The runbook's prompts were read -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 own if ! 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.
  • FIX — the secret creates are idempotent. Three independent create calls meant a failure in the second or third left the earlier Secrets in the cluster and the re-run failed with AlreadyExists — 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-literal would trade one defect for a worse one.
  • Registered, not taken — the draft page's window is evaluated before the LIMIT. PostgreSQL computes the running octet_length window over the whole filtered set and then applies the limit, so MAX_PAGE_SIZE bounds 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 5247313926 at 3517222e) — two threads

Classified: 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 05e13af9 before it was written.

  • FIX — round 29's bound leaked, which is the finding's own point. That round excluded / 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/opendox falls to the plain branch, which stops at the space, and the message keeps word@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@b now loses the text between), [^\n]* never crosses a newline, and a line with no @ is untouched past the URI.
  • FIX — an empty password provisioned a login role with a blank credential. read succeeds on an empty line, and the managed-database prerequisite ran create role … password %L with 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 the else, so nothing downstream runs on a password that was never given.

Review rounds 34 and 35 (Copilot reviews 5247428924 at 1faa18d3 and 5247510939 at 1c6cd9e6) — three threads and five suppressed comments

Classified: 7 FIX, 0 REPEAT, 0 out of scope, 0 answered by measurement. Every case below fails against the previous head.

  • FIX — the served and migration DSNs could select different schemas, and nothing compared them. They are independently configurable: the runner derives its schema from OPENDOX_MIGRATION_DATABASE_URL and the served Database from OPENDOX_DATABASE_URL. Two DSNs at one database with different search_path options let a run apply and verify schema A while /readyz and 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_by reads 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 a str.split() read missed) — and only the first entry, because that is where an unqualified create table lands, which is the question migrations.selected_schema asks of a live connection. load_settings refuses 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 default search_path on the server is not in either string, and selected_schema is the guard there.
  • FIX — serve lends the process to uvicorn, and uvicorn's log was outside the redaction contract. A failed lifespan is logged by uvicorn itself, with exc_info, before cmd_serve reaches its own handler, and psycopg names the whole conninfo in the text of an exception raised for an unparsable DSN — so a malformed OPENDOX_DATABASE_URL printed its password to stderr in a traceback while the JSON beside it was scrupulously redacted. The boundary is logging.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 own dictConfig replaces the handlers on uvicorn.error and uvicorn.access when Config is 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 in exc_text where logging.Formatter uses it instead of formatting exc_info again, after which exc_info is dropped so a formatter that ignores exc_text prints 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 carries hunter2, with it up it does not and RuntimeError: could not connect survives.
  • FIX — thirteen handlers put an exception's own text into evidence, not the five that were noticed. discover_migrations() names the configured OPENDOX_MIGRATIONS_DIR in its error text, so a directory path holding a DSN or password=… was printed raw by init, migrate --plan, migrate and status — 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 every except … as exc, the name may be reached only by _safe_message(exc) or type(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.
  • FIX — the compose healthcheck dialled localhost while the bind host is a setting (suppressed). OPENDOX_BIND_HOST is 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 got connection 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 to 0.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 dialled localhost for all of them.
  • FIX — the Secret subshell's set -e did not see a failed left side of a pipeline (suppressed). Every create in it is kubectl 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 reached prints reached and exits 0; set -e -o pipefail stops the block with status 3. The block is bash already — read -rs -p is not POSIX — so pipefail costs it no portability it had, and the test measures both shells rather than asserting the claim.
  • FIX — the managed-database prerequisite ran on after its first SQL error (suppressed). psql's default is to report a failed statement and run the next one, so an unprovisioned migration owner made create role fail 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 on is the same setting deploy/*/init-runtime-role.sh spell psql -v ON_ERROR_STOP=1, in the form a pasted session takes.
  • FIX — and it would provision a role with no password even after the shell block refused one (suppressed). That block can only decline to export: it must export into the operator's own shell for \getenv to see anything, so it cannot run in a subshell, and exit 1 in 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 reached create role … password %L with 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 with ON_ERROR_STOP a raised exception is what gives psql a nonzero exit. Not measured against a server: there is no psql binary in the validate job, 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 5248010092 at c1414cbb) — four threads and six suppressed comments

Classified: 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.

  • FIX — the preflight split search_path with .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 to tenant and two DSNs selecting genuinely different schemas passed round 34's comparison. _path_entries and _unquoted move to config as search_path_entries and unquoted_identifier and migrations aliases them — one definition, asserted with is, so the string answer and the live-connection answer cannot diverge again.
  • FIX — and the layer above them removed the quoting before any parser saw it. POSIX shlex strips double quotes, so -c search_path="tenant,blue",public arrived as search_path=tenant,blue,public. libpq's options has no quote processing at all: whitespace separates arguments and a backslash escapes the next character, which is what _libpq_option_words does — the double quotes belong to PostgreSQL's identifier syntax and survive. The conninfo layer above that does take single quotes, and shlex is 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.
  • FIX — two DSNs at different DATABASES with the same schema name passed. public in one database and public in another are two different sets of tables. database_named_by reads the name from the URI path or the dbname= 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 /readyz reports not-applied rather than ready.
  • FIX — the readiness probe's bound was per-statement and it runs four statements (suppressed). select 1, then plan() and drift(), 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 own timeoutSeconds — 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 term test_deploy_shape.py adds to the checkout and JWKS budgets. timeoutSeconds moves 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 inside with conn.transaction():, since SET LOCAL outside one is a no-op with a warning and a session-level SET leaks onto the next borrower of a pooled connection.
  • FIX — every grant in the bootstrap named public while 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_access then failed the migration and the install could not start. OPENDOX_PG_SCHEMA carries 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.
  • FIX — alter default privileges follows 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 replacing grant … on all tables in schema public was 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 owns invoices — and that row's do block raises naming both. \gexec runs nothing when there is no row, so the having count(*) > 0 is 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.
  • Answered by measurement — the figure pair (suppressed). The review reports the body naming 1c6cd9e/174/291 against the workflow's bb84c6c6/181/298. The body was updated to bb84c6c6, 181 and 298 before that review was written, and both places said the same head and the same counts at that moment; they say ad077e2f, 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 fixed

Not 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 passed hermetic, 301 passed DB-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 against 0860270f.

  • BLOCKING (A25-1) — a malformed OPENDOX_OIDC_ISSUER printed its own password. config._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 got to run. Measured: OPENDOX_OIDC_ISSUER='https://svc:hunter2@broker℀evil.example/realms/x' put hunter2 on stdout from opendox-runtime runtime status and ... runtime init, inside the JSON the lifecycle contract calls redacted evidence — and cli._safe_message passed it through untouched, because the leaked run is netloc 'svc:hunter2@…', with no :// and no password=. The exception TYPE is named now and the value is not; the cause is dropped with from 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.
  • MINOR (A25-4) — and the scan that exists to catch exactly that read one file. Round 35 answered five unredacted handlers by making the contract a shape; the walk was Path(cli.__file__) and nothing else, while config.py, oidc.py, migrations.py, identity.py, app.py and db.py all 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 separates app._found's str(exc) on an identity.NotFoundError from _split_url's {exc} on a CPython ValueError. A benign-attribute table (reason, start, code, sqlstate, …) covers the data reads, raise … from exc is allowed, and traceback.format_exc() / print_exc() / sys.exc_info() inside a handler are newly flagged. A bare raise is deliberately not flagged, with the reason given. The scan is run against four shapes it must flag and six it must not.
  • MAJOR (A25-2) — an anonymous request was a 500. CachingJwks._match selected by kid alone and never asked whether the selected key's TYPE could carry the token's alg, and PyJWT's RSAAlgorithm.prepare_key answers an EC key with a plain TypeError("Expecting a PEM-formatted key.") — not a PyJWTError — so it escaped _decode's seven typed clauses, escaped verify, and escaped get_principal, which catches OidcError. 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 both kids are public facts from the unauthenticated JWKS endpoint: any anonymous caller could send Bearer <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; _decode grew a final (TypeError, ValueError) clause so no future PyJWT shape reopens it. A bonus the binding buys: a kid-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/me is 401, not 500.
  • MAJOR (A25-3) — the two-DSN schema guard could not fire in either shipped deployment. Rounds 34 and 36 built it against "migrations apply and VERIFY schema A while /readyz and the API read schema B" — and no shipped workload holds both DSNs: the Deployment carries OPENDOX_DATABASE_URL, the migration Job carries OPENDOX_MIGRATION_DATABASE_URL, compose splits them the same way, migrate and reset do not call load_settings at 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_SCHEMA is 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_read refuses before the ledger is bootstrapped, and both deployments take the value from the same pg_schema the 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.
  • MINOR (A25-5) — 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 ever expires — a security property turned off by a number, with nothing saying so. MAXIMUM_BY_SETTING bounds 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 to int(), which takes Python's underscore separators: 3_0_0 was 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, the search_path/options parsing, 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 5248370624 at 0860270f, 5248856351 at b9bc3167, 5248961642 at 48de5833) — five threads, one batch

Answered 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, the 52b237e base merge into 48de5833, and 2c3e9bae/056d1597 here), and two merges of main are 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.

  • FIX — schema_selected_by took the FIRST -c search_path= where libpq takes the LAST. options is 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" then show search_path prints new. 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 -c for 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.
  • FIX — database_named_by read the URI path and ignored dbname in the query. postgresql://host/?dbname=one and ...?dbname=two both answered None, 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 against PQconninfoParse itself (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.
  • FIX — /readyz bounded each PHASE and called it a total. SET LOCAL statement_timeout is per statement, and a phase is several: driving the real MigrationRunner.plan() and .drift() against a recording connection issues seven statements under three bounds (selected_schema, the to_regclass ledger probe and the ledger read, twice over, plus select 1) — a worst case of 7 × 1.5s = 10.5s against a declared 3.0s budget, all of it inside the probe's own 25s timeoutSeconds, so nothing downstream would have reported it and probes would simply have overlapped. WithinTheDeadline wraps 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 raw conn.execute inside the readiness transaction.
  • FIX — project_repositories.remote_url was free text with nothing judging it. The migration argues only the column's NULLABILITY, 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 by GET /api/v1/project-repositories to every member of the project, in every backup, and handed to git by § 3.6. Both layers, because either alone is half: identity.refuse_a_remote_url_that_carries_a_credential refuses at the store — the column's only writer, and both of its writers — and _repository_json plus ProjectRepository.__repr__ redact a row that got in some other way (an earlier build, a restore, psql). config.credential_in_a_remote_url judges the two shapes git accepts — the URL authority and the scp-like [user[:password]@]host:path, which urlsplit reads as a bare path — and calls an ordinary ssh://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, repr printed it and the API returned it.
  • Answered by measurement — the description's figures were already reconciled. The review read 0860270/184/301 in this description while the workflow recorded 2e400a4a/196/317; the description had already been updated to 2e400a4a and b9bc316 with 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 say 2c3e9bae, 197 and 320.

Review round 40 (Copilot review 5249443180 at 056d1597) — one thread, four suppressed, three FACT

Submitted 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.

  • FIX — runtime reset never asked the served-schema declaration, and migrate --plan did not either. A25-3's guard was a METHOD reached from apply() alone, so of the three acts that change or preview a schema, two did not ask. Measured at 056d1597 with a migration DSN selecting t_35e62eb47603 and OPENDOX_SERVED_SCHEMA=somewhere-else: migrate --plan exited 0 printing planned: ['0001', '0002'] — a preview of a run apply() would refuse, which is the answer an operator checks before committing to the real one — and a confirmed reset exited 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 first DROP and 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.py pins all three call sites by position, matching the DDL and not the paragraph that quotes it.
  • FIX — the credential-parameter test matched SUBSTRINGS. _SECRET_PARAMETER was re.compile("|".join(SECRET_PARAMETER_KEYS)) asked with .search(), so any name merely containing one of the words matched. Measured at 056d1597: monkey, sigma, tokenizer, authority, keyspace and keyboard all matched, and redacted_url("https://broker/certs?monkey=1") returned monkey=<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, so access_token, X-Api-Key and sessionToken still 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.
  • Already reconciled — the 320-vs-317 figure. The description was updated in the same push that recorded 320 in the workflow; both now say 61ab857c, 198 and 322.
  • Answered and left as it stands — the drafts page budget. bytes_before < budget bounds 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 so after pagination 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

  • FIX — a password containing / walked through the scp branch, and it was this batch's own defect. credential_in_a_remote_url read the text before the FIRST /, which is the shape of an scp-like authority — so ci:hun/ter2@github.com:o/r.git was reduced to ci:hun, read as a username with no password and called clean. Measured at 0968ff8b: the predicate answered None, the store accepted the row, 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 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_userinfo is 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 explicit dbname, database_named_by answers None for 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 with search_path="$user",public compare 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_SCHEMA is 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. At 68ebea49 the guard ACCEPTED three of the four shapes these cases forbid, and refused the fourth for the wrong reason.

  • FIX — 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/ — no database anywhere in the string — connects and select current_database() answers opendox; PQconninfoParse does not fill the default in, so it is invisible in the parse and applied at connect. effective_database resolves dbname, 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.
  • FIX — "$user" is a token and was compared as a literal. Two roles' DSNs both selecting "$user",public agreed on the string while PostgreSQL resolved them to two different schemas. Measured on postgres 16, three ways: set search_path = "$user", public with no matching schema gives current_schema() = public; with a schema literally named $user created it is still public; 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 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.) 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_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; 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_SCHEMA is 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 against current_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 its setup.py in the job; measured in a clean venv before it was declared); the CI Postgres password and its DSN both marked, on xFactory-Hermes-Install's own precedent, which marks both halves; jwt.get_unverified_header marked 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 an except tuple, verify's cognitive complexity (the seven-clause PyJWT mapping is now _decode), responses=REFUSALS on every authenticated router, four invalid # noqa comments, one duplicated literal, and fifteen test-file nits (bare @pytest.fixture, composite assertions split so a failure names which half failed, one throwing call per pytest.raises block).

Answered, not fixed, and each is recorded rather than argued away:

  • githubactions:S8544 / docker:S8544 — "dependencies without locking resolved versions". This is the --require-hashes lockfile pyproject.toml already names as the obvious successor and as a real act with a real owner; xFactory-Hermes-Install carries a uv.lock for 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:S8541 at validate.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 the responses=REFUSALS the 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 made validate.yml unparseable (: is a mapping indicator), so at head 4d3ce664 GitHub ran no job at all — gh api .../actions/runs?head_sha=… returns a run named for the file itself, and neither validate nor runtime appears in the check list. The absence of a run looks like nothing on a PR page, so the repair commit also adds four suites to tests_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-runtime console script, a real Postgres, a real socket. docs/runtime.md § 8a carries the transcript.

step result
runtime init ok — created the project-repository root, reported the pinned canonical digest and ["0001","0002"] on disk
runtime migrate ok — applied 0001 and 0002
runtime status database reachable, both applied, nothing pending, no drift, broker unreachable → ok: false
GET /livez 200 {"status":"live"}
GET /readyz 503 {"database":"ok","schema":"applied","broker_keys":"unavailable: …"}
GET /docs 404 — off unless OPENDOX_PUBLISH_OPENAPI
GET /api/v1/projects 401 — no bearer token
runtime reset --confirm … ok — dropped in the topological order

status and /readyz are 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 is e9bec39 on this branch and the matching commit on #26:

  1. The repository the § 3.6 act creates stays BARE, with an empty first commit. (§ 3.6: openDox creates a repository as a first-class act, with RULING C3's conformant local-git adapter #26's repository_act.)
  2. write_back RECORDS basis_revision as 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's local_git_adapter.)
  3. The runtime CI 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.
  4. The verbs are wired into opendox.cli in the BUILD-arc act that repairs opendox.serve; opendox-runtime is the spelling until then. Cited in opendox/runtime/cli.py's header, where the two spellings are explained.

Review round 5 (Copilot review 5225958167 at 7213b0a4) — every finding fixed, each with an assertion

  • The two 404s on GET /users/{id} were not the same answer. The row was read first, so a missing user came back as no 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_USER constant that names no id at all.
  • The migration Job hard-coded the role protect_ledger narrows. 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_role is now a literal in the opendox-runtime-config ConfigMap, read through configMapKeyRef, and the runbook says beside the Secret that the two are one role.
  • The readiness gate hard-coded the bundled Postgres Service in a base that documents managed-database overlays — where it burned its whole 240-second budget and failed the Job before the configured DSN was ever used. Host and port come from the same ConfigMap, and an EMPTY host means "nothing in this cluster to wait for" and exits immediately.
  • OPENDOX_PUBLISH_OPENAPI reached no container. .env.example declared it, config.SETTINGS read 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 /docs stayed 404 with no way to tell why. Both deployments pass it now, default OFF.
  • The JWKS cache amplified traffic at exactly the wrong moment. now was 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.
  • A skipped suite exits 0. A runtime job whose postgres:16 service failed to start went green while running no database-backed assertion. In CI that absence is now a failure; a developer still skips.
  • runtime reset dropped through the search path. drop table if exists users in a schema that has no users resolves to public.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 with current_schema() through psycopg.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.
  • The runbook created Secrets in a namespace it had not created, and the Dockerfile's comment claimed a dependency-layer cache the forced COPY src order does not give it. Both are fixed in the only direction that is true, and the comment names the --require-hashes lockfile act where the split belongs.

brettheap and others added 3 commits September 16, 2026 13:51
…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 AI lite review requested due to automatic review settings September 16, 2026 15:02
@brettheap

Copy link
Copy Markdown
Contributor Author

@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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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_url in the migration container privileged; do not alias the migration credential to the served setting just to satisfy load_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_URL as well as OPENDOX_MIGRATION_DATABASE_URL. That is not a separate served identity: any accidental use of settings.database_url in 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 opendox role, but unlike the Compose package it has no init script or job creating the least-privileged role used by opendox-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

  • /readyz is registered without PrincipalDep or any other authentication dependency, so it is another public route and returns database/broker availability to unauthenticated callers. This contradicts the PR's explicit “/livez is 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_id is 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 1 only; 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, or serve can 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 MigrationError is converted to _emit; connection/pool failures from Database or psycopg escape this block with a traceback and no JSON evidence, contrary to the lifecycle CLI contract. Map operational failures to a redacted refusal as status does.
    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. Consequently EdDSA becomes EDDSA, is classified as symmetric here, and would not match PyJWT's case-sensitive token algorithm name either. Preserve PyJWT's canonical spelling or canonicalize EdDSA explicitly 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.

Comment thread src/opendox/runtime/app.py Resolved
Comment thread src/opendox/runtime/migrations.py Resolved
Comment thread src/opendox/runtime/oidc.py Resolved
Comment thread deploy/compose/docker-compose.yaml Resolved
Comment thread src/opendox/runtime/app.py Resolved
Comment thread src/opendox/runtime/cli.py Resolved
Comment thread src/opendox/runtime/cli.py Resolved
Comment thread src/opendox/runtime/identity.py Resolved
Comment thread tests_runtime/conftest.py Resolved
Copilot AI review requested due to automatic review settings September 16, 2026 15:12
@brettheap

Copy link
Copy Markdown
Contributor Author

@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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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_store subdependency before entering get_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
  • readyz has no PrincipalDep, so it is callable without a bearer token even though the PR defines /livez as 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 MigrationError is caught below. A refused or unreachable Postgres raises a psycopg/pool exception from this context or from runner.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 _emit without including connection details.
    src/opendox/runtime/cli.py:261
  • runner is used after the with Database(...) block has exited, so its pool is already closed. On a reachable database, runner.applied() raises, the broad handler rewrites database to unreachable, 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, reset raises from Database/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 EdDSA to EDDSA; the later Ed branch then rejects it, and the resulting value would not match PyJWT's EdDSA header anyway. The code advertises Ed as 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 and RuntimeSettings.database_url contains the privileged credential. That contradicts the two-identity separation described above; make migrate load 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 migrate service before up -d, but this service has only image: opendox-runtime:local; the build stanza exists only on opendox. With no pre-existing local image, docker compose ... run migrate tries to pull that local tag and fails before migrations run. Give migrate the 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_migrations once 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 requiring OPENDOX_DATABASE_URL rather 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 opendox database role; unlike Compose it mounts no role-initialization SQL or grant step. The Deployment nevertheless consumes opendox-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; use newDigest with 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.json routes 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 principal makes 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 from create_membership is not an identity.ConflictError, so it escapes _conflict as 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 /readyz reports 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: TABLES puts memberships before projects, so this loop drops projects while memberships still 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 SELECT and subsequent INSERT are 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 an INSERT ... 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_id can both pass the SELECT, 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 to ConflictError.
        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 execute 0001; the second then fails on the canonical create table or 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_URL is unset. If the variable is set but Postgres is unreachable, database later raises while opening admin, so the DB suites fail instead of skipping with the promised reason. Probe the DSN here and convert connection failures to pytest.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

Comment thread src/opendox/runtime/app.py Resolved
Copilot AI review requested due to automatic review settings September 16, 2026 15:24
Copilot stopped work on behalf of brettheap due to an error September 16, 2026 15:25
Copilot stopped work on behalf of brettheap due to an error September 16, 2026 15:26

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 store is a dependency of get_principal, FastAPI enters get_store and checks out a database transaction before line 141 checks the Authorization header. 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
  • /readyz has no PrincipalDep, so it is publicly callable alongside /livez and exposes database/broker availability even though the application contract says /livez is 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 /readyz reports 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 MigrationError is 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 EdDSA configuration becomes EDDSA and 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 migrate before up, but this service has only an image: and no build:. On a fresh checkout there is no opendox-runtime:local image yet, so docker compose ... run migrate tries to pull/fails instead of building the Dockerfile from opendox; 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 apply path 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's digest: 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_id only; put_draft accepts any session_id and 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.json by default here. That creates three unauthenticated routes despite the runtime contract saying /livez is 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 this with block exits at line 258, so runner.applied() and runner.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 in status; 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.TABLES is not a valid dependency order: it drops projects before memberships, which still has a foreign key to it. PostgreSQL will reject that DROP TABLE, roll back the transaction, and make reset unusable; 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_serve never calls _emit; a successful long-running invocation goes straight into uvicorn.run and 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 exempt serve and 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.mkdir runs before any refusal handler. A permission error or invalid OPENDOX_PROJECT_REPOSITORY_ROOT therefore produces a traceback and no JSON evidence, even though init is one of the lifecycle verbs promised to report every refusal. Catch filesystem errors and route them through _emit without 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=0 is 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.conflict this route promises. Make the insert itself conflict-safe (for example ON CONFLICT (slug) DO NOTHING RETURNING) and raise ConflictError when 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 RETURNING insert and translate an empty result to ConflictError.
        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. Consequently runtime migrate --plan returns 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_URL is set but stale or unreachable, Database(...) fails in the database fixture and the runtime suites go red instead of skipping with the documented reason. Probe the DSN at session setup and convert connectivity failures to pytest.skip without 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

Comment thread deploy/compose/init-runtime-role.sh Resolved
…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>
Copilot AI review requested due to automatic review settings September 16, 2026 15:38
brettheap and others added 2 commits September 16, 2026 15:41
…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>
brettheap added a commit that referenced this pull request Sep 16, 2026
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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 run will not build the image merely because the service declares build: and can try to pull the local tag. Add --build here as well so the example actually works before up has 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 configMapKeyRef environment 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 run does not build a declared build: section unless --build (or a separate build) is requested. On a fresh checkout this first documented command can therefore try to pull opendox-runtime:local before the image exists, despite the compose file defining the build. Add --build to 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 serve path calls uvicorn.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 how serve reports 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 message without 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__.py contract include local_git_adapter and repository_act, but neither module is in STDLIB_ONLY_MODULES. As a result, the missing allow-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

Comment thread docs/runtime.md Resolved
Comment thread src/opendox/runtime/app.py Resolved
Comment thread src/opendox/runtime/cli.py Resolved
Comment thread src/opendox/runtime/cli.py Resolved
Comment thread src/opendox/runtime/app.py Resolved
Comment thread src/opendox/runtime/app.py Resolved
Comment thread src/opendox/runtime/app.py Resolved
Comment thread src/opendox/runtime/cli.py Resolved
Comment thread src/opendox/runtime/app.py Resolved
Copilot AI review requested due to automatic review settings September 16, 2026 15:50
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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 records bb84c6c6/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 via options=-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, so verify_runtime_access fails 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 via options=-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, so verify_runtime_access fails 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_owner in public becomes 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 custom search_path creates the coordination tables elsewhere, but this block grants the served role only on public, 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() and drift() each call applied(), so this readiness transaction can execute three queries per call plus select 1, each with its own 3-second statement_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

Comment thread deploy/compose/init-runtime-role.sh Resolved
Comment thread src/opendox/runtime/config.py Resolved
Comment thread src/opendox/runtime/config.py Resolved
brettheap and others added 2 commits September 18, 2026 13:20
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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 c1414cb with 181/298 tests, but this workflow marks ad077e2f as 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 GRANT contains only c.relname, so it is resolved through this psql session's default search_path rather than the selected OPENDOX_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 GRANT contains only c.relname, so it is resolved through this psql session's default search_path rather than the selected OPENDOX_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 generated GRANT names only %I/c.relname. Unless the operator's session happens to have that schema in search_path, a non-public install grants a same-named table elsewhere or fails; generate schema.table here.
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 build is hidden by grep's status and the else branch 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 | grep without checking the build command's exit status, so a build failure can fall through to kubectl apply instead of refusing the re-run. Check the build result before piping its manifest to kubectl.
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 build fails after emitting any YAML, this pipeline's status is taken from grep, so the else branch can run and pipe a second build's partial/empty output to kubectl apply; the guard is not fail-closed. Capture the build result (or enable pipefail in 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 that get_store() rolls back whenever the handler raises an HTTPException. 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

Comment thread src/opendox/runtime/config.py Resolved
brettheap and others added 3 commits September 18, 2026 14:11
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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 build on the left side of the pipeline is masked by grep's status, so the else can send empty or partial output to kubectl 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 build failure: grep determines the condition, so a failed or partial render can fall through to kubectl 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 build error is hidden by grep, and the placeholder branch ends with a successful echo, 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 to kubectl 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) and runner.drift(conn) each call applied(), which issues multiple SQL statements, but _bound_by sets SET LOCAL statement_timeout only 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 --plan does not run refuse_a_schema_the_api_will_not_read, even though the real apply() does. In the shipped split workload, a migration DSN selecting schema A with OPENDOX_SERVED_SCHEMA set 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 calling runner.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

Comment thread src/opendox/runtime/config.py Resolved
Comment thread .github/workflows/validate.yml Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 though MAX_PAGE_BODY_BYTES is 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

  • alg comes 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, raising TypeError; get_principal() catches only OidcError, 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 calls pytest.fail() whenever CI is 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

Comment thread src/opendox/runtime/app.py Resolved
brettheap and others added 2 commits September 18, 2026 15:08
…, 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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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_migrate passes served_schema into the runner, but MigrationRunner.plan() only reads the ledger and does not call refuse_a_schema_the_api_will_not_read; that guard is only reached by apply(). With OPENDOX_SERVED_SCHEMA different from the migration DSN's selected schema, runtime migrate --plan therefore reports a successful pending plan even though the actual migration will refuse. Run the same schema preflight before emitting the preview (or make plan() enforce it) so --plan describes an executable run.
                evidence = {"verb": "migrate",
                            "planned": [m.version for m in runner.plan()],
                            "applied": []}

src/opendox/runtime/config.py:248

  • _SECRET_PARAMETER is a raw substring alternation, so a non-secret parameter such as monkey=1 matches key and 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 < budget tests only the sum of preceding rows, so it admits the current row even when that row pushes the response over MAX_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 actual budget + one row bound.
            "  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

Comment thread src/opendox/runtime/cli.py Resolved
brettheap and others added 2 commits September 18, 2026 16:58
…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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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_USER is 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 dev overlay 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 echo succeeds, the pasted/automated block exits 0 even though it deliberately skipped kubectl 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 echo succeeds, the pasted/automated block exits 0 even though it deliberately skipped kubectl 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 echo succeeds, the pasted/automated block exits 0 even though it deliberately skipped kubectl 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 reset loads settings.served_schema but never invokes MigrationRunner.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 on lock before selecting/dropping the schema.
                    # into DDL, and the schema is reported in the evidence so

src/opendox/runtime/cli.py:434

  • --plan only runs the canonical digest check; it does not apply the served_schema guard that the real apply() path runs before mutating anything. A migration DSN aimed at the wrong schema can therefore produce a successful plan that the immediately-following migrate command 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 ², but int("²") raises a raw ValueError. Consequently a malformed integer setting can escape _positive_int without the promised ConfigurationError naming the setting (and load_settings callers that handle only ConfigurationError break). 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 $user is treated as PostgreSQL's special $user token. If that literal schema is current_schema() while the role-named schema exists but lacks USAGE, this branch adds the role schema to skipped and 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_NAMES is not the runtime extra's complete import closure; it omits transitive top-level modules such as anyio, starlette, and typing_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

Comment thread src/opendox/runtime/config.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 with dev can 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 supports overlays/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-coded dev path.
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 -rs succeeds 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 -rs also succeeds for an empty line here, so the block writes a zero-byte runtime-password. init-runtime-role.sh explicitly refuses an empty OPENDOX_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 ² that int() cannot parse. With OPENDOX_* set to such a value, line 649 raises a raw ValueError instead of the promised ConfigurationError naming 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() returns None when no explicit dbname is present, but libpq can derive the database from the connection user (or a service profile). Thus served and migration DSNs such as runtime@.../ and migrator@.../ compare as None == None even 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

Comment thread src/opendox/runtime/config.py Resolved
Comment thread src/opendox/runtime/config.py Resolved
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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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_ROOT to any non-default absolute path makes this named volume target a directory the image never creates or chowns. The container runs as opendox, 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_URL while the Deployment receives only OPENDOX_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. When OPENDOX_PUBLISH_OPENAPI=true, generated clients will see these operations as unauthenticated and omit Authorization, 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 None and _refuse_two_dsns_that_select_different_schemas treats 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 as None; 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

  • $user is a dynamic search_path token, 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 ², but int("²") raises ValueError; that bypasses the promised ConfigurationError boundary and makes an invalid environment value escape as a traceback/evidence failure. Validate ASCII decimal digits (or catch the conversion) before calling int().
    if not raw.isdigit():

src/opendox/runtime/migrations.py:839

  • The ledger bootstrap is committed before the initial protect_ledger call. 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-committed opendox_schema_migrations table 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 CONNECT on 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:-}
Comment on lines +77 to +81
- name: OPENDOX_DATABASE_URL
valueFrom:
secretKeyRef:
name: opendox-db-runtime
key: dsn
brettheap and others added 2 commits September 18, 2026 18:00
…"$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>
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Security Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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 dev overlay. Following it for a managed install reintroduces the bundled Postgres resources and dev broker settings instead of reapplying managed-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

  • --plan only runs runner.plan(), which discovers filenames and consults the ledger but never decodes the migration bytes. A pending 0002_*.sql containing invalid UTF-8 is therefore reported in planned, while the real apply() refuses it in snapshot_run() before any mutation; the preview is not an executable plan. Preflight the same snapshot_run()/decode validation before emitting the plan (and surface its MigrationError as 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 ², but int("²") raises ValueError. That lets an invalid numeric environment value escape _positive_int as a raw exception instead of the promised ConfigurationError, so configuration loading/CLI handling is inconsistent. Restrict this check to ASCII digits before calling int().
    if not raw.isdigit():
  • Files reviewed: 36/39 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@brettheap

Copy link
Copy Markdown
Contributor Author

Registered, not taken — the review at the landed-candidate head abc7f634

Read in full. 0 new comments, 3 suppressed, and none is BLOCKING-class (no data loss, no credential exposure, no refusal bypass), so under the holder's ruling they are REGISTERED here rather than taken in a fourth batch.

  1. src/opendox/runtime/cli.py:443 — migrate --plan does not decode the migration bytes. FACT: runner.plan() discovers filenames and consults the ledger, while apply() refuses invalid UTF-8 in snapshot_run() before any mutation — so a pending 0002_*.sql that apply() will refuse still appears in planned. It is the same family as the served-schema finding taken at 61ab857c (a preview that does not describe an executable run) and the remedy is the same shape: run snapshot_run() before emitting the plan and surface its MigrationError as the refusal.
  2. src/opendox/runtime/config.py:670 — str.isdigit() accepts non-ASCII digits. FACT: "²".isdigit() is True and int("²") raises a raw ValueError, so a malformed numeric setting escapes _positive_int as an unnamed exception instead of the ConfigurationError this module promises. str.isascii() and str.isdigit() is the repair.
  3. docs/runtime.md:541 — the re-run block under the managed-database instructions hard-codes the dev overlay. FACT: following it for a managed install reapplies the bundled Postgres resources. Needs either the selected overlay or two guarded commands.

Still open and already registered above (threads left unresolved deliberately): the served DATABASE's non-secret declaration (OPENDOX_SERVED_DATABASE, ruled a FOLLOW-UP ACT under the same claim), and the served process not asserting its own current_user against runtime_pg_role — which this description has carried as a declared residual since round 12.

The two security-relevant findings of this round's predecessor WERE taken, at 3d587ae8: two DSNs that name no database no longer compare equal (libpq defaults it to the connection user — measured), and "$user" is expanded before it is compared (measured three ways on postgres 16).

validate and runtime are green at abc7f634. SonarCloud's failure is the advisory one this description answers in full.

Lane: openxfactory-4 (openXfactory-4-openDox_extraction)

@brettheap

Copy link
Copy Markdown
Contributor Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants