Skip to content

test(engine): cover unauthenticated session creation's org binding - #2027

Merged
jhoffner merged 2 commits into
mainfrom
fix/engine-unauthenticated-org-binding-test
Sep 22, 2026
Merged

jhoffner merged 2 commits into
mainfrom
fix/engine-unauthenticated-org-binding-test

Conversation

@jhoffner

@jhoffner jhoffner commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

What

Adds the missing regression coverage for FIX-1442's org-binding fix: the unauthenticated case for session creation.

packages/engine/test/principal-org-spoofing.test.ts already covered a resolved principal's orgId beating body.orgId on action dispatch. It did not cover handleCreateSession (packages/engine/src/routes/session-routes.ts:235) on a flow with no authentication configured at all, on a host with no principal resolver either — the condition under which the whole app runs on DEFAULT_ORG_ID. That gap was proved by a throwaway probe during FIX-1477 and discarded; this makes it permanent.

One new test in the existing describe("session creation with no principal resolver", ...) block: a brand-new session on a flow with no authentication binds to DEFAULT_ORG_ID, never to body.orgId.

Why this shape

handleCreateSession and the action-dispatch route (already covered above it in this file) are two different code paths with two different guarantees:

  • Action dispatch (action-routes.ts) always resolves a principal (falling back to DEFAULT_ORG_ID internally), so principal.orgId is always defined.
  • Session creation (session-routes.ts) uses ctx.principal?.orgId ?? DEFAULT_ORG_ID — ctx.principal can genuinely be undefined, and that's the path this PR covers.

Cross-org resource-collection isolation is a separate claim and is not covered here. An earlier revision of this PR carried a second test that tried to prove it end-to-end (a second flow, a shared org-scoped collection, seed/read handlers). Review caught that its assertion order meant it never actually went red under the mutation this PR proves red — its distinctive claim was never shown able to fail. It was dropped rather than fixed in place; that isolation claim belongs on fix/FIX-1477-pr-a2-roster-boards, where the read gate it depends on is actually being opened.

Scope

Test-only. No source file is changed by this PR.

BP-003 evidence (red → green)

Snapshotted the working tree first (git stash create, no bare git stash).

Red — reverted session-routes.ts:235 to ctx.principal === undefined ? getString(body.orgId) : ctx.principal.orgId:

× session creation with no principal resolver > binds a new session to DEFAULT_ORG_ID, not the body's orgId
  → expected 'victim-org' to be '__fsd_default_org__'

 Test Files  1 failed (1)
      Tests  1 failed | 2 passed (3)

The failure lands on the claim itself (the session running as victim-org instead of DEFAULT_ORG_ID).

Restore — git restore -- packages/engine/src/routes/session-routes.ts (never bare git restore .); confirmed git diff HEAD -- packages/engine/src/routes/session-routes.ts is empty.

Green — same test file against the restored source:

✓ test/principal-org-spoofing.test.ts (3 tests) 38ms

 Test Files  1 passed (1)
      Tests  3 passed (3)

Verification

  • pnpm --filter @flow-state-dev/engine typecheck — clean
  • pnpm --filter @flow-state-dev/engine test — 204 files / 2616 passed, 4 skipped (pre-existing skips)
  • pnpm knip:ci — exit 0, only pre-existing config hints unrelated to this change

Changeset

None — test-only change, no consumer-visible behavior (BP-022).

🤖 Generated with Claude Code

https://claude.ai/code/session_01ANuyMVi3YS653fcghb9gtB

FIX-1442 made a session's orgId non-caller-steerable, but the coverage in
principal-org-spoofing.test.ts only exercised the authenticated path (a
resolved principal beats body.orgId). It never exercised handleCreateSession
on a flow with no `authentication` at all, on a host with no principal
resolver either — the condition under which the whole app runs on
DEFAULT_ORG_ID.

Add that case: a new session on such a flow still binds to DEFAULT_ORG_ID
regardless of body.orgId, and a session so bound cannot read another org's
resource-collection rows no matter what the caller claims in the body or in
headers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ANuyMVi3YS653fcghb9gtB
@vercel

vercel Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

3 Skipped Deployments
Project Deployment Actions Updated
flow-state-dev-docs Ignored Ignored Sep 22, 2026 2:26am UTC
flow-state-dev-kitchen-sink Ignored Ignored Sep 22, 2026 2:26am UTC
flow-state-dev-ui Ignored Ignored Preview Sep 22, 2026 2:26am UTC

Request Review

