fix(api): create and revoke API keys from a CLI OAuth session

Merged
KI
1mo ago
+20-6

Summary

  • apiKey.create and apiKey.revoke now work when the caller is the CLI signed in with OAuth. Until now both failed with "Unauthorized or invalid session".
  • Needed by superset hosts add (plan: plans/20261010-add-host-over-ssh.md, PR to follow). That command mints the new host's API key from the user's CLI. Per packages/trpc/AGENTS.md rule 9, this ships first.

Why

Both procedures passed ctx.headers to better-auth. better-auth can only resolve a browser or desktop session from headers. A CLI OAuth token is a JWT, and apps/api/src/trpc/context.ts turns it into a session itself (sessionFromOAuthBearer). better-auth never sees that session, so the call is rejected.

How

  • create: makes better-auth's server-only call, which names the user (body.userId = ctx.session.user.id) and sends no headers. The owner, name and metadata.organizationId are the same as before.
  • revoke: deletes the row where id and referenceId = session user both match. Another user's key still throws NOT_FOUND, as before. No secondary storage is configured for API keys, so the database row is the whole key.

Inputs, outputs, procedure types and error codes are unchanged, so released desktop and CLI builds are not affected.

Testing

  • Script against the dev database through @superset/auth/server:
    • the server-only create returns an sk_live_ key owned by the user, and verifyApiKey accepts it;
    • the scoped delete removes it, and verifyApiKey then rejects it.
  • Biome clean.
  • End-to-end through superset hosts add once this is deployed.

Summary by cubic

Fixes apiKey.create and apiKey.revoke so they work when the caller is a CLI signed in with OAuth; both previously failed with "Unauthorized or invalid session". The tRPC context builds a session from the CLI's JWT, but both procedures passed request headers to better-auth, which cannot resolve that synthesized session. create now uses a server-only call that names the session user, and revoke deletes the key scoped to that user. Inputs, outputs, procedure types, and error codes are unchanged.

This is needed by superset hosts add, which mints the new host's API key from the CLI session.

Summary by CodeRabbit

  • Bug Fixes
    • API keys created while signed in are now associated with the signed-in account.
    • Revoking an API key now removes it only if it belongs to the signed-in account. If no matching key is found, the request reports “API key not found” instead of silently failing or attempting to remove another account’s key. This makes key ownership and revocation outcomes more consistent.