Repository navigation
feat(auth): close cross-tenant holes, gate by email domain, add password sign in - #31
Conversation
…assword sign in Five authorization holes an audit found are shut, each with a test proving it. removeTeamMember and every team-taking service resolve the team scoped to the caller's organization, so an admin of one org can no longer touch another org's team or its roster. assertInTeam takes a resolved team row rather than an id, so a caller-supplied team id from another org 404s instead of leaking. The invite create path enforces the role guard it was skipping, so a plain member can no longer invite an admin, and a revoked invite can no longer be resurrected. Removing a member deletes their sessions in the same transaction and closes their live websocket, so access ends at once rather than when they close the tab. Non-admin reads are team scoped. ALLOWED_EMAIL_DOMAINS gates every sign-in path including OAuth and magic link, honouring both the env allowlist and the per-organization column, and an empty setting means no restriction. Password authentication is added alongside the passwordless methods, hashed with argon2id through Bun.password, behind ORBIT_PASSWORD_AUTH which defaults off, with the attempts rate limited.
# Conflicts: # packages/core/src/work/cycle-service.test.ts # packages/core/src/work/cycle-service.ts
📝 WalkthroughWalkthroughThe changes centralize organization-aware team authorization, add optional password authentication and email-domain restrictions, enforce invite and session policies, protect work-service reads and writes across tenants, and revoke realtime connections after organization membership deletion. ChangesAuthorization and membership boundaries
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant LoginPage
participant LoginForm
participant AuthServer
User->>LoginPage: open login page
LoginPage->>AuthServer: read passwordAuthEnabled
AuthServer-->>LoginPage: authentication configuration
LoginPage->>LoginForm: render passwordEnabled
User->>LoginForm: submit password or magic-link form
LoginForm->>AuthServer: sign in, sign up, or send link
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
apps/web/src/components/auth/login-form.tsx (1)
289-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winToggle button bypasses shared focus-ring styling.
Every other interactive control in this form uses the shared
Buttoncomponent, which bakes in focus-visible styling. This one is a raw<button>with nofocus-visibleclass, so its keyboard focus indicator may be inconsistent with the rest of the form.As per path instructions, "Keep the UI keyboard-operable, provide visible focus rings, and use real semantics from Radix primitives."
♻️ Proposed fix
- <button - type="button" - className="text-center text-muted text-xs underline-offset-2 hover:underline" - onClick={() => setCreatingAccount((current) => !current)} - > - {creatingAccount ? 'I already have an account' : 'Create an account with a password'} - </button> + <button + type="button" + className="text-center text-muted text-xs underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent" + onClick={() => setCreatingAccount((current) => !current)} + > + {creatingAccount ? 'I already have an account' : 'Create an account with a password'} + </button>🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/web/src/components/auth/login-form.tsx` around lines 289 - 297, Update the password account toggle in the passwordEnabled branch of login-form to use the shared Button component, or otherwise apply the form’s established focus-visible styling, while preserving its button semantics, click behavior, and existing text styling.Source: Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/realtime/src/server.ts`:
- Around line 153-158: Update the error handler attached to
revalidate(connection) so membership revalidation failures fail closed: close
the affected socket and remove its cached connection/scopes using the existing
connection cleanup mechanism, in addition to logging the error. Keep the normal
successful revalidation path unchanged.
In `@apps/web/src/lib/auth/server.ts`:
- Around line 81-89: Update assertSignUpAllowed so it only converts the specific
typed forbidden-domain error from assertEmailDomainAllowed into APIError with
EMAIL_DOMAIN_NOT_ALLOWED; allow configuration and other unexpected errors to
propagate unchanged. Reuse the domain error type from `@orbit/shared/errors` and
preserve the existing user-facing message for genuine disallowed domains.
In `@CLAUDE.md`:
- Line 94: Update the “Email domains” documentation in CLAUDE.md to hyphenate
“comma-separated” while preserving the existing wording and meaning.
---
Nitpick comments:
In `@apps/web/src/components/auth/login-form.tsx`:
- Around line 289-297: Update the password account toggle in the passwordEnabled
branch of login-form to use the shared Button component, or otherwise apply the
form’s established focus-visible styling, while preserving its button semantics,
click behavior, and existing text styling.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d0238b02-e01c-4f8b-b326-39baf0c8f91e
📒 Files selected for processing (28)
.env.exampleCLAUDE.mdapps/realtime/src/auth.tsapps/realtime/src/membership-revocation.test.tsapps/realtime/src/server.tsapps/web/src/app/(auth)/login/page.tsxapps/web/src/components/auth/login-form.test.tsxapps/web/src/components/auth/login-form.tsxapps/web/src/lib/auth/server.test.tsapps/web/src/lib/auth/server.tsapps/web/src/lib/env.tspackages/core/src/content/comment-service.tspackages/core/src/org/invite-service.test.tspackages/core/src/org/invite-service.tspackages/core/src/org/member-service.test.tspackages/core/src/org/member-service.tspackages/core/src/org/organization-service.tspackages/core/src/org/team-service.test.tspackages/core/src/org/team-service.tspackages/core/src/s1-adversarial.test.tspackages/core/src/work/cycle-service.test.tspackages/core/src/work/cycle-service.tspackages/core/src/work/issue-service.test.tspackages/core/src/work/issue-service.tspackages/core/src/work/workflow-state-service.test.tspackages/core/src/work/workflow-state-service.tspackages/shared/src/policy/index.tspackages/shared/src/policy/policy.test.ts
…n rejections Close the socket when a membership recheck throws instead of leaving a possibly revoked member connected, and let non-forbidden errors from the email domain check surface instead of masking them as a domain rejection.
Fix the cross-tenant authorization holes, enforce ALLOWED_EMAIL_DOMAINS on invite and user creation, and add optional password sign in behind a flag.
Greptile Summary
This PR closes several cross-tenant authorization holes, enforces an
ALLOWED_EMAIL_DOMAINSallowlist on invite creation and user sign-up (covering every auth provider via abeforedatabase hook), and adds optional password authentication behind anORBIT_PASSWORD_AUTHflag. The changes are backed by a broad adversarial test suite (s1-adversarial.test.ts) and new service-level tests.isInTeam/assertInTeamnow carryorganizationIdin theirTeamScopearg, so cross-org team IDs returnnotFoundinstead offorbidden; all issue, cycle, workflow-state, and team-service mutations now route throughrequireTeamorloadIssue(principal, ...)before touching data.assertCanInviteRole) and re-validated at acceptance time; revoked invites can no longer be resurrected viaresendInvite.member:deletesync action is published, the realtime server checks membership and closes the WebSocket withORGANIZATION_FORBIDDEN_CLOSE_CODEif the member is gone;removeMemberalso atomically deletes all sessions for the removed user.Confidence Score: 3/5
Two access-control gaps remain open: non-admin org members can update or delete any cycle regardless of team membership, and
unsubscribebypasses the org/team scope guard enforced by every other subscription operation.The PR makes substantial progress on cross-tenant isolation with strong adversarial test coverage, but
updateCycleanddeleteCyclewere not updated alongsidecompleteCycleandgetCycle, andunsubscribewas not updated alongsidesubscribeandlistSubscribers. Both are active paths on the same critical access-control boundary the PR was written to fix.packages/core/src/work/cycle-service.ts(updateCycle and deleteCycle) andpackages/core/src/work/issue-service.ts(unsubscribe).Security Review
updateCycle/deleteCyclemissing team-membership check (packages/core/src/work/cycle-service.ts): cycle mutations do not callassertInTeam(principal, teamScope(cycle)), allowing a non-admin org member to modify or delete cycles belonging to teams they are not on.unsubscribeskips issue-ownership guard (packages/core/src/work/issue-service.ts): unlikesubscribeandlistSubscribers,unsubscribeperforms no org or team scope check on the issue, permitting cross-org deletion of a user's own subscription rows.Important Files Changed
requireTeamandassertInTeam(teamScope(...))guards to read and complete paths, butupdateCycleanddeleteCycleare missing the team-membership check — a non-admin member of one team can mutate cycles belonging to a sibling team.loadIssuenow takingprincipal,visibleTeamFiltersfor list queries, andrequireTeamfor creation/move.unsubscribeis the lone holdout missing theloadIssueguard.isInTeam/assertInTeamto accept aTeamScopestruct carryingorganizationId, so cross-org team IDs now returnnotFoundinstead offorbidden— closes the org-boundary leak.ORBIT_PASSWORD_AUTHflag with argon2id hashing, rate limiting, and email-domain enforcement in thebeforeuser-create hook.assertCanInviteRoleblocks members from inviting admins at creation time;acceptInvitere-checks the inviter's current role at acceptance time; revoked invite status now enforced on resend.assertEmailDomainAllowedcombining globalALLOWED_EMAIL_DOMAINSenv var with per-org list; clean extraction ofemailDomainandnormalizeDomainshelpers.member:deletesync action arrives,revalidateAffectedre-checks DB membership and closes the socket withORGANIZATION_FORBIDDEN_CLOSE_CODEif the member is gone.loadTeam/requireTeamhelpers scope all team lookups toprincipal.organizationIdbefore applying team membership checks, eliminating cross-workspace team ID attacks.requireTeamorassertInTeam(teamScope(...)), adding org-boundary and team-membership enforcement that was previously missing.passwordEnabledprop, with sign-up/sign-in toggle,minLength=12enforcement, and social buttons refactored intoSocialButtons.Flowchart
%%{init: {'theme': 'neutral'}}%% flowchart TD REQ([Incoming mutation]) --> PERM{assertCan\npermission check} PERM -->|fails| FORBIDDEN[throw forbidden] PERM -->|passes| SCOPE SCOPE{Resource type} SCOPE -->|team-scoped| RT[requireTeam\nloads by org+teamId\nassertInTeam] RT -->|org mismatch| NF1[throw notFound] RT -->|not in team| FB1[throw forbidden] RT -->|ok| MUTATE SCOPE -->|issue-scoped| LI[loadIssue\nloads by org+issueId\nisInTeam check] LI -->|not in team| NF2[throw notFound] LI -->|ok| MUTATE SCOPE -->|cycle write| CW{updateCycle\ndeleteCycle} CW -->|loads by org only| MUTATE CW -. missing assertInTeam .-> WARN[/team-membership NOT checked/] SCOPE -->|unsubscribe| US[unsubscribe\nno loadIssue call] US -. missing loadIssue .-> WARN MUTATE[Execute DB write] --> SYNC[Publish SyncAction to Redis] SYNC --> RT_SERVER[Realtime server fan-out] RT_SERVER -->|member:delete| REVAL[revalidateAffected] REVAL -->|removed| CLOSE[close WS ORGANIZATION_FORBIDDEN] REVAL -->|still member| KEEP[keep connection] style WARN fill:#ff9999,color:#000Comments Outside Diff (4)
packages/core/src/work/cycle-service.ts, line 105-168 (link)updateCycleanddeleteCycleBoth
updateCycle(line 105) anddeleteCycle(line 171) load a cycle byorganizationIdalone and callrequireRow, but never verify the caller is a member of that cycle's team. Every other cycle mutation in this PR (completeCycleat line 209, plusgetCycleused bycycleProgress/cycleIssueCount) correctly receivedassertInTeam(principal, teamScope(cycle)). A non-member of Team B who belongs to Team A in the same org can update or delete Team B's cycles by guessing the cycle ID.Prompt To Fix With AI
packages/core/src/work/issue-service.ts, line 1035-1065 (link)unsubscribeskips the team-membership guard added tosubscribesubscribeandlistSubscriberswere updated in this PR to callloadIssue(tx, principal, issueId), which now enforces org + team membership viaisInTeam.unsubscribestill deletes the subscription row using onlyissueId + userIdwith no org or team scope check, letting any authenticated user in the org unsubscribe another user from any issue by knowing the IDs.Prompt To Fix With AI
packages/core/src/work/cycle-service.ts, line 105-168 (link)updateCycleanddeleteCycleBoth functions load the cycle by
cycleId + organizationIdand proceed to mutate it without verifying the caller is a member of the cycle's team.completeCycle(line 359) andgetCycle(line 230) both receivedassertInTeam(principal, teamScope(cycle))in this PR, butupdateCycleanddeleteCyclewere not updated. A non-admin member of Team A in the same org can update or delete Team B's cycles by knowing the cycle ID.Prompt To Fix With AI
packages/core/src/work/issue-service.ts, line 1035-1068 (link)unsubscribeskips the issue-ownership guard added tosubscribesubscribe(line 1010) andlistSubscribers(line 1075) both callloadIssue(tx/db, principal, issueId), which enforces org and team membership.unsubscribeonly checksassertCan(principal, 'issue:read')and then deletes byissueId + userIdwith no org or team scope. A user can probe arbitrary issue IDs across any org and remove their own subscription rows — bypassing the same boundary every other subscription operation now enforces.Prompt To Fix With AI
Prompt To Fix All With AI
Reviews (2): Last reviewed commit: "fix(auth): fail closed on revalidation e..." | Re-trigger Greptile
Context used: