Skip to content

Let a manager link for everyone an account already serving an app they edit - #103

Merged
shuv1337 merged 12 commits into
v2from
fix/app-link-org-account
Nov 18, 2026
Merged

shuv1337 merged 12 commits into
v2from
fix/app-link-org-account

Conversation

@shuv1337

@shuv1337 shuv1337 commented Nov 18, 2026 •

Copy link
Copy Markdown
Owner

Refs #99 (related, but a separate root cause; see below). Lauren asked for this fix on Nov 17, 4:18 PM PT. Do not deploy without Lauren's sign-off.

Problem

appAccounts.appLink accepted only the caller's own account. Every account is personal (hosted_account_access.personal_user_id), so an admin or agent could not fill another app's slot with an org credential that already serves an app. For example, pebble-index's Workers AI account acc_e2013e11… could not go into latitudes-kb's workersAi slot. The call returned 403 OrganizationForbidden, and appGet offered 0 accounts. The only workaround was to save the same key again (acc_29ea2764… "Default 2").

Change

  • Who may reuse an account. appLinkableAccountsAs (resource-policy) still lets an owner link their own account. Reuse (app_link) is allowed only when all of these hold:
    • the caller is an organization owner or admin;
    • the account already serves an app for everyone, the caller can read and edit that app with the same credential, and the account's owner is still a member;
    • the target app has a creator who owns the account or is currently an organization owner or admin.
  • Use-time recheck. The same target-creator rule applies when credentials are resolved for an explicitly reused link, including rechecks around OAuth renewal. Demotion or departure can stop a reused link serving without deleting it; promotion can restore it. Creator-less apps neither accept nor serve reuses, and deleting the creator's user removes those reuses. Owner-made and pre-PR links keep their prior behavior.
  • Lock-time recheck. The second check, under the app lock, share-locks the source app-link rows and the target's access row.
  • appGet (app scope only) offers the same accounts. User links are unchanged.
  • Owner unlink. An account's owner may unlink it from any app.
  • Review LOWs:
    • Every reuse takes a per-org pg_advisory_xact_lock before any app lock, so two admins swapping accounts at once can't deadlock (40P01 → 500).
    • removeAppLinksOf re-reads until no app link is left, so a reuse that commits during user deletion doesn't leave a link behind.
    • appLink/appUnlink now audit through audited (failures and interrupts too, plus changed and authority). An app-scope connect completion records app_account.link with via=connect.
  • Docs and OpenAPI descriptions are updated.

Not covered here: #99

The cause is in versionAccounts/requireConnectionAccounts, not appLink. #86 already returns ConnectionAccountUnlinked, and #86 is in prod build a87d49c. This PR does not close #99.

Tests

  • hostedAppLinkReuseChain (new): the reviewer's chain.
    • Steps: O links for everyone; M is refused (403); the admin's reuse into M's app is refused (403) and not offered; M → M2 is refused (403); M2 never receives the token (409 AccountRequired); the admin's unlink finds nothing (404); M → M4 is refused (403).
    • Fails on 0e50c17: expected 200 to be 403 at the admin's reuse into M1. With an observation probe on 0e50c17, every chain step returned 200, and M2 and M4 returned OWNER-SECRET-TOKEN. Passes on this head.
  • hostedAppLinkReuse: an admin reuses into owner-created apps; refusals for an unlinked account, a member, and self-linking; owner-unlink; the delete guard.
  • hostedAppLinkHeldAccess: the unlink phase now unlinks the owner's account. The admin's own account can be unlinked by its owner regardless of role, which is the new rule.
  • Local self-host run: 9/9 passed. The app-account-app-links (6), held-access (2) and departed-member (1) scenarios. bun run check passed.
  • Not covered by a test: the deadlock fix (PGlite self-host serializes connections) and the audit records (self-host exports no logs to the collector). Both typecheck. The role-lock and user-removal scenarios are cloud-only.
