Skip to content

feat(auth): close cross-tenant holes, gate by email domain, add password sign in - #31

Merged
pulkitxm merged 3 commits into
mainfrom
feat/s1-auth
Jul 23, 2026
Merged

pulkitxm merged 3 commits into
mainfrom
feat/s1-auth

Conversation

@pulkitxm

@pulkitxm pulkitxm commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

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_DOMAINS allowlist on invite creation and user sign-up (covering every auth provider via a before database hook), and adds optional password authentication behind an ORBIT_PASSWORD_AUTH flag. The changes are backed by a broad adversarial test suite (s1-adversarial.test.ts) and new service-level tests.

  • Policy hardening: isInTeam/assertInTeam now carry organizationId in their TeamScope arg, so cross-org team IDs return notFound instead of forbidden; all issue, cycle, workflow-state, and team-service mutations now route through requireTeam or loadIssue(principal, ...) before touching data.
  • Invite security: Role-escalation blocked at creation time (assertCanInviteRole) and re-validated at acceptance time; revoked invites can no longer be resurrected via resendInvite.
  • Realtime revocation: When a member:delete sync action is published, the realtime server checks membership and closes the WebSocket with ORGANIZATION_FORBIDDEN_CLOSE_CODE if the member is gone; removeMember also 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 unsubscribe bypasses 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 updateCycle and deleteCycle were not updated alongside completeCycle and getCycle, and unsubscribe was not updated alongside subscribe and listSubscribers. 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) and packages/core/src/work/issue-service.ts (unsubscribe).

Security Review

  • updateCycle / deleteCycle missing team-membership check (packages/core/src/work/cycle-service.ts): cycle mutations do not call assertInTeam(principal, teamScope(cycle)), allowing a non-admin org member to modify or delete cycles belonging to teams they are not on.
  • unsubscribe skips issue-ownership guard (packages/core/src/work/issue-service.ts): unlike subscribe and listSubscribers, unsubscribe performs no org or team scope check on the issue, permitting cross-org deletion of a user's own subscription rows.

Important Files Changed

Filename Overview
packages/core/src/work/cycle-service.ts Added requireTeam and assertInTeam(teamScope(...)) guards to read and complete paths, but updateCycle and deleteCycle are missing the team-membership check — a non-admin member of one team can mutate cycles belonging to a sibling team.
packages/core/src/work/issue-service.ts Cross-tenant issue access well-hardened via loadIssue now taking principal, visibleTeamFilters for list queries, and requireTeam for creation/move. unsubscribe is the lone holdout missing the loadIssue guard.
packages/shared/src/policy/index.ts Upgraded isInTeam/assertInTeam to accept a TeamScope struct carrying organizationId, so cross-org team IDs now return notFound instead of forbidden — closes the org-boundary leak.
apps/web/src/lib/auth/server.ts Password auth added behind ORBIT_PASSWORD_AUTH flag with argon2id hashing, rate limiting, and email-domain enforcement in the before user-create hook.
packages/core/src/org/invite-service.ts Role escalation fixed: assertCanInviteRole blocks members from inviting admins at creation time; acceptInvite re-checks the inviter's current role at acceptance time; revoked invite status now enforced on resend.
packages/core/src/org/organization-service.ts New assertEmailDomainAllowed combining global ALLOWED_EMAIL_DOMAINS env var with per-org list; clean extraction of emailDomain and normalizeDomains helpers.
apps/realtime/src/server.ts Membership-revocation push: when a member:delete sync action arrives, revalidateAffected re-checks DB membership and closes the socket with ORGANIZATION_FORBIDDEN_CLOSE_CODE if the member is gone.
packages/core/src/org/member-service.ts Session deletion added atomically alongside member row removal, ensuring immediate revocation without waiting for expiry.
packages/core/src/org/team-service.ts New loadTeam/requireTeam helpers scope all team lookups to principal.organizationId before applying team membership checks, eliminating cross-workspace team ID attacks.
packages/core/src/work/workflow-state-service.ts All workflow state mutations now go through requireTeam or assertInTeam(teamScope(...)), adding org-boundary and team-membership enforcement that was previously missing.
packages/core/src/s1-adversarial.test.ts New adversarial test suite covering D-01 through D-54: cross-workspace team access, role escalation, revoked invite resurrection, session destruction on removal, and email domain enforcement.
apps/web/src/components/auth/login-form.tsx Password sign-in and account-creation flow added behind passwordEnabled prop, with sign-up/sign-in toggle, minLength=12 enforcement, and social buttons refactored into SocialButtons.

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:#000
Loading

