Skip to content

fix(api): an org admin 404'd on an application their own list returned - #608

Merged
thinkclay merged 1 commit into
mainfrom
claude/deploy-dev2
Aug 12, 2026
Merged

thinkclay merged 1 commit into
mainfrom
claude/deploy-dev2

Conversation

@thinkclay

Copy link
Copy Markdown
Contributor

Found by smoke-testing dev after deploying #607 — which is the point of smoke-testing dev.

The symptom

GET /v1/employer/applications/{id} returned 404 for an application the same user had just received from GET /v1/employer/applications.

#607 fixed the list read to run above RLS. The authorisation still resolved the row through RLS, and core.applications' policies recognise the organisation owner — so resolveApplicationOrgAccess found no row and every caller reported "Application not found".

On dev the row is invisible under RLS to the owner too, so this was not limited to role-holders.

The change

resolveApplicationOrgAccess takes an explicit readClient for the row lookup. The default is unchanged — callers passing nothing behave exactly as before, and the helper's 15 unit tests pass untouched. The employer routes pass a service-role client: GET and PATCH on /v1/employer/applications/{id}, and the per-application scheduling authorisation.

This does not widen access. The lookup only answers "who is the applicant, and which organisation posted the job" so the decision can be made. isApplicant and hasOrgAccess are computed exactly as before, and callers still choose what to return. It stops RLS silently answering a question it was not asked.

Fifth patch over the same mismatch

This is the fifth place the org-vs-team axis has forced a service-role read — after attachStageHistory, the EEO route, the scheduling routes, and the applications list. #544 is the actual fix; each of these is a plaster over it, and the pattern is now well enough evidenced that the real change is worth scheduling.

Verification

deno lint, deno fmt --check clean on all three files; the access helper's 15 unit tests pass. Dev smoke results follow in a comment once deployed.

CI still cannot start jobs (2–3s failures, no logs), so this carries local + dev verification only.

Found by smoke-testing dev after the previous fix, which is the point of
smoke-testing dev.

GET /v1/employer/applications/{id} returned 404 for an application the
same user had just received from GET /v1/employer/applications. The list
read was fixed to run above RLS; the *authorisation* still resolved the
row through RLS, and `core.applications`' policies recognise the
organisation owner, so `resolveApplicationOrgAccess` found no row and every
caller reported "Application not found".

On dev the same row is invisible under RLS to the owner as well, so this
was not limited to role-holders.

resolveApplicationOrgAccess now takes an explicit `readClient` for the row
lookup. The default is unchanged — callers that pass nothing behave exactly
as before, and the helper's 15 unit tests pass untouched. The employer
routes pass a service-role client: GET and PATCH on
/v1/employer/applications/{id}, and the per-application scheduling
authorisation.

This does not widen access. The lookup only answers "who is the applicant,
and which organisation posted the job" so the decision can be made;
`isApplicant` and `hasOrgAccess` are computed exactly as before and callers
still choose what to return. It stops RLS silently answering a question it
was not asked.