app-account-app-links.spec.ts
app-account-link-held-access.spec.ts
app-account-link-role-lock.spec.ts
departed-member-app-links.spec.ts
tool-call-log.spec.ts
mcp-execute-failures.spec.ts
personal-accounts-migration.spec.ts
app-account-webhooks.spec.ts
oauth-refresh-resilience.spec.ts
user-removal.spec.ts

Deploy / rollback

There is no schema or migration change. The previous image (a87d49c, sha256:0d42f6b5…) ignores reuse provenance and serves those links as ordinary app links. Rolling back also removes the G2 use-time enforcement.

Fix round 1

  • B1: Reuse intersects source apps with permittedAppIds(CurrentPolicy) and requires the credential's read and manage actions, alongside live user authority. The shared helper covers appGet, the pre-lock link check, and the under-lock link check. A scoped caller cannot gain an account through a source app outside its selection.
  • M1: Added owner-only appAccounts.appUnlinkOwned (DELETE /api/organizations/:organization/apps/:app/accounts/app/:account). It removes all of that account's app links from one app under the existing locks, without needing or returning requirement names or reading the app. Missing, unrelated, already-unlinked and arbitrary app ids receive OrganizationForbidden. Success is audited as app_account.unlink, authority owner; failures and interruptions use the existing audit wrapper.
  • Existing requirement-specific unlink now derives its audit authority under the lock and checks the owner's existing link before resolving an otherwise unreadable app. Updated AccountLinkedToApp repair instructions and both account docs to point owners at the new route.
  • Extended hostedAppLinkReuse: a connection-narrowed admin session cannot list or link an account sourced only outside its selection, while the same admin's unscoped session can. This fork refuses connection keys at the HTTP API, so this exercises the supported host-attached calling-connection path used by agent API calls. An owner cannot read a private app or discover its requirement names, but can remove their account from both requirements by app id alone.
  • The branch advanced concurrently to 7a436f53b during this work. Integrated those existing commits without rewriting history, retaining their administrator-only reuse restrictions, target-editor restrictions, locking and audit improvements.

Round 1 verification

  • All commands ran under nice -n 19, one heavy run at a time, with at most four build jobs and one E2E worker.
  • Frozen install, format, lint and all nine typecheck projects passed. Typecheck used TYPECHECK_CONCURRENCY=2 RAYON_NUM_THREADS=2 and reported existing warnings. Format/lint/typecheck passed again for the different, integrated tree; e2e:check passed before integration.
  • E2E preparation passed with installed Node 24/npm 11 and Rust on PATH. The first attempt lacked Rust on PATH; no system changes were needed.
  • Regression proof: temporarily disabling only the source-app policy intersection made the scoped choices assertion fail (expected [[account, false]] to deeply equal []). Restored it before the passing runs.
  • Integrated tree: e2e:self-host --test-name '^(hosted app requirements use|a hosted app requirement links for everyone|a hosted manager links for everyone|a hosted administrator cannot reuse)' --workers 1 gave 3 passed (hostedAppLinks, hostedAppLinkConnections, hostedAppLinkReuseChain). The concurrent commit renamed "manager" to "administrator", so the reuse scenario was filtered out; a separate --test-name '^a hosted administrator links for everyone' --workers 1 then gave 1 passed (hostedAppLinkReuse). Four distinct scenarios passed, with no repeat of a passing scenario on that tree.
  • Evidence: .local/e2e/2026-11-18T01-17-58.387Z-self-host-8a7fb4 and .local/e2e/2026-11-18T01-18-29.611Z-self-host-8161ac.
  • Rat-stack pages followed: ratstack://skills/security-audit, ratstack://systems/auth, ratstack://lore/errors-are-part-of-the-interface.
  • e2e:check-description --file .local/pr103-body.md --base v2: blocked by the unrelated, unchanged cloudOAuthProxyRefusal scenario being scheduled on Cloud without a CI job. The existing e2e block remains intact and names both PR spec files; this round does not change CI scheduling.
  • New head: 1593aeb912538bbd53a120d879388bdb3c1397a3 (fix commit eda1f2f1e plus the integration commit).