Comments Outside Diff (4)

  1. packages/core/src/work/cycle-service.ts, line 105-168 (link)

    P1 Missing team membership check in updateCycle and deleteCycle

    Both updateCycle (line 105) and deleteCycle (line 171) load a cycle by organizationId alone and call requireRow, but never verify the caller is a member of that cycle's team. Every other cycle mutation in this PR (completeCycle at line 209, plus getCycle used by cycleProgress/cycleIssueCount) correctly received assertInTeam(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
    This is a comment left during a code review.
    Path: packages/core/src/work/cycle-service.ts
    Line: 105-168
    
    Comment:
    **Missing team membership check in `updateCycle` and `deleteCycle`**
    
    Both `updateCycle` (line 105) and `deleteCycle` (line 171) load a cycle by `organizationId` alone and call `requireRow`, but never verify the caller is a member of that cycle's team. Every other cycle mutation in this PR (`completeCycle` at line 209, plus `getCycle` used by `cycleProgress`/`cycleIssueCount`) correctly received `assertInTeam(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.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code

  2. packages/core/src/work/issue-service.ts, line 1035-1065 (link)

    P2 unsubscribe skips the team-membership guard added to subscribe

    subscribe and listSubscribers were updated in this PR to call loadIssue(tx, principal, issueId), which now enforces org + team membership via isInTeam. unsubscribe still deletes the subscription row using only issueId + userId with 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
    This is a comment left during a code review.
    Path: packages/core/src/work/issue-service.ts
    Line: 1035-1065
    
    Comment:
    **`unsubscribe` skips the team-membership guard added to `subscribe`**
    
    `subscribe` and `listSubscribers` were updated in this PR to call `loadIssue(tx, principal, issueId)`, which now enforces org + team membership via `isInTeam`. `unsubscribe` still deletes the subscription row using only `issueId + userId` with no org or team scope check, letting any authenticated user in the org unsubscribe another user from any issue by knowing the IDs.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code

  3. packages/core/src/work/cycle-service.ts, line 105-168 (link)

    P1 security Missing team membership guard in updateCycle and deleteCycle

    Both functions load the cycle by cycleId + organizationId and proceed to mutate it without verifying the caller is a member of the cycle's team. completeCycle (line 359) and getCycle (line 230) both received assertInTeam(principal, teamScope(cycle)) in this PR, but updateCycle and deleteCycle were 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
    This is a comment left during a code review.
    Path: packages/core/src/work/cycle-service.ts
    Line: 105-168
    
    Comment:
    **Missing team membership guard in `updateCycle` and `deleteCycle`**
    
    Both functions load the cycle by `cycleId + organizationId` and proceed to mutate it without verifying the caller is a member of the cycle's team. `completeCycle` (line 359) and `getCycle` (line 230) both received `assertInTeam(principal, teamScope(cycle))` in this PR, but `updateCycle` and `deleteCycle` were 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.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code

  4. packages/core/src/work/issue-service.ts, line 1035-1068 (link)

    P1 security unsubscribe skips the issue-ownership guard added to subscribe

    subscribe (line 1010) and listSubscribers (line 1075) both call loadIssue(tx/db, principal, issueId), which enforces org and team membership. unsubscribe only checks assertCan(principal, 'issue:read') and then deletes by issueId + userId with 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
    This is a comment left during a code review.
    Path: packages/core/src/work/issue-service.ts
    Line: 1035-1068
    
    Comment:
    **`unsubscribe` skips the issue-ownership guard added to `subscribe`**
    
    `subscribe` (line 1010) and `listSubscribers` (line 1075) both call `loadIssue(tx/db, principal, issueId)`, which enforces org and team membership. `unsubscribe` only checks `assertCan(principal, 'issue:read')` and then deletes by `issueId + userId` with 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.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code

Fix All in Claude Code

Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
packages/core/src/work/cycle-service.ts:105-168
**Missing team membership guard in `updateCycle` and `deleteCycle`**

Both functions load the cycle by `cycleId + organizationId` and proceed to mutate it without verifying the caller is a member of the cycle's team. `completeCycle` (line 359) and `getCycle` (line 230) both received `assertInTeam(principal, teamScope(cycle))` in this PR, but `updateCycle` and `deleteCycle` were 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.

