Skip to content

fix(office): the verification queue and violation reports answer at all (#900, #901) - #909

Merged
thinkclay merged 1 commit into
mainfrom
redesign/fix-office-authz
Sep 26, 2026
Merged

thinkclay merged 1 commit into
mainfrom
redesign/fix-office-authz

Conversation

@thinkclay

Copy link
Copy Markdown
Contributor

Closes #900. Closes #901.

Two admin screens were dead in the product — the two whose layouts #839 had just rebuilt. Both failed the same way: a query error nobody read, turned into a plausible-looking empty state.

#900 — verification 403s for everyone, super_admin included

The gate was a local helper in office-communities.ts:

const { data: user } = await supabase
  .schema("core").from("users").select("role").eq("id", userId).maybeSingle();
return user?.role === "office" || user?.role === "admin";

core.users has no role column. The select errored, only data was destructured so the error went nowhere, user?.role was undefined, and the helper returned false unconditionally. Listing, approving and rejecting were all unreachable for every caller.

Roles live in core.role_assignments → core.roles, which is what the shared requireRole("office", "platform") middleware reads. Every other office route already mounts it; this file now does too, and uses the supabaseAdmin client it attaches — which these handlers need, since an administrator reads across every community and community.memberships is RLS-scoped to the member.

The same file had the same mistake twice. The enrichment selected id, display_name, email from core.users, which has no email column either — so every row came back nameless. A queue of "Unknown User" is not a queue anyone can act on. Names now come from columns that exist; email comes from the admin API, since auth.users isn't exposed through PostgREST even to the service role.

#901 — violation reports 500 on every request

I filed this one with the wrong cause, and have corrected the issue. I claimed the foreign key was missing, having read information_schema.constraint_column_usage — which is privilege-filtered on the referenced table, so keys pointing into auth are invisible there. pg_constraint shows them.

The constraints exist. Migration 129 created the table with its user columns split across two schemas:

reported_by_user_id UUID REFERENCES auth.users(id),
worker_user_id      UUID REFERENCES core.users(id) ON DELETE SET NULL,
reviewed_by_user_id UUID REFERENCES auth.users(id),

The request runs against core, and PostgREST resolves named embeds only within exposed schemas — auth is not one. So the embed had no target and the whole select failed, taking the worker embed down with it even though that one was always fine.

Migration 359 re-points both at core.users (core.users.id already references auth.users(id) on cascade, so they share an id space). It also gives them ON DELETE SET NULL, which they lacked: defaulting to NO ACTION against auth.users meant deleting the account of anyone who had filed or reviewed a report would fail at that constraint — account deletion blocked by a violation report.

Behind that sat the same email bug, since the embeds use it as a display-name fallback. username is on the table.

Tests

Six api tests in tests/routers/, hitting real HTTP. Run against origin/main's handlers first:

FAILED | 1 passed | 5 failed

The one that passes is "a worker is refused" — which the broken code passes for the wrong reason. That is why both directions are pinned: a gate that denies everyone satisfies half its contract.

With the fix: ok | 6 passed | 0 failed.

Constraints recorded

.radium/supabase-backend.md gains two notes — never destructure only data from a Supabase query, and PostgREST embeds only resolve inside exposed schemas, including the information_schema trap that sent me down the wrong path above.

Verification

result
office user lists the queue 200, rows named
office user rejects, then approves 200 / 200, queue total 1 → 0
worker hits the queue 403 Requires office role with platform scope
/office/violations renders rows naming reporter, organisation and worker
both screens at 1440 and 390 hScroll 0

pnpm prepush green; migration numbers unique (195).

Note for whoever merges: migration 359 needs applying to dev/preview/prod. It is idempotent and touches two constraints on one table.

🤖 Generated with Claude Code

@thinkclay

Copy link
Copy Markdown
Contributor Author

Reviewed while clearing the queue. Strong PR — the "a query error nobody read, turned into a plausible-looking empty state" framing is exactly right, and pinning both directions of the gate because "a gate that denies everyone satisfies half its contract" is the detail that makes the tests worth having. Correcting your own diagnosis on #901 in the issue rather than quietly shipping the right fix is the right call too.

Not touching the branch — redesign/fix-office-authz is checked out in another session's worktree (.claude/worktrees/redesign-r1), so a push from here could land on top of uncommitted work. Three things to pick up:

1. Migration number collision — blocking

main now has 359_application_submitted_at.sql (#905, merged 21:55). This PR adds 359_circumvention_reports_user_fkeys.sql. Two 359s.

prepush's migration numbers unique check will refuse it, and more importantly the remote-deploy path applies by numeric prefix — see the note in [[remote-deploy]] about numeric migrations bypassing schema_migrations. Rename to 360. Safe to rename since it has not been applied anywhere yet.

2. Run API Tests is infrastructure, not you

It reads as supabase start is not running at the types check, but the real cause is 40-odd lines earlier:

Error response from daemon: toomanyrequests: Rate exceeded

Docker Hub rate-limited the image pulls, Supabase never came up, and every later step inherited it. Just needs a re-run — though note the whole queue has been pulling images hard for the last hour, so give it a moment.

3. Lint REST API Code — one-line format

deno fmt wants the import in office-communities.ts wrapped:

import {
  type ApiEnv,
  authMiddleware,
  requireRole,
} from "../middleware/auth.ts";

Lint, typecheck & build, Unit tests, Security Scan and all three drift-audits are green.

One question on the migration itself

Re-pointing reported_by_user_id and reviewed_by_user_id from auth.users to core.users is right for the PostgREST embed, and adding ON DELETE SET NULL genuinely unblocks account deletion — good catch that it was NO ACTION.

Worth stating explicitly in the migration comment: this only holds while core.users.id references auth.users(id) on cascade, which is what makes the id spaces interchangeable. If that ever becomes non-cascading, these two columns silently start pointing at rows that can outlive their auth user. One sentence in the file, since that is the assumption the whole change rests on.

…ll (#900, #901)

Two admin screens were dead in the product. Both failed the same way — a
query error that nobody read, turned into a plausible-looking empty state.

## #900 — verification 403s for everyone, including super_admin

The gate was a local helper in `office-communities.ts`:

    const { data: user } = await supabase
      .schema("core").from("users").select("role").eq("id", userId).maybeSingle();
    return user?.role === "office" || user?.role === "admin";

`core.users` has no `role` column. The select errored, only `data` was
destructured so the error went nowhere, `user?.role` was `undefined`, and the
helper returned false unconditionally. Listing the queue, approving and
rejecting were all unreachable — for every caller, including holders of
`super_admin`, `admin` and `office`.

Roles live in `core.role_assignments` joined to `core.roles`, which is what
the shared `requireRole("office", "platform")` middleware reads. Every other
office route already mounts it; this file now does too, and gets the
`supabaseAdmin` client it attaches — which these handlers need, since an
administrator reads pending verifications across every community and
`community.memberships` is RLS-scoped to the member.

The same file had a second instance of the same mistake: the enrichment
selected `id, display_name, email` from `core.users`, which has no `email`
column either, so every row in the queue came back nameless. A queue of
"Unknown User" is not a queue anyone can act on. Names come from the columns
that exist; email comes from the admin API, since `auth.users` is not exposed
through PostgREST even to the service role. The `limit` cap of 100 bounds that
fan-out.

## #901 — violation reports 500 on every request

I filed this one with the wrong cause and have corrected the issue. I said the
foreign key was missing, having read `information_schema.constraint_column_usage`
— which is privilege-filtered on the *referenced* table, so keys pointing into
`auth` are invisible there. `pg_constraint` shows them.

The constraints exist. Migration 129 created the table with its user columns
split across two schemas: `worker_user_id` references `core.users`, while
`reported_by_user_id` and `reviewed_by_user_id` reference `auth.users`. The
request runs against `core`, and PostgREST resolves named embeds only within
the schemas it exposes — `auth` is not one — so the embed had no target and
the whole select failed, taking the `worker` embed down with it even though
that one was always fine.

Migration 360 re-points both at `core.users`. `core.users.id` is itself
`REFERENCES auth.users(id) ON DELETE CASCADE`, so the two share an id space
and nothing is lost. It also gives them `ON DELETE SET NULL`, which the old
constraints lacked: they defaulted to NO ACTION against `auth.users`, so
deleting the account of anyone who had filed or reviewed a report would fail
at that constraint — account deletion blocked by a violation report. The
report should outlive the accounts; that is what the table is for.

Behind that sat the same `email` bug, since the embeds select it from
`core.users` as a display-name fallback. `username` is on the table and is the
name people are known by.

## Tests

Six api tests in `tests/routers/`, hitting real HTTP. They were run against
`origin/main`'s handlers first: five fail. The sixth — "a worker is refused" —
passes on the broken code, which is the point of pinning both directions: a
gate that denies everyone satisfies half its contract.

## Constraints recorded

`.radium/supabase-backend.md` gains two notes: never destructure only `data`
from a Supabase query (both bugs here), and PostgREST embeds only resolve
inside exposed schemas — with the `information_schema` filtering trap that
sent me down the wrong path on #901.

Verified locally: an office user lists, rejects and approves (queue total 1 →
0); a worker gets 403; `/office/violations` renders rows naming reporter,
organisation and worker; both screens at 1440 and 390 with no horizontal
scroll.

Co-Authored-By: Claude Opus 5 <[email protected]>
@thinkclay
thinkclay force-pushed the redesign/fix-office-authz branch from a7226de to 2710be3 Compare September 26, 2026 19:55
@thinkclay

Copy link
Copy Markdown
Contributor Author

Pushed a fix for the red CI. Three things, one of them a real defect in the branch:

1. Migration number collision (the actual failure). #905 merged its own 359_application_submitted_at.sql while this was in flight. Two files with the same numeric prefix means supabase start fails on duplicate key value violates unique constraint "schema_migrations_pkey" — so Supabase never came up, and every later step in that job failed as collateral ("supabase start is not running"). Mine is now 360_circumvention_reports_user_fkeys.sql, rebased on current main so both are present and ordered.

My local pnpm prepush reported "migration numbers unique" because I branched before #905 landed. That check only ever sees the branch.

2. types.ts was stale. The new foreign keys show up in the generated Relationships, which the "Check types.ts matches the migrations" step compares. Regenerated, then trimmed back to only the core additions — a straight supa:generate on this machine also pulled in unrelated storage.buckets / storage.objects drift from the local CLI version, which the owned-schemas slice ignores but which has no business in this diff. Verified with CI's exact command: ✅ types.ts matches the migrations.

3. deno fmt. The import in office-communities.ts needed splitting. deno lint and deno fmt --check both clean from packages/supabase/functions/api.

All six api tests re-run green after the rebase.


One thing worth flagging separately, since it is why both of these outages lasted: the tests I added do not run in CI. api-tests.yml runs only functions/api/__tests__/{lib,routes,integration}/*.test.ts, and both of those steps are continue-on-error: true. The whole tests/routers/ directory — which is where the existing HTTP-level api tests live, including office-jobs-rest.test.ts — is executed by nothing; prepush only load-probes it to check the files parse.

So these six tests protect a local run and a reviewer, not the build. I have not changed that here because it is a CI-topology decision rather than part of this fix, but it seems worth its own issue — happy to file one.

@github-actions

Copy link
Copy Markdown
Contributor

📊 Performance Benchmark Results


@thinkclay
thinkclay merged commit b168ea4 into main Sep 26, 2026
17 checks passed
@thinkclay
thinkclay deleted the redesign/fix-office-authz branch September 26, 2026 20:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant