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 @@ -141,6 +141,11 @@ GITDB_ENCRYPTION_KEY="development"
# Retry-After beyond it). Per process. Default 120.
# MCP_RATE_LIMIT_PER_MINUTE=120

# OAuth 2.1 for the Claude.ai MCP connector (docs/adr/0006-mcp-oauth.md). Comma-separated URLs of the
# MCP resources GitOps may issue tokens for. Empty or absent: OAuth is off and /oauth/* and
# /.well-known/oauth-authorization-server answer 404. Manual MCP keys work either way.
# MCP_OAUTH_RESOURCES=https://mcp.cloud.getgitops.com/mcp

# ─── 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
10 changes: 10 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,16 @@ to `mcp` keys twice: `hooks.server.ts` answers 403 on `/api/vault/**` and `canAp
`*: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()`.

GitOps is also an OAuth 2.1 Authorization Server for the Claude.ai MCP connector (ADR 0006), only when
`MCP_OAUTH_RESOURCES` lists the allowed MCP URLs (otherwise every endpoint is 404). `oauthService` in
`#modules/auth` serves `/.well-known/oauth-authorization-server`, `/oauth/register` (dynamic public
clients, `oauth_clients`), `/oauth/authorize` (consent page with session; the authorization code is a
signed stateless token, single use per process), `/oauth/token` and `/oauth/revoke`. A token is a
personal `audience: 'mcp'` API key with `oauthClientId`, 1 h life and a `gvr_` refresh token (sha256 in
`refreshHash`, 30 days sliding, rotated on every use), so it goes through the normal Bearer path of
`hooks.server.ts`. The four public endpoints read no cookie and are CSRF exempt; OAuth keys cannot be
regenerated, only revoked from the profile. `GET /api/whoami` tells who a credential is.

`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
6 changes: 4 additions & 2 deletions docs/adr/0005-mcp-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ Claude Code ──MCP (HTTP + Bearer gvs_…)──▶ gitops-mcp ──REST + s
--header "Authorization: Bearer gvs_…"
```