Fifth patch over the org-vs-team axis mismatch. #544 is still the fix.
@thinkclay
thinkclay merged commit b1c66ce into main Aug 12, 2026
3 of 9 checks passed
@thinkclay
thinkclay deleted the claude/deploy-dev2 branch August 12, 2026 08:32
thinkclay added a commit that referenced this pull request Aug 12, 2026
…called (#447) (#614)

core.reviews and its five child tables have been in place since migration 099,
and ReviewWizard drives a full multi-step flow against @scaffald/sdk. The router
implemented four of the thirteen endpoints the SDK exposes, so every step of
writing a review 404'd. Same shape as the profile epic: a good database, a built
UI, and no wire between them.

Added:

  GET   /reviews/my-reviews                    reviews the caller has written
  GET   /reviews/soft-skills/by-category       the catalog grouped for the tabs
  GET   /reviews/{id}/draft                    reopen a part-written review
  PATCH /reviews/{id}/draft                    whole-blob autosave
  PATCH /reviews/{id}/step                     wizard progress
  PATCH /reviews/{id}/skill-ratings            technical scores
  PATCH /reviews/{id}/category-rating          one category at a time
  PATCH /reviews/{id}/soft-skill-votes         strengths and improvements
  PATCH /reviews/{id}/comment                  body + public visibility
  GET   /reviews/analytics                     aggregates for a subject

Ownership is the review system's whole integrity, so it lives in one helper
rather than being retyped per handler: loadOwnReview filters on id AND
author_user_id, and a miss is a 404 rather than a 403 — the convention #608/#609
settled on, because "exists but not yours" leaks that it exists. Verified
against a live stack: another user's draft is 404 on both read and write.

Mutations additionally require the review to still be a draft. A submitted
review is a published statement about someone; letting the author keep editing
would change what a reader already saw.

Three things the live run caught that static reading would not have:

- **Two endpoints 500'd on "permission denied".** `authenticated` had no DELETE
  grant on review_skill_ratings or review_soft_skill_votes, and both endpoints
  replace their set rather than merging — the reviewer sends the full list, so a
  removed skill has to actually disappear. Migration 346 adds the grants, plus a
  DELETE policy on review_skill_ratings mirroring its insert predicate
  (review_soft_skill_votes already had an author-scoped ALL policy). Same class
  as #481: RLS and a policy exist, the GRANT that makes the policy reachable
  does not, and it surfaces as a server error rather than a permission one.

- **Analytics resolved skill names from the wrong table.** I joined
  data.masterformat; review_skill_ratings.skill_id has a foreign key to
  core.skills. It returned blank names until a live call showed it.

- **POST /{id}/submit was destroying the review.** It set
  `metadata: { status: "submitted" }` — a whole-object write over the jsonb
  column holding the draft body, the wizard's step progress and the is_public
  flag the comment step had just saved. Everything the reviewer filled in was
  dropped at the moment they submitted it. Now merged, and it checks ownership
  like the rest.

KNOWN_GAPS drops 83 -> 73, and the contract suite is added to
test:api:rest:suite — it has never run in CI, which is the same gap #604 fixed
for __tests__/lib.

Co-authored-by: Claude Opus 5 <[email protected]>
thinkclay added a commit that referenced this pull request Aug 25, 2026
…649)

Closes #646.

Moving a candidate from the ATS board has never worked. PATCH
/v1/employer/applications/{id} returned 404 "Application not found" for a
row the same user's own list had just returned.

#608 fixed exactly this shape once, by moving the ACCESS lookup above RLS
with `readClient: getServiceClient()`. It left the two statements a few
lines below on the request client:

    const { data: existing } = await supabase   // RLS, as the caller
      .schema("core").from("applications")
      .select("id, status, assigned_to").eq("id", id).single()

`core.applications`' policies recognise the organisation OWNER and the
applicant. An org admin is neither, so the row came back empty, `readError`
was set, and the handler 404'd — after both authorisation checks had already
passed against the organisation. The update statement below had the same
problem and would have written zero rows had the read ever got past it.

Both now use the service client, which is the pattern this file already
documents for the list path: authorisation happened above, against the
organisation, and reading through RLS here silently re-decides it on a
different axis.

Also selects `user_id`. The hire fee check reads `existing.user_id`, and the
select did not include it — so it was undefined on every hire.

─── How it was found, and one wrong turn ─────────────────────────────────

The wire-level smoke added for #643 caught it: the board said a candidate
had moved while the PATCH behind it 404'd. Nobody had noticed before because
a failed move produced no feedback at all — `setError` was set, nothing
rendered it, and the card simply did not move.

Mid-investigation I talked myself into believing this was the stale local
edge-runtime trap, on the strength of finding #608 in the log. It was not:
restarting the runtime from current source reproduced the 404 exactly.
Checking beat concluding, in both directions — the first check ruled out a
real cause, the second ruled out a false one.