@jhoffner
jhoffner marked this pull request as ready for review September 22, 2026 02:15
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-22T02:19:27.816794Z 2df45b6 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.

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Unauthenticated POST …/sessions ignoring body.orgId is a real gap: registry-routes pins the same invariant on the action path, and management-route-auth pins it on session create only when a verified principal exists. This PR targets the right seam (handleCreateSession → ctx.principal?.orgId ?? DEFAULT_ORG_ID).

The behavior looks correct (local vitest run test/principal-org-spoofing.test.ts passes), but the shape of the change overshoots what the invariant needs.

Cleaner approach (recommended)

Keep one focused test (~15–25 lines) in this file or in management-route-auth.test.ts using the existing call helper:

  • Register a flow with no authentication (same as openFlow).
  • POST /:flowKind/sessions with { userId, orgId: "victim-org" }.
  • Assert stores.session.get(…)?.orgId === DEFAULT_ORG_ID.

That directly exercises the route named in the file header without new HTTP helpers.

If you want end-to-end proof that binding drives resource visibility, you still do not need two symmetric flows with four helpers. A lighter pattern:

  1. One org-scoped collection + read probe on the unauth flow (capture ctx.request.identity.orgId and optional list()), same as the existing probe handler in the first describe.
  2. Seed victim data via stores + existing patterns or a single authenticated flow registered from a shared verifiedOrgPrincipal(userId) factory—not duplicate ownerFlow / unauthenticatedFlow bodies.
  3. One action dispatch with spoofed body.orgId + headers; assert probe org is DEFAULT_ORG_ID and victim labels are absent.

That preserves the security story with roughly half the surface area.

Duplication inside the diff

  • postAction vs postFlowAction — same POST/SSE wiring; unify or extend postAction with a path array.
  • x-verified-org resolvePrincipal appears three times (buildAuthenticatedFlow, ownerFlow, and conceptually elsewhere in the repo).
  • ownerFlow / unauthenticatedFlow differ only by kind and optional authentication — one parameterized builder would do.
  • ctx: any on the new handlers — the file already types the probe without it; match that.

Overlap to be aware of (not a reason to drop coverage)

Existing test What it already proves
registry-routes — binds session to framework default… Unauth action create ignores body.orgId
management-route-auth — takes orgId from the principal… Auth session create ignores body.orgId
This PR (test 1) Unauth session create ignores body.orgId ← net new
This PR (test 2) Cross-org resource isolation via full router ← net new, but could be slimmer

Skipped (optional / larger refactors)

  • Extract shared drain / createSession to engine/test/helpers/ — good repo follow-up, not required here.
  • Direct handleCreateSession unit test (lineage-address-ownership style) — complements but does not replace router coverage.

Verdict

Comment, not approve: direction and tests are sound, but I would trim the harness before merge unless you explicitly want this file to own the full resource isolation story. Happy to re-review after a slim-down.

Open in Web View Automation 

Sent by Cursor Automation: Review For Best Approach

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Snob — a better shape exists.

The new describe stands up a second flow, an org-scoped collection, seed/read handlers, and an isolation case to pin handleCreateSession ignoring body.orgId when nobody authenticates. That route's contract is the stored binding. Both of this PR's documented reds already said so: expected 'victim-org' to be '__fsd_default_org__'. The isolation expects never went red. Collection isolation is a different layer.

Drop the board. Keep one test in this file's existing shape: a no-auth flow, POST /sessions with a spoofed orgId, assert stores.session.get(...).orgId === DEFAULT_ORG_ID. 317 → 160 lines. Same production code. Same session-create contract.

Proven on a throwaway branch: #2031

  • pnpm --filter @flow-state-dev/engine exec vitest run test/principal-org-spoofing.test.ts — 3 passed
  • Red on the old session-routes.ts:235 (body.orgId when principal is missing) is still the claim itself

Agent on this PR: fold that subtraction here, then close #2031 unmerged after this lands. Do not merge the POC.

View PR

Open in Web View Automation 

Sent by Cursor Automation: Code Snob

Code Snob's review of the previous commit caught a real defect: the
"cannot read another org's rows" test asserted capture.orgId before
capture.rows, so under vitest's fail-fast semantics the mutation proof
only ever exercised the org-binding claim test 1 already makes. The rows
isolation assertions had never been shown able to fail.

Drop that test and everything that existed only for it (the org-scoped
resource collection, the seed/read handlers, the two-flow router, the
per-call header spoofing). Cross-org resource-collection isolation gets
its own red-state proof on the PR that actually opens that read gate
(fix/FIX-1477-pr-a2-roster-boards), not duplicated here.