### Issue 2 of 2
packages/core/src/work/issue-service.ts:1035-1068
**`unsubscribe` skips the issue-ownership guard added to `subscribe`**

`subscribe` (line 1010) and `listSubscribers` (line 1075) both call `loadIssue(tx/db, principal, issueId)`, which enforces org and team membership. `unsubscribe` only checks `assertCan(principal, 'issue:read')` and then deletes by `issueId + userId` with 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.

Reviews (2): Last reviewed commit: "fix(auth): fail closed on revalidation e..." | Re-trigger Greptile

Context used:

  • Context used - CLAUDE.md (source)

pulkitxm added 2 commits July 24, 2026 00:17
…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
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Authorization and membership boundaries

Layer / File(s) Summary
Team-scoped policy contracts
packages/shared/src/policy/*
Team authorization now includes organization identity, admins are restricted across organizations, and retired permissions are removed.
Organization and membership enforcement
packages/core/src/org/*, packages/core/src/s1-adversarial.test.ts
Invite roles, email domains, revoked invites, session cleanup, and team lookup now enforce organization and membership boundaries.
Work-service team and issue isolation
packages/core/src/content/*, packages/core/src/work/*
Cycles, issues, comments, workflow states, and team operations use principal-scoped team resolution and visibility checks.
Optional password authentication
apps/web/src/lib/auth/*, apps/web/src/components/auth/*, apps/web/src/app/(auth)/login/page.tsx
Password authentication is controlled by ORBIT_PASSWORD_AUTH, uses Argon2id hashing and rate limits, and exposes conditional password login and signup UI.
Realtime membership revocation
apps/realtime/src/*
Member-delete deltas recheck database membership and close connections lacking organization membership.
Configuration and conventions
.env.example, CLAUDE.md
The new authentication and email-domain environment settings and enforcement rules are documented.

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
Loading

Possibly related PRs

  • Noveum/orbit#4: Introduced the core organization and invite service layer used by these enforcement changes.
  • Noveum/orbit#11: Established the realtime delta delivery path extended here for membership revalidation.
  • Noveum/orbit#17: Added websocket organization-forbidden close handling used by membership revocation.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main auth hardening changes: cross-tenant fixes, email-domain gating, and optional password sign-in.
Description check ✅ Passed The description is directly related to the changeset and accurately describes the auth, allowlist, and password-login updates.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/s1-auth

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/web/src/components/auth/login-form.tsx (1)

289-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Toggle button bypasses shared focus-ring styling.

Every other interactive control in this form uses the shared Button component, which bakes in focus-visible styling. This one is a raw <button> with no focus-visible class, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7ae17cb and e2081d3.

📒 Files selected for processing (28)
  • .env.example
  • CLAUDE.md
  • apps/realtime/src/auth.ts
  • apps/realtime/src/membership-revocation.test.ts
  • apps/realtime/src/server.ts
  • apps/web/src/app/(auth)/login/page.tsx
  • apps/web/src/components/auth/login-form.test.tsx
  • apps/web/src/components/auth/login-form.tsx
  • apps/web/src/lib/auth/server.test.ts
  • apps/web/src/lib/auth/server.ts
  • apps/web/src/lib/env.ts
  • packages/core/src/content/comment-service.ts
  • packages/core/src/org/invite-service.test.ts
  • packages/core/src/org/invite-service.ts
  • packages/core/src/org/member-service.test.ts
  • packages/core/src/org/member-service.ts
  • packages/core/src/org/organization-service.ts
  • packages/core/src/org/team-service.test.ts
  • packages/core/src/org/team-service.ts
  • packages/core/src/s1-adversarial.test.ts
  • packages/core/src/work/cycle-service.test.ts
  • packages/core/src/work/cycle-service.ts
  • packages/core/src/work/issue-service.test.ts
  • packages/core/src/work/issue-service.ts
  • packages/core/src/work/workflow-state-service.test.ts
  • packages/core/src/work/workflow-state-service.ts
  • packages/shared/src/policy/index.ts
  • packages/shared/src/policy/policy.test.ts

Comment thread apps/realtime/src/server.ts Resolved
Comment thread apps/web/src/lib/auth/server.ts Resolved
Comment thread CLAUDE.md Resolved
…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.
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