Skip to content

fix(api): an org admin passed both auth checks and then 404'd anyway - #649

Merged
thinkclay merged 1 commit into
mainfrom
fix/employer-application-patch-404
Aug 25, 2026
Merged

thinkclay merged 1 commit into
mainfrom
fix/employer-application-patch-404

Conversation

@thinkclay

Copy link
Copy Markdown
Contributor

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.

The bug

#608 fixed exactly this shape once, 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 and the handler 404'd — after both authorisation checks had already passed against the organisation.

The update below had the same problem and would have written zero rows had the read ever got past it.

Both now use the service client — the pattern this file already documents for the list path: authorisation happened above, against the organisation; 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 didn't include it, so it was undefined on every hire.

Isolating it

The data ruled out the obvious explanations one at a time:

check result
zach's role assignments on the org two admin rows — PIPELINE_ROLES admits him
auth.uid() resolving under RLS fine, reads his own assignments (200)
userHasOrgAccess's exact query, as zach returns both admin rows → hasOrgAccess: true
access row lookup, as service found
access row lookup, as zach "Cannot coerce the result to a single JSON object"

That last line is the bug: an RLS read of core.applications as an org admin returns nothing. Both access checks were already using the service client — so the failure had to be a third read further down, which is exactly what it was.

One wrong turn worth recording

Mid-investigation I found #608 in the log and talked myself into believing this was the stale local edge-runtime trap — the one that has produced false alarms in this repo before, and which I'd explicitly claimed in #646 to have ruled out.

It wasn't. 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.

Verification

End to end, not just at the endpoint — the 200 is not taken as proof the row moved:

PATCH status: 200
row status after PATCH: reviewing     ← re-read from the list

Through the UI, via smoke-move-undo.mjs:

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

The smoke is tightened from "at least one write" to "exactly one, 2xx" — the acceptance criterion #646 was filed with. It now asserts the status too, since a 404 is still a write on the wire and counting it as a successful move is how the board came to claim moves the server was refusing.

Effect on #647

The duplicate write is gone with the 404: that second request was the client retrying a failure. So #647's reproduction disappears, but its underlying question — should a 404 be retried when 404 is in NON_RETRYABLE_STATUSES? — is unanswered and it needs a fresh repro. Commented there rather than closing it.

Note on test coverage

No unit test added. The existing route tests stub the Supabase client, which would mock away the exact thing that broke — which client the handler uses. The live smoke is the honest guard here.

🤖 Generated with Claude Code

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
thinkclay merged commit 63c85be into main Aug 25, 2026
1 of 6 checks passed
@thinkclay
thinkclay deleted the fix/employer-application-patch-404 branch August 25, 2026 09:41
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.

fix(ats): moving a candidate 404s — PATCH /v1/employer/applications/{id} rejects rows the list returns

1 participant