OAuth is only required for the Claude.ai web/desktop connectors (future phase, #132).
OAuth is only required for the Claude.ai web/desktop connectors (see
[ADR 0006](0006-mcp-oauth.md), #132).

### Vault is out, with two independent barriers

Expand Down Expand Up @@ -197,4 +198,5 @@ errors become tool errors (`isError: true`) with the `code` and message, never a
## Out of scope (v1)

Vault and secrets in general; editing or deleting monitors; launching scans; alerts and channels;
State IaC (possible v2); OAuth 2.1 and Claude.ai connectors (#132).
State IaC (possible v2). OAuth 2.1 and the Claude.ai connectors are covered by
[ADR 0006](0006-mcp-oauth.md) (#132).
113 changes: 113 additions & 0 deletions docs/adr/0006-mcp-oauth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# ADR 0006: OAuth 2.1 for the MCP server, GitOps as Authorization Server

- Status: Accepted
- Date: 2026-11-30
- Issues: #132 (follows [ADR 0005](0005-mcp-server.md))

## Context

ADR 0005 authenticates MCP clients with a personal API key sent in the `Authorization` header. That
works for Claude Code, which lets you set a header. The **Claude.ai web and desktop connectors do
not**: a custom connector is added by URL and the client performs the MCP authorization flow
itself (OAuth 2.1 with PKCE, metadata discovery and dynamic client registration). Without OAuth the
MCP server cannot be used from Claude.ai.

Constraints:

- Manual MCP keys must keep working unchanged: Claude Code users and scripts depend on them.
- Permissions, audit, rate limit and the vault block already live in the Bearer path of
`hooks.server.ts`. OAuth must reuse it, not fork it.
- Every GitDB write is a commit. Short-lived state must not be written to it.
- `gitops-mcp` stays stateless and without credentials of its own (ADR 0005).

## Decision

### GitOps is the Authorization Server; `gitops-mcp` is only the Resource Server

`gitops-mcp` (a separate repository) answers `401` to unauthenticated requests and points the client
at GitOps through its protected-resource metadata. The client discovers
`/.well-known/oauth-authorization-server` on the GitOps origin and runs the flow against it.
`gitops-mcp` validates every token by calling `GET /api/whoami` with it, so an expired or revoked
token becomes an HTTP 401 and the client refreshes it.

OAuth is **opt-in**: `MCP_OAUTH_RESOURCES` is a comma-separated list of the MCP resource URLs GitOps
may issue tokens for (for example `https://mcp.cloud.getgitops.com/mcp`). Empty or absent, every
endpoint below answers `404`. The issuer is the public origin (`ORIGIN`, or the request's origin).

### A token is an MCP API key

An OAuth access token **is** a personal `audience: 'mcp'` `ApiKeyEntity` with extra fields:
`oauthClientId` (null for manual keys; old rows without it are manual), `refreshHash` (sha256 of the
refresh token) and `refreshExpiresAt`. It lives one hour (`expiresAt`). Therefore the whole Bearer
path is reused: vault block, per-key rate limit, actor `mcp:<name>`, the user's permissions, the
disabled-user check, `lastUsedAt`, and the `api_key.created` / `api_key.revoked` events. Manual and
OAuth keys coexist; OAuth tokens never replace manual keys.

### Endpoints

| Endpoint | Notes |
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /.well-known/oauth-authorization-server` | RFC 8414 metadata: `S256` only, `token_endpoint_auth_methods_supported: ['none']`, scope `mcp` |
| `POST /oauth/register` | RFC 7591 dynamic registration of **public** clients. 1-5 redirect URIs, `https` or `http` on loopback, no fragment. 20/hour per address |
| `GET /oauth/authorize` (+ form POST) | consent page, needs a session; exact `redirect_uri` match; PKCE `S256` mandatory; `resource` must be allowed |
| `POST /oauth/token` | `authorization_code` (PKCE) and `refresh_token`; form-encoded or JSON; `Cache-Control: no-store` |
| `POST /oauth/revoke` | RFC 7009; revokes the key behind an access or refresh token; always 200 |
| `GET /api/whoami` | `{ type: 'api_key', audience, name, oauth }` or `{ type: 'user', userId }`, for `gitops-mcp` |

The four public endpoints read no session cookie, are CORS-open (`Access-Control-Allow-Origin: *`,
no credentials, `OPTIONS` answered) and are exempt from the CSRF origin check: they are called by
other servers, use no cookies, and the protocol authenticates them (PKCE, refresh token).
`/oauth/authorize` is **not** exempt: its form uses the session cookie. Without a session the auth
guard stores the full URL (`/oauth/authorize?...`) in the return-to cookie and the user comes back
after `/auth/login`. The consent page cannot be framed.

### Consent

The page shows the client name (declared by the client itself, so labelled as such), the host of the
redirect URI, the signed-in user and a warning: the connector acts with the user's permissions in
all organizations and projects, never reaches the vault, and can be revoked from the profile. An
unknown client or a `redirect_uri` that is not registered shows an error page and **never
redirects**; other errors redirect with `error`, `error_description`, `state` and `iss`. The action
revalidates every parameter on the server.

### Authorization code: signed, stateless, single use per process

The code is an HMAC-signed token (`signToken`, purpose `oauth-code`, key derived from the same server
secret that signs sessions) with `userId`, `clientId`, `redirectUri`, `codeChallenge`, `resource`,
`jti` and a 60-second expiry. **Nothing is written to GitDB.** Single use is enforced with an
in-memory set of redeemed `jti` with TTL, so it is **per process**: with several replicas a code
could be redeemed once on each within its minute, still needing the PKCE verifier. Accepted, like the
other in-memory limiters.

### Tokens and refresh

`authorization_code` revalidates that the user exists, is active and not disabled, creates the key
(`<client name> (OAuth)`, 1 hour) with a `gvr_` refresh token valid 30 days, and updates the client's
`lastUsedAt` (only here, to avoid commits). `refresh_token` looks the key up by `refreshHash`,
requires it not revoked, the refresh window alive, the same `client_id` and an active user, and
**rotates** both tokens in one GitDB write (`updateKeyMaterial`); the previous access and refresh
tokens stop working. The refresh window is sliding (30 days from the last refresh).

### Profile

OAuth keys show in the profile with an "OAuth" badge, the client name and "connected until
`refreshExpiresAt`". They can be revoked and **cannot be regenerated** (the UI hides it and the
service and action refuse it).

## Consequences

- The Claude.ai connector works; Claude Code with a manual key is untouched.
- Each authorization costs two or three GitDB commits (client at registration, key at exchange,
client `lastUsedAt`), and each refresh one. The registration limit bounds abuse of the first.
- Revoking an OAuth key in the profile (or `/oauth/revoke`) cuts the connector off within the
next request, because `gitops-mcp` checks `whoami` on every call.
- Dynamic clients are never garbage collected in this phase.
- Two simultaneous refreshes with the same token can both succeed before the rotation lands; the
loser's token is invalid on its next use.

## Out of scope

Client ID Metadata Documents (CIMD) instead of dynamic registration; confidential clients and client
secrets; scopes beyond `mcp`; per-organization or per-project restriction of a grant; listing or
deleting registered clients; an admin switch to disable OAuth per organization (the environment
variable is the only switch); sharing the used-code set between replicas.
6 changes: 5 additions & 1 deletion e2e/specs/cves-api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ test.describe('/api/cves', () => {
await loginAs('orgCveFeedReader');
const watchlist = await page.request.get(`${base}/watchlist?${query}`);
expect(watchlist.status()).toBe(200);
await expect(watchlist.json()).resolves.toMatchObject({ feedEnabled: false, technologies: [] });
await expect(watchlist.json()).resolves.toMatchObject({
feedEnabled: false,
// cve-feed.spec.ts may have followed technologies before this spec runs
technologies: expect.any(Array),
});

const feed = await page.request.get(`${base}/feed?${query}`);
expect(feed.status()).toBe(200);
Expand Down
1 change: 1 addition & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export const variables = defineEnvVars({
MONITORING_HOURLY_RETENTION_DAYS: optional,
MONITORING_INCIDENT_RETENTION_DAYS: optional,
MCP_RATE_LIMIT_PER_MINUTE: optional,
MCP_OAUTH_RESOURCES: optional,
CVE_FEED_ENABLED: optional,
CVE_FEED_SYNC_INTERVAL: optional,
CVE_FEED_MIN_SEVERITY: optional,
Expand Down
10 changes: 7 additions & 3 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ import {
} from '#lib/server/app-environment';
import { runWithActor } from '#lib/server/request-context';
import { csrfForbiddenResponse, isCsrfForbidden } from '#lib/server/csrf';
import { returnToCookie } from '#lib/server/return-to';
import { OAUTH_AUTHORIZE_PATH, returnToCookie } from '#lib/server/return-to';
import { isOAuthPublicPath } from '#lib/server/oauth/http';
import {
SLACK_CALLBACK_PATH,
SLACK_COMMANDS_PATH,
Expand Down Expand Up @@ -200,7 +201,9 @@ const authGuard: Handle = async ({ event, resolve }) => {
pathname === '/auth/invitation' ||
pathname === '/auth/registration' ||
pathname === '/auth/recover-password' ||
pathname === '/auth/reset-password'
pathname === '/auth/reset-password' ||
// OAuth for MCP clients (ADR 0006): no session, no cookie; the protocol authenticates them
isOAuthPublicPath(pathname)
) {
return resolve(event);
}
Expand Down Expand Up @@ -263,7 +266,8 @@ const authGuard: Handle = async ({ event, resolve }) => {
}
const headers = new Headers({ location: '/auth/login' });
// `/gitops login`: come back to the link once signed in
if (pathname === SLACK_LINK_PATH) {
// the OAuth consent (`/oauth/authorize?...`): come back with the same query once signed in
if (pathname === SLACK_LINK_PATH || pathname === OAUTH_AUTHORIZE_PATH) {
const cookie = returnToCookie(event.cookies, `${pathname}${event.url.search}`);
if (cookie) headers.append('set-cookie', cookie);
}
Expand Down
21 changes: 21 additions & 0 deletions src/lib/database/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,32 @@ export const ApiKeyEntity = entity('api_keys', {
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'),
/** Cliente OAuth (ADR 0006) que obtuvo esta clave; null = clave manual. Las filas antiguas sin el campo son manuales. */
oauthClientId: text(),
/** sha256 del refresh token de una clave OAuth (nunca el token). */
refreshHash: text(),
/** Caducidad del refresh token de una clave OAuth (ventana deslizante). */
refreshExpiresAt: timestamp(),
createdAt: timestamp()
.notNull()
.$defaultFn(() => new Date().toISOString()),
});

// clientes OAuth públicos registrados dinámicamente (RFC 7591, ADR 0006)
export const OAuthClientEntity = entity('oauth_clients', {
id: uuid().primaryKey(),
/** Identificador público (`goc_…`) que el cliente envía como client_id. */
clientId: text().notNull(),
clientName: text().notNull(),
redirectUris: json()
.notNull()
.$defaultFn(() => []),
createdAt: timestamp()
.notNull()
.$defaultFn(() => new Date().toISOString()),
lastUsedAt: timestamp(),
});

export const UserAccessEntity = entity('user_access', {
id: uuid().primaryKey(),
userId: uuid().notNull(),
Expand Down
23 changes: 22 additions & 1 deletion src/lib/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,11 @@
"gcpDescription": "Sign in with your Google Workspace account.",
"passwordHint": "At least 8 characters.",
"languageSaved": "Language changed",
"googleSso": "Google Workspace SSO"
"googleSso": "Google Workspace SSO",
"oauthBadge": "OAuth",
"oauthConnectedUntil": "connected until",
"oauthKeyHelp": "Connected through OAuth: it renews itself. You can only revoke it.",
"oauthCannotRegenerate": "OAuth keys cannot be regenerated; revoke the connection and connect again."
},
"common": {
"loading": "Loading...",
Expand Down Expand Up @@ -3034,5 +3038,22 @@
"notFoundDescription": "It is assigned to the project but no longer shows up in the backend. It may have been deleted or renamed.",
"backToStacks": "Back to the stacks"
}
},
"oauth": {
"title": "Authorize access",
"eyebrow": "Connector",
"consentSubtitle": "An application wants to connect to your GitOps account.",
"clientName": "Application",
"clientNameNote": "This name is declared by the application itself; GitOps cannot verify it.",
"redirectsTo": "After you decide, you will be sent to",
"signedInAs": "Signed in as",
"warning": "It will act with your permissions in all your organizations and projects. It will never have access to the vault. You can revoke it from your profile.",
"allow": "Allow",
"deny": "Deny",
"errorTitle": "We cannot continue",
"errorUnknownClient": "The application is not registered or the link is incomplete. Go back to the application and try connecting again.",
"errorInvalidRedirect": "The return address does not match the one registered by the application, so nothing was authorized.",
"errorDisabled": "This connector is not enabled on this GitOps instance.",
"backToGitops": "Back to GitOps"
}
}
23 changes: 22 additions & 1 deletion src/lib/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,11 @@
"gcpDescription": "Inicio de sesión con tu cuenta de Google Workspace.",
"passwordHint": "Mínimo 8 caracteres.",
"languageSaved": "Idioma cambiado",
"googleSso": "Google Workspace SSO"
"googleSso": "Google Workspace SSO",
"oauthBadge": "OAuth",
"oauthConnectedUntil": "conectada hasta",
"oauthKeyHelp": "Conectada por OAuth: se renueva sola. Solo puedes revocarla.",
"oauthCannotRegenerate": "Las claves OAuth no se pueden regenerar; revoca la conexión y vuelve a conectar."
},
"common": {
"loading": "Cargando...",
Expand Down Expand Up @@ -3034,5 +3038,22 @@
"notFoundDescription": "Está asignado al proyecto, pero ya no aparece en el backend. Puede haberse borrado o renombrado.",
"backToStacks": "Volver a los stacks"
}
},
"oauth": {
"title": "Autorizar acceso",
"eyebrow": "Conector",
"consentSubtitle": "Una aplicación quiere conectarse a tu cuenta de GitOps.",
"clientName": "Aplicación",
"clientNameNote": "Este nombre lo declara la propia aplicación; GitOps no puede verificarlo.",
"redirectsTo": "Cuando decidas, volverás a",
"signedInAs": "Sesión iniciada como",
"warning": "Actuará con tus permisos en todas tus organizaciones y proyectos. Nunca tendrá acceso al vault. Puedes revocarlo en tu perfil.",
"allow": "Permitir",
"deny": "Denegar",
"errorTitle": "No podemos continuar",
"errorUnknownClient": "La aplicación no está registrada o el enlace está incompleto. Vuelve a la aplicación e inténtalo de nuevo.",
"errorInvalidRedirect": "La dirección de retorno no coincide con la que registró la aplicación, así que no se ha autorizado nada.",
"errorDisabled": "Este conector no está activado en esta instancia de GitOps.",
"backToGitops": "Volver a GitOps"
}
}
17 changes: 15 additions & 2 deletions src/lib/server/csrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
* ['*']` in `vite.config.ts`) so a few routes can be exempt: Slack posts its commands and forms
* as `application/x-www-form-urlencoded` without an `Origin` header, which SvelteKit would refuse
* in production. Those routes authenticate every request with Slack's HMAC signature instead.
* The OAuth endpoints for MCP clients (ADR 0006) are exempt for the same reason: they are called
* by other servers, not by a browser form, use no cookies and authenticate by the protocol itself.
*/

const FORM_CONTENT_TYPES = [
Expand All @@ -14,8 +16,19 @@ const FORM_CONTENT_TYPES = [
];
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);

/** Routes that verify their own signed requests (`X-Slack-Signature`), and nothing else. */
export const CSRF_EXEMPT_PATHS = new Set(['/api/slack/commands', '/api/slack/interactions']);
/**
* Routes that verify their own requests, and nothing else: Slack's `X-Slack-Signature`, and the
* OAuth endpoints that read no cookie and are authenticated by PKCE (`/oauth/token`), the refresh
* token (`/oauth/token`, `/oauth/revoke`) or nothing sensitive at all (`/oauth/register`).
* `/oauth/authorize` is NOT exempt: its consent form uses the session cookie.
*/
export const CSRF_EXEMPT_PATHS = new Set([
'/api/slack/commands',
'/api/slack/interactions',
'/oauth/register',
'/oauth/token',
'/oauth/revoke',
]);

function isFormContentType(header: string | null): boolean {
const type = header?.split(';', 1)[0].trim().toLowerCase() ?? '';
Expand Down
Loading
Loading