The PR remains open; no deployment was performed. Lauren's deployment sign-off is still required. On rollback to a87d49c, reused links remain but the owner-only consent routes disappear; app managers must unlink those accounts.

Round 3 (e4d9f51), after the lead's fix-check

  • G1: a target app whose creator is no longer a member counts as a member's; reuse into it is refused. At that head, creator-less apps were still eligible; the final G2 rule below excludes them.
  • removeAppLinksOf takes the organization's reuse lock before any app lock, so no reuse commits a copy while it runs; if links still remain after its bounded re-reads it fails (user deletion surfaces the error and can be retried) instead of returning. appUnlinkOwned takes the same lock first, keeping one lock order.
  • Audit: link/unlink records name the app only once it was resolved, never the request's text; connect-flow link records are held until the account save commits (withCommittedAudits around submit/startOAuth/completeOAuth).
  • Reuse vs app removal deadlock: traced, not reachable. A reuse locks the target app row, then share-locks the source link rows; app removal locks its own app row, then deletes its links. Neither waits on a lock the other takes later, in either interleaving.
  • New E2E: departed creator (fails on 1593aeb: the account was offered there), departed account owner, demotion while a reuse waits and right after, and the audit records (fails on 1593aeb: the refused link named the request's app).
  • G2 was open at this head. It is addressed below.

Fix round (G2)

  • Link time and use time: An explicitly reused link requires a non-null app creator who owns the account or is currently an organization owner/admin. A demotion or departure pauses use; promotion can restore it. Author commits d442a132c, 1d9fa8898, and 65b9de186 are retained: deleting a user unlinks reuses in apps they created, including in organizations they already left, and a creator-less app cannot accept or serve a reused link even if a row remains. The existing linked_by column marks reuses; no migration. Owner-made and pre-PR links keep serving under their prior rules. An account owner with app edit access can take over a reuse by linking it directly.
  • Typed refusal: AppLinkCreatorNotAuthorized (HTTP 409) applies both to initial account selection and to the credential rechecks around OAuth refresh. It explains that the app's creator is missing or no longer an organization admin or owner, and tells the caller to ask an admin to relink an eligible account or ask the account's owner to link directly.
  • Audit: security.audit records app_account.use_refused, outcome failure, target kind account and ID, app ID, requirement, and reason creator_not_admin_or_owner. No credentials or tokens. A bounded per-process/isolate cache deduplicates by link and stored membership revision; it does not cache authorization. Restarts or eviction can repeat a best-effort log. Creator deletion also audits each unlink with authority: creator_removal.
  • Negative control: With the use-time predicate disabled, both hostedAppLinkCreatorDemotion and hostedAppLinkCreatorDemotionDuringRefresh failed as expected: the tool returned HTTP 200 rather than 409. Both passed once the check was restored. The OAuth issuer holds the refresh response until demotion commits, so that test reaches the credential recheck after refresh. Both scenarios verify a secret-free refusal audit; the demotion scenario verifies dedupe, promotion, and that an owner-made link still serves.
  • Named verification: Self-host 17 passed (app links, OAuth retargeting, reuse/chain/departure/held access, demotion and in-flight refresh, audit, migration compatibility, webhook cleanup, OAuth listing renewal, REST error contract). Managed Cloud 4 passed across runs (demotion, role-lock, user removal, and creator removal). The creator-removal case also checks a stored reuse with a null creator, fresh reuse refusal, and direct linking by the owner. The case initially failed because the Cloud fixture app was private; declaring the intended shared access fixed it. All named runs used --workers 1. e2e:prepare, format, lint, typecheck (9 projects), and actionlint passed. Full bun run check was not run locally because of the known install-store issue.
  • Evidence: .local/e2e/2026-11-18T06-29-26.765Z-self-host-3d17c8 (negative); .local/e2e/2026-11-18T06-30-21.095Z-self-host-85e9c0 (self-host); .local/e2e/2026-11-18T06-32-25.229Z-cloud-76a572 (three Cloud passes); .local/e2e/2026-11-18T06-35-15.333Z-cloud-ce56a4 (creator-removal pass).
  • CI: Fork CI selects both new self-host scenarios by title; the Cloud selector includes creator removal. The upstream PR-description checker still reports the fork's existing cloudOAuthProxyRefusal schedule/job mismatch. Not merged or deployed.

Known design limits (from round 2 review, kept as is):

  • One refused reused link 409s every tool in the app, including tools that use no account. A requirement with nothing linked already blocks the app the same way.
  • Every caller of the app sees the 409 with the account id and the reason (no secrets).

…y edit

appLink refused every account but the caller's own (OrganizationForbidden), so
an admin or agent could not fill another app's slot with an org credential that
already serves an app they edit, and had to save the same key again.

An account may now be linked for everyone by its owner, or by someone who can
edit an app it is already linked to for everyone, whose owner is still a member.
Editing that app already lets them run code with the account, so this grants no
use they lack. The account stays its owner's: no direct use, no user links, no
reads; appGet offers these accounts for app requirements only. The lock-time
recheck share-locks the source app link rows until commit.

An account's owner may now unlink it from any app, since someone else may have
linked it to one they cannot edit. Both routes record security.audit events
(app_account.link / app_account.unlink) naming the authority used.

Refs #99
@shuv1337

Copy link
Copy Markdown
Owner Author

Review status (lead: executor). Round 1: Astra (security pass) MERGE; Opus (primary) FIX FIRST. A fix round is running for:

  • B1: an app-scoped credential could list or link an account through a source app outside its scope.
  • M1: an owner can't unlink their account from an app they can't read.

Needs Lauren's explicit decision before deploy (Opus M2). This PR widens whom an account owner implicitly trusts. An admin who edits an app the account already serves can link that account into another app for everyone, including a member's own app. That member can then edit their app to read the credential and reuse the account in their other apps. The owner isn't notified; after the fix they can unlink, but only after the fact.

Options:

  1. Accept as designed (the audit log records every link).
  2. Narrow it: only allow target apps the account's owner can also edit.
  3. Narrow it further: also notify the owner on each link.

Lead's pick: 2. It keeps the fix for the pebble-index → latitudes-kb case, where the owner edits both apps, and closes the reuse-by-member path.

shuv1337 and others added 4 commits November 17, 2026 17:07
PR review (MED): an admin's reuse into a member-created app let that member
chain the owner's account into their own apps, read its secret, and keep it
after the admin unlinked it.

Reuse (app_link) now needs an organization owner or admin, and is refused when
the target app's creator is a member other than the account's owner. Members
never reuse, so nothing a member edits holds another person's account unless
its owner linked it there, and no chain can outlive an unlink. The lock-time
recheck also share-locks the target's access row.

LOWs:
- Reuses serialize on a per-organization advisory lock taken before any app
  lock, so two admins swapping accounts cannot deadlock (40P01 -> 500).
- removeAppLinksOf reads again until no app link is left, so a reuse that
  committed during user deletion is removed too.
- appLink/appUnlink audit through `audited` (failures and interrupts recorded,
  `changed` noted), and a connection completing for an app requirement records
  app_account.link (via=connect).

Refs #99
@shuv1337

Copy link
Copy Markdown
Owner Author

Lead (executor) fix-check: Opus round 2 says FIX FIRST. No blocker, but two majors remain against the new admin-only rule. B1, M1 and most of M2 are resolved. By the charter's review budget there is no third patch round from the lead, so here are the invariants for whoever finishes this (author thread or Lauren):

Invariant: nothing a member can edit holds another person's account unless that person linked it there, at link time and for as long as the link lasts.

  • G1 (major, one line): resource-policy.ts:682 treats a target app whose creator has left the org (role null) as "not a member's", so an admin can reuse an owner's account into it. If the creator is re-invited, they can edit the app and read the credential. Fix: treat a creator who isn't a member exactly like a member (refuse). Add an E2E case.

  • G2 (major, Lauren's decision): the target check runs only at link time. An admin who created the target and is later demoted to member keeps editing an app that holds someone else's account. Options:

    • (a) Re-check when the link is used, via linked_by/creator role (no migration needed).
    • (b) Unlink reused links when the creator is demoted.
    • (c) Accept it explicitly in the PR text.

    Lead's pick: (a).

  • Tests still missing (m4): the account owner leaves the org, an admin is demoted mid-reuse, and the audit records themselves.

Minors are in the review: the failure audit takes the app id from the request, the connect-path audit is logged before its commit, removeAppLinksOf gives up silently during user deletion, and a possible reuse/app-removal deadlock that wasn't traced.

Not merging until G1 is fixed and G2 is decided. Deploy waits on Lauren's sign-off regardless.

…er commit with the app found, and serialize app-link removal with reuse

- A target app whose creator is no longer a member counts as a member's (G1).
- removeAppLinksOf takes the organization's reuse lock first and fails instead of
  returning with links left behind; appUnlinkOwned takes that lock before the app's.
- Audit records name the app only once it was found; connection links are recorded
  once their save commits.
- E2E: departed creator and departed owner, demotion during and after a reuse, and
  the audit records themselves.
@shuv1337

Copy link
Copy Markdown
Owner Author

Lead (executor): fresh Opus review of e4d9f518 says FIX FIRST on G2 only. B1, M1 and G1 are fixed, and so are the lock order, the audit-after-commit change and removeAppLinksOf. No deadlock, cross-org path or secrets in audits were found.

G2: the target-creator check runs only when the link is made. If an admin or owner reuses O's account into an app created by admin A2, and A2 is later demoted, or leaves and is re-invited as a member, A2 still edits that app. A2 can then read O's credential, including refreshed OAuth tokens, with no end date. O isn't notified. The comment at resource-policy.ts:627-630 and the PR body claim this can't happen.

Not merging until Lauren decides:

  • (a) Lead's pick. Re-check when the link is used, in usableAppLinks, with no migration. Serve a reused link only if the account's owner made it, or the app's creator is null or is the owner, or the creator is currently an admin or owner. Add a demotion E2E. Links made before this PR all keep serving.
  • (b) Accept the exposure and reword the overclaiming comment and PR text.

Review: ~/.cache/agent-ws/executor-pr103-review-opus-r3.md on shuvdev.

@shuv1337

Copy link
Copy Markdown
Owner Author

Deploy sign-off: approved by the user, Nov 17 18:5x PST (relayed by the PM). This covers the sign-off this PR asks for. It holds only after the G2 use-time fix lands, a fresh Opus fix-check says MERGE on the exact head and CI is green. It doesn't cover deploying with G2 open.

@shuv1337

Copy link
Copy Markdown
Owner Author

Lead (executor) final fix-check: fresh Opus high review of 8ffad938d says VERDICT: MERGE (no blockers, no majors; G2 closed across link time and every credential resolution path including post-OAuth-refresh recheck; creator removal + null-creator refusal consistent; 409 AppLinkCreatorNotAuthorized typed across host/SDK/MCP/REST; secret-free refusal audit; lock order acyclic; zero DDL/migration). Fork CI (check, security-e2e, Socket) is green.

Non-blocking minors noted for follow-up / Lauren's call:

  • m1: unlinking/replacing a refused reuse runs webhook-unregister once with the token if a webhook requirement exists (could route refused reuse: links to manual removal in removeLink).
  • m2: stale docstring on removeReusedLinksInAppsOf (app-accounts.ts:667-673).
  • m3: hostedAppLinkCreatorDemotion asserts a single use_refused audit across two calls sharing a trace (can emit twice across isolates on multi-isolate deployed Cloud).
  • m4: app-ui.ts maps AppLinkCreatorNotAuthorized to generic UiFailed instead of an account notice.

Merging under the user's deploy sign-off relayed earlier tonight.

@shuv1337
shuv1337 merged commit 64a2d47 into v2 Nov 18, 2026
4 checks passed
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.

Pinned connection with an unlinked account fails as OrganizationForbidden

1 participant