fix(security): audit remediation 2026-09-01: api_keys identity, viewer gates, OAuth binding, XSS, MFA gate (#2155)
* fix(security): bind api_keys to the caller, lock hash-as-bearer RPCs and provider token tables Security audit 2026-09-01, critical items. - api_keys INSERT requires user_id = auth.uid() again (an admin could forge a key for any co-member and act as them in every company they belong to); SELECT is own-keys-or-admin; a BEFORE trigger freezes the identity and credential columns against user-session UPDATEs. - rotate_mcp_refresh_token and validate_and_increment_api_key become service_role only: they match rows by a presented SHA-256, so a hash readable by co-members was a bearer credential. - validate_and_increment_api_key fails closed when the key's user is no longer a member of the key's company. - provider_consent_tokens and provider_otc: the DELETE policies collapsed to "caller has any team row" (correlated subquery on a non-existent team_members.company_id). All member policies dropped; service_role only, matching every existing code path. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): role gates, ownership guards and posting integrity in the database Security audit 2026-09-01, high items at the database layer. - One table-level guard, enforce_company_writer_role(), blocks the read-only viewer role on 55 company-scoped tables including through the 15 membership-only SECURITY DEFINER writers. Keyed on the JWT role claim so it fires inside definer bodies; no-op for service_role and trigger cascades. - company_members user_id/company_id immutable from user sessions; invitations can never grant owner; team_members gains a transition guard (admins keep non-owner role moves); companies team_id and archiving are owner-only and team attachment needs team membership. - Direct statements (current_user = authenticated) can no longer insert posted headers, add lines under posted verifikat, or post a draft with a voucher number the sequence never issued. Sanctioned RPCs run as the definer and are untouched; the engine's own draft-then-post shapes still pass. - create_document_version refuses viewers and foreign storage paths; validate_version_chain needs membership and loses anon EXECUTE; match_documents / match_booking_templates lose anon; cron maintenance RPCs become service_role only; the production-only seed_asset_categories is dropped. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * build: pin tsx as an exact devDependency instead of fetching it with npx at build time prebuild ran "npx tsx" with no lockfile entry, so every Vercel, Docker and CI build downloaded tsx@latest and its transitive tree from the registry with no integrity check, inside the build environment. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): refuse the viewer role on API-key and MCP write paths The v1 wrapper and the MCP company routing checked company membership but never role, and both run as service role, so a read-only viewer holding an API key could post vouchers and change settings through the API. Mutating methods and non-read scopes now return 403 ROLE_READ_ONLY for viewers on v1; MCP write tools refuse viewers the same way. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): stop serving uploaded SVG, XML and HTML as executable content on the app origin Uploads persisted the browser-declared mime type and the inline proxy served it verbatim, sandboxing only text/html; the storage proxy forwarded the uploader's Content-Type. Any writer, or any Peppol sender, could plant a scripted SVG or XHTML that executed on app.gnubok.se. - inline route: allow-list of natively safe types (PDF, raster images) served as before; everything else gets the opaque sandbox CSP. - storage proxy: octet-stream + attachment + sandbox unless the DB mime for the key is on the allow-list. - document-service: the stored mime is the magic-byte validated type. - logo upload: magic-byte validation, SVG refused. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): byrå brand logo upload decides the type by magic bytes and drops SVG Same pattern as the company logo route: the logos bucket is public, so a scripted SVG (or anything declared as an image) must never land there. The upload pickers stop advertising SVG. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): bind Enable Banking, Stripe and WooCommerce callbacks to the initiating user The callbacks resolved the pending row by oauth_state alone, so a victim who completed an attacker-initiated consent had their bank account, merchant account or store attached to the attacker's company. requireFlowInitiator() now requires the cookie session of the user who started the flow: no session redirects to login with the callback URL preserved, a different user is refused and nothing is exchanged. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): guard tenant-controlled outbound fetches and surface the disabled rate limiter WooCommerce and Shopify syncs fetched a member-editable store URL with plain fetch() and redirect following under the service role, and the invoice PDF renderer fetched company_settings.logo_url unguarded. All three go through a new safeFetch() (public-IP validation via url-guard, https only, redirect: 'manual', body size cap) and re-normalise the stored host at use time. checkRateLimit() keeps failing open on hosted but logs one error per process when Upstash is not configured and exports isRateLimiterConfigured(). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): decide the API MFA gate from server-authenticated factors, not the session cookie getAuthenticatorAssuranceLevel() without arguments derives nextLevel from session.user.factors, which comes from the unsigned sb-*-auth-token cookie. Deleting factors from the cookie made an enrolled account look like it had nothing to step up to, on every /api route and in requireAuth. Both gates now read factors from the getUser() result or listFactors() and the level from the verified JWT claim, and fail closed on errors. Page-branch gate hardened the same way. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): bind Fortnox/Visma, Gmail and Skatteverket callbacks to the initiating user The arcim-migration callback exchanged the provider code onto whatever consent the one-time state named, with no check of who completed the flow and no org-number comparison, so a phished Fortnox admin handed their ledger to the attacker's company. provider_otc now records the initiating user (migration 20260902100000); the callback requires that session and, after the exchange, refuses a provider company whose org number differs from the consent's company. The Gmail and Skatteverket callbacks enforce the same initiator check. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): BankID signup confirms the email before linking the identity Signup created an email-confirmed, MFA-exempt account for any address the caller typed and returned a magic link, so an attacker could pre-register a victim's email and keep a permanent BankID login into the account the victim later adopted. The user is now created unconfirmed, the identity carries email_verified_at NULL (migration 20260902101000), bankid_linked is not set until the mailed confirmation is clicked, and BankID login of a pending identity is refused with the confirmation re-sent. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(security): bind MCP OAuth redirect URIs to the consenting user and cap scopes A user-registered redirect URI was allowlisted globally, the consent page named no client, and all scopes were pre-checked, so one phishing link handed an attacker a full-scope key for the victim's company. Registered URIs now resolve only for the registrant or a colleague sharing a company; the consent page shows the client identity and redirect host; non-built-in clients default to read-only pre-checks; scopes are capped by the user's role (viewer: read only) at consent and at /token. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(auth): client follow-ups for BankID confirmation, callback mismatch copy and decision log - register client handles the new confirmation_sent response from BankID signup with the existing inbox screen instead of calling verifyOtp. - BankID login surfaces the email_unconfirmed explanation. - WooCommerce settings map woocommerce_error=wrong_user to its own copy. - Logo help text no longer advertises SVG. - DECISIONS.md records the audit remediation choices. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(mcp-oauth): literal SoD columns in the api_keys insert so the phantom-column scanner resolves them Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test(logo): type the upload fixtures as Uint8Array<ArrayBuffer> so they are valid BlobParts Fixes the typecheck ratchet on PR #2155 and ratchets the baseline down by the one legacy error the change removed. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
6e8d76a9cb
commit
18cbc4c30a
@@ -0,0 +1,210 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import crypto from 'crypto'
|
||||
|
||||
/**
|
||||
* /authorize with the REAL redirect-URI allowlist. The route tests in
|
||||
* route.test.ts stub resolveRedirectUri; here only the service-role client is
|
||||
* faked, so the tests prove the phishing fix end to end: a redirect URI that
|
||||
* some unrelated account registered is refused for this user, a colleague's
|
||||
* registration is accepted, and built-in Claude never touches the table.
|
||||
*/
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createClient: vi.fn(),
|
||||
serviceClient: vi.fn(),
|
||||
getActiveCompanyId: vi.fn(),
|
||||
getBranding: vi.fn(),
|
||||
createAuthCode: vi.fn<(...args: unknown[]) => string>(() => 'test-auth-code'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/oauth-codes', () => ({
|
||||
createAuthCode: (...args: unknown[]) => mocks.createAuthCode(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => mocks.createClient(),
|
||||
}))
|
||||
|
||||
// The allowlist imports createServiceClientNoCookies from lib/auth/api-keys
|
||||
// (relative path); the alias resolves to the same module, so this stub is
|
||||
// what resolveRedirectUri constructs for its registration lookup.
|
||||
vi.mock('@/lib/auth/api-keys', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/auth/api-keys')>()
|
||||
return {
|
||||
...actual,
|
||||
createServiceClientNoCookies: () => mocks.serviceClient(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => mocks.getActiveCompanyId(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/branding/service', () => ({
|
||||
getBranding: () => mocks.getBranding(),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
type Row = Record<string, unknown>
|
||||
|
||||
/**
|
||||
* Minimal PostgREST-shaped fake over in-memory tables: eq/is filters are
|
||||
* applied, everything else is a no-op, and the chain resolves to the filtered
|
||||
* rows (all rows when awaited, first row via maybeSingle).
|
||||
*/
|
||||
function fakeServiceClient(tables: Record<string, Row[]>) {
|
||||
const from = vi.fn((table: string) => {
|
||||
const filters: [string, unknown][] = []
|
||||
const run = () =>
|
||||
(tables[table] ?? []).filter((row) =>
|
||||
filters.every(([col, val]) => (val === null ? row[col] == null : row[col] === val)),
|
||||
)
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['select', 'order', 'range', 'limit']) chain[method] = () => chain
|
||||
chain.eq = (col: string, val: unknown) => {
|
||||
filters.push([col, val])
|
||||
return chain
|
||||
}
|
||||
chain.is = (col: string, val: unknown) => {
|
||||
filters.push([col, val])
|
||||
return chain
|
||||
}
|
||||
chain.maybeSingle = async () => ({ data: run()[0] ?? null, error: null })
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve({ data: run(), error: null })
|
||||
return chain
|
||||
})
|
||||
return { from }
|
||||
}
|
||||
|
||||
function userClient(userId: string, role = 'owner') {
|
||||
const chainFor = (result: { data: unknown; error: unknown }) => {
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['select', 'eq', 'is', 'order', 'range', 'limit']) chain[method] = () => chain
|
||||
chain.single = async () => result
|
||||
chain.maybeSingle = async () => result
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve(result)
|
||||
return chain
|
||||
}
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: { id: userId } }, error: null }),
|
||||
mfa: {
|
||||
getAuthenticatorAssuranceLevel: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ data: { currentLevel: 'aal2', nextLevel: 'aal2' }, error: null }),
|
||||
listFactors: vi.fn().mockResolvedValue({ data: { totp: [] }, error: null }),
|
||||
},
|
||||
},
|
||||
from: vi.fn((table: string) =>
|
||||
table === 'company_members'
|
||||
? chainFor({ data: { role }, error: null })
|
||||
: chainFor({ data: { company_name: 'Test AB' }, error: null }),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
const DB = {
|
||||
oauth_client_registrations: [
|
||||
// A colleague of user-1 (both in company-1) registered this one.
|
||||
{ id: 'reg-1', user_id: 'user-2', client_name: 'Byråns bot', redirect_uri: 'https://app.example.com/cb', revoked_at: null },
|
||||
// An unrelated account on the same instance registered this one.
|
||||
{ id: 'reg-2', user_id: 'user-9', client_name: 'Claude (Anthropic)', redirect_uri: 'https://claude-login.example/cb', revoked_at: null },
|
||||
// user-1's own registration.
|
||||
{ id: 'reg-3', user_id: 'user-1', client_name: 'Min egen app', redirect_uri: 'https://mine.example/cb', revoked_at: null },
|
||||
],
|
||||
company_members: [
|
||||
{ id: 'm1', user_id: 'user-1', company_id: 'company-1', role: 'owner' },
|
||||
{ id: 'm2', user_id: 'user-2', company_id: 'company-1', role: 'member' },
|
||||
{ id: 'm3', user_id: 'user-9', company_id: 'company-9', role: 'owner' },
|
||||
],
|
||||
}
|
||||
|
||||
function authorizeUrl(redirectUri: string): string {
|
||||
const url = new URL('http://localhost/api/mcp-oauth/authorize')
|
||||
url.searchParams.set('response_type', 'code')
|
||||
url.searchParams.set('redirect_uri', redirectUri)
|
||||
url.searchParams.set('code_challenge', 'abc')
|
||||
url.searchParams.set('code_challenge_method', 'S256')
|
||||
url.searchParams.set('state', 'xyz')
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
function consentForm(): FormData {
|
||||
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
|
||||
const sig = crypto.createHmac('sha256', key).update('').digest('base64url')
|
||||
const formData = new FormData()
|
||||
formData.set('consent', 'allow')
|
||||
formData.set('scope_binding', '')
|
||||
formData.set('scope_binding_sig', sig)
|
||||
formData.append('scopes', 'reports:read')
|
||||
return formData
|
||||
}
|
||||
|
||||
describe('/api/mcp-oauth/authorize with the real redirect-URI allowlist', () => {
|
||||
let service: ReturnType<typeof fakeServiceClient>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
service = fakeServiceClient(DB)
|
||||
mocks.serviceClient.mockReturnValue(service)
|
||||
mocks.createClient.mockResolvedValue(userClient('user-1'))
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
|
||||
it('GET rejects a redirect URI registered by an unrelated user, even one named like Claude', async () => {
|
||||
const response = await GET(new Request(authorizeUrl('https://claude-login.example/cb')))
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('invalid_request')
|
||||
expect(body.error_description).toBe('redirect_uri is not allowed')
|
||||
})
|
||||
|
||||
it('POST rejects the same URI and mints no code', async () => {
|
||||
const response = await POST(
|
||||
new Request(authorizeUrl('https://claude-login.example/cb'), { method: 'POST', body: consentForm() }),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
expect(mocks.createAuthCode).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('GET accepts a redirect URI registered by a colleague in a shared company and names it', async () => {
|
||||
const response = await GET(new Request(authorizeUrl('https://app.example.com/cb')))
|
||||
expect(response.status).toBe(200)
|
||||
const html = await response.text()
|
||||
expect(html).toContain('Byråns bot')
|
||||
expect(html).toContain('Registrerad av en kollega')
|
||||
expect(html).toContain('app.example.com')
|
||||
expect(html).not.toContain('Verifierad')
|
||||
})
|
||||
|
||||
it("GET accepts the consenting user's own registration", async () => {
|
||||
const response = await GET(new Request(authorizeUrl('https://mine.example/cb')))
|
||||
expect(response.status).toBe(200)
|
||||
const html = await response.text()
|
||||
expect(html).toContain('Min egen app')
|
||||
expect(html).toContain('Registrerad av dig')
|
||||
})
|
||||
|
||||
it('POST for a colleague registration issues a code to that URI', async () => {
|
||||
const response = await POST(
|
||||
new Request(authorizeUrl('https://app.example.com/cb'), { method: 'POST', body: consentForm() }),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
const location = new URL(response.headers.get('location')!)
|
||||
expect(location.origin).toBe('https://app.example.com')
|
||||
expect(location.searchParams.get('code')).toBe('test-auth-code')
|
||||
})
|
||||
|
||||
it('GET accepts the built-in Claude callback without consulting the registration table', async () => {
|
||||
const response = await GET(new Request(authorizeUrl('https://claude.ai/api/mcp/auth_callback')))
|
||||
expect(response.status).toBe(200)
|
||||
expect(mocks.serviceClient).not.toHaveBeenCalled()
|
||||
expect(service.from).not.toHaveBeenCalled()
|
||||
const html = await response.text()
|
||||
expect(html).toContain('Claude (Anthropic)')
|
||||
expect(html).toContain('Verifierad')
|
||||
})
|
||||
})
|
||||
@@ -1,24 +1,32 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import crypto from 'crypto'
|
||||
import type { RedirectUriResolution } from '@/lib/auth/oauth-allowlist'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createClient: vi.fn(),
|
||||
isAllowedRedirectUri: vi.fn(),
|
||||
resolveRedirectUri: vi.fn(),
|
||||
getActiveCompanyId: vi.fn(),
|
||||
getBranding: vi.fn(),
|
||||
createAuthCode: vi.fn<(...args: unknown[]) => string>(() => 'test-auth-code'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/oauth-codes', () => ({
|
||||
createAuthCode: vi.fn(() => 'test-auth-code'),
|
||||
createAuthCode: (...args: unknown[]) => mocks.createAuthCode(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => mocks.createClient(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/oauth-allowlist', () => ({
|
||||
isAllowedRedirectUri: (...args: unknown[]) => mocks.isAllowedRedirectUri(...args),
|
||||
}))
|
||||
// Only the redirect-URI resolution is replaced: the role cap helpers from the
|
||||
// same module run for real so the tests exercise the actual ceiling logic.
|
||||
vi.mock('@/lib/auth/oauth-allowlist', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/auth/oauth-allowlist')>()
|
||||
return {
|
||||
...actual,
|
||||
resolveRedirectUri: (...args: unknown[]) => mocks.resolveRedirectUri(...args),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => mocks.getActiveCompanyId(...args),
|
||||
@@ -30,18 +38,50 @@ vi.mock('@/lib/branding/service', () => ({
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
const CLAUDE: RedirectUriResolution = { allowed: true, kind: 'built_in', provider: 'claude' }
|
||||
const CHATGPT: RedirectUriResolution = { allowed: true, kind: 'built_in', provider: 'chatgpt' }
|
||||
const REGISTERED: RedirectUriResolution = {
|
||||
allowed: true,
|
||||
kind: 'registered',
|
||||
clientName: 'Byråns bokföringsbot',
|
||||
registeredByConsentingUser: false,
|
||||
}
|
||||
|
||||
function buildAuthorizeUrl(params: Record<string, string>): string {
|
||||
const url = new URL('http://localhost/api/mcp-oauth/authorize')
|
||||
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v))
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Chainable query stub: every builder method returns the chain, and the chain
|
||||
* resolves to `result` whether awaited directly or via single()/maybeSingle().
|
||||
*/
|
||||
function tableChain(result: { data: unknown; error: unknown }) {
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['select', 'eq', 'is', 'in', 'order', 'range', 'limit']) {
|
||||
chain[method] = vi.fn(() => chain)
|
||||
}
|
||||
chain.single = vi.fn().mockResolvedValue(result)
|
||||
chain.maybeSingle = vi.fn().mockResolvedValue(result)
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve(result)
|
||||
return chain
|
||||
}
|
||||
|
||||
type Membership = { role: string | null } | { error: string }
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string; email?: string } | null,
|
||||
companyName = 'Test AB',
|
||||
aal: { currentLevel: string; nextLevel: string } = { currentLevel: 'aal2', nextLevel: 'aal2' },
|
||||
verifiedFactors: number = aal.nextLevel === 'aal2' ? 1 : 0,
|
||||
membership: Membership = { role: 'owner' },
|
||||
) {
|
||||
const settingsResult = { data: { company_name: companyName }, error: null }
|
||||
const membershipResult =
|
||||
'error' in membership
|
||||
? { data: null, error: { message: membership.error } }
|
||||
: { data: membership.role === null ? null : { role: membership.role }, error: null }
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user }, error: null }),
|
||||
@@ -58,25 +98,43 @@ function buildSupabase(
|
||||
}),
|
||||
},
|
||||
},
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
single: vi.fn().mockResolvedValue({
|
||||
data: { company_name: companyName },
|
||||
error: null,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
from: vi.fn((table: string) =>
|
||||
table === 'company_members' ? tableChain(membershipResult) : tableChain(settingsResult),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Mirrors getScopeSigningKey/signScopeBinding in the route so a POST can
|
||||
// present a scope binding that verifies against the test service key.
|
||||
function signScope(scopeParam: string): string {
|
||||
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
|
||||
return crypto.createHmac('sha256', key).update(scopeParam).digest('base64url')
|
||||
}
|
||||
|
||||
function consentForm(scopeParam: string, scopes: string[] = []): FormData {
|
||||
const formData = new FormData()
|
||||
formData.set('consent', 'allow')
|
||||
formData.set('scope_binding', scopeParam)
|
||||
formData.set('scope_binding_sig', signScope(scopeParam))
|
||||
for (const s of scopes) formData.append('scopes', s)
|
||||
return formData
|
||||
}
|
||||
|
||||
function checkboxFor(html: string, scope: string): string | undefined {
|
||||
return html.match(new RegExp(`<input[^>]*value="${scope}"[^>]*>`))?.[0]
|
||||
}
|
||||
|
||||
function lastMintedPayload(): Record<string, unknown> {
|
||||
const calls = mocks.createAuthCode.mock.calls as unknown[][]
|
||||
return calls[calls.length - 1]![0] as Record<string, unknown>
|
||||
}
|
||||
|
||||
describe('GET /api/mcp-oauth/authorize: CSP', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(true)
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
@@ -188,22 +246,12 @@ describe('GET /api/mcp-oauth/authorize: CSP', () => {
|
||||
|
||||
// Every row starts checked: the deliberate act is the visible Allow
|
||||
// click, and unticking stays available per row inside the details fold.
|
||||
const writeRow = html.match(/<input[^>]*value="transactions:write"[^>]*>/)?.[0]
|
||||
expect(writeRow).toBeDefined()
|
||||
expect(writeRow!).toContain('checked')
|
||||
|
||||
const approveRow = html.match(/<input[^>]*value="pending_operations:approve"[^>]*>/)?.[0]
|
||||
expect(approveRow).toBeDefined()
|
||||
expect(approveRow!).toContain('checked')
|
||||
|
||||
const bookkeepingRow = html.match(/<input[^>]*value="bookkeeping:write"[^>]*>/)?.[0]
|
||||
expect(bookkeepingRow).toBeDefined()
|
||||
expect(bookkeepingRow!).toContain('checked')
|
||||
expect(checkboxFor(html, 'transactions:write')).toContain('checked')
|
||||
expect(checkboxFor(html, 'pending_operations:approve')).toContain('checked')
|
||||
expect(checkboxFor(html, 'bookkeeping:write')).toContain('checked')
|
||||
|
||||
// The :read counterpart is pre-checked too.
|
||||
const readRow = html.match(/<input[^>]*value="transactions:read"[^>]*>/)?.[0]
|
||||
expect(readRow).toBeDefined()
|
||||
expect(readRow!).toContain('checked')
|
||||
expect(checkboxFor(html, 'transactions:read')).toContain('checked')
|
||||
})
|
||||
|
||||
it('renders only the requested scopes when the client passes them explicitly', async () => {
|
||||
@@ -229,8 +277,8 @@ describe('GET /api/mcp-oauth/authorize: CSP', () => {
|
||||
expect(html).not.toContain('value="bookkeeping:write"')
|
||||
})
|
||||
|
||||
it('rejects disallowed redirect_uri before any CSP would be emitted', async () => {
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(false)
|
||||
it('rejects a redirect_uri the allowlist refuses for this user before any CSP would be emitted', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue({ allowed: false })
|
||||
const request = new Request(
|
||||
buildAuthorizeUrl({
|
||||
response_type: 'code',
|
||||
@@ -246,6 +294,296 @@ describe('GET /api/mcp-oauth/authorize: CSP', () => {
|
||||
// untrusted origin. A 400 here keeps the allowlist as the single source
|
||||
// of truth for which origins can land at this endpoint.
|
||||
})
|
||||
|
||||
it('binds the redirect_uri check to the consenting user on GET and POST', async () => {
|
||||
// The allowlist can only tell a colleague's registration from a
|
||||
// stranger's when it knows who is consenting. Both handlers must pass it.
|
||||
const params = {
|
||||
response_type: 'code',
|
||||
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
|
||||
code_challenge: 'abc',
|
||||
code_challenge_method: 'S256',
|
||||
scope: 'mcp',
|
||||
}
|
||||
await GET(new Request(buildAuthorizeUrl(params)))
|
||||
expect(mocks.resolveRedirectUri).toHaveBeenLastCalledWith(
|
||||
'https://claude.ai/api/mcp/auth_callback',
|
||||
undefined,
|
||||
{ consentingUserId: 'user-1' },
|
||||
)
|
||||
|
||||
await POST(new Request(buildAuthorizeUrl(params), { method: 'POST', body: consentForm('mcp') }))
|
||||
expect(mocks.resolveRedirectUri).toHaveBeenLastCalledWith(
|
||||
'https://claude.ai/api/mcp/auth_callback',
|
||||
undefined,
|
||||
{ consentingUserId: 'user-1' },
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('client identity on the consent page', () => {
|
||||
const params = {
|
||||
response_type: 'code',
|
||||
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
|
||||
code_challenge: 'abc',
|
||||
code_challenge_method: 'S256',
|
||||
scope: 'mcp',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
|
||||
it('names Claude as a verified client and shows the redirect host', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
const html = await (await GET(new Request(buildAuthorizeUrl(params)))).text()
|
||||
|
||||
expect(html).toContain('Claude (Anthropic)')
|
||||
expect(html).toContain('Verifierad')
|
||||
expect(html).toContain('Skickar dig vidare till')
|
||||
expect(html).toContain('claude.ai')
|
||||
// The generic "en extern applikation" wording is gone: the client is named.
|
||||
expect(html).not.toContain('En extern applikation')
|
||||
})
|
||||
|
||||
it('names ChatGPT for chatgpt.com callbacks', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CHATGPT)
|
||||
const html = await (
|
||||
await GET(
|
||||
new Request(
|
||||
buildAuthorizeUrl({ ...params, redirect_uri: 'https://chatgpt.com/connector/oauth/abc' }),
|
||||
),
|
||||
)
|
||||
).text()
|
||||
|
||||
expect(html).toContain('ChatGPT (OpenAI)')
|
||||
expect(html).toContain('chatgpt.com')
|
||||
})
|
||||
|
||||
it('shows client_name and redirect host for a DB-registered client, never marked verified', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue(REGISTERED)
|
||||
const html = await (
|
||||
await GET(
|
||||
new Request(buildAuthorizeUrl({ ...params, redirect_uri: 'https://app.example.com/cb' })),
|
||||
)
|
||||
).text()
|
||||
|
||||
expect(html).toContain('Byråns bokföringsbot')
|
||||
expect(html).toContain('app.example.com')
|
||||
expect(html).toContain('Registrerad av en kollega')
|
||||
expect(html).not.toContain('Verifierad')
|
||||
expect(html).not.toContain('Claude')
|
||||
})
|
||||
|
||||
it('HTML-escapes a hostile client_name', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue({
|
||||
...REGISTERED,
|
||||
clientName: '<img src=x onerror=alert(1)>Claude (Anthropic)',
|
||||
registeredByConsentingUser: true,
|
||||
})
|
||||
const html = await (
|
||||
await GET(
|
||||
new Request(buildAuthorizeUrl({ ...params, redirect_uri: 'https://app.example.com/cb' })),
|
||||
)
|
||||
).text()
|
||||
|
||||
expect(html).not.toContain('<img src=x')
|
||||
expect(html).toContain('<img src=x onerror=alert(1)>')
|
||||
expect(html).toContain('Registrerad av dig')
|
||||
})
|
||||
})
|
||||
|
||||
describe('scope defaults for DB-registered clients', () => {
|
||||
const params = {
|
||||
response_type: 'code',
|
||||
redirect_uri: 'https://app.example.com/cb',
|
||||
code_challenge: 'abc',
|
||||
code_challenge_method: 'S256',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
|
||||
mocks.resolveRedirectUri.mockResolvedValue(REGISTERED)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
|
||||
it('pre-checks only read scopes when a registered client sends no scope', async () => {
|
||||
// The ceiling stays ALL_SCOPES so the user can still opt in, but a
|
||||
// registration is just a URL a member typed into settings: writes and
|
||||
// approval must be a deliberate tick, never a default.
|
||||
const html = await (await GET(new Request(buildAuthorizeUrl(params)))).text()
|
||||
|
||||
expect(checkboxFor(html, 'transactions:read')).toContain('checked')
|
||||
expect(checkboxFor(html, 'reports:read')).toContain('checked')
|
||||
|
||||
expect(checkboxFor(html, 'transactions:write')).toBeDefined()
|
||||
expect(checkboxFor(html, 'transactions:write')).not.toContain('checked')
|
||||
expect(checkboxFor(html, 'bookkeeping:write')).not.toContain('checked')
|
||||
expect(checkboxFor(html, 'pending_operations:approve')).not.toContain('checked')
|
||||
expect(checkboxFor(html, 'webhooks:manage')).not.toContain('checked')
|
||||
|
||||
expect(html).toContain('Endast läs förvalt')
|
||||
expect(html).toContain('Endast läsbehörigheter är förvalda')
|
||||
})
|
||||
|
||||
it('pre-checks write scopes only when the registered client explicitly requested them', async () => {
|
||||
const html = await (
|
||||
await GET(
|
||||
new Request(
|
||||
buildAuthorizeUrl({ ...params, scope: 'transactions:read transactions:write' }),
|
||||
),
|
||||
)
|
||||
).text()
|
||||
|
||||
expect(checkboxFor(html, 'transactions:write')).toContain('checked')
|
||||
expect(checkboxFor(html, 'transactions:read')).toContain('checked')
|
||||
// Not requested: not even rendered.
|
||||
expect(html).not.toContain('value="pending_operations:approve"')
|
||||
})
|
||||
|
||||
it('states the segregation-of-duties rule when stage and approve scopes are both on offer', async () => {
|
||||
const html = await (await GET(new Request(buildAuthorizeUrl(params)))).text()
|
||||
expect(html).toContain('medgivande')
|
||||
|
||||
const readOnly = await (
|
||||
await GET(new Request(buildAuthorizeUrl({ ...params, scope: 'transactions:read' })))
|
||||
).text()
|
||||
expect(readOnly).not.toContain('medgivande')
|
||||
})
|
||||
})
|
||||
|
||||
describe('role cap on consent', () => {
|
||||
const params = {
|
||||
response_type: 'code',
|
||||
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
|
||||
code_challenge: 'abc',
|
||||
code_challenge_method: 'S256',
|
||||
scope: 'mcp',
|
||||
state: 'xyz',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
|
||||
it('viewer: GET offers read scopes only and says why', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: 'viewer' }),
|
||||
)
|
||||
const response = await GET(new Request(buildAuthorizeUrl(params)))
|
||||
expect(response.status).toBe(200)
|
||||
const html = await response.text()
|
||||
|
||||
expect(checkboxFor(html, 'transactions:read')).toContain('checked')
|
||||
expect(html).not.toContain('value="transactions:write"')
|
||||
expect(html).not.toContain('value="pending_operations:approve"')
|
||||
expect(html).not.toContain('value="webhooks:manage"')
|
||||
expect(html).toContain('läsare')
|
||||
})
|
||||
|
||||
it('viewer: POST caps a forged write selection to read scopes and records the company', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: 'viewer' }),
|
||||
)
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(params), {
|
||||
method: 'POST',
|
||||
body: consentForm('mcp', ['transactions:read', 'transactions:write', 'pending_operations:approve']),
|
||||
}),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
expect(new URL(response.headers.get('location')!).searchParams.get('code')).toBe('test-auth-code')
|
||||
|
||||
const payload = lastMintedPayload()
|
||||
expect(payload.scopes).toEqual(['transactions:read'])
|
||||
expect(payload.companyId).toBe('company-1')
|
||||
expect(payload.userId).toBe('user-1')
|
||||
})
|
||||
|
||||
it('viewer: a write-only client request is bounced with invalid_scope instead of a read grant it never asked for', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: 'viewer' }),
|
||||
)
|
||||
const response = await GET(
|
||||
new Request(buildAuthorizeUrl({ ...params, scope: 'transactions:write' })),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
const location = new URL(response.headers.get('location')!)
|
||||
expect(location.origin).toBe('https://claude.ai')
|
||||
expect(location.searchParams.get('error')).toBe('invalid_scope')
|
||||
expect(location.searchParams.get('state')).toBe('xyz')
|
||||
expect(location.searchParams.get('code')).toBeNull()
|
||||
})
|
||||
|
||||
it('member: POST keeps requested write and approve scopes', async () => {
|
||||
// Mirrors app/api/settings/api-keys: any writer role may hold approve;
|
||||
// the stage+approve combination is acknowledged, not blocked.
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: 'member' }),
|
||||
)
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(params), {
|
||||
method: 'POST',
|
||||
body: consentForm('mcp', ['transactions:read', 'transactions:write', 'pending_operations:approve']),
|
||||
}),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
expect(lastMintedPayload().scopes).toEqual([
|
||||
'transactions:read',
|
||||
'transactions:write',
|
||||
'pending_operations:approve',
|
||||
])
|
||||
})
|
||||
|
||||
it('no membership row: caps to read scopes rather than trusting the form', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: null }),
|
||||
)
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(params), {
|
||||
method: 'POST',
|
||||
body: consentForm('mcp', ['reports:read', 'bookkeeping:write']),
|
||||
}),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
expect(lastMintedPayload().scopes).toEqual(['reports:read'])
|
||||
})
|
||||
|
||||
it('GET fails closed with server_error when the role lookup errors', async () => {
|
||||
// A transient error must neither widen the grant (treat as owner) nor
|
||||
// silently downgrade a legitimate connection to read-only.
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { error: 'boom' }),
|
||||
)
|
||||
const response = await GET(new Request(buildAuthorizeUrl(params)))
|
||||
expect(response.status).toBe(500)
|
||||
expect((await response.json()).error).toBe('server_error')
|
||||
})
|
||||
|
||||
it('POST fails closed with server_error when the role lookup errors', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { error: 'boom' }),
|
||||
)
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(params), { method: 'POST', body: consentForm('mcp', ['reports:read']) }),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
const location = new URL(response.headers.get('location')!)
|
||||
expect(location.searchParams.get('error')).toBe('server_error')
|
||||
expect(location.searchParams.get('code')).toBeNull()
|
||||
expect(mocks.createAuthCode).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('MFA step-up on /api/mcp-oauth/authorize', () => {
|
||||
@@ -267,7 +605,7 @@ describe('MFA step-up on /api/mcp-oauth/authorize', () => {
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(true)
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
@@ -407,15 +745,10 @@ describe('account with no company yet (issue #1814)', () => {
|
||||
state: 'xyz',
|
||||
}
|
||||
|
||||
function signScope(scopeParam: string): string {
|
||||
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
|
||||
return crypto.createHmac('sha256', key).update(scopeParam).digest('base64url')
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(true)
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue(null)
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
@@ -431,7 +764,7 @@ describe('account with no company yet (issue #1814)', () => {
|
||||
expect(html).toContain('ny@example.se')
|
||||
expect(html).toContain('inget företag')
|
||||
expect(html).not.toContain('Test AB')
|
||||
// No company to look up: company_settings is never queried.
|
||||
// No company to look up: neither company_settings nor company_members is queried.
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -441,30 +774,28 @@ describe('account with no company yet (issue #1814)', () => {
|
||||
const response = await GET(new Request(buildAuthorizeUrl(authorizeParams)))
|
||||
const html = await response.text()
|
||||
|
||||
const companiesWrite = html.match(/<input[^>]*value="companies:write"[^>]*>/)?.[0]
|
||||
expect(companiesWrite).toBeDefined()
|
||||
expect(companiesWrite!).toContain('checked')
|
||||
const transactionsWrite = html.match(/<input[^>]*value="transactions:write"[^>]*>/)?.[0]
|
||||
expect(transactionsWrite).toBeDefined()
|
||||
expect(transactionsWrite!).toContain('checked')
|
||||
expect(checkboxFor(html, 'companies:write')).toContain('checked')
|
||||
expect(checkboxFor(html, 'transactions:write')).toContain('checked')
|
||||
})
|
||||
|
||||
it('POST still issues an authorization code', async () => {
|
||||
it('POST still issues an authorization code with no role cap and a null company', async () => {
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1', email: 'ny@example.se' }))
|
||||
|
||||
const formData = new FormData()
|
||||
formData.set('consent', 'allow')
|
||||
formData.set('scope_binding', 'mcp')
|
||||
formData.set('scope_binding_sig', signScope('mcp'))
|
||||
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(authorizeParams), { method: 'POST', body: formData }),
|
||||
new Request(buildAuthorizeUrl(authorizeParams), {
|
||||
method: 'POST',
|
||||
body: consentForm('mcp', ['companies:write', 'companies:read']),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(303)
|
||||
const location = new URL(response.headers.get('location')!)
|
||||
expect(location.searchParams.get('code')).toBe('test-auth-code')
|
||||
expect(location.searchParams.get('state')).toBe('xyz')
|
||||
|
||||
const payload = lastMintedPayload()
|
||||
expect(payload.companyId).toBeNull()
|
||||
expect(payload.scopes).toEqual(['companies:write', 'companies:read'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -478,19 +809,12 @@ describe('RFC 9207 iss parameter on authorization responses', () => {
|
||||
state: 'xyz',
|
||||
}
|
||||
|
||||
// Mirrors getScopeSigningKey/signScopeBinding in the route so the POST can
|
||||
// present a scope binding that verifies against the test service key.
|
||||
function signScope(scopeParam: string): string {
|
||||
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
|
||||
return crypto.createHmac('sha256', key).update(scopeParam).digest('base64url')
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.test.example')
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(true)
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
@@ -500,13 +824,8 @@ describe('RFC 9207 iss parameter on authorization responses', () => {
|
||||
})
|
||||
|
||||
it('includes iss alongside code and state on the success redirect', async () => {
|
||||
const formData = new FormData()
|
||||
formData.set('consent', 'allow')
|
||||
formData.set('scope_binding', 'mcp')
|
||||
formData.set('scope_binding_sig', signScope('mcp'))
|
||||
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(authorizeParams), { method: 'POST', body: formData }),
|
||||
new Request(buildAuthorizeUrl(authorizeParams), { method: 'POST', body: consentForm('mcp') }),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(303)
|
||||
|
||||
@@ -6,13 +6,19 @@ import { createAuthCode } from '@/lib/auth/oauth-codes'
|
||||
import { shouldEnforceMfa } from '@/lib/auth/mfa'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { isAllowedRedirectUri } from '@/lib/auth/oauth-allowlist'
|
||||
import {
|
||||
capScopesForRole,
|
||||
lookupCompanyRole,
|
||||
resolveRedirectUri,
|
||||
type RedirectUriResolution,
|
||||
} from '@/lib/auth/oauth-allowlist'
|
||||
import { resolveDiscoveryBaseUrl } from '@/lib/api/v1/base-url'
|
||||
import {
|
||||
ALL_SCOPES,
|
||||
API_KEY_SCOPES,
|
||||
DEFAULT_OAUTH_SCOPES,
|
||||
SCOPE_GROUPS,
|
||||
findStageApproveConflict,
|
||||
scopeKind,
|
||||
validateScopes,
|
||||
type ApiKeyScope,
|
||||
@@ -173,9 +179,10 @@ function errorRedirect(request: Request, redirectUri: string, state: string | nu
|
||||
export async function GET(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
const redirectUri = url.searchParams.get('redirect_uri')
|
||||
// state and code_challenge are carried through to the POST handler via
|
||||
// the form action's url.search, so we don't read them here: they're only
|
||||
// validated on POST.
|
||||
// state is read only to echo it on error redirects issued from GET;
|
||||
// code_challenge is carried through to the POST handler via the form
|
||||
// action's url.search and validated there.
|
||||
const state = url.searchParams.get('state')
|
||||
const codeChallengeMethod = url.searchParams.get('code_challenge_method') || 'S256'
|
||||
const responseType = url.searchParams.get('response_type')
|
||||
const scopeParam = url.searchParams.get('scope')
|
||||
@@ -222,9 +229,13 @@ export async function GET(request: Request) {
|
||||
const mfaRedirect = await requireAal2(supabase, user, request)
|
||||
if (mfaRedirect) return mfaRedirect
|
||||
|
||||
// Validate redirect_uri against allowlist (prevents open redirect). Passing
|
||||
// the authenticated client makes the trust boundary explicit (SOC 2 CC6.1).
|
||||
if (!(await isAllowedRedirectUri(redirectUri, supabase))) {
|
||||
// Validate redirect_uri against the allowlist (prevents open redirect) and
|
||||
// resolve who the client is. DB-registered URIs are bound to the consenting
|
||||
// user: only their own or a colleague's registration counts, so a stranger
|
||||
// cannot register a callback and phish consent from every account on the
|
||||
// instance (SOC 2 CC6.1).
|
||||
const resolution = await resolveRedirectUri(redirectUri, undefined, { consentingUserId: user.id })
|
||||
if (!resolution.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
|
||||
{ status: 400 }
|
||||
@@ -238,6 +249,7 @@ export async function GET(request: Request) {
|
||||
const companyId = await getActiveCompanyId(supabase, user.id)
|
||||
|
||||
let companyName: string | null = null
|
||||
let role: string | null = null
|
||||
if (companyId) {
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
@@ -245,15 +257,41 @@ export async function GET(request: Request) {
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
companyName = settings?.company_name || user.email || null
|
||||
|
||||
// The user's role in the company shown on this page caps what the page
|
||||
// may offer (viewer = read-only). A failed lookup is a hard stop, not a
|
||||
// silent downgrade or widening.
|
||||
const lookup = await lookupCompanyRole(supabase, user.id, companyId)
|
||||
if (lookup.error) {
|
||||
return NextResponse.json(
|
||||
{ error: 'server_error', error_description: 'Could not resolve your role in the company' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
role = lookup.role
|
||||
}
|
||||
|
||||
const appNameLower = escapeHtml(getBranding().appName.toLowerCase())
|
||||
|
||||
// Client identity and the host the browser will be sent to after consent.
|
||||
// Both are shown unconditionally so a look-alike registration cannot pass
|
||||
// for Claude and the user always sees where the code is going.
|
||||
const client = describeClient(resolution)
|
||||
const redirectHost = new URL(redirectUri).host
|
||||
const clientRowsHtml = `<div class="fact">
|
||||
<span class="fact-label">Klient</span>
|
||||
<span class="fact-value">${escapeHtml(client.name)} <span class="fact-tag${client.verified ? ' verified' : ''}">${escapeHtml(client.tag)}</span></span>
|
||||
</div>
|
||||
<div class="fact">
|
||||
<span class="fact-label">Skickar dig vidare till</span>
|
||||
<span class="fact-value fact-host">${escapeHtml(redirectHost)}</span>
|
||||
</div>`
|
||||
|
||||
const accountRowHtml = companyName
|
||||
? `<span class="account-label">Företag</span>
|
||||
<span class="account-name">${escapeHtml(companyName)}</span>`
|
||||
: `<span class="account-label">Konto</span>
|
||||
<span class="account-name">${escapeHtml(user.email ?? '')}</span>`
|
||||
? `<span class="fact-label">Företag</span>
|
||||
<span class="fact-value">${escapeHtml(companyName)}</span>`
|
||||
: `<span class="fact-label">Konto</span>
|
||||
<span class="fact-value">${escapeHtml(user.email ?? '')}</span>`
|
||||
const noCompanyNoteHtml = companyId
|
||||
? ''
|
||||
: `<p class="note">Du har inget företag i ${appNameLower} ännu. Du kan ansluta ändå: skapa företaget i appen så använder anslutningen det automatiskt, utan att du behöver ansluta på nytt.</p>`
|
||||
@@ -271,25 +309,71 @@ export async function GET(request: Request) {
|
||||
const scopeBindingValue = scopeParam ?? ''
|
||||
const scopeBindingSignature = signScopeBinding(scopeBindingValue)
|
||||
|
||||
// Two-level model for the consent UI:
|
||||
// Three inputs shape the consent UI:
|
||||
//
|
||||
// - Client requested specific scopes → ceiling = that set, pre-checked =
|
||||
// that set (RFC 6749 §3.3 strict least-privilege).
|
||||
// - Client passed no scope (or only the legacy `mcp` marker, Claude's
|
||||
// connector today) → ceiling = ALL_SCOPES and pre-checked = ALL_SCOPES:
|
||||
// one-click consent (founder decision 2026-08-26; the read-only default
|
||||
// killed the agent flow with an insufficient-scope dead-end mid-chat).
|
||||
// The mitigations that make full-by-default defensible: every write is
|
||||
// STAGED for explicit approval before anything touches the ledger, the
|
||||
// full scope list stays on the page (collapsed but expandable) with
|
||||
// every row untickable, the warn line states the staging rule above the
|
||||
// button, and the grant is revocable under Inställningar › API-nycklar.
|
||||
// RFC 6749 §3.3 lets the resource owner authorise the set presented;
|
||||
// the consent is the click on a page that shows exactly that set.
|
||||
const grantCeiling = new Set<ApiKeyScope>(parsed.scopes ?? ALL_SCOPES)
|
||||
const preChecked = new Set<ApiKeyScope>(parsed.scopes ?? ALL_SCOPES)
|
||||
// - Ceiling: the client's requested scopes (RFC 6749 §3.3 strict
|
||||
// least-privilege), or ALL_SCOPES when it passed none (or only the
|
||||
// legacy `mcp` marker, Claude's connector today), then capped to what
|
||||
// the user's role in the selected company permits (viewer = read-only).
|
||||
// Rows outside the ceiling are not rendered; the POST handler enforces
|
||||
// the same bound server-side.
|
||||
// - Pre-checked, built-in client (Claude, ChatGPT, localhost): the whole
|
||||
// ceiling. One-click consent (founder decision 2026-08-26; the read-only
|
||||
// default killed the agent flow with an insufficient-scope dead-end
|
||||
// mid-chat). The mitigations that make full-by-default defensible: every
|
||||
// write is STAGED for explicit approval before anything touches the
|
||||
// ledger, the full scope list stays on the page (collapsed but
|
||||
// expandable) with every row untickable, the warn line states the
|
||||
// staging rule above the button, and the grant is revocable under
|
||||
// Inställningar › API-nycklar. RFC 6749 §3.3 lets the resource owner
|
||||
// authorise the set presented; the consent is the click on a page that
|
||||
// shows exactly that set.
|
||||
// - Pre-checked, DB-registered client: only what it explicitly asked for,
|
||||
// or the :read scopes when it asked for nothing. Write and approve
|
||||
// scopes stay unticked until the user opts in: a registration is just a
|
||||
// URL some member typed into settings, not a vetted integration.
|
||||
const clientCeiling: ApiKeyScope[] = parsed.scopes ?? [...ALL_SCOPES]
|
||||
const roleCapped = companyId ? capScopesForRole(clientCeiling, role) : clientCeiling
|
||||
if (roleCapped.length === 0) {
|
||||
return errorRedirect(
|
||||
request,
|
||||
redirectUri,
|
||||
state,
|
||||
'invalid_scope',
|
||||
'None of the requested scopes are available to your role in this company'
|
||||
)
|
||||
}
|
||||
const roleLimited = roleCapped.length < clientCeiling.length
|
||||
const grantCeiling = new Set<ApiKeyScope>(roleCapped)
|
||||
const preChecked = new Set<ApiKeyScope>(
|
||||
resolution.kind === 'built_in' || parsed.scopes
|
||||
? roleCapped
|
||||
: roleCapped.filter((s) => scopeKind(s) === 'read')
|
||||
)
|
||||
const allPreChecked = preChecked.size === grantCeiling.size
|
||||
const ceilingHasWrite = roleCapped.some((s) => scopeKind(s) === 'write')
|
||||
const scopeCheckboxesHtml = renderScopeCheckboxes(preChecked, grantCeiling)
|
||||
|
||||
const ledeHtml = !ceilingHasWrite
|
||||
? `${escapeHtml(client.name)} begär läsåtkomst till ditt ${appNameLower}-konto. Inga skrivbehörigheter ingår.`
|
||||
: allPreChecked
|
||||
? `${escapeHtml(client.name)} begär åtkomst till ditt ${appNameLower}-konto. Alla behörigheter är förvalda; varje skrivning kräver ändå ditt godkännande innan den bokförs.`
|
||||
: `${escapeHtml(client.name)} begär åtkomst till ditt ${appNameLower}-konto. Endast läsbehörigheter är förvalda: skrivbehörigheter måste du själv välja nedan, och varje skrivning kräver ändå ditt godkännande innan den bokförs.`
|
||||
const roleNoteHtml = roleLimited
|
||||
? `<p class="note">Din roll i företaget är läsare, så bara läsbehörigheter kan ges här.</p>`
|
||||
: ''
|
||||
const summaryHintHtml = allPreChecked
|
||||
? 'Alla förvalda · visa och justera'
|
||||
: 'Endast läs förvalt · visa och justera'
|
||||
// Segregation of duties: a key that can both stage and approve lets the
|
||||
// agent commit bookkeeping without a human review in the app. Mirrors
|
||||
// app/api/settings/api-keys, where the same combination needs an explicit
|
||||
// acknowledgement: here the statement sits above the button and the token
|
||||
// route records the consent click as that acknowledgement.
|
||||
const sodNoteHtml = findStageApproveConflict(roleCapped)
|
||||
? ` Ger du både skriv- och godkännandebehörighet kan klienten både förbereda och godkänna bokföring utan din granskning i ${appNameLower}; ditt godkännande här registreras som ett medgivande till det.`
|
||||
: ''
|
||||
|
||||
// Render consent page
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="sv">
|
||||
@@ -388,31 +472,59 @@ export async function GET(request: Request) {
|
||||
line-height: 1.55;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.account {
|
||||
.facts {
|
||||
background: var(--muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0 0.875rem;
|
||||
margin-bottom: 1.75rem;
|
||||
}
|
||||
.fact {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
background: var(--muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.75rem 0.875rem;
|
||||
margin-bottom: 1.75rem;
|
||||
padding: 0.625rem 0;
|
||||
}
|
||||
.account-label {
|
||||
.fact + .fact { border-top: 1px solid var(--border); }
|
||||
.fact-label {
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--fg-faint);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.account-name {
|
||||
.fact-value {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--fg);
|
||||
text-align: right;
|
||||
word-break: break-word;
|
||||
}
|
||||
.fact-host {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
.fact-tag {
|
||||
display: inline-block;
|
||||
margin-left: 0.375rem;
|
||||
font-size: 0.625rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
padding: 0.0625rem 0.375rem;
|
||||
border-radius: 4px;
|
||||
background: var(--secondary);
|
||||
color: var(--fg-muted);
|
||||
border: 1px solid var(--border-strong);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.fact-tag.verified {
|
||||
background: hsl(140 40% 94%);
|
||||
color: hsl(150 45% 24%);
|
||||
border-color: hsl(140 35% 78%);
|
||||
}
|
||||
.note {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--fg-muted);
|
||||
@@ -636,12 +748,16 @@ export async function GET(request: Request) {
|
||||
<main class="card" role="main">
|
||||
<div class="eyebrow">${appNameLower} · mcp</div>
|
||||
<h1>Anslut MCP-klient</h1>
|
||||
<p class="lede">En extern applikation begär åtkomst till ditt ${appNameLower}-konto. Alla behörigheter är förvalda; varje skrivning kräver ändå ditt godkännande innan den bokförs.</p>
|
||||
<p class="lede">${ledeHtml}</p>
|
||||
|
||||
<div class="account">
|
||||
${accountRowHtml}
|
||||
<div class="facts">
|
||||
${clientRowsHtml}
|
||||
<div class="fact">
|
||||
${accountRowHtml}
|
||||
</div>
|
||||
</div>
|
||||
${noCompanyNoteHtml}
|
||||
${roleNoteHtml}
|
||||
|
||||
<form method="POST" action="${escapeHtml(url.pathname + url.search)}" id="consent-form">
|
||||
<input type="hidden" name="scope_binding" value="${escapeHtml(scopeBindingValue)}">
|
||||
@@ -650,7 +766,7 @@ export async function GET(request: Request) {
|
||||
<details class="scopes-details">
|
||||
<summary>
|
||||
<span class="scopes-title">Behörigheter</span>
|
||||
<span class="scopes-summary-hint">Alla förvalda · visa och justera</span>
|
||||
<span class="scopes-summary-hint">${summaryHintHtml}</span>
|
||||
<svg class="scopes-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M6 4l4 4-4 4" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||
</summary>
|
||||
<div class="scopes-header">
|
||||
@@ -670,7 +786,7 @@ export async function GET(request: Request) {
|
||||
<path d="M8 5v3.5" stroke-linecap="round"/>
|
||||
<circle cx="8" cy="11" r="0.5" fill="currentColor" stroke="none"/>
|
||||
</svg>
|
||||
<span>Skrivbehörigheter låter agenten stagea verifikationer, fakturor och löner. Varje skrivoperation kräver ditt godkännande i ${appNameLower} innan den skrivs till databasen.</span>
|
||||
<span>Skrivbehörigheter låter agenten stagea verifikationer, fakturor och löner. Varje skrivoperation kräver ditt godkännande i ${appNameLower} innan den skrivs till databasen.${sodNoteHtml}</span>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
@@ -711,7 +827,7 @@ export async function GET(request: Request) {
|
||||
// returns a 303 to the OAuth client's callback (e.g. claude.ai), and CSP
|
||||
// form-action re-checks every hop in the redirect chain. With only 'self'
|
||||
// the browser would block the post-consent redirect. The origin is safe
|
||||
// to whitelist here because isAllowedRedirectUri() already gated it above.
|
||||
// to whitelist here because resolveRedirectUri() already gated it above.
|
||||
const redirectOrigin = new URL(redirectUri).origin
|
||||
const csp = [
|
||||
"default-src 'none'",
|
||||
@@ -760,19 +876,16 @@ export async function POST(request: Request) {
|
||||
const mfaRedirect = await requireAal2(supabase, user, request)
|
||||
if (mfaRedirect) return mfaRedirect
|
||||
|
||||
// Pass the authenticated client so the lookup is bound to the same session
|
||||
// that the consent display ran under (SOC 2 CC6.1).
|
||||
if (!(await isAllowedRedirectUri(redirectUri, supabase))) {
|
||||
// Same binding as GET: a DB-registered URI must be the consenting user's own
|
||||
// or a colleague's registration (SOC 2 CC6.1).
|
||||
const resolution = await resolveRedirectUri(redirectUri, undefined, { consentingUserId: user.id })
|
||||
if (!resolution.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// No company check here: the auth code carries only the user id, and the
|
||||
// token endpoint resolves (or leaves unbound) the company when it mints the
|
||||
// key. An account without a company may consent (issue #1814).
|
||||
|
||||
// Parse form body
|
||||
const formData = await request.formData()
|
||||
const consent = formData.get('consent')
|
||||
@@ -781,6 +894,27 @@ export async function POST(request: Request) {
|
||||
return errorRedirect(request, redirectUri, state, 'access_denied', 'User denied the request')
|
||||
}
|
||||
|
||||
// The company the consent page showed and the user's role in it. Null for
|
||||
// an account without a company (issue #1814): consent still goes through
|
||||
// uncapped and the token endpoint mints the key unbound. The role caps the
|
||||
// grant below and is re-checked at /token against the same company, which
|
||||
// travels in the code payload.
|
||||
const companyId = await getActiveCompanyId(supabase, user.id)
|
||||
let role: string | null = null
|
||||
if (companyId) {
|
||||
const lookup = await lookupCompanyRole(supabase, user.id, companyId)
|
||||
if (lookup.error) {
|
||||
return errorRedirect(
|
||||
request,
|
||||
redirectUri,
|
||||
state,
|
||||
'server_error',
|
||||
'Could not resolve your role in the company'
|
||||
)
|
||||
}
|
||||
role = lookup.role
|
||||
}
|
||||
|
||||
// Verify the scope binding signed at consent display matches what was
|
||||
// submitted with the form. This pins the form to the GET that minted it,
|
||||
// so an attacker who tricks the user into submitting a crafted form can't
|
||||
@@ -813,7 +947,7 @@ export async function POST(request: Request) {
|
||||
return errorRedirect(request, redirectUri, state, 'invalid_scope', parsed.description)
|
||||
}
|
||||
|
||||
// The user selects scopes via checkboxes on the consent page. Two upper
|
||||
// The user selects scopes via checkboxes on the consent page. Three upper
|
||||
// bounds apply server-side, regardless of what the form posts:
|
||||
//
|
||||
// 1. validateScopes drops any value that isn't in API_KEY_SCOPES: guards
|
||||
@@ -830,14 +964,27 @@ export async function POST(request: Request) {
|
||||
// resource owner's instructions"). The silent fallback when the
|
||||
// user selects nothing remains DEFAULT_OAUTH_SCOPES (read-only),
|
||||
// preserving GDPR Art. 25(2) data-protection-by-default.
|
||||
// 3. The ceiling is capped to the user's role in the selected company: a
|
||||
// viewer cannot hand an agent write scopes the viewer does not hold
|
||||
// themselves, however the form was built.
|
||||
const submittedScopes = formData.getAll('scopes').filter((s): s is string => typeof s === 'string')
|
||||
const validated = validateScopes(submittedScopes)
|
||||
const clientCeiling: ApiKeyScope[] = parsed.scopes ?? [...ALL_SCOPES]
|
||||
const ceilingSet = new Set<ApiKeyScope>(clientCeiling)
|
||||
const roleCapped = companyId ? capScopesForRole(clientCeiling, role) : clientCeiling
|
||||
const ceilingSet = new Set<ApiKeyScope>(roleCapped)
|
||||
const boundedToClient = (validated ?? []).filter(s => ceilingSet.has(s))
|
||||
const grantedScopes: ApiKeyScope[] = boundedToClient.length > 0
|
||||
? boundedToClient
|
||||
: [...DEFAULT_OAUTH_SCOPES].filter(s => ceilingSet.has(s))
|
||||
if (grantedScopes.length === 0) {
|
||||
return errorRedirect(
|
||||
request,
|
||||
redirectUri,
|
||||
state,
|
||||
'invalid_scope',
|
||||
'None of the requested scopes are available to your role in this company'
|
||||
)
|
||||
}
|
||||
|
||||
// Create auth code with userId (NO API key: that's created at /token after PKCE)
|
||||
const code = createAuthCode({
|
||||
@@ -845,6 +992,7 @@ export async function POST(request: Request) {
|
||||
codeChallenge,
|
||||
redirectUri,
|
||||
scopes: grantedScopes,
|
||||
companyId,
|
||||
})
|
||||
|
||||
// Redirect to callback with the code
|
||||
@@ -865,9 +1013,9 @@ export async function POST(request: Request) {
|
||||
* Render the scope checkbox UI grouped by domain. Only scopes in `ceiling`
|
||||
* are surfaced: scopes outside the ceiling are dropped from the consent UI
|
||||
* so the user can't tick boxes that the POST handler would refuse anyway.
|
||||
* The ceiling is either the client's `scope` querystring (when specified)
|
||||
* or DEFAULT_OAUTH_SCOPES (when the client passed no scope), matching the
|
||||
* server-side enforcement in the POST handler.
|
||||
* The ceiling is the client's `scope` querystring (or ALL_SCOPES when it
|
||||
* passed none) capped to the user's role, matching the server-side
|
||||
* enforcement in the POST handler.
|
||||
*/
|
||||
function renderScopeCheckboxes(
|
||||
preChecked: Set<ApiKeyScope>,
|
||||
@@ -928,6 +1076,33 @@ function scopeRow(scope: ApiKeyScope, checked: boolean, kind: 'read' | 'write'):
|
||||
`
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable identity of the client behind an allowed redirect URI, for
|
||||
* the consent page. Built-in patterns are named after the connector that owns
|
||||
* the callback host (and marked verified, since only that vendor can receive
|
||||
* the code there); DB registrations show the name the registering member
|
||||
* typed in settings, tagged with who registered it, never as verified.
|
||||
*/
|
||||
function describeClient(
|
||||
resolution: Exclude<RedirectUriResolution, { allowed: false }>,
|
||||
): { name: string; tag: string; verified: boolean } {
|
||||
if (resolution.kind === 'built_in') {
|
||||
switch (resolution.provider) {
|
||||
case 'claude':
|
||||
return { name: 'Claude (Anthropic)', tag: 'Verifierad', verified: true }
|
||||
case 'chatgpt':
|
||||
return { name: 'ChatGPT (OpenAI)', tag: 'Verifierad', verified: true }
|
||||
case 'local':
|
||||
return { name: 'Lokal utveckling (localhost)', tag: 'Din egen dator', verified: false }
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: resolution.clientName,
|
||||
tag: resolution.registeredByConsentingUser ? 'Registrerad av dig' : 'Registrerad av en kollega',
|
||||
verified: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every interpolation into the consent-page template goes through this,
|
||||
* including the form's own action attribute (url.pathname + url.search).
|
||||
|
||||
@@ -15,10 +15,14 @@ import { truncateIp } from '@/lib/api/v1/with-api-v1'
|
||||
*
|
||||
* Security model:
|
||||
* - Anonymous by design (RFC 7591 §3 allows it); the endpoint does NOT
|
||||
* write to oauth_client_registrations: only owner/admin users can
|
||||
* write to oauth_client_registrations: members with a writer role
|
||||
* insert via /api/settings/oauth-clients. This endpoint just echoes
|
||||
* a client_id back to callers whose redirect_uris are already on the
|
||||
* allowlist.
|
||||
* - With no user session there is nobody to bind a DB registration to, so
|
||||
* any active registration passes here. That is harmless: a code is only
|
||||
* ever minted at /authorize, which accepts a registered URI solely for
|
||||
* the registering user and their colleagues (lib/auth/oauth-allowlist.ts).
|
||||
* - Per-/24 sliding-window rate-limit prevents the endpoint being used
|
||||
* as a high-rate oracle for enumerating registered URIs.
|
||||
* - Error responses are uniform across "built-in", "DB-registered", and
|
||||
|
||||
@@ -36,9 +36,32 @@ function formRequest(body: Record<string, string>) {
|
||||
})
|
||||
}
|
||||
|
||||
const codeExchange = {
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
}
|
||||
|
||||
/**
|
||||
* Query results in the order handleAuthorizationCodeGrant issues them:
|
||||
* used-code insert, expired-code cleanup, (role lookup when a company is
|
||||
* known), api_keys insert. The role step is skipped for companyless grants.
|
||||
*/
|
||||
function exchangeResults(role: { role: string } | null | 'skip' = { role: 'owner' }) {
|
||||
const results: { data?: unknown; error?: unknown }[] = [
|
||||
{ data: null, error: null }, // insert into oauth_used_codes
|
||||
{ data: null, error: null }, // delete expired codes (best-effort)
|
||||
]
|
||||
if (role !== 'skip') results.push({ data: role, error: null }) // company_members role
|
||||
results.push({ data: null, error: null }) // insert into api_keys
|
||||
return results
|
||||
}
|
||||
|
||||
describe('POST /api/mcp-oauth/token', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
})
|
||||
|
||||
describe('grant_type validation', () => {
|
||||
@@ -72,20 +95,9 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null }, // insert into oauth_used_codes
|
||||
{ data: null, error: null }, // delete expired codes (best-effort)
|
||||
{ data: null, error: null }, // insert into api_keys
|
||||
])
|
||||
enqueueMany(exchangeResults())
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.access_token).toMatch(/^gnubok_sk_/)
|
||||
@@ -97,11 +109,14 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
it('mints an unbound key (company_id null) when the user has no company yet', async () => {
|
||||
// Signup inside the OAuth popup (issue #1814): the account exists, the
|
||||
// company does not. The key is stored unbound and validateApiKey binds
|
||||
// it on the first call after the company is created.
|
||||
// it on the first call after the company is created. No company means
|
||||
// no role to cap against: the consented scopes go through as-is.
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['companies:read', 'companies:write'],
|
||||
companyId: null,
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
vi.mocked(verifyPkce).mockReturnValue(true)
|
||||
@@ -109,28 +124,19 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null }, // insert into oauth_used_codes
|
||||
{ data: null, error: null }, // delete expired codes (best-effort)
|
||||
{ data: null, error: null }, // insert into api_keys
|
||||
])
|
||||
enqueueMany(exchangeResults('skip'))
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.access_token).toMatch(/^gnubok_sk_/)
|
||||
expect(body.scope).toBe('companies:read companies:write')
|
||||
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted).toBeDefined()
|
||||
expect(inserted.user_id).toBe('user-1')
|
||||
expect(inserted.company_id).toBeNull()
|
||||
expect(findCall('company_members', 'select')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects an already-used auth code (replay)', async () => {
|
||||
@@ -146,14 +152,7 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueue({ data: null, error: { message: 'unique violation' } })
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe('invalid_grant')
|
||||
@@ -168,14 +167,7 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
})
|
||||
vi.mocked(verifyPkce).mockReturnValue(false)
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'wrong',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest({ ...codeExchange, code_verifier: 'wrong' }))
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe('invalid_grant')
|
||||
@@ -183,6 +175,180 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('company binding and role cap', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(verifyPkce).mockReturnValue(true)
|
||||
})
|
||||
|
||||
it('binds the key to the company carried in the code instead of re-resolving the active company', async () => {
|
||||
// The consent page showed company-7 and capped the grant to the user's
|
||||
// role there; the key must land on that company, not on whatever the
|
||||
// user switched to in the meantime.
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['reports:read'],
|
||||
companyId: 'company-7',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall, findCalls } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'member' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(mocks.getActiveCompanyId).not.toHaveBeenCalled()
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted.company_id).toBe('company-7')
|
||||
// The role lookup ran against that same company.
|
||||
const eqArgs = findCalls('company_members', 'eq')
|
||||
expect(eqArgs).toContainEqual(['company_id', 'company-7'])
|
||||
expect(eqArgs).toContainEqual(['user_id', 'user-1'])
|
||||
})
|
||||
|
||||
it('viewer consent yields a read-only key even when the code carries write scopes', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:read', 'transactions:write', 'pending_operations:approve', 'reports:read'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'viewer' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.scope.split(' ').sort()).toEqual(['reports:read', 'transactions:read'])
|
||||
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted.scopes).toEqual(['transactions:read', 'reports:read'])
|
||||
expect(inserted.sod_acknowledged_at).toBeNull()
|
||||
expect(inserted.sod_acknowledged_by).toBeNull()
|
||||
})
|
||||
|
||||
it('viewer whose code carries only write scopes falls back to the read-only defaults', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['bookkeeping:write'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'viewer' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const granted = (await res.json()).scope.split(' ')
|
||||
expect(granted).toContain('reports:read')
|
||||
expect(granted).not.toContain('bookkeeping:write')
|
||||
expect(granted.every((s: string) => s.endsWith(':read'))).toBe(true)
|
||||
})
|
||||
|
||||
it('membership removed between consent and exchange caps to read-only', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:read', 'transactions:write'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults(null))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
expect((await res.json()).scope).toBe('transactions:read')
|
||||
})
|
||||
|
||||
it('records the segregation-of-duties acknowledgement when stage and approve are both granted', async () => {
|
||||
// Mirrors app/api/settings/api-keys: the combination is allowed for a
|
||||
// writer role but leaves a durable self-attestation on the key row.
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:write', 'pending_operations:approve'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'member' }))
|
||||
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
warn.mockRestore()
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted.scopes).toEqual(['transactions:write', 'pending_operations:approve'])
|
||||
expect(typeof inserted.sod_acknowledged_at).toBe('string')
|
||||
expect(inserted.sod_acknowledged_by).toBe('user-1')
|
||||
})
|
||||
|
||||
it('records no acknowledgement for a non-conflicting grant', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:write', 'pending_operations:read'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'owner' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted.sod_acknowledged_at).toBeNull()
|
||||
})
|
||||
|
||||
it('returns 500 and mints no key when the role lookup fails', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:read'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: { message: 'connection reset' } },
|
||||
])
|
||||
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
error.mockRestore()
|
||||
expect(res.status).toBe(500)
|
||||
expect((await res.json()).error).toBe('server_error')
|
||||
expect(findCall('api_keys', 'insert')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('refresh_token grant', () => {
|
||||
it('rotates both tokens and returns a fresh access_token', async () => {
|
||||
const { token: refreshToken } = generateRefreshToken()
|
||||
@@ -317,20 +483,9 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
])
|
||||
enqueueMany(exchangeResults())
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
// DEFAULT_OAUTH_SCOPES is read-only by design. Write and approval scopes
|
||||
@@ -366,25 +521,35 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
])
|
||||
enqueueMany(exchangeResults())
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.scope).toBe('transactions:read invoices:read')
|
||||
})
|
||||
|
||||
it('keeps an owner grant with write scopes intact (no cap for writer roles)', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:read', 'transactions:write', 'bookkeeping:write'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
vi.mocked(verifyPkce).mockReturnValue(true)
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'owner' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.scope).toBe('transactions:read transactions:write bookkeeping:write')
|
||||
})
|
||||
|
||||
it('rejects a code whose embedded scopes are all unknown', async () => {
|
||||
// V9.2.1 defense-in-depth: even though /authorize already filters
|
||||
// unknown scopes, the token endpoint must not silently mint a
|
||||
@@ -406,14 +571,7 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
{ data: null, error: null }, // delete expired codes
|
||||
])
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe('invalid_grant')
|
||||
|
||||
@@ -7,9 +7,11 @@ import {
|
||||
hashRefreshToken,
|
||||
createServiceClientNoCookies,
|
||||
validateScopes,
|
||||
findStageApproveConflict,
|
||||
DEFAULT_OAUTH_SCOPES,
|
||||
type ApiKeyScope,
|
||||
} from '@/lib/auth/api-keys'
|
||||
import { capScopesForRole, lookupCompanyRole } from '@/lib/auth/oauth-allowlist'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
|
||||
const ACCESS_TOKEN_TTL_SECONDS = 3600
|
||||
@@ -126,10 +128,16 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
.lt('created_at', new Date(Date.now() - 10 * 60 * 1000).toISOString())
|
||||
.then(() => {})
|
||||
|
||||
// null for an account that has no company yet (signed up from the OAuth
|
||||
// popup, issue #1814). The key is minted unbound; validateApiKey binds it
|
||||
// to the user's first company on the first call after one exists.
|
||||
const companyId = await getActiveCompanyId(supabase, payload.userId)
|
||||
// Bind the key to the company the consent page showed (carried in the code
|
||||
// payload), so the role cap below is checked against the company the user
|
||||
// actually consented for. Codes minted before the field existed, and
|
||||
// companyless consents (signed up from the OAuth popup, issue #1814),
|
||||
// resolve the active company here instead; null leaves the key unbound and
|
||||
// validateApiKey binds it on the first call after a company exists.
|
||||
const companyId =
|
||||
typeof payload.companyId === 'string' && payload.companyId.length > 0
|
||||
? payload.companyId
|
||||
: await getActiveCompanyId(supabase, payload.userId)
|
||||
|
||||
const { key, hash, prefix } = generateApiKey()
|
||||
const refresh = generateRefreshToken()
|
||||
@@ -155,6 +163,30 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
grantedScopes = DEFAULT_OAUTH_SCOPES
|
||||
}
|
||||
|
||||
// Re-apply the role cap /authorize computed, against the live membership:
|
||||
// a viewer's key is read-only even if the code payload says otherwise, and
|
||||
// a role demoted between consent and exchange is honoured. A failed lookup
|
||||
// is a hard stop rather than a silent downgrade or widening.
|
||||
if (companyId) {
|
||||
const lookup = await lookupCompanyRole(supabase, payload.userId, companyId)
|
||||
if (lookup.error) {
|
||||
console.error('[mcp-oauth/token] role lookup failed', { message: lookup.error })
|
||||
return NextResponse.json(
|
||||
{ error: 'server_error', error_description: 'Failed to resolve company role' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
const capped = capScopesForRole(grantedScopes, lookup.role)
|
||||
grantedScopes = capped.length > 0 ? capped : capScopesForRole(DEFAULT_OAUTH_SCOPES, lookup.role)
|
||||
}
|
||||
|
||||
// Segregation of duties, mirrored from app/api/settings/api-keys: a key
|
||||
// that can both stage and approve is recorded as an acknowledged risk
|
||||
// acceptance. The consent page states the rule above the Allow button, so
|
||||
// the consent click is the self-attestation (ASVS V16.1.1 / SOC 2 CC6.1).
|
||||
const conflictingScope = findStageApproveConflict(grantedScopes)
|
||||
const sodAcknowledgedAt = conflictingScope ? new Date().toISOString() : null
|
||||
|
||||
const { error: insertError } = await supabase
|
||||
.from('api_keys')
|
||||
.insert({
|
||||
@@ -165,6 +197,10 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
name: OAUTH_MCP_KEY_NAME,
|
||||
scopes: grantedScopes,
|
||||
refresh_token_hash: refresh.hash,
|
||||
// Literal keys (null when no conflict): the no-phantom-columns scanner
|
||||
// resolves object literals only, never spreads.
|
||||
sod_acknowledged_at: sodAcknowledgedAt,
|
||||
sod_acknowledged_by: sodAcknowledgedAt ? payload.userId : null,
|
||||
})
|
||||
|
||||
if (insertError) {
|
||||
@@ -181,6 +217,17 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
)
|
||||
}
|
||||
|
||||
if (conflictingScope) {
|
||||
// High-risk security event, same shape the manual create route logs.
|
||||
console.warn('[mcp-oauth/token] api_key.sod_acknowledged', {
|
||||
keyPrefix: prefix,
|
||||
conflictingScope,
|
||||
scopes: grantedScopes,
|
||||
acknowledgedBy: payload.userId,
|
||||
companyId,
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
access_token: key,
|
||||
token_type: 'Bearer',
|
||||
|
||||
Reference in New Issue
Block a user