Skip to content

preflight: ask each copy-and-swap door only for the owner access it needs - #736

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd96-owner-access-per-door
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd96-owner-access-per-door

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

Each copy-and-swap entry point now checks only the schema access the table's owner actually needs for what it does: a discard checks USAGE before it drops anything, and a resume that only finishes an already-committed swap no longer needs CREATE.

Why

Copy-and-swap does its writes as the table's owner, so before a run starts pg-sprite checks that the owner can reach the table's schema (USAGE) and create in it (CREATE). Every entry point asked for both, which was wrong in two ways. A discard, which abandons a stopped run, drops the half-built copy as the owner but never checked USAGE, so it could fail with "permission denied" halfway through cleaning up. A resume whose swap had already committed creates nothing, but it was still refused without CREATE, while its replication slot kept holding WAL on the server.

What

  • checkCopySwapOwnerSchema takes a needCreate flag. CheckCopySwapEnvironment passes false for a run that only finishes a committed swap (Held.SwapCommitted). That run still needs USAGE, because it drops the retained source as the owner.
  • New preflight.CheckCopySwapOwnerUsage. Runner.Discard calls it in both discard paths once it has found a shadow, before the first drop. A discard that finds no shadow is not checked.
  • The USAGE-only refusal reuses *preflight.PrivilegeError (reason insufficient-privileges), with its own hint and a grant for USAGE alone. pg-sprite discard maps it to its refusal report. No new cause.
  • Fresh runs, --restart, desired-plan statements and resumes before the swap still need both privileges.
  • Two container tests, both failing on main:
    • A discard is refused for the owner's missing USAGE with nothing dropped, then succeeds once the owner holds USAGE through a granted role.
    • A finish-only resume is refused for USAGE alone. Once PUBLIC holds USAGE it is admitted and finishes, while a fresh run and a restart are still refused for CREATE.
  • Docs: engine-role.md lists what each entry point needs. copy-and-swap.md, copy-and-swap-design.md, cli.md, invariants.md, refusal-classes.md and tcb-model.md now match.

Before / after

The table app.orders belongs to orders_owner, who has lost USAGE and CREATE on schema app. Two operators each run a different command against a stopped run.

pg-sprite discard app.orders          (a run stopped while verifying; its copy stands)

Before
  check the owner's access     not checked
  drop the copy as the owner   ERROR permission denied for schema app
  result                       the discard stops part-way; the run's slot or write block may still stand

After
  check the owner's access     orders_owner has no USAGE on app
  result                       refused before anything is dropped:
                               "GRANT USAGE ON SCHEMA app TO orders_owner"


pg-sprite migrate --alter "<same statement>"   (the swap already committed; only cleanup is left)
  ...and orders_owner has been given USAGE again, but not CREATE

Before
  check the owner's access     needs USAGE + CREATE -> refused for CREATE
  result                       the run cannot finish; its slot keeps holding WAL

After
  check the owner's access     needs USAGE only (it creates nothing) -> passes
  result                       the run drops the old table and finishes

…eeds

A discard drops the shadow as the owner and now refuses missing USAGE up
front instead of failing mid-drop; a resume that only finishes a committed
swap creates nothing and is no longer refused for missing CREATE.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 4, 2026 12:45
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-12-04T12:45:49.333296Z
We couldn’t complete this review. Comment @codex review to try again.
6294af7 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@aparajon

aparajon commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Correctness review at 6294af7: is each narrowed owner preflight exactly the set its later steps need?