Verified end to end, not just at the endpoint:

  PATCH status: 200
  row status after PATCH: reviewing        (re-read from the list, not the 200)

  ✓ undo      writes=0 (expected exactly 0)
  ✓ let-it-go writes=1 ↳ 200 (expected exactly 1, 2xx)

smoke-move-undo.mjs is tightened from "at least one write" to "exactly one,
2xx" — the acceptance criterion #646 was filed with. The duplicate write it
used to tolerate is gone with the 404: that second request was the client
retrying a failure, which also removes the reproduction for #647.

Co-authored-by: Claude Opus 5 <[email protected]>
thinkclay added a commit that referenced this pull request Sep 10, 2026
… screen (#738)

Closes #476. Second step on #660.

Two separate faults in one file, and only one of them was the one on the tin.

**The phantom routes.** GET / and POST / read core.inquiries, which does not
exist. They were not a rename of core.application_inquiries: the list filtered
on sender_id / recipient_id and the create inserted subject, message and
inquiry_type, none of which are columns on the real table. Every inquiry child
table — comments, sections, capability responses, reminders, audit log — has a
foreign key to application_inquiries. So these two described a generic
person-to-person messaging feature nobody built.

Deleted rather than implemented, per the method on #660: nothing called them.
Inquiries.list() and Inquiries.create() were the only callers and are retired
in Scaffald/sdk#23; no hook or screen used either. Building the table would
have shipped it for an endpoint nothing can reach.

**The fault that actually mattered, and was not in the issue.** While verifying
the above, GET /by-application/{applicationId} — the real thread screen —
returned 404 for an employer looking at an application their own list had just
shown them. checkApplicationAccess read core.applications with the REQUEST
client, and RLS does not expose an org's applications to its staff. It answered
"Application not found" to the very people it then goes on to authorise. That
is the same fault #608/#649 fixed in employer-applications.ts, in a different
file.

Fixing only that turned the 404 into a 200 with a null body, because the
inquiry itself, its sections, comments, capability responses and the
application detail were all read the same way. Measured on one employer:

  core.applications           RLS: NO   service: yes
  core.application_inquiries  RLS: NO   service: yes

So the reads now go through the service client, AFTER checkApplicationAccess
has authorised the caller. The authorisation decision is unchanged — same
user_id match, same organisation owner, same org-scoped role assignment. Only
the read is escalated, which is the difference between "you may not see this"
and "this does not exist".

  before   404 Application not found
  partial  200 null
  now      200 inquiry, sections, comments, capabilityResponses,
               application, candidate, job, capabilityQuestions

Found on the way and NOT fixed here, because it is a different problem
(#447): /v1/inquiries/templates and /v1/inquiries/{id}/history both 404, and
both are called by live hooks on this same screen. The router now serves
exactly one path. Reported on #447 rather than folded in.

Guard 6/6 with core.inquiries removed from BASELINE_BROKEN, leaving 3 entries,
all #658. Deno check on the changed file goes 5 errors -> 3; the remainder are
pre-existing narrowing on access.ok. Typecheck 12/12.
thinkclay added a commit that referenced this pull request Sep 26, 2026
…tead of 3

Most of the ~250 failing api tests were not 250 problems. Four faults in
shared plumbing accounted for the bulk of them, and each looked like a broken
endpoint rather than a broken fixture.

## The magic link carried `token_hash`, not `token`

`completeMagicLinkAuth` read `url.searchParams.get("token")`. GoTrue's
confirmation link is `/auth/confirm?token_hash=...&type=signup`, so the read
found nothing, the helper returned null, and every suite built on magic-link
registration asserted `user !== null` and failed. The same bug sat in both
test trees, and it is why `tests/routers/auth.test.ts` could never produce the
cached token fixture — which in turn failed every suite calling
`requireAuthSetup()` with "Auth setup is incomplete".

One line each. It is the single biggest cause in this change.

## The application fixture invented two columns

`createTestApplication` inserted `custom_answers` and `type`. Neither is a
column on `core.applications`; no migration has ever created either. PostgREST
rejects the whole insert when a key does not exist, so every test needing a
seeded application died in its fixture rather than in its assertions.

## Production code that could not be reached by a test

Two modules read their configuration in a way that works under the edge
runtime and cannot work under `deno test`:

  - `checkApplicationAccess` built its own service client internally, so the
    stub its unit tests pass as the first argument never reached the lookup.
    It takes the client as a parameter now; the production call site passes
    `getServiceClient()` explicitly, so the service-role read (#608, #649) is
    unchanged.
  - `auth.ts` captured the magic-link redirect target in a module-level const,
    freezing the environment as it stood at import. Read per request now.

Both are small changes that make the modules configurable by their callers.
Neither alters what the edge runtime does.

## No token with the office role

`TEST_USERS.admin` carries `worker/platform` only (#478), so office suites
reaching for it got a 403 and read it as a broken endpoint. There is an
`office` entry now — `[email protected]`, seeded with the role by
`002_seed-users.sql` — cached alongside the others, and the two office REST
suites use it.

## Result

    functions/api/__tests__   344 passed,  72 failed  ->  387 passed, 29 failed
    tests/routers/            122 passed, 177 failed  ->  221 passed, 78 failed

249 failures to 107. `GATED.txt` grows from 3 files to 19 — 152 tests that
now fail the build if they regress, verified passing together.

What remains is per-suite assertion drift rather than shared plumbing, worst
first: work-logs, profileCompletion, applications, payments, education. One
known environmental gap is also left: the magic-link endpoint answers
`500 Configuration Error` because the local edge runtime has no site URL
configured, which is a stack-config question rather than a code one.

Co-Authored-By: Claude Opus 5 <[email protected]>
thinkclay added a commit that referenced this pull request Sep 26, 2026
…922)

* fix(test): repair the shared api test fixtures, and gate 19 files instead of 3

Most of the ~250 failing api tests were not 250 problems. Four faults in
shared plumbing accounted for the bulk of them, and each looked like a broken
endpoint rather than a broken fixture.

## The magic link carried `token_hash`, not `token`

`completeMagicLinkAuth` read `url.searchParams.get("token")`. GoTrue's
confirmation link is `/auth/confirm?token_hash=...&type=signup`, so the read
found nothing, the helper returned null, and every suite built on magic-link
registration asserted `user !== null` and failed. The same bug sat in both
test trees, and it is why `tests/routers/auth.test.ts` could never produce the
cached token fixture — which in turn failed every suite calling
`requireAuthSetup()` with "Auth setup is incomplete".

One line each. It is the single biggest cause in this change.

## The application fixture invented two columns

`createTestApplication` inserted `custom_answers` and `type`. Neither is a
column on `core.applications`; no migration has ever created either. PostgREST
rejects the whole insert when a key does not exist, so every test needing a
seeded application died in its fixture rather than in its assertions.

## Production code that could not be reached by a test

Two modules read their configuration in a way that works under the edge
runtime and cannot work under `deno test`:

  - `checkApplicationAccess` built its own service client internally, so the
    stub its unit tests pass as the first argument never reached the lookup.
    It takes the client as a parameter now; the production call site passes
    `getServiceClient()` explicitly, so the service-role read (#608, #649) is
    unchanged.
  - `auth.ts` captured the magic-link redirect target in a module-level const,
    freezing the environment as it stood at import. Read per request now.

Both are small changes that make the modules configurable by their callers.
Neither alters what the edge runtime does.

## No token with the office role

`TEST_USERS.admin` carries `worker/platform` only (#478), so office suites
reaching for it got a 403 and read it as a broken endpoint. There is an
`office` entry now — `[email protected]`, seeded with the role by
`002_seed-users.sql` — cached alongside the others, and the two office REST
suites use it.

## Result

    functions/api/__tests__   344 passed,  72 failed  ->  387 passed, 29 failed
    tests/routers/            122 passed, 177 failed  ->  221 passed, 78 failed

249 failures to 107. `GATED.txt` grows from 3 files to 19 — 152 tests that
now fail the build if they regress, verified passing together.

What remains is per-suite assertion drift rather than shared plumbing, worst
first: work-logs, profileCompletion, applications, payments, education. One
known environmental gap is also left: the magic-link endpoint answers
`500 Configuration Error` because the local edge runtime has no site URL
configured, which is a stack-config question rather than a code one.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(test): mint the auth fixture on demand instead of failing the suite

`requireAuthSetup()` threw "Auth setup is incomplete. Run auth.test.ts first"
— an ordering dependency between test FILES. `deno test` walks a directory
alphabetically, so every suite whose name sorts before `auth.test.ts` ran
before the suite that writes the token fixture and failed for no reason of its
own. Running one file on its own failed the same way, which made the tree
hostile to work on a single suite at a time — the exact thing anyone repairing
it needs to do.

It mints the tokens itself now when the fixture is missing or stale: password
sign-in for the seeded accounts, no mailbox round-trip, including the `office`
entry added alongside. Suites that mean to exercise the magic-link path still
call it directly.

Proof it is not order-dependent any more: delete `tests/fixtures/tokens.json`
and run `office-jobs-rest.test.ts` alone — 3 passed, where it previously
failed with the message above.

    tests/routers/   221 passed, 78 failed  ->  233 passed, 66 failed

`GATED.txt` is unchanged at 19 files: this fixed tests inside suites that
still fail for their own reasons, so no additional file went fully green.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(test): trim the gate to what a clean stack can actually prove

I added five files to GATED.txt on the strength of a local green run and CI
rejected them immediately: 40 of 152 tests, every one of them "Failed to get
or create auth token".

The five — auth, auth-session-regression, ccpa, onet, resume — mint their
users through the magic-link flow. That flow completes against my local stack,
which has a warm mailbox and users left by earlier runs, and does not complete
on the fresh stack CI builds. Local green was not evidence, and I treated it
as evidence.

They come back out. The gate is 14 files, 74 tests, verified after
`pnpm supa db reset` — a stack as close to CI's as I can make locally.

GATED.txt now says this in the file itself, above the list, because the next
person to add a line will be standing exactly where I was.

The headline numbers in this branch survive the same re-measurement on a clean
database, so they were sound; it was only the gate list that was wrong:

    functions/api/__tests__   387 passed, 29 failed   (unchanged)
    tests/routers/            232 passed, 67 failed   (was 233/66 dirty)

Also recorded: the magic-link endpoint answers `500 Configuration Error:
Magic link redirect target is not configured` wherever no site URL is set,
which is the environmental half of why those five cannot be gated yet.

Co-Authored-By: Claude Opus 5 <[email protected]>

* ci(api): give the lint job time to run the type-check it was handed

`Lint REST API Code` has been cancelled at exactly 5:00 on every run since
#924, which surfaces as `##[error]The operation was canceled` with no failing
check named, and then fails `All Tests Passed`.

It is a job timeout, not a lint failure. #924 added a "Type Check (ratchet)"
step that runs `deno check` across all 25 edge functions — roughly four
minutes on its own — to a job whose `timeout-minutes` was 5, already partly
spent on lint and format.

Reproduced on main at 28e1550, the commit that added the step:

    Lint REST API Code | cancelled | 22:57:47Z -> 23:03:03Z
    All Tests Passed   | failure

So this is not specific to any branch — every PR touching packages/supabase
has been red for it since. 15 minutes, with the reasoning in the file so the
next person to add a step to this job knows what it costs.

The ratchet itself is fine: run locally on this branch it reports 380 errors,
within baseline (api 334, unchanged).

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant