Skip to content

feat(platform): make API keys for members, teams, projects and the org - #4501

Merged
yannickmonney merged 20 commits into
mainfrom
feat/api-key-owners
Oct 8, 2026
Merged

yannickmonney merged 20 commits into
mainfrom
feat/api-key-owners

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

What

Owners and Admins can now create an API key for someone or something else, under Settings > API > REST → Create API key → Belongs to:

  • Another member — the key acts as that member, with their live role and teams, in this organization only, and its spend counts toward the member's limits. Only members whose role is below the maker's can be chosen, and the key acts only while its maker is still an Owner or Admin above the member. The member gets a notification, sees the key in their list and can revoke it.
  • A team, a project or the organization — the key is not a person. It acts as its own identity, with the role picked under Acts as (Member, Editor or Developer; Admin for the organization's key only; never above the maker's role), and keeps working when its maker leaves. A team's key sees what the team sees; a project's key reaches its project alone — every other /api/v1 route answers 403 API_KEY_SCOPE_FORBIDDEN, and through the chat assistant it reads its project's files and tasks, none of the organization's contacts, products, websites or inbox.

Such a key works in its one organization: it needs no X-Organization-Slug, and a header naming another organization answers 403 ORG_FORBIDDEN. It ends with what it belongs to — deleting the team or project or removing the member revokes it, and the audit log says why; deleting the organization deletes it.

Budgets. A key that is not a person spends under its own name: no personal, role or default rule binds it; the organization's limits and the key's own rules do, and a team's key counts toward, and is held to, its team's caps. Usage analytics shows it as a row of its own, never as an active user. (A Project budget scope follows in the next PR.)

The keys table gains a Belongs to column; Owners and Admins see every key made here for others, members see the keys made for them. The team's delete confirmation counts the team's keys.

How

  • Migration 0154_api_key_owners: the binding table; its CHECKs encode the target and role rules. Every bound key — a member's included — is minted for an identity of its own (key_user_id); only the binding says whom it acts as.
  • backend/domains/api_keys: create, list and revoke at /api/app/api-keys. The api-key plugin mints the secret as a server call; the binding, audit row and hint are written in one transaction before the secret leaves, and a failure removes the key and its identity again.
  • REST door: reads the binding on every keyed request (rest/bound-key.ts) and confines a project's key (rest/api-key-scope.ts); GET /me answers key.owner — contract 3.21.0.
  • Readers: findActingMember / the acting audience for the doors a key reaches; findOrganizationMember stays person-only for checks about other people. Chat's conversation search and knowledge mail now follow the same rule (a project's key gets neither).
  • Better Auth: /api-key/update and /api-key/delete refuse a key bound to an organization (API_KEY_ORGANIZATION_MANAGED); such keys are ended at the organization's door.
  • Docs (en/de/fr), two screenshots, domain spec APIKEY-R1–R10, manual boxes SET-F77–F79, SET-B34, GOV-F53.

Verification

  • Unit: platform server + PII suites, UI suite, guards, docs tests, knip, tsc, oxlint.
  • Real Postgres + HTTP: ITEST_LANES=checkApiKeyOwners,checkOrganizationLifecycle — all checks pass, including the binding constraints, the project scope, each cascade, the maker-demotion refusal and the organization teardown.
  • Three independent reviews (security, budgets, UI/docs); their findings are fixed in the follow-up commits.
  • Browser: created organization, team and member keys in the dialog; the member's bell and list; /me, scope refusals and revocation with the minted keys.

Rolling deploy

The table is new and the previous image never reads it. Every key this image makes authenticates as an identity with no membership, so the previous image — mid-roll or after a rollback — refuses it rather than reading it as anyone's own key.

Stacked on #4495.

