diff --git a/.env.example b/.env.example index c5f21c21..914c354a 100644 --- a/.env.example +++ b/.env.example @@ -136,6 +136,11 @@ GITDB_ENCRYPTION_KEY="development" # Closed incidents older than this are deleted (default 365) # MONITORING_INCIDENT_RETENTION_DAYS=365 +# ─── MCP API keys (docs/adr/0005-mcp-server.md) ──────────────────────────────────────────────── +# Requests per minute allowed to each personal API key created for MCP / AI agents (429 with +# Retry-After beyond it). Per process. Default 120. +# MCP_RATE_LIMIT_PER_MINUTE=120 + # ─── CVE feed (/org//cves, "CVEs por tecnología" tab; docs/adr/0004-cve-feed.md) ───────── # Follows the CVEs published in public sources (OSV.dev, NVD, CISA KEV, FIRST EPSS) for the # technologies each organization chooses, and emits cve_feed.* events. OFF by default: with false diff --git a/CLAUDE.md b/CLAUDE.md index 0402366a..b680c62a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -739,6 +739,14 @@ Machine-to-machine requests authenticate with `Authorization: Bearer gvs_...`; ` resolves them into `locals.apiKey` and `cancanService.canApiKey()` confines a project key to its own project. +API keys have an `audience` (`api` by default, or `mcp`). An `mcp` key is always personal (project +keys are always `api`) and is meant for AI agents (ADR 0005): `canApiKey()` (async) resolves it with +the permissions of its user in every organization and project (`canForUser`, most-specific-wins, +cluster admin included). Personal `api` keys still have no role and no permissions. Vault is closed +to `mcp` keys twice: `hooks.server.ts` answers 403 on `/api/vault/**` and `canApiKey()` denies any +`*:vault:*` permission. Calls run as actor `mcp:` and are rate limited per key +(`MCP_RATE_LIMIT_PER_MINUTE`, default 120; 429 + `Retry-After`). Always `await canApiKey()`. + `organization:notifications:read` and `organization:notifications:update` gate external email recipients at the organization level; `project:notifications:update` lets project alerts add them. Existing roles are not migrated: enable them from the role editor. diff --git a/e2e/fixtures/seed.ts b/e2e/fixtures/seed.ts index 8313e908..784509ae 100644 --- a/e2e/fixtures/seed.ts +++ b/e2e/fixtures/seed.ts @@ -60,6 +60,10 @@ export type SeedOutput = { readOnly: string; write: string; outsiderProject: string; + /** Personal `mcp` key of the Project Admin persona (acts with the user's permissions, no vault). */ + mcpProjectAdmin: string; + /** Personal `api` key of the same user: has no role, so no permissions. */ + personalProjectAdmin: string; }; }; @@ -490,6 +494,18 @@ export async function seedAll(): Promise { createdByUserId: clusterAdmin.userId, }); + const { token: mcpProjectAdminToken } = await apiKeysService.createApiKey( + projectAdminUser.userId, + 'e2e-mcp-project-admin', + null, + 'mcp', + ); + const { token: personalProjectAdminToken } = await apiKeysService.createApiKey( + projectAdminUser.userId, + 'e2e-personal-project-admin', + null, + ); + return { personas: { clusterAdmin: { userId: clusterAdmin.userId, username: clusterAdmin.username }, @@ -566,6 +582,8 @@ export async function seedAll(): Promise { readOnly: readOnlyApiKeyToken, write: writeApiKeyToken, outsiderProject: outsiderApiKeyToken, + mcpProjectAdmin: mcpProjectAdminToken, + personalProjectAdmin: personalProjectAdminToken, }, }; } diff --git a/e2e/specs/mcp-api-key.spec.ts b/e2e/specs/mcp-api-key.spec.ts new file mode 100644 index 00000000..bb7735ab --- /dev/null +++ b/e2e/specs/mcp-api-key.spec.ts @@ -0,0 +1,38 @@ +import { test, expect } from '@playwright/test'; +import { getSeed } from '../fixtures/auth'; + +const seed = getSeed(); +const mcp = { Authorization: `Bearer ${seed.apiKeys.mcpProjectAdmin}` }; +const stacksUrl = `/api/state-iac/stacks?projectId=${seed.primaryProjectId}`; + +test('an mcp key gets 403 on the vault, even for a Project Admin', async ({ request }) => { + const read = await request.get(`/api/vault/secret/any-key?projectId=${seed.primaryProjectId}`, { + headers: mcp, + }); + expect(read.status()).toBe(403); + expect((await read.json()).code).toBe('forbidden'); + + const create = await request.post('/api/vault/secret', { + headers: mcp, + data: { projectId: seed.primaryProjectId, key: 'nope', values: { dev: 'x' } }, + }); + expect(create.status()).toBe(403); + expect((await create.json()).code).toBe('forbidden'); + + const exported = await request.get(`/api/vault/export?projectId=${seed.primaryProjectId}`, { + headers: mcp, + }); + expect(exported.status()).toBe(403); +}); + +test('an mcp key reads with the permissions of its user', async ({ request }) => { + const response = await request.get(stacksUrl, { headers: mcp }); + expect(response.status()).toBe(200); +}); + +test('a personal api key (not mcp) still has no permissions', async ({ request }) => { + const response = await request.get(stacksUrl, { + headers: { Authorization: `Bearer ${seed.apiKeys.personalProjectAdmin}` }, + }); + expect(response.status()).toBe(403); +}); diff --git a/src/env.ts b/src/env.ts index 536d4684..dd2e2733 100644 --- a/src/env.ts +++ b/src/env.ts @@ -51,6 +51,7 @@ export const variables = defineEnvVars({ MONITORING_FLUSH_SECONDS: optional, MONITORING_HOURLY_RETENTION_DAYS: optional, MONITORING_INCIDENT_RETENTION_DAYS: optional, + MCP_RATE_LIMIT_PER_MINUTE: optional, CVE_FEED_ENABLED: optional, CVE_FEED_SYNC_INTERVAL: optional, CVE_FEED_MIN_SEVERITY: optional, diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 32b36e97..393b3ced 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -33,10 +33,18 @@ import { SLACK_LINK_PATH, } from '#modules/notifications'; import { rememberDevOrigin } from '#lib/server/infra/notifications'; +import { apiError } from '#lib/server/api'; +import { + consumeMcpRateLimit, + createMcpRateLimiter, + parseMcpRateLimit, +} from '#lib/server/infra/mcp-rate-limit'; import { createLogger, createRequestLogger, logHttpRequest, logger } from '#lib/server/logger'; const startupLog = createLogger('startup'); +const mcpRateLimiter = createMcpRateLimiter(parseMcpRateLimit(env.MCP_RATE_LIMIT_PER_MINUTE)); + const appEnvironment = resolveAppEnvironment(env.GITOPS_ENVIRONMENT, import.meta.env.DEV, (value) => startupLog.warn({ value }, '[startup] invalid GITOPS_ENVIRONMENT, using the default'), ); @@ -215,9 +223,20 @@ const authGuard: Handle = async ({ event, resolve }) => { event.locals.apiKey = apiKey; + const isMcp = apiKey.audience === 'mcp'; + + if (isMcp) { + // vault never reaches an MCP key, whatever its user's role allows (ADR 0005) + if (pathname === '/api/vault' || pathname.startsWith('/api/vault/')) { + return apiError(403, 'forbidden', 'Vault is not available to MCP API keys'); + } + const limited = consumeMcpRateLimit(mcpRateLimiter, apiKey.id); + if (limited) return limited; + } + return runWithActor( { - name: `apikey:${apiKey.name}`, + name: `${isMcp ? 'mcp' : 'apikey'}:${apiKey.name}`, email: `apikey+${apiKey.id}@gitops.local`, apiKeyId: apiKey.id, apiKeyProjectId: apiKey.projectId, diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index 52b70513..432e05dc 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -68,6 +68,8 @@ export const ApiKeyEntity = entity('api_keys', { revokedAt: timestamp(), /** Última vez que se regeneró el secreto de la clave; null si nunca se ha rotado. */ rotatedAt: timestamp(), + /** Para qué superficie es la clave: 'api' (por defecto) o 'mcp' (agentes IA, siempre personal, sin vault). Las filas antiguas sin el campo cuentan como 'api'. */ + audience: text().default('api'), createdAt: timestamp() .notNull() .$defaultFn(() => new Date().toISOString()), diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 369d7bb4..724bc1aa 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -91,6 +91,21 @@ "close": "Dismiss what's new" }, "profile": { + "mcpOption": "For MCP / AI agents", + "mcpOptionHelp": "The key acts with your permissions in every organization and project, except the vault. Use it to connect Claude Code or another agent.", + "mcpBadge": "MCP", + "mcpSnippetTitle": "Connect Claude Code", + "mcpSnippetOnce": "Copy this now: the token and these snippets will not be shown again.", + "mcpSnippetCli": "Command", + "mcpSnippetJson": ".mcp.json file", + "apiKeysNever": "Never", + "lastUsed": "Last used", + "token": "Token", + "apiKeyCreated": "API key created", + "apiKeyRegenerated": "API key regenerated", + "apiKeyRevoked": "API key revoked", + "keyFailed": "The key could not be saved", + "namePlaceholder": "Claude Code (laptop)", "title": "Profile", "subtitle": "Manage your identity, password and API access from one place.", "account": "Account", diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index b4244f20..103cdc2f 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -91,6 +91,21 @@ "close": "Cerrar novedades" }, "profile": { + "mcpOption": "Para MCP / agentes IA", + "mcpOptionHelp": "La clave actúa con tus permisos en todas tus organizaciones y proyectos, salvo el vault. Úsala para conectar Claude Code u otro agente.", + "mcpBadge": "MCP", + "mcpSnippetTitle": "Conecta Claude Code", + "mcpSnippetOnce": "Cópialo ahora: el token y estos fragmentos no se volverán a mostrar.", + "mcpSnippetCli": "Comando", + "mcpSnippetJson": "Fichero .mcp.json", + "apiKeysNever": "Nunca", + "lastUsed": "Último uso", + "token": "Token", + "apiKeyCreated": "Clave de API creada", + "apiKeyRegenerated": "Clave de API regenerada", + "apiKeyRevoked": "Clave de API revocada", + "keyFailed": "No se pudo guardar la clave", + "namePlaceholder": "Claude Code (portátil)", "title": "Perfil", "subtitle": "Gestiona tu identidad, contraseña y acceso API desde un solo lugar.", "account": "Cuenta", diff --git a/src/lib/server/infra/mcp-rate-limit.test.ts b/src/lib/server/infra/mcp-rate-limit.test.ts new file mode 100644 index 00000000..0b3b5dbb --- /dev/null +++ b/src/lib/server/infra/mcp-rate-limit.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { RateLimiter } from './rate-limit'; +import { consumeMcpRateLimit, parseMcpRateLimit } from './mcp-rate-limit'; + +describe('consumeMcpRateLimit', () => { + it('answers 429 with Retry-After once the key is over its limit', async () => { + let now = 0; + const limiter = new RateLimiter({ limit: 2, windowMs: 60_000 }, () => now); + expect(consumeMcpRateLimit(limiter, 'k1')).toBeNull(); + expect(consumeMcpRateLimit(limiter, 'k1')).toBeNull(); + + now = 59_500; + const res = consumeMcpRateLimit(limiter, 'k1'); + expect(res?.status).toBe(429); + expect(res?.headers.get('retry-after')).toBe('1'); + expect((await res!.json()).code).toBe('rate_limited'); + + now = 1000; + expect(consumeMcpRateLimit(limiter, 'k1')?.headers.get('retry-after')).toBe('59'); + }); + + it('counts each key on its own and recovers after the window', () => { + let now = 0; + const limiter = new RateLimiter({ limit: 1, windowMs: 60_000 }, () => now); + expect(consumeMcpRateLimit(limiter, 'a')).toBeNull(); + expect(consumeMcpRateLimit(limiter, 'b')).toBeNull(); + expect(consumeMcpRateLimit(limiter, 'a')?.status).toBe(429); + now = 60_000; + expect(consumeMcpRateLimit(limiter, 'a')).toBeNull(); + }); +}); + +describe('parseMcpRateLimit', () => { + it('uses the default for missing or invalid values', () => { + expect(parseMcpRateLimit(undefined)).toBe(120); + expect(parseMcpRateLimit('abc')).toBe(120); + expect(parseMcpRateLimit('0')).toBe(120); + expect(parseMcpRateLimit('30')).toBe(30); + }); +}); diff --git a/src/lib/server/infra/mcp-rate-limit.ts b/src/lib/server/infra/mcp-rate-limit.ts new file mode 100644 index 00000000..0cbc05f7 --- /dev/null +++ b/src/lib/server/infra/mcp-rate-limit.ts @@ -0,0 +1,31 @@ +import { apiError } from '#lib/server/api'; +import { RateLimiter } from './rate-limit'; + +export const DEFAULT_MCP_RATE_LIMIT_PER_MINUTE = 120; + +/** Parses `MCP_RATE_LIMIT_PER_MINUTE`; anything that is not a positive integer falls back to the default. */ +export function parseMcpRateLimit(value: string | undefined | null): number { + const parsed = Number(value); + return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MCP_RATE_LIMIT_PER_MINUTE; +} + +/** + * Counts one request of an `mcp` key (key = api key id). Returns the 429 response when the key is + * over its limit, `null` otherwise. Per process, like every other limiter. + */ +export function consumeMcpRateLimit(limiter: RateLimiter, apiKeyId: string): Response | null { + const decision = limiter.consume(apiKeyId); + if (decision.allowed) return null; + const retryAfter = Math.max(1, Math.ceil(decision.retryAfterMs / 1000)); + return apiError( + 429, + 'rate_limited', + 'Too many requests for this MCP key. Try again later.', + undefined, + { 'retry-after': String(retryAfter) }, + ); +} + +export function createMcpRateLimiter(limitPerMinute: number): RateLimiter { + return new RateLimiter({ limit: limitPerMinute, windowMs: 60_000 }); +} diff --git a/src/modules/auth/application/apikeys.service.test.ts b/src/modules/auth/application/apikeys.service.test.ts index fefd3128..36a26316 100644 --- a/src/modules/auth/application/apikeys.service.test.ts +++ b/src/modules/auth/application/apikeys.service.test.ts @@ -15,6 +15,7 @@ function apiKey(overrides: Partial = {}): ApiKeyView { expiresAt: null, lastUsedAt: null, revokedAt: null, + audience: 'api', createdAt: '2026-08-18T00:00:00.000Z', ...overrides, }; @@ -125,6 +126,7 @@ describe('ApiKeysService', () => { keyPrefix: result.token.slice(0, 10), keyHash: expect.any(String), expiresAt: '2026-12-31T00:00:00.000Z', + audience: 'api', }); }); @@ -170,6 +172,95 @@ describe('ApiKeysService', () => { expect(repository.create).not.toHaveBeenCalled(); }); + it('creates an mcp key as a personal key and returns its audience', async () => { + const repository = createRepositoryMock(); + const service = new ApiKeysService(repository); + + const { key } = await service.createApiKey('user-1', 'Claude Code', null, 'mcp'); + + expect(repository.create).toHaveBeenCalledWith( + expect.objectContaining({ + userId: 'user-1', + projectId: null, + roleId: null, + audience: 'mcp', + }), + ); + expect(key.audience).toBe('mcp'); + }); + + it('never gives a project key the mcp audience', async () => { + const repository = createRepositoryMock(); + const service = new ApiKeysService(repository, createRoleRepositoryMock()); + + const { key } = await service.createProjectApiKey({ + projectId: 'project-1', + roleId: 'role-1', + name: 'CI', + expiresAt: null, + createdByUserId: 'user-1', + }); + + expect(key.audience).toBe('api'); + expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ audience: 'api' })); + }); + + it('authenticate returns the audience of the key', async () => { + const repository = createRepositoryMock(); + const service = new ApiKeysService(repository, undefined, undefined, undefined, { + findById: async () => ({ disabled: false, status: 'active' }), + }); + + repository.findValidByHash.mockImplementation(async () => apiKey({ audience: 'mcp' })); + await expect(service.authenticate('gvs_121212')).resolves.toMatchObject({ + userId: 'user-1', + projectId: null, + role: null, + audience: 'mcp', + }); + + repository.findValidByHash.mockImplementation(async () => apiKey()); + await expect(service.authenticate('gvs_121212')).resolves.toMatchObject({ audience: 'api' }); + }); + + it.each([ + ['disabled', { disabled: true, status: 'active' }], + ['invited', { disabled: false, status: 'invited' }], + ['missing', null], + ])('does not authenticate an mcp key of a %s user', async (_label, user) => { + const repository = createRepositoryMock(); + repository.findValidByHash.mockImplementation(async () => apiKey({ audience: 'mcp' })); + const service = new ApiKeysService(repository, undefined, undefined, undefined, { + findById: async () => user, + }); + + await expect(service.authenticate('gvs_121212')).resolves.toBeNull(); + }); + + it('authenticates an mcp key of an active user', async () => { + const repository = createRepositoryMock(); + repository.findValidByHash.mockImplementation(async () => apiKey({ audience: 'mcp' })); + const service = new ApiKeysService(repository, undefined, undefined, undefined, { + findById: async () => ({ disabled: false, status: 'active' }), + }); + + await expect(service.authenticate('gvs_121212')).resolves.toMatchObject({ audience: 'mcp' }); + }); + + it('keeps the audience when regenerating a key', async () => { + const repository = createRepositoryMock(); + repository.findById.mockImplementation(async () => apiKey({ audience: 'mcp' })); + const service = new ApiKeysService(repository); + + const { key } = await service.regenerateApiKey('user-1', 'key-1'); + + expect(key.audience).toBe('mcp'); + expect(repository.updateKeyMaterial).toHaveBeenCalledWith( + 'key-1', + expect.not.objectContaining({ audience: expect.anything() }), + ); + }); + it('authenticates a project key into a project + role identity', async () => { const repository = createRepositoryMock(); repository.findValidByHash.mockImplementation(async () => diff --git a/src/modules/auth/application/apikeys.service.ts b/src/modules/auth/application/apikeys.service.ts index fad92181..aff13939 100644 --- a/src/modules/auth/application/apikeys.service.ts +++ b/src/modules/auth/application/apikeys.service.ts @@ -28,12 +28,17 @@ type ProjectLookup = { getProject(id: string): Promise<{ id: string; organization?: { id: string } | null } | null>; }; +type UserLookup = { + findById(id: string): Promise<{ disabled?: boolean; status?: string } | null>; +}; + export class ApiKeysService { constructor( private readonly apiKeyRepository: ApiKeyRepository, private readonly roleRepository?: RoleLookup, private readonly projectLookup?: ProjectLookup, private readonly events?: EventPublisher, + private readonly userLookup?: UserLookup, ) {} async listActiveApiKeys(userId: string): Promise { @@ -76,6 +81,14 @@ export class ApiKeysService { return null; } + // an mcp key acts as its user: a missing, disabled or still invited user leaves it useless + if (key.audience === 'mcp') { + const user = key.userId ? await this.userLookup?.findById(key.userId) : null; + if (!user || user.disabled || user.status !== 'active') { + return null; + } + } + let organizationId: string | null = role?.project?.organization?.id ?? null; if (key.projectId && !organizationId && this.projectLookup) { const project = await this.projectLookup.getProject(key.projectId).catch(() => null); @@ -90,6 +103,7 @@ export class ApiKeysService { organizationId, userId: key.userId, role: role ? (role.toJson() as SessionRole) : null, + audience: key.audience, }; } @@ -97,8 +111,10 @@ export class ApiKeysService { userId: string, name: string, expiresAt: string | null, + audience: 'api' | 'mcp' = 'api', ): Promise<{ token: string; key: ApiKeyView }> { return this.persist({ + audience, userId, projectId: null, roleId: null, @@ -232,6 +248,7 @@ export class ApiKeysService { createdByUserId: string | null; name: string; expiresAt: string | null; + audience?: 'api' | 'mcp'; }): Promise<{ token: string; key: ApiKeyView }> { const name = input.name.trim(); if (!name) { @@ -255,6 +272,7 @@ export class ApiKeysService { keyPrefix, keyHash, expiresAt: input.expiresAt, + audience: input.audience ?? 'api', }); await this.publishKeyEvent('api_key.created', { @@ -278,6 +296,7 @@ export class ApiKeysService { expiresAt: input.expiresAt, lastUsedAt: null, revokedAt: null, + audience: input.audience ?? 'api', createdAt: new Date().toISOString(), }, }; diff --git a/src/modules/auth/application/cancan.service.test.ts b/src/modules/auth/application/cancan.service.test.ts index 619ca938..585caf8e 100644 --- a/src/modules/auth/application/cancan.service.test.ts +++ b/src/modules/auth/application/cancan.service.test.ts @@ -131,7 +131,7 @@ describe('CanCanService', () => { expect(legacy.permissions).toEqual(['project:vault:secrets:read', 'project:project:all']); }); - it('authorizes an api key only inside its own project', () => { + it('authorizes an api key only inside its own project', async () => { const apiKey = { projectId: 'kettu', role: role({ @@ -142,28 +142,30 @@ describe('CanCanService', () => { }), }; - expect( + await expect( service.canApiKey(apiKey, 'project:codereport:reports:create', { scope: 'project', projectId: 'kettu', }), - ).toBe(true); - expect( + ).resolves.toBe(true); + await expect( service.canApiKey(apiKey, 'project:codereport:reports:create', { scope: 'project', projectId: 'other', }), - ).toBe(false); - expect(service.canApiKey(apiKey, 'cluster:settings:read', { scope: 'cluster' })).toBe(false); - expect( + ).resolves.toBe(false); + await expect( + service.canApiKey(apiKey, 'cluster:settings:read', { scope: 'cluster' }), + ).resolves.toBe(false); + await expect( service.canApiKey(apiKey, 'project:roles:delete', { scope: 'project', projectId: 'kettu' }), - ).toBe(false); - expect( + ).resolves.toBe(false); + await expect( service.canApiKey(null, 'project:codereport:reports:create', { scope: 'project', projectId: 'kettu', }), - ).toBe(false); + ).resolves.toBe(false); }); it('matches an N-segment wildcard grant against a narrower same-resource check', () => { @@ -293,6 +295,195 @@ describe('CanCanService', () => { ); }); + describe('mcp api keys', () => { + const projectAdmin = () => + role({ + id: 'project-admin', + slug: 'project-admin', + scope: 'project', + permissions: ['project:project:all', 'project:vault:secrets:all'], + }); + const mcpKey = (userId: string | null = 'jose') => ({ + projectId: null, + userId, + role: null, + audience: 'mcp' as const, + }); + + it('resolves the permissions of its user per organization and project', async () => { + userRepository.rows.set('jose', user({ id: 'jose', role: null })); + projectLookup.organizationsByProjectId.set('kettu', 'gitops'); + userAccessRepository.rows.push( + access({ + id: 'a1', + userId: 'jose', + scope: 'organization', + organizationId: 'gitops', + role: role({ + id: 'viewer', + slug: 'viewer', + scope: 'organization', + permissions: ['organization:projects:read'], + }), + }), + access({ + id: 'a2', + userId: 'jose', + scope: 'project', + projectId: 'billing', + role: projectAdmin(), + }), + ); + + await expect( + service.canApiKey(mcpKey(), 'organization:projects:read', { + scope: 'organization', + organizationId: 'gitops', + }), + ).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey(), 'organization:projects:read', { + scope: 'organization', + organizationId: 'other', + }), + ).resolves.toBe(false); + // an organization role carries organization:projects:read into the project + await expect( + service.canApiKey(mcpKey(), 'project:project:read', { + scope: 'project', + projectId: 'kettu', + }), + ).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey(), 'project:project:delete', { + scope: 'project', + projectId: 'billing', + }), + ).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey(), 'project:project:delete', { + scope: 'project', + projectId: 'kettu', + }), + ).resolves.toBe(false); + }); + + it('lets a cluster admin key act everywhere except in the vault', async () => { + userRepository.rows.set( + 'root', + user({ id: 'root', role: role({ id: 'admin', slug: 'admin' }) }), + ); + await expect( + service.canApiKey(mcpKey('root'), 'project:project:delete', { + scope: 'project', + projectId: 'kettu', + }), + ).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey('root'), 'project:vault:secrets:read', { + scope: 'project', + projectId: 'kettu', + }), + ).resolves.toBe(false); + }); + + it('denies vault permissions even to a Project Admin', async () => { + userRepository.rows.set('jose', user({ id: 'jose', role: null })); + userAccessRepository.rows.push( + access({ + id: 'a1', + userId: 'jose', + scope: 'project', + projectId: 'kettu', + role: projectAdmin(), + }), + ); + const context = { scope: 'project' as const, projectId: 'kettu' }; + + await expect(service.can('jose', 'project:vault:secrets:read', context)).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey(), 'project:vault:secrets:read', context), + ).resolves.toBe(false); + await expect( + service.canApiKey(mcpKey(), 'project:vault:environments:read', context), + ).resolves.toBe(false); + await expect( + service.canApiKey(mcpKey(), 'organization:vault:secrets:read', { + scope: 'organization', + organizationId: 'gitops', + }), + ).resolves.toBe(false); + }); + + it('denies a disabled or still invited user', async () => { + const context = { scope: 'project' as const, projectId: 'kettu' }; + const admin = role({ id: 'admin', slug: 'admin' }); + const disabled = user({ id: 'off', role: admin }); + disabled.disabled = true; + const invited = user({ id: 'inv', role: admin }); + invited.status = 'invited'; + userRepository.rows.set('off', disabled); + userRepository.rows.set('inv', invited); + + await expect(service.canApiKey(mcpKey('off'), 'project:project:read', context)).resolves.toBe( + false, + ); + await expect(service.canApiKey(mcpKey('inv'), 'project:project:read', context)).resolves.toBe( + false, + ); + }); + + it('denies an unknown user, a missing userId and a project-bound key', async () => { + const context = { scope: 'project' as const, projectId: 'kettu' }; + await expect( + service.canApiKey(mcpKey('ghost'), 'project:project:read', context), + ).resolves.toBe(false); + await expect(service.canApiKey(mcpKey(null), 'project:project:read', context)).resolves.toBe( + false, + ); + await expect( + service.canApiKey({ ...mcpKey(), projectId: 'kettu' }, 'project:project:read', context), + ).resolves.toBe(false); + }); + + it('leaves personal api keys without permissions and project keys unchanged', async () => { + userRepository.rows.set( + 'root', + user({ id: 'root', role: role({ id: 'admin', slug: 'admin' }) }), + ); + const context = { scope: 'project' as const, projectId: 'kettu' }; + await expect( + service.canApiKey( + { projectId: null, userId: 'root', role: null, audience: 'api' }, + 'project:project:read', + context, + ), + ).resolves.toBe(false); + await expect( + service.canApiKey( + { projectId: null, userId: 'root', role: null }, + 'project:project:read', + context, + ), + ).resolves.toBe(false); + + const projectKey = { + projectId: 'kettu', + userId: null, + audience: 'api' as const, + role: role({ + id: 'r', + slug: 'dev', + scope: 'project', + permissions: ['project:vault:secrets:read'], + }), + }; + await expect( + service.canApiKey(projectKey, 'project:vault:secrets:read', context), + ).resolves.toBe(true); + }); + }); + describe('organization role authority cascades into its projects', () => { it('lets organization:projects: satisfy the matching project:* check', async () => { userRepository.rows.set('jose', user({ id: 'jose', role: null })); diff --git a/src/modules/auth/application/cancan.service.ts b/src/modules/auth/application/cancan.service.ts index 59462f86..ed5a6165 100644 --- a/src/modules/auth/application/cancan.service.ts +++ b/src/modules/auth/application/cancan.service.ts @@ -36,6 +36,12 @@ type ProjectLookup = { getProject(id: string): Promise; }; +/** `:vault:<…>` (or the legacy flat `vault:<…>`). */ +function isVaultPermission(permission: string): boolean { + const parts = permission.split(':'); + return parts[0] === 'vault' || parts[1] === 'vault'; +} + export class CanCanService { constructor( private readonly userRepository: UserLookup, @@ -94,14 +100,34 @@ export class CanCanService { /** * Authorizes a machine identity. A project-scoped key can only ever act inside its own project, * so any cluster- or cross-project context is denied regardless of the role permissions. + * + * An `mcp` key is personal and acts with the permissions of its user (most-specific-wins, like + * a session), except for vault: every `*:vault:*` permission is denied to it. Personal `api` + * keys have no role and therefore no permissions. */ - canApiKey( - apiKey: { projectId: string | null; role: PermissionRole } | null | undefined, + async canApiKey( + apiKey: + | { + projectId: string | null; + role: PermissionRole; + userId?: string | null; + audience?: 'api' | 'mcp'; + } + | null + | undefined, permission: PermissionGrant, context: CanCanContext, - ): boolean { + ): Promise { if (!apiKey) return false; + if (apiKey.audience === 'mcp') { + if (apiKey.projectId || !apiKey.userId) return false; + if (isVaultPermission(permission)) return false; + const user = await this.userRepository.findById(apiKey.userId); + if (!user || user.disabled || user.status !== 'active') return false; + return this.canForUser(user, permission, context); + } + if (apiKey.projectId) { if (context.scope !== 'project' || context.projectId !== apiKey.projectId) return false; } diff --git a/src/modules/auth/domain/entities.ts b/src/modules/auth/domain/entities.ts index fb57a239..23112ae5 100644 --- a/src/modules/auth/domain/entities.ts +++ b/src/modules/auth/domain/entities.ts @@ -76,6 +76,8 @@ export type ApiKeyView = { revokedAt: string | null; /** Última rotación del secreto (regenerar); null si nunca se ha rotado. */ rotatedAt?: string | null; + /** 'mcp' keys are personal, act with their user's permissions and never reach the vault. */ + audience: 'api' | 'mcp'; createdAt: string; }; @@ -88,6 +90,6 @@ export type AuthenticatedApiKey = { organizationId: string | null; userId: string | null; role: SessionRole | null; - /** Filled in by #124; absent means 'api'. */ + /** Absent means 'api'. */ audience?: 'api' | 'mcp'; }; diff --git a/src/modules/auth/index.ts b/src/modules/auth/index.ts index c978ab1c..21b7a778 100644 --- a/src/modules/auth/index.ts +++ b/src/modules/auth/index.ts @@ -37,6 +37,7 @@ export const apiKeysService = new ApiKeysService( roleRepository, projectService, eventBus, + userRepository, ); export const authService = new AuthService( diff --git a/src/modules/auth/infrastructure/repositories/apikey.repository.ts b/src/modules/auth/infrastructure/repositories/apikey.repository.ts index 6008cc7d..cca7dbd0 100644 --- a/src/modules/auth/infrastructure/repositories/apikey.repository.ts +++ b/src/modules/auth/infrastructure/repositories/apikey.repository.ts @@ -15,6 +15,7 @@ type ApiKeyRow = { lastUsedAt: string | null; revokedAt: string | null; rotatedAt?: string | null; + audience?: string | null; createdAt: string; }; @@ -88,6 +89,7 @@ export class ApiKeyRepository extends Repository { keyPrefix: string; keyHash: string; expiresAt: string | null; + audience?: 'api' | 'mcp'; }): Promise { await this.db.insert(ApiKeyEntity).values({ id: input.id, @@ -99,6 +101,7 @@ export class ApiKeyRepository extends Repository { keyPrefix: input.keyPrefix, keyHash: input.keyHash, expiresAt: input.expiresAt, + audience: input.audience ?? 'api', lastUsedAt: null, revokedAt: null, createdAt: new Date().toISOString(), @@ -160,6 +163,7 @@ export class ApiKeyRepository extends Repository { lastUsedAt: row.lastUsedAt, revokedAt: row.revokedAt, rotatedAt: row.rotatedAt ?? null, + audience: row.audience === 'mcp' ? 'mcp' : 'api', createdAt: row.createdAt, }; } diff --git a/src/routes/api/code-report/scan/+server.ts b/src/routes/api/code-report/scan/+server.ts index 9f09bf3c..0e223084 100644 --- a/src/routes/api/code-report/scan/+server.ts +++ b/src/routes/api/code-report/scan/+server.ts @@ -131,10 +131,10 @@ export async function POST({ request, locals }) { } if ( - !cancanService.canApiKey(apiKey, 'project:codereport:reports:create', { + !(await cancanService.canApiKey(apiKey, 'project:codereport:reports:create', { scope: 'project', projectId: project.id, - }) + })) ) { return json({ error: 'Forbidden' }, { status: 403 }); } diff --git a/src/routes/api/vault/export/+server.ts b/src/routes/api/vault/export/+server.ts index fdd51c87..4d8971bd 100644 --- a/src/routes/api/vault/export/+server.ts +++ b/src/routes/api/vault/export/+server.ts @@ -51,7 +51,7 @@ export async function GET({ url, locals }) { if (apiKey.projectId !== project.id) { return json({ error: 'Project mismatch' }, { status: 403 }); } - if (!cancanService.canApiKey(apiKey, 'project:vault:secrets:export', context)) { + if (!(await cancanService.canApiKey(apiKey, 'project:vault:secrets:export', context))) { return json({ error: 'Permission denied' }, { status: 403 }); } } else if ( diff --git a/src/routes/api/vault/secret/+server.ts b/src/routes/api/vault/secret/+server.ts index 6493e225..dab01a80 100644 --- a/src/routes/api/vault/secret/+server.ts +++ b/src/routes/api/vault/secret/+server.ts @@ -51,7 +51,7 @@ export async function POST({ request, locals }) { if (apiKey.projectId !== project.id) { return json({ error: 'Forbidden' }, { status: 403 }); } - if (!cancanService.canApiKey(apiKey, 'project:vault:secrets:create', context)) { + if (!(await cancanService.canApiKey(apiKey, 'project:vault:secrets:create', context))) { return json({ error: 'Forbidden' }, { status: 403 }); } } else if ( @@ -77,4 +77,3 @@ export async function POST({ request, locals }) { ); } } - diff --git a/src/routes/api/vault/secret/[key]/+server.ts b/src/routes/api/vault/secret/[key]/+server.ts index dcb6701a..60e5681f 100644 --- a/src/routes/api/vault/secret/[key]/+server.ts +++ b/src/routes/api/vault/secret/[key]/+server.ts @@ -14,7 +14,8 @@ function errorMessage(err: unknown) { } function notFoundStatus(err: unknown) { - return err instanceof Error && (err.message === 'Secret not found' || err.message === 'Folder not found') + return err instanceof Error && + (err.message === 'Secret not found' || err.message === 'Folder not found') ? 404 : 400; } @@ -29,7 +30,8 @@ function normalizePath(path: string | null) { async function authorize( url: URL, locals: App.Locals, - permission: 'project:vault:secrets:read' | 'project:vault:secrets:update' | 'project:vault:secrets:delete', + permission: + 'project:vault:secrets:read' | 'project:vault:secrets:update' | 'project:vault:secrets:delete', ) { const projectId = url.searchParams.get('projectId')?.trim(); if (!projectId) { @@ -53,7 +55,7 @@ async function authorize( if (apiKey.projectId !== project.id) { return { error: json({ error: 'Forbidden' }, { status: 403 }) }; } - if (!cancanService.canApiKey(apiKey, permission, context)) { + if (!(await cancanService.canApiKey(apiKey, permission, context))) { return { error: json({ error: 'Forbidden' }, { status: 403 }) }; } } else if (!(await cancanService.canSessionUser(locals.user, permission, context))) { @@ -72,7 +74,11 @@ export async function GET({ params, url, locals }) { try { const folder = await vaultService.getFolderByPath(auth.project.id, path); - const secret = await vaultService.findSecretByKey(auth.project.id, folder?.id ?? null, params.key); + const secret = await vaultService.findSecretByKey( + auth.project.id, + folder?.id ?? null, + params.key, + ); if (!secret) return json({ error: 'Secret not found' }, { status: 404 }); return json({ secret }); } catch (err) { diff --git a/src/routes/profile/+page.server.ts b/src/routes/profile/+page.server.ts index 9358d4f1..45babd41 100644 --- a/src/routes/profile/+page.server.ts +++ b/src/routes/profile/+page.server.ts @@ -27,7 +27,7 @@ export async function load({ locals }) { throw redirect(302, '/auth/login'); } - const apiKeys = await apiKeysService.listActiveApiKeys(user.id); + const apiKeys = (await apiKeysService.listActiveApiKeys(user.id)).filter((key) => !key.revokedAt); return { user: { @@ -107,10 +107,16 @@ export const actions = { } const expiresAt = expiresAtFromDays(expiresInDays || null); + const audience = formData.get('mcp') ? 'mcp' : 'api'; - const { token } = await apiKeysService.createApiKey(locals.user.id, name, expiresAt); + const { token } = await apiKeysService.createApiKey(locals.user.id, name, expiresAt, audience); - return { section: 'apiKeys', message: 'API key created.', createdKey: token }; + return { + section: 'apiKeys', + message: 'API key created.', + createdKey: token, + createdAudience: audience, + }; }, regenerateApiKey: async ({ request, locals }) => { @@ -123,9 +129,14 @@ export const actions = { return fail(400, { section: 'apiKeys', message: 'Key id is required.' }); } - const { token } = await apiKeysService.regenerateApiKey(locals.user.id, keyId); + const { token, key } = await apiKeysService.regenerateApiKey(locals.user.id, keyId); - return { section: 'apiKeys', message: 'API key regenerated.', createdKey: token }; + return { + section: 'apiKeys', + message: 'API key regenerated.', + createdKey: token, + createdAudience: key.audience, + }; }, revokeApiKey: async ({ request, locals }) => { diff --git a/src/routes/profile/+page.svelte b/src/routes/profile/+page.svelte index d5cbabba..8cd5716c 100644 --- a/src/routes/profile/+page.svelte +++ b/src/routes/profile/+page.svelte @@ -1,6 +1,6 @@