From b1a03de34e6ce2d73b0d7346b6bb3a70a60d309a Mon Sep 17 00:00:00 2001 From: Jakob Wennberg Date: Wed, 26 Aug 2026 09:58:25 +0200 Subject: [PATCH] fix(mcp-oauth): api_keys.company_id nullable so companyless signups can mint their key (#1919) Every fresh Claude.ai authorization died at POST /api/mcp-oauth/token with a silent 500: the multi-tenant refactor's dynamic loop (20260330130000, line ~250) set company_id NOT NULL on api_keys, and the companyless key insert from the popup-signup flow (#1814) violates it. Nothing exercised the real insert before (unit tests mock the client; no pg test inserted an unbound key), so repo, CI and prod all agreed and all were wrong. DROP NOT NULL, log the insert/rotation failures at the token endpoint, and pin the unbound insert + lazy bind on real Postgres. Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6 Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 --- app/api/mcp-oauth/token/route.ts | 8 ++++ ...826090000_api_keys_company_id_nullable.sql | 16 ++++++++ tests/pg/api-keys-unbound.pg.test.ts | 41 +++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 supabase/migrations/20260826090000_api_keys_company_id_nullable.sql create mode 100644 tests/pg/api-keys-unbound.pg.test.ts diff --git a/app/api/mcp-oauth/token/route.ts b/app/api/mcp-oauth/token/route.ts index 2ba8d1b7..a0f9e5bb 100644 --- a/app/api/mcp-oauth/token/route.ts +++ b/app/api/mcp-oauth/token/route.ts @@ -167,6 +167,13 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) { }) if (insertError) { + // This 500 was silent while api_keys.company_id was NOT NULL and every + // companyless signup died here (2026-08-26): always log the DB error. + console.error('[mcp-oauth/token] api key insert failed', { + code: insertError.code, + message: insertError.message, + companyless: companyId === null, + }) return NextResponse.json( { error: 'server_error', error_description: 'Failed to create API key' }, { status: 500 } @@ -214,6 +221,7 @@ async function handleRefreshTokenGrant(params: URLSearchParams) { }) if (error) { + console.error('[mcp-oauth/token] refresh rotation failed', { code: error.code, message: error.message }) return NextResponse.json( { error: 'server_error', error_description: 'Failed to rotate refresh token' }, { status: 500 } diff --git a/supabase/migrations/20260826090000_api_keys_company_id_nullable.sql b/supabase/migrations/20260826090000_api_keys_company_id_nullable.sql new file mode 100644 index 00000000..011f3892 --- /dev/null +++ b/supabase/migrations/20260826090000_api_keys_company_id_nullable.sql @@ -0,0 +1,16 @@ +-- Migration: api_keys.company_id becomes nullable +-- +-- Agent-first onboarding (#1814): a key minted from the OAuth popup before +-- the user's first company exists is stored unbound (company_id NULL) and +-- bound lazily by validateApiKey once a company exists. The column was made +-- NOT NULL by the dynamic loop in 20260330130000_multi_tenant_company_refactor +-- (line ~250 sets NOT NULL for every table in its list, api_keys included), +-- which nothing exercised until the companyless flow: the token endpoint's +-- insert violated it and every fresh Claude.ai authorization died with a 500 +-- ("Authorization with Accounted failed", 2026-08-26). +-- +-- Consumers already handle NULL: validateApiKey returns companyId +-- string|null, the MCP dispatcher answers NO_COMPANY_YET for company-scoped +-- tools on an unbound key, and /api/events fails closed. + +ALTER TABLE public.api_keys ALTER COLUMN company_id DROP NOT NULL; diff --git a/tests/pg/api-keys-unbound.pg.test.ts b/tests/pg/api-keys-unbound.pg.test.ts new file mode 100644 index 00000000..e432d15e --- /dev/null +++ b/tests/pg/api-keys-unbound.pg.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest' +import { randomUUID, createHash } from 'node:crypto' +import { getPool } from './setup' +import { insertAuthUser } from './fixtures' + +/** + * Unbound API keys (migration 20260826090000): a key minted from the OAuth + * popup before the user's first company exists carries company_id NULL. + * The NOT NULL from 20260330130000's dynamic loop made the token endpoint's + * insert fail with a plain 500 on every fresh Claude.ai authorization; a + * mocked client cannot see a column constraint, so this pins it on real + * Postgres. + */ +describe('api_keys unbound insert.pg', () => { + it('accepts a key with no company binding', async () => { + const userId = await insertAuthUser() + const keyHash = createHash('sha256').update(randomUUID()).digest('hex') + const inserted = await getPool().query<{ id: string; company_id: string | null }>( + `INSERT INTO public.api_keys (user_id, company_id, key_hash, key_prefix, name, scopes) + VALUES ($1, NULL, $2, 'gnubok_sk_test', 'MCP-klient (OAuth)', ARRAY['companies:read']) + RETURNING id, company_id`, + [userId, keyHash], + ) + expect(inserted.rows[0]!.company_id).toBeNull() + + // The lazy bind heals exactly the unbound row. + const companyRes = await getPool().query<{ id: string }>( + `SELECT public.create_company_for_user($1::uuid, 'Bind AB', 'aktiebolag', NULL) AS id`, + [userId], + ) + await getPool().query( + `UPDATE public.api_keys SET company_id = $1 WHERE id = $2 AND company_id IS NULL`, + [companyRes.rows[0]!.id, inserted.rows[0]!.id], + ) + const healed = await getPool().query<{ company_id: string | null }>( + `SELECT company_id FROM public.api_keys WHERE id = $1`, + [inserted.rows[0]!.id], + ) + expect(healed.rows[0]!.company_id).toBe(companyRes.rows[0]!.id) + }) +})