DatePicker takes minDate/maxDate (days outside are disabled and read
"Not available" in the UI language) and forwards id, aria-labelledby
and aria-describedby to its trigger, which dropped them before.
The create dialog offered 7/30/90 days, a year or never, and the date a
key stopped working was shown nowhere. Expiration now adds Custom date,
a calendar bounded to tomorrow through a year from today (the api-key
plugin's window), and names the day the key expires under the field.
The keys table gets an Expires column: the date, Never, or Expired for a
key that ran out while the list was open.
Nothing outside the expiry helpers reads the 365-day ceiling, and Knip refuses an export no module imports.
Owners and Admins can now make an API key for another member, a team, a
project or the organization itself. A member's key acts as that member, in
this organization only; the member is notified, sees it and can revoke it.
A team's, a project's or the organization's key is not a person: it acts as
its own identity with the role chosen under Acts as (never above the
maker's), keeps working when its maker leaves, and works in its one
organization. A team's key sees what the team sees; a project's key reaches
its project alone, and any other REST route answers 403
API_KEY_SCOPE_FORBIDDEN.

Such a key spends under its own name: no personal, role or default limit
binds it, the organization's limits and the key's own rules do, and a
team's key counts toward and is held to its team's caps. Usage analytics
shows it as its own row, never an active user. A key ends with what it
belongs to: deleting the team or the project, removing the member or
deleting the organization revokes it, audited as the system.

The binding lives in app.api_key_owners (0154). The REST door reads it on
every keyed request, GET /me answers key.owner (contract 3.18.0), and the
api-key plugin's update and delete refuse a key an organization manages.
The keys table gains a Belongs to column.
API keys, policies and limits, usage attribution and the API reference say who a key made for someone else acts as, what it reaches and whose limits its spend counts toward, in English, German and French. The Create API key screenshot shows Belongs to, and a second one shows the organization's own key acting as a Developer.
A run a team's, project's or organization's key started through a REST comment books under the key's identity without naming the key, so the key's own cap never saw it. The key's bucket now counts the identity's bookings and holds too. The budget gate also reads a revoked binding: the work a key started before its revocation keeps spending as the key instead of being measured as a person with the default cap.
The capability dispatch behind POST /api/v1/mcp read the member table directly, so a team's or the organization's own key passed the door and was refused there. It now reads the acting member, and refuses a project's key, which reaches its project alone.

@yannickmonney yannickmonney left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Independent review of PR #4501 at 245008596aacf322db8b372623a44e0642d100e7: changes requested (API-only, security first)

  • Reviewer: Engineering agent #4 5f5307c9-4cbd-416a-a456-8bb667fc584d, run e869b78a-78fe-4aab-9015-fdf2b72e9dca, card TALE-1154 (5c5061a2-1d5d-4d7b-baaa-82c8f43b7c2f), routed by Fleet coordination run 25ea0ed5. I did not write this PR. Its 4 commits (18:32:53Z–18:44:26Z, shared push account) predate this run (started 18:45:53Z), and no ref, reflog entry or worktree in my workspace names the branch or its commits.
  • Head moved after dispatch: dispatched at efd1ce4b90a9c1f808f5a793ad289f4ecc046969. Two fix commits followed at 18:44Z: af5d9252 "count all of a key identity's spend toward its key" and 24500859 "let team and organization keys call the MCP tools". This review is at 245008596a….
  • Base: feat/api-key-expiry @ 0f95ef5d4ac8a0ad69bd296ffa9ec54a931ff7b6.
  • Merge order: #4501 is stacked on #4495 and cannot merge before #4495.
  • Implementation agent/run: not identified. The PR was opened by the shared push account outside Fleet routing.
  • Method: read the exact head and base sources over the REST API (compare, contents, check-runs). Nothing was executed: no tests, builds or live probes. Each finding is a code-path proof at head, with file:line. I re-checked findings 1–6 in the source myself. Some Part A and should-fix details come from parallel read-only passes over the same head; those not re-checked are marked.

Verdict: REQUEST CHANGES

Blocking findings: 1–5 (security and data) and 6 (CI). Should-fix items: 7–11.

Blocking: security and data

1. A project's key gets out of its project through its own project chat (APIKEY-R6; the PR says "a project's key reaches its project alone").

  • The door admits the chat. It admits everything under /projects/<own>/… (rest/api-key-scope.ts:26-39), so POST /api/v1/projects/<own>/threads/<t>/messages (rest/v1-threads.ts:980) enqueues a turn that runs runChatTurn as the key's identity (domains/chat/rest-turn.ts).
  • The tools' role gate admits the key for every subject. This PR changed resolveWorkspaceReadAccess to findActingMember with no project-key exclusion: return { allowed: member !== null && member.role !== 'disabled' } (domains/chat/shim.ts:871-879).
    • The rag_search contacts leg (core/chat/assistant_tools.ts:1256-1268) and list kind=… (:1556) check only that gate.
    • queryContacts filters on WHERE org_id = ${args.organizationId} alone (shim.ts:1081-1110).
    • Products, websites and knowledge entries go the same way.
    • Result: a Launch-project key gets 403 on GET /contacts, yet "list our contacts" in a Launch thread returns the organization's contacts (names, e-mails, phones, addresses, notes).
  • Hub documents leak too. resolveAccessScope sets includeHub: auth.projectScope === undefined (shim.ts:162), but listForAgent honours the caller's flag (...(projectReadable && args.includeHub === true ? { includeHub: true } : {}), shim.ts:824), and the chat tool always sends includeHub: true in a readable project chat (assistant_tools.ts:1975). A project key's list kind=document therefore shows the hub rows of the project's teams.
  • Asked:
    • Refuse project keys in the role gate for subjects that are organization-wide (contacts, products, websites, knowledge entries), as dispatchCapabilityAs already does (member.apiKeyOwner?.kind === 'project').
    • Use scope.includeHub in listForAgent.
    • Add tests in which a project-key turn's rag_search/list returns no contact and no hub row. No test covers the chat tools for any key kind today.

2. On any image that doesn't read the binding, a member's key acts as that member in every organization they belong to. This covers the rolling deploy and any rollback below 0154. It contradicts APIKEY-R2: "It never works in another organization the member belongs to".

  • Why. The key is minted as the member's own Better Auth key (const principalUserId = owner.memberUserId ?? generateId(32), then createApiKey({ body: { name, userId: principalUserId, … } }), domains/api_keys/service.ts:290,313-319), and the secret goes to the maker (routes.ts:124-125).
  • Effect. On the previous image, X-Organization-Slug: <the member's other org> resolves that organization from the member's memberships. An Admin of Acme can then act as Mia in Beta, where Mia may be Owner, until the roll ends, or indefinitely after a rollback.
  • The PR knows the hazard. The code names it at domains/organizations/service.ts:572-576 ("a member's key whose binding vanished would read as that person's own key, valid in every other organization they belong to"). The "Rolling deploy" section of the PR (and migration 0154:29-33) presents the fallback as harmless.
  • Asked: make the member kind fail closed on a reader-less image. Options:
    • Ship the binding reader in a release before the member kind can be created (a flag or two-step rollout).
    • Mint through a principal the old image refuses.
    • At minimum, correct the PR and release text and make "revoke every member key before rolling back below this release" an explicit step.

3. The role-below rule (APIKEY-R3) holds only at creation, yet the maker keeps the secret.

  • Where. service.ts:163 compares the maker's and the member's roles once. At request time the door uses the member's live role and never reads created_by (rest/bound-key.ts:63-78, role = member.role). Retirement matches only the member (retire.ts:81-82).
  • Effect. If the Owner later promotes Mia to Admin or Owner, or demotes or removes Ada, Ada still holds a key that acts as someone at or above her own authority. That is exactly what R3 forbids at creation ("Acting as someone takes more authority than they hold"). No test covers a role change after creation.
  • Asked: at the door, require the maker to still be an active member who outranks the member, or retire the member's keys when either role changes. If the current behaviour is intended, R3 and docs/*/platform/admin/api-keys.md must say so, including the maker-removal case.

4. Expiry does not end a non-person key's identity on the background doors; revocation does.

  • Where. readServicePrincipal checks only revoked_at_ms IS NULL (domains/api_keys/owners.ts:166-183). Nothing stamps a binding when Better Auth deletes an expired key (migration 0154:26-27). findActingMember falls back to it (auth/membership.ts:371).
  • Effect. After expiry, the identity still passes these checks with its role and audience:
    • deferredAgentKickRefusal (domains/tasks/service.ts:4790): a deferred agent kick starts a new run as the expired key. A revoked key gets not_permitted here.
    • the connector bridge (domains/connectors/bridge-routes.ts:212).
    • file access (domains/files/access.ts:223).
    • run authority (domains/tasks/run-authority.ts:88).
  • No way to stop it. The expired key also leaves the keys table (listApiKeysForViewer reads FROM "apikey" k, service.ts:543), so no admin can revoke it to stop the identity.
  • This breaks R10 ("works until then") and the spec's own line "Revoking a key stops what it would start".
  • Asked: treat an expired or missing apikey row as not live in readServicePrincipal (join apikey with expiresAt), or stamp bindings on expiry. Add a test.

5. A member's key borrows the member's standing in other organizations wherever a gate reads member rows across organizations.

  • The gate. The REST browser-session gate (rest/v1-browser-sessions.ts:58-66) calls assertBrowserSessionImporter. That function reads every membership of the user (SELECT "organizationId", "role" FROM "member" WHERE "userId" = … LIMIT 50, domains/browser_sessions/service.ts:131-154, unchanged), and decideInstanceAdmin passes on an admin row in any organization plus the e-mail allowlist (core/deployment/auth_policy.ts:36-49).
  • Why member keys reach it. The door sets the member's e-mail for a member key (rest/v1.ts:321).
  • Effect. Suppose Mia is a Member of Acme, an Admin of another organization, and on TALE_DEPLOYMENT_CONFIG_ADMINS. Ada, an Acme Admin who is not on the allowlist, can then import or delete Acme's browser-session cookie jars through Mia's key.
  • /me misreports it. It answers capabilities.deploymentEditor from the bound organization alone (rest/v1-core.ts:333-341), so it reports false for a key the gate admits.
  • Asked: evaluate bound keys against the bound organization only. Pass a membership list confined to it, or refuse bound keys at this gate. Sweep the other "member" WHERE "userId" = … reads that a key's request can reach.

Blocking: CICD

6. The CLI build fails on linux, windows and macos at this head (check runs 112958833594, 112958833668 and 112958833609; CI ready (CLI) 112962328092 answers "build: expected success, got failure").

  • Failing test. tools/cli/src/lib/config/platform-docs.test.ts:408 ("cached CLI checks hash every imported module and generated source tree") received services/platform/backend/domains/api_keys/owners.ts, …/api_keys/retire.ts and services/platform/backend/realtime/outbox.ts.
  • Cause. The CLI bundles auth/membership.ts, which now imports the key modules, and @tale/cli's turbo inputs do not hash them.
  • Asked: add them to the CLI transit inputs and the cli.yml path filters, or keep membership.ts free of the import.
Aggregator at 245008596a (read 19:05:25Z) State
CI ready (SAST) success (check run 112958244471, 18:50:48Z)
CI ready (CLI) failure (check run 112962328092, 18:58:59Z; finding 6)
CI ready (Checks) NOT_RUN: checks.yml runs pull_request for base main only
CI ready (Build) NOT_RUN: build.yml runs for base main only
CI ready (E2E) NOT_RUN: e2e.yml runs for base main only
CI ready (Security) NOT_RUN: security.yml runs for base main only
CI ready (Commitlint) NOT_RUN: commitlint.yml runs for base main only

Unit, integration (ITEST_LANES=checkApiKeyOwners,…), type-check, lint and E2E evidence therefore exists only as the author's claim; no CI run at either head covers it. Once #4495 merges and this PR targets main, a new push or a reopen is needed: a base change (edited) is not among these workflows' trigger types.

Should fix (not blocking on their own)

  1. A key can outlive what it belongs to.
    • Create is not atomic with its target. resolveOwner runs before, and outside, the transaction that writes the binding (service.ts:281-286 vs :336-347). A team, project or member removed in between leaves a live binding the cascade never saw. A member's binding then revives if they are re-added.
    • The plugin's remove-team hook retires after its commit and only logs a failure (auth/auth.ts:1495-1510).
    • A team key whose team is gone keeps its role (bound-key.ts:79-80 never checks the team).
    • Asked: re-check (and lock) the target inside the binding transaction, and fail closed at the door when a team or project key's target row is missing.
  2. Audit gaps.
    • Deleting the organization removes bound keys and identities without one audit row per key (retire.ts:113-134), though R7 and the PR say "the audit log says why".
    • api_key.revoked rows do not name the team, project or member (retire.ts:91-103, service.ts:655-680).
    • The api_key.created row does not record the identity's user id, so retained rows whose actorId is the identity resolve to nothing.
  3. The late MCP fix covers knowledge only. authorizeActorRun still reads the member table (domains/automations/dispatch-store.ts:113-124), so team and organization keys still get ORG_FORBIDDEN from the automation tools and engine methods. It refuses rather than leaks. The new test mocks findActingMember and exercises only get_knowledge.
  4. Smaller project-key gaps.
    • A project key gets 403 on GET /api/v1/models, yet the send validation in its own threads points callers there (v1-threads.ts:457,993).
    • Team mail attachments still read the member table, so team keys get none, though R6 promises "the team's … inbox" (file_metadata/mail-attachments.ts:102-114; parallel pass, not re-checked).
  5. Non-person keys survive their maker's demotion or removal with their original role, as R4 intends. Consider marking keys whose maker left or was demoted in the Belongs to list, so admins can find them.

Part B: tests and authentication cost

Tests that fail without the change (static map, nothing run):

  • Strong, with the real door or hook running:
    • project-key refusal (rest/v1.test.ts [APIKEY-R6], rest/api-key-scope.test.ts, which includes the project-1x prefix case).
    • binding read and revoked binding (v1.test.ts R2/R5/R7, bound-key.test.ts).
    • Better Auth update/delete refusal (auth/auth.api-key-bound.test.ts, unmocked createAuth).
    • conversation search and knowledge mail refusing a project key.
  • Weaker:
    • The budget tests mostly match SQL text, and no budget SQL runs against Postgres.
    • The service, owners and retire units answer with canned rows, so their WHERE clauses never run.
    • Atomicity of binding, audit and hint is not proven: the fake begin has no transaction semantics.
    • v1-mcp.ts getMemberRole has no test.
    • The "never above the maker" check (service.ts:184) cannot fire with today's role set and has no test.
  • Missing: findings 1, 3 and 4. Also the plugin-door hooks (afterDeleteTeam, afterRemoveMember) and the project_target CHECK.
  • CI: the real-Postgres lane (checkApiKeyOwners) is registered in integration-check.ts, but no CI run at this head executed it (see the CICD table).

Authentication cost per keyed request:

  • A key with no binding (every existing key): one more serial primary-key read (v1.ts:298).
  • Every caller, browser sessions included: each getUserTeamIds now carries a UNION branch over app.api_key_owners (auth/membership.ts:310-322). It is cheap and indexed by org_id, but the plan was not checked.
  • A member key: about the same count as before (binding, organization by id, member).
  • A non-person key: each findActingMember costs 2 queries (member miss, then readServicePrincipal on the partial unique index), with no per-request cache.

Not blocking. Carrying the resolved owner in the request context would remove the repeated reads.

Part A: clarity, locales, accessibility (static)

Clarity of "Belongs to" and "Acts as". Both are labelled selects whose hints are linked by aria-describedby. The member, team and project pickers are keyboard-reachable comboboxes (aria-activedescendant, role="option"). Gaps, all minor:

  • The targetRequired error is raised on memberId/teamId/projectId but never rendered or linked (no aria-invalid or aria-describedby). Create key just stays disabled with no reason given (api-key-create-dialog.tsx:166,344; api-key-owner-field.tsx:204-281).
  • The pickers ignore loading and error states: a failed member read says "No member whose role is below yours" (api-key-owner-field.tsx:187,231,261).
  • Members at or above the maker are hidden, not shown as disabled. The "Another member" hint never states the rule (only the empty text does).
  • Switching from the organization to a team silently resets an Admin choice to Member (api-key-create-dialog.tsx:378).
  • The success view still says "Copy your API key now" for a key made for someone else.
  • The fallback strings read badly when composed: "Team deleted team" and "Made by Former member", and in de "Erstellt von Ehemaliges Mitglied" uses the wrong case (api-key-owner-cell.tsx:39-59).

de/fr parity.

  • All 45 new message keys (settings 37, governance 3, analytics 3, inbox 2) and the changed usage.tables.users.note exist in en, de and fr, with identical placeholders and no English left in de/fr.
  • keys-dynamic.yml lists the two inbox keys.
  • The 6 docs pages carry the same edits in all three languages.
  • Two nits:
    • The de docs say "nie als aktive Person" while the UI says "Aktive Benutzer" (docs/de/platform/admin/api-keys.md:82, governance/usage-attribution.md:30).
    • "Gehört zu" reads as "is part of".

Accessibility evidence. No axe audit covers the new controls: the dialog's axe tests render without canCreateForOthers, and the table's fixtures hold only owner: user rows. Contrast and assistive-technology behaviour were not measured (API-only review).

Verified at this head (holds)

  • Making keys. Only Owners and Admins can make bound keys (service.ts:265).
    • The maker's role is read live (routes.ts:69,82).
    • Team and project keys are limited to Member, Editor or Developer, and no key's role can be above the maker's at creation (service.ts:181-192). The table's CHECKs enforce the target and role rules (0154:41-66).
    • The target team or project must be in the same organization, and an archived project is refused.
  • The door.
    • The binding is read on every keyed request (v1.ts:298).
    • A revoked binding or a principal mismatch gets 401. A deleted organization, a removed or disabled member, and a foreign X-Organization-Slug get 403 ORG_FORBIDDEN (bound-key.ts).
    • /me lists the one organization.
    • Project-key confinement runs before every route family (v1.ts:422-436 vs :471-481). It fails closed on %2F, double slashes, case and malformed escapes. Nested project resources are bound to the path's project.
  • Other doors.
    • A client-sent x-api-key is refused on every inbound request (apiKeyHeaderGuard), so /api/app, /api/auth and SSE never accept a key.
    • /api-key/update and /api-key/delete refuse bound keys (API_KEY_ORGANIZATION_MANAGED).
  • Existing keys. A key with no binding takes the unchanged path, and an unknown kind fails closed (owners.ts:129-133).
  • Migration 0154. It is additive (IF NOT EXISTS) with no foreign keys, and 0154 is unique.
  • Cascades. The app doors' cascades run inside the deleting transaction: team, project, member removal (including SCIM) and the organization.
  • Spend. A member key's spend goes to the member, and a non-person identity is measured as the key.
  • Secrets. No secret is logged or stored in audit metadata.

Not covered

Nothing was executed: no tests, lint, type-check, browser or Postgres. Every file below was read, but only to the depth stated.

  • Contract artifacts. services/platform/public/openapi.json, scripts/openapi/spec.ts, scripts/openapi/contract-fingerprint.json and lib/shared/constants/api-contract.ts (3.18.0) were not compared against the routes.
  • Screenshots and manifests (not inspected).
    • services/docs/public/images/get-started/settings-api-keys.webp
    • services/docs/public/images/platform/settings-api-keys-organization.webp
    • services/docs/public/images/manifest.json
    • services/platform/tests/docs-screenshots/manifest.ts
  • Manual suites. services/platform/tests/manual/{readme.md,reference/error-codes.md,suites/governance.md,suites/settings.md} (SET-F77–F79, SET-B34, GOV-F53): lint:manual was not run.
  • Read lightly.
    • Backend: backend/telemetry.ts, core/collab/types.ts, core/notifications/{notification_link_cases,personal_notification_url}.ts, lib/shared/notifications/target.ts, domains/governance/{README.md,routes.ts,service.ts}, core/governance/get_org_usage_metrics.ts (its spend SQL was not run against Postgres).
    • Frontend: app/features/analytics/usage/users-table.tsx, app/features/settings/governance/components/budget-editor.tsx, app/lib/backend/contract/governance.ts, app/routes/dashboard/$id/settings/api/rest.tsx.
    • Tests: jobs/task-list.agent-retry.test.ts, core/tasks/agent_run_host.connector_caller.test.ts.
  • Open questions, not verified:
    • Some readers ignore the project scope: files/access.ts (taskReadable, threadReadable), chat/threads.ts (projectChatAccess), tasks/run-authority.ts and tasks/service.ts:4790. I found no REST door that hands a project key another project's file reference.
    • Whether rag_fetch serves the content of the hub documents listed in finding 1.
    • Team and organization keys on v1-conversations, v1-websites, v1-notifications and the REST run start.
    • Whether key identities appear in any user list across the instance.
    • Trusted-header deployments.
    • The Better Auth behaviour cited, which was read from upstream 1.7.5 source, not checked against the lockfile.

A review found ways a key made for someone else could reach further than
its owner meant:

- A project's key could read the organization's contacts, products,
  websites and inbox through the chat assistant, and hub document titles
  through its file listing. The chat tools now give it its project's files
  and tasks alone.
- A key made for a member authenticated as the member, so an image that
  does not read the binding (mid-roll or after a rollback) let it act as
  the member in every organization. Every bound key now authenticates as an
  identity of its own, and only the binding says whom it acts as.
- A member's key outlived its maker's authority: an admin could demote a
  peer, make a key for them and promote them back. The key now acts only
  while its maker is an Owner or Admin above the member, and the keys a
  member made end when they leave.
- An expired key's identity kept acting in runs it had started, a key
  identity could be made a member, a member's key carried the member's
  standing in other organizations into the browser-session gate, and a
  key could be bound to a target removed while it was minted. Each is
  closed: acting needs a live key row, the members door refuses key
  identities, the gate reads the bound membership alone, and the binding
  transaction checks its target again.
The team's delete confirmation now counts the API keys that belong to the
team, which stop working with it.

The key dialogs also say what they could not before: a picker for whom a
key belongs to names why Create stays off when nothing is picked, a search
that matches nobody says so instead of claiming there is no one to pick,
a key made for someone else is not "your" key on the success view, a key
of a deleted team or project reads as such, and a failed revocation is
reported once, with the refusal's own words.
Owners and Admins see and revoke the keys made here for others, never a member's own keys. A member's key stops when its maker no longer outranks the member; deleting a team or a project, or removing a member, revokes keys, while deleting the organization deletes them. A project's key reads none of the organization's contacts, products, websites or inbox through the chat assistant, and keys made for others have their own rate-limit budget. The team and member pages, usage analytics and the API reference say so, and the manual boxes and error-code rows match.

@yannickmonney yannickmonney left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

REQUEST CHANGES — PR #4501

Reviewed head: 1ed6561c9b09ac64fe44d2105669e90e4534de76; base: 0f95ef5d4ac8a0ad69bd296ffa9ec54a931ff7b6; previous review: 5447037507 at 245008596aacf322db8b372623a44e0642d100e7.

Independent reviewer: Codex worker #7, agent ecfaae72-93ee-4d66-b93d-7a90d59234c7, run 7a8599d2-45c4-47bb-848d-5c781df6ad1b, task TALE-1162 (4ce94f28-ceb0-47b4-9afb-d997b9bc489e). I did not write this implementation. API-only, coordination phase: no checkout, tests, installs, builds, live probes, push or merge. #4501 cannot merge before #4495.

Findings requiring repair

  1. SECURITY — project-key chat still discloses organization-wide knowledge-entry content (prior finding 1 remains OPEN). At this head, services/platform/backend/domains/chat/shim.ts:195 includes documents in the project-key subject allowlist; the gate at :926 therefore admits it. services/platform/backend/core/chat/assistant_tools.ts:1019 reads that permission, and :1232–1248 uses it for the separate knowledge-entry search leg. The shim at domains/chat/shim.ts:1247–1260 forwards only organization, topic and pagination to listEntriesForAgent; it forwards no user/project scope. domains/knowledge_entries/service.ts:810–833 selects ke.content using organization/status/topic/cursor filters alone, and :955–970 returns that content. Thus a Launch-project key can send a message in its permitted Launch thread asking the assistant to search knowledge entries for a known organization topic and receive content outside Launch. The new contact/product/website gate and document-hub exclusion do not close this leg. Refuse this leg for project keys or apply the actual project document ACL before returning entries. Add a regression through the real chat executor/shim: an organization entry outside Launch must not reach a Launch-key tool result, while an ordinary permitted member still receives it. The new shim.knowledge-scope.test.ts:137–179 tests hub exclusion and subject permissions, but leaves documents allowed and never tests this knowledge-entry leg.

  2. CICD — the CLI repair hashes its new imports but leaves them outside workflow scope (prior finding 6 remains OPEN in part). tools/cli/turbo.json:20–21,31 now hashes domains/api_keys/owners.ts, domains/api_keys/retire.ts and realtime/outbox.ts. However, .github/ci-scope.yml:49–74 and .github/workflows/cli.yml:19–44 omit all three. A subsequent PR changing only these imported modules can be scoped out of CLI validation; a main push changing only those modules will not trigger CLI. Add the three sources to both scope lists and cover such an isolated change with the existing scope/closure guards. The actual CLI build failure at the prior head is resolved: all five current native/cross build rows and the current CLI aggregator report success. That success does not establish future source-filter coverage.

Disposition of every finding in review 5447037507

Paths below beginning with domains/, rest/, auth/ or core/ are relative to services/platform/backend/. CLOSED means the specific source defect is repaired and a source-bound test would fail against the old implementation; it does not claim this reviewer executed it.

Prior finding Disposition at this head Exact repair/regression or remaining gap
1. Project chat escapes project OPEN Contacts/products/websites refused at domains/chat/shim.ts:913–929; hub listing constrained at :827–853. Tests shim.knowledge-scope.test.ts:140–179 would fail old code. Knowledge-entry content remains exposed as numbered finding 1 above.
2. Member key acts across orgs on reader-less image CLOSED for newly minted keys domains/api_keys/service.ts:311–315,331–335 always makes/mints a separate unseated identity; rest/v1.ts:298–329 translates it only after binding resolution. service.test.ts:285–310 demands an identity distinct from Mia and minting for it, which old code cannot satisfy. Integration source owners.integration.ts:315–318,349–356 also asserts distinct referenceId and one-org /me. Upgrade from an already-applied earlier 0154 remains unproved; see DATA below.
3. Maker role checked only at creation CLOSED for the REST door rest/bound-key.ts:82–110 rereads both org-local memberships and requires an active Owner/Admin maker strictly above the target. bound-key.test.ts:141–170 refuses maker departure/demotion and target promotion, unlike old code. Integration source owners.integration.ts:388–400 checks 200 before demotion and 403 afterwards. This is not a claim that every asynchronous member-key continuation retains key identity.
4. Expired non-person identity stays live CLOSED at the shared reader; semantic execution NOT_RUN domains/api_keys/owners.ts:186–191 joins the key row and requires no revocation, enabled and unexpired. Missing/deleted rows produce no principal. owners.test.ts:64–78 fails old SQL by requiring join/expiry predicates; it is a SQL-shape test, not an actual expired-row test. Inspected consumers: auth/membership.ts:375–390, domains/tasks/service.ts:4790–4803, domains/connectors/bridge-routes.ts:212–215, domains/files/access.ts:223–234, domains/tasks/run-authority.ts:88–101. Real DB and deferred-start expiry proof remain missing.
5. Browser-session gate borrows another org's admin membership CLOSED for this gate rest/v1-browser-sessions.ts:60–77,90–94 supplies the bound membership; the shared import/delete gate domains/browser_sessions/service.ts:141–153 uses it instead of all memberships. v1-browser-sessions.test.ts:155–181 expects 403 and no membership query with an admin row elsewhere; old code fails. A full sweep of other cross-org membership readers remains uncovered.
6. CLI failure and incomplete input coverage OPEN in part Current failure resolved; tools/cli/src/lib/config/platform-docs.test.ts:400–408 is the existing old-failing imported-source input guard. Both source-filter omissions remain (numbered finding 2).
7. Keys outlive deleted targets / mint-delete race OPEN in part service.ts:354–379 now rechecks target/maker in its serializable binding transaction; service.test.ts:341–382 exercises a member leaving/maker demoted during mint. bound-key.ts:122–141 refuses deleted team/project targets; test bound-key.test.ts:215–226 fails old door. No concurrent PostgreSQL deletion proof inspected. The shared background principal reader still does not check target existence, so REST target refusal alone does not cover a failed post-commit retirement.
8. Audit gaps OPEN domains/api_keys/retire.ts:124–135 deletes org bindings/keys/identities without per-key audit; :36,107–108 retains kind/name but not target IDs; service.ts:401–414 still omits the key's identity ID in created audit state. No closing test.
9. Automation authorization refuses service identities OPEN domains/automations/dispatch-store.ts:113–123 still requires a real member row. Neither delta nor inspected source closes team/org-key automation support.
10. Model discovery and team mail attachments OPEN rest/api-key-scope.ts:18–27 refuses /models; domains/model_api/wire.ts:42–46 allows only /openai and /anthropic model doors. domains/file_metadata/mail-attachments.ts:105–113 still returns empty for identities without member rows. No closing test.
11. Visibility of keys after non-person maker departure/demotion OPEN, advisory Continued authority is explicitly intended by domains/api_keys/spec.md R4, not a new privilege-escalation finding. No departed/demoted-maker warning proof inspected.

SECURITY and DATA limits

Creation checks retain the org-local target checks and role ceilings (domains/api_keys/service.ts:140–230), with the maker rechecked in the binding transaction. Member-key requests recheck live maker/target authority; non-person roles intentionally survive maker departure. REST binding resolution checks revoked identity, org existence, foreign slug, and deleted team/project (rest/bound-key.ts:54–75,122–162). The inspected expiry/revocation consumer paths share readServicePrincipal; this bounded review does not establish every authenticated path or every downstream project scope.

Migration compatibility is not proved for existing bound keys created by the earlier PR head. The delta rewrites 0154_api_key_owners.sql to add mandatory key_user_id and a new index, inside CREATE TABLE IF NOT EXISTS, rather than adding an upgrade migration. db/migrate.ts:263–275 skips an already-recorded filename. A database that applied the earlier 0154 will not receive this column; current readers reference it. Earlier member keys also have a member referenceId, so an upgrade must migrate/revoke them to obtain the new reader-less-image guarantee. If no supported deployment ever applied that earlier schema, record that release fact; otherwise add a forward migration and old-schema/key fixture proof. No serving/deployment evidence was available or requested here. Existing personal keys without bindings retain the old path at rest/v1.ts:331 onward, but real previous-schema PostgreSQL proof is NOT_RUN.

Seven CI-ready aggregators

Read once via paginated commits/<head>/check-runs?per_page=100&filter=latest; one complete page, 16 checks, all carrying the reviewed head. Response retained at 2026-10-07T19:47:03Z. No unfinished aggregator was present; none was polled.

Aggregator Observed result Check ID / explanation
CI ready (CLI) success 112977553499
CI ready (SAST) success 112976384465
CI ready (Checks) NOT_RUN / absent checks.yml:14–17 restricts PR base to main
CI ready (Build) NOT_RUN / absent build.yml:19–22 restricts PR base to main
CI ready (E2E) NOT_RUN / absent e2e.yml:20–23 restricts PR base to main
CI ready (Security) NOT_RUN / absent security.yml:10–13 restricts PR base to main
CI ready (Commitlint) NOT_RUN / absent commitlint.yml:10–13 restricts PR base to main

After #4495 merges, retargeting alone is insufficient for these PR events: edited is absent from the listed trigger types. The owner must obtain the ordinary applicable checks on the final head/base. The green check API receipts establish reported conclusions; job logs/cache/artifacts were not inspected, so no fresh test-execution claim follows.

Uncovered scope and handoff

The whole compare response enumerates 163 changed files; the four-commit repair delta enumerates 73. This is a targeted security/data re-review, not complete PR acceptance. coverage.json enumerates all 163 exact paths and blob IDs, marks 22 as targeted source/diff review and 141 as uncovered, and includes hashes/source URLs for fetched context. Source coverage on large files is limited to relevant excerpts. full.json and delta.json retain the API diffs; the two binary WebP files have no textual patches.

Uncovered acceptance includes frontend behavior/accessibility/responsiveness, all rendered locales/docs/screenshots, OpenAPI/contract parity, full affected-consumer sweeps, real PostgreSQL constraints/cascades/upgrades, trusted-header/Better Auth runtime behavior, complete downstream member-key continuation and project scope, budgets/spend queries, performance/resources, deployment/recovery and operational effects. No visual/browser/manual/unit/integration/lint/typecheck/build tests were run. Root AGENTS.md and .agents/repo.md were read; nested instruction discovery was not exhaustive. No Ops access used. Platform-wide recurring coverage is outside this bounded card.

Next owner: Fleet coordination routes the implementer to repair findings 1–2 and resolve the migration history/proof gap, then a distinct reviewer rereads the settled head and ordinary check evidence. No local repository or consuming processes were created; cleanup is limited to retained task-owned evidence files. This GitHub verdict is separate from native task review: fresh task pendingReview was null, so no native task_review verdict was attempted.

# Conflicts:
#	services/platform/backend/domains/organizations/service.ts
#	services/platform/lib/shared/constants/api-contract.ts
#	services/platform/public/openapi.json
#	services/platform/scripts/openapi/contract-fingerprint.json
# Conflicts:
#	services/platform/tests/manual/readme.md
Base automatically changed from feat/api-key-expiry to main October 8, 2026 18:34
# Conflicts:
#	docs/de/platform/admin/api-keys.md
#	docs/en/platform/admin/api-keys.md
#	docs/fr/platform/admin/api-keys.md
#	services/platform/app/features/settings/api-keys/components/api-key-create-dialog.test.tsx
#	services/platform/app/features/settings/api-keys/components/api-key-create-dialog.tsx
#	services/platform/app/features/settings/api-keys/hooks/use-api-keys-table-config.test.tsx
#	services/platform/app/features/settings/api-keys/hooks/use-api-keys-table-config.tsx
#	services/platform/app/features/settings/api-keys/lib/expiry.test.ts
#	services/platform/messages/de/settings.yml
#	services/platform/messages/en/settings.yml
#	services/platform/messages/fr/settings.yml
#	services/platform/tests/manual/readme.md
#	services/platform/tests/manual/suites/settings.md
@yannickmonney
yannickmonney enabled auto-merge (squash) October 8, 2026 18:35
@yannickmonney
yannickmonney merged commit 66162f2 into main Oct 8, 2026
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