What I checked. I traced every door that now asks the owner for less, from the preflight call down to the SQL each later step runs and the role it runs it as.

  • CheckCopySwapEnvironment with needCreate = !env.Held.SwapCommitted, which covers the run doors (fresh run, resume, restart, dry run) through the shared checkCopySwap helper.
  • CheckCopySwapOwnerUsage and the new requireOwnerUsage in both discardStoppedRun and discardLeftovers.
  • The finish-only path: MeasureResumeHeld / swapCommitted, the admission refusals in runner_dispatch.go, settleOldTable, DropOldTable (runs under SET LOCAL ROLE as the swapped table's owner), and finishedSwapStatistics.
  • Discard: dropShadow (owner session), dropWriteFence / dropWriteFenceFromOld (engine role, no SET ROLE), and the checkpoint-row delete.
  • has_schema_privilege(role, schema, 'USAGE' | 'CREATE') semantics: it honors inherited roles and PUBLIC, so the group-role and PUBLIC grants in the new tests are real grants as far as the check is concerned. DROP TABLE needs USAGE on the schema for name lookup and ownership of the table, not CREATE. Dropping dependent objects (indexes, triggers, owned sequences) needs no separate check.
  • PG 14-18: nothing in the narrowed check touches pg_has_role(..., 'SET') (PG16+), so the narrowing behaves the same on all five majors. The CI matrix agrees (14, 15, 16, 17, 18 all green).
  • Refusal text: the Grant line lists only the privileges actually missing, and the hint matches the step that needs them (ownerBuildHint for builds, ownerDropHint for drops).
  • CLI mapping: discardRefusal now maps *preflight.PrivilegeError to insufficient_privileges.
  • Tests: the two new integration tests assert specific values (a GRANT USAGE-only statement, discarded.Nothing(), shadow, fence and checkpoint row still standing after the refusal, then all three gone after a group-role grant). The finish-only test covers refuse, then PUBLIC grant, then done with _old dropped, and checks that fresh run and restart are still refused for GRANT CREATE.

0 blocking, 4 non-blocking.

Blocking

None. I could not construct an input where the narrowed preflight passes and a later step then fails on a privilege the preflight no longer asks for:

  • A committed swap only renames and drops, so USAGE (lookup) plus table ownership is the whole requirement, and CREATE is no longer needed.
  • A fresh run, resume or restart still builds a new shadow and installs a fence, so those keep asking for CREATE.
  • Discard drops the shadow as the owner, and now asks for USAGE before the first drop.

Non-blocking

  1. DiscardGone is not covered by the new USAGE check, and the docs say all discard doors are. runner_discard_gone.go drops the recorded shadow as the owner (dropRecordedShadowTx) without calling requireOwnerUsage. An owner who lost USAGE gets a raw permission denied for schema from the drop rather than the typed PrivilegeError with a GRANT USAGE line. The failure is still clean, since the drop is one transaction and nothing is half-dropped, so this is a message-quality gap and not a safety one. Either add the same requireOwnerUsage call there, or word the Discard doc comment, docs/cli.md and the PR description so they say "stopped-run and leftover discard" instead of every door.
  2. The finish-only check asks for USAGE in two cases where it may not be needed. When _old is already gone, or when KeepOld is set and the run only has to settle statistics, the later steps still run inspect_swapped under SET LOCAL ROLE, which does need USAGE to resolve names. So I think the ask is right for the statistics step, but it is worth a one-line comment on CheckCopySwapEnvironment saying why a finish that drops nothing still asks for USAGE, so the next reader does not "narrow" it to nothing.
  3. ownerDropHint wording. The hint reads as if the owner will drop things in the schema. For a finish-only run the thing being dropped is the retained _old table. Naming the step ("to drop the retained old table") would make the refusal self-explanatory in the finish-only case, where the operator has just seen a successful swap.
  4. create = true override in checkCopySwapOwnerSchema. When !needCreate the function sets create = true and swaps the hint, so the variable means "CREATE is satisfied" in one branch and "CREATE is required and held" in the other. It is correct, but a reader has to hold the boolean inversion in their head. Naming it createOK (or computing missingCreate := needCreate && !create) would make ownerSchemaRefusal's arguments read as what they are.

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon

aparajon commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Second pass at 6294af7 on tests and edge cases: coverage gaps, PG-version differences and failure paths. This does not repeat the first comment.

What I checked. The new and changed tests against the paths they are meant to pin, the existing owner-privilege and discard tests they sit beside, and the failure paths that now return a PrivilegeError instead of a raw driver error.

0 blocking, 4 non-blocking.

Blocking

None. Every changed behavior has at least one test that fails if the change is reverted:

  • Narrowed finish-only ask: TestCheckCopySwapAsksFinishingACommittedSwapForTheOwnersUsageAlone fails if CREATE comes back, because the refusal would then list GRANT CREATE.
  • Discard refusal before any drop: the new discard integration test fails if the check moves after the first drop, because it asserts the shadow, fence and row all stand.
  • CLI classification: the new case in TestDiscardRefusalSortsCauses fails if the PrivilegeError mapping is removed.

Non-blocking

  1. No test drives the refusal through the CLI. TestDiscardRefusalSortsCauses pins the classification function, and the integration test pins the runner, but nothing runs discard end to end against a USAGE-less owner and asserts the report carries insufficient_privileges with the exit code the docs promise. internal/cli/discard_refusal_integration_test.go already has the scaffolding for a refused discard; one more case there would close the loop.
  2. discardLeftovers with no checkpoint row is not exercised. The new integration test stops a run at verifying, so it goes through discardStoppedRun. The discardLeftovers call site (shadow and fence found, no row) has the same requireOwnerUsage call but no test that reaches it.
  3. No negative test for the "no shadow, owner not asked" branch. requireOwnerUsage returns nil when !found.shadow. That is the behavior that lets an operator discard a run that never built a shadow even when the owner has lost USAGE. A case that revokes USAGE, leaves no shadow, and asserts the discard still succeeds would keep a later refactor from asking for more than it needs.
  4. Finish-only edge cases and owner-membership semantics are untested. The finish-only test covers the plain "drop _old" path. There is no case for KeepOld or for _old already gone, which are the two finish-only paths that do not drop anything. Separately, the grant in the discard test is through a group role: on PG 14-15 the owner's membership is inherited by default, while on PG16+ INHERIT is a per-grant option (GRANT ... WITH INHERIT FALSE) that has_schema_privilege honors. The CI matrix passes on all five majors with the default grant, so there is no failure today, but a WITH INHERIT FALSE case on PG16+ would pin that the check follows inheritance and not mere membership.

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon aparajon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Approving at 6294af7: 0 blocking, 8 non-blocking (details in the comments above).

Each narrowed owner preflight matches what its later steps run, and the new tests pin both the refusal and the leftovers that must stand after it. The non-blocking items are a missing USAGE check on the DiscardGone door (and the matching doc wording) plus test and wording gaps.

This review was generated by Claude Code (claude-sonnet-5-5).

@JashLal

JashLal commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Reviewed 6294af7. No new blocking findings. The stopped-run and leftover discard paths check the owner's schema access before dropping a shadow, and the CLI maps the typed refusal to insufficient privileges. Finish-only resume still checks USAGE, while fresh runs and restarts keep the build-time CREATE check. The integration tests assert that the shadow, fence, and checkpoint survive refusal and that resume can finish after USAGE is restored. The separate DiscardGone behavior is covered in the earlier review. I reviewed the diff statically and checked the passing PostgreSQL 14–18 CI results. Earlier review · CI

The automated review result was unavailable. No local tests were run.

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.

3 participants