Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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
Expand Down
8 changes: 8 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<key name>` 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.
Expand Down
18 changes: 18 additions & 0 deletions e2e/fixtures/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
};

Expand Down Expand Up @@ -490,6 +494,18 @@ export async function seedAll(): Promise<SeedOutput> {
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 },
Expand Down Expand Up @@ -566,6 +582,8 @@ export async function seedAll(): Promise<SeedOutput> {
readOnly: readOnlyApiKeyToken,
write: writeApiKeyToken,
outsiderProject: outsiderApiKeyToken,
mcpProjectAdmin: mcpProjectAdminToken,
personalProjectAdmin: personalProjectAdminToken,
},
};
}
38 changes: 38 additions & 0 deletions e2e/specs/mcp-api-key.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
1 change: 1 addition & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
21 changes: 20 additions & 1 deletion src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
);
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/lib/database/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
15 changes: 15 additions & 0 deletions src/lib/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
15 changes: 15 additions & 0 deletions src/lib/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
40 changes: 40 additions & 0 deletions src/lib/server/infra/mcp-rate-limit.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
31 changes: 31 additions & 0 deletions src/lib/server/infra/mcp-rate-limit.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
91 changes: 91 additions & 0 deletions src/modules/auth/application/apikeys.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ function apiKey(overrides: Partial<ApiKeyView> = {}): ApiKeyView {
expiresAt: null,
lastUsedAt: null,
revokedAt: null,
audience: 'api',
createdAt: '2026-08-18T00:00:00.000Z',
...overrides,
};
Expand Down Expand Up @@ -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',
});
});

Expand Down Expand Up @@ -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 () =>
Expand Down
Loading
Loading