Also drops the x-org-id header spoof from what remains: grepping the
package confirms no production route reads that header, so asserting it
is ignored could not fail either. Kept as a one-line comment recording
the finding, so nobody re-adds a header assertion mistaking it for
coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ANuyMVi3YS653fcghb9gtB

Copy link
Copy Markdown
Collaborator Author

Addressed both reviews. Summary of what changed (2df45b6e6 → 6eaccb881):

Code Snob's finding was correct and is the one that mattered. Test 2's assertion order was capture.orgId before capture.rows, so under vitest's fail-fast semantics the red run documented in this PR's original description only ever exercised the org-binding claim test 1 already makes (expected 'victim-org' to be '__fsd_default_org__'). The rows-isolation assertions had never been shown able to fail. I confirmed this by reading the branch rather than taking it on faith.

Dropped test 2 entirely — the second flow, the org-scoped collection, the seed/read handlers, and every helper that existed only for them (rowCollection, rowActions, ownerFlow, unauthenticatedFlow, buildUnauthenticatedRouter, postFlowAction). Cross-org resource-collection isolation gets its own red-state proof on fix/FIX-1477-pr-a2-roster-boards, where that read gate is actually being opened — not duplicated here. I did not merge or branch from the throwaway POC at #2031; the subtraction is folded into this branch directly, so #2031 can close unmerged.

"Review For Best Approach"'s x-org-id finding stands, simplified further: I grepped packages/ myself — zero production hits for x-org-id, engine routes only read accept, last-event-id, content-type, content-length, and a deployment-set tenant header (extractTenantId, route-utils.ts:79 — a separate, already-verified axis per FIX-682). Since the test that asserted the header is ignored is gone along with test 2, I kept a one-line comment recording the finding instead, so a future reader doesn't add a header assertion mistaking it for coverage.

Declined: relocating the surviving test onto management-route-auth.test.ts's call helper. This file already carries the sibling case (authenticated session creation ignoring body.orgId); the unauthenticated case belongs beside it, not in a different file, for the same seam.

Kept, from the first review's smaller findings: dropped the redundant expect(stored?.orgId).not.toBe("victim-org") — toBe(DEFAULT_ORG_ID) already proves it. Everything else that review flagged (ctx: any, postAction/postFlowAction duplication, the two-flow parameterization, the section banner) is moot — that code no longer exists.

PR is now one test, ~20 lines added to the file (170 lines removed from the previous commit). Re-proved red → green on the survivor after the cut:

× session creation with no principal resolver > binds a new session to DEFAULT_ORG_ID, not the body's orgId
  → expected 'victim-org' to be '__fsd_default_org__'
 Test Files  1 failed (1)
      Tests  1 failed | 2 passed (3)

Restored, git diff HEAD on session-routes.ts empty, then:

✓ test/principal-org-spoofing.test.ts (3 tests) 38ms
 Test Files  1 passed (1)
      Tests  3 passed (3)

pnpm --filter @flow-state-dev/engine typecheck clean · test 204 files / 2616 passed, 4 skipped · pnpm knip:ci exit 0.

PR description updated to match what the PR now is.


Generated by Claude Code

@jhoffner
jhoffner merged commit 60a0675 into main Sep 22, 2026
12 checks passed
@jhoffner
jhoffner deleted the fix/engine-unauthenticated-org-binding-test branch September 22, 2026 13:06
jhoffner pushed a commit that referenced this pull request Sep 22, 2026
…d one import model

Three findings folded.

PLAN.md said "POC: none built" while this amendment adds poc/read-gate/ and
EVOLUTION cites it as the evidence. An implementer asking whether there is a
POC got two answers from one document. Split in two: none for the navigator,
whose premises are shipped code, and poc/read-gate/ for the two panel premises
that could not be read off the code.

read-gate-probe's second case was named for two claims — the refusal and the
ledger declaring no client config — and asserted only the first. The
declaration was a console.log, so half of what the test's name promised could
not fail. Now an assertion, with its own red state verified: assigning a client
config onto the ledger turns it red before the route is called. Recorded in
EVOLUTION as well as fixed, because it is the same defect class the rest of the
page is about, one level in.

premise-proof imported from "../src" while read-gate-probe imported by package
name, giving one POC folder two mental models. Both now import by package name.
Verified it resolves and passes that way rather than assumed.

Re-verified every cited line against main at 1196611 after rebasing across
#2027, #2033, #2034 and #2037; all still resolve. Observed output in the README
re-derived from a fresh run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ANuyMVi3YS653fcghb9gtB
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