From c6a2a31b6ccc771c291cdca39bcfbccb15317a95 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 21:02:20 +0100 Subject: [PATCH 1/2] OAuth 2.1 para el conector MCP de Claude.ai (#132) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GitOps actúa como Authorization Server (metadata RFC 8414, registro dinámico, Authorization Code + PKCE S256, refresh con rotación, revoke). Cada conexión es una clave personal audience mcp con oauthClientId, revocable desde /profile. Añade GET /api/whoami y el ADR 0006. Co-Authored-By: Claude Opus 5.5 --- .env.example | 5 + CLAUDE.md | 10 + docs/adr/0005-mcp-server.md | 6 +- docs/adr/0006-mcp-oauth.md | 113 +++++ src/env.ts | 1 + src/hooks.server.ts | 10 +- src/lib/database/schemas.ts | 21 + src/lib/i18n/locales/en.json | 23 +- src/lib/i18n/locales/es.json | 23 +- src/lib/server/csrf.ts | 17 +- src/lib/server/oauth/http.ts | 69 +++ src/lib/server/return-to.ts | 5 +- .../auth/application/apikeys.service.ts | 118 +++++ .../auth/application/oauth.service.test.ts | 470 ++++++++++++++++++ src/modules/auth/application/oauth.service.ts | 344 +++++++++++++ src/modules/auth/domain/entities.ts | 6 + src/modules/auth/domain/oauth.domain.ts | 139 ++++++ src/modules/auth/index.ts | 17 + .../infrastructure/config/oauth.config.ts | 7 + .../repositories/apikey.repository.test.ts | 32 ++ .../repositories/apikey.repository.ts | 39 +- .../repositories/oauth-client.repository.ts | 49 ++ src/routes/+layout.svelte | 1 + .../oauth-authorization-server/+server.ts | 26 + src/routes/api/whoami/+server.ts | 16 + src/routes/api/whoami/server.test.ts | 37 ++ src/routes/oauth/authorize/+page.server.ts | 103 ++++ src/routes/oauth/authorize/+page.svelte | 84 ++++ src/routes/oauth/register/+server.ts | 58 +++ src/routes/oauth/revoke/+server.ts | 12 + src/routes/oauth/server.test.ts | 274 ++++++++++ src/routes/oauth/token/+server.ts | 56 +++ src/routes/profile/+page.server.ts | 11 + src/routes/profile/+page.svelte | 32 +- 34 files changed, 2212 insertions(+), 22 deletions(-) create mode 100644 docs/adr/0006-mcp-oauth.md create mode 100644 src/lib/server/oauth/http.ts create mode 100644 src/modules/auth/application/oauth.service.test.ts create mode 100644 src/modules/auth/application/oauth.service.ts create mode 100644 src/modules/auth/domain/oauth.domain.ts create mode 100644 src/modules/auth/infrastructure/config/oauth.config.ts create mode 100644 src/modules/auth/infrastructure/repositories/apikey.repository.test.ts create mode 100644 src/modules/auth/infrastructure/repositories/oauth-client.repository.ts create mode 100644 src/routes/.well-known/oauth-authorization-server/+server.ts create mode 100644 src/routes/api/whoami/+server.ts create mode 100644 src/routes/api/whoami/server.test.ts create mode 100644 src/routes/oauth/authorize/+page.server.ts create mode 100644 src/routes/oauth/authorize/+page.svelte create mode 100644 src/routes/oauth/register/+server.ts create mode 100644 src/routes/oauth/revoke/+server.ts create mode 100644 src/routes/oauth/server.test.ts create mode 100644 src/routes/oauth/token/+server.ts diff --git a/.env.example b/.env.example index 914c354a..b7a00c6c 100644 --- a/.env.example +++ b/.env.example @@ -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//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 40f57990..204c0923 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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:` 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. diff --git a/docs/adr/0005-mcp-server.md b/docs/adr/0005-mcp-server.md index 39798eb8..64970000 100644 --- a/docs/adr/0005-mcp-server.md +++ b/docs/adr/0005-mcp-server.md @@ -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 @@ -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). diff --git a/docs/adr/0006-mcp-oauth.md b/docs/adr/0006-mcp-oauth.md new file mode 100644 index 00000000..34f7e6f8 --- /dev/null +++ b/docs/adr/0006-mcp-oauth.md @@ -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:`, 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 +(` (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. diff --git a/src/env.ts b/src/env.ts index dd2e2733..de170e85 100644 --- a/src/env.ts +++ b/src/env.ts @@ -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, diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 393b3ced..481f2d2b 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -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, @@ -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); } @@ -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); } diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index 432e05dc..7246485a 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -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(), diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 724bc1aa..a4b15371 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -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...", @@ -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" } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 103cdc2f..bfd9606c 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -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...", @@ -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" } } diff --git a/src/lib/server/csrf.ts b/src/lib/server/csrf.ts index 10fe3aad..d641aec3 100644 --- a/src/lib/server/csrf.ts +++ b/src/lib/server/csrf.ts @@ -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 = [ @@ -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() ?? ''; diff --git a/src/lib/server/oauth/http.ts b/src/lib/server/oauth/http.ts new file mode 100644 index 00000000..b91d1f69 --- /dev/null +++ b/src/lib/server/oauth/http.ts @@ -0,0 +1,69 @@ +import * as env from '$app/env/private'; +import { oauthService } from '#modules/auth'; + +/** + * Shared bits of the public OAuth endpoints (ADR 0006): they are CORS-open (no credentials, no + * cookies: the protocol authenticates them), `no-store`, and 404 when OAuth is not configured. + */ +export const OAUTH_PUBLIC_PATHS = [ + '/.well-known/oauth-authorization-server', + '/oauth/register', + '/oauth/token', + '/oauth/revoke', +] as const; + +const CORS_HEADERS = { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET, POST, OPTIONS', + 'access-control-allow-headers': 'Content-Type, Authorization', + 'access-control-max-age': '86400', +}; + +export function isOAuthPublicPath(pathname: string): boolean { + return (OAUTH_PUBLIC_PATHS as readonly string[]).includes(pathname); +} + +/** Public origin of GitOps without a trailing slash: `ORIGIN` when set, the request's otherwise. */ +export function oauthIssuer(url: URL): string { + return (env.ORIGIN?.trim() || url.origin).replace(/\/+$/, ''); +} + +export function oauthJson(body: unknown, status = 200, headers: HeadersInit = {}): Response { + return Response.json(body, { + status, + headers: { 'cache-control': 'no-store', pragma: 'no-cache', ...CORS_HEADERS, ...headers }, + }); +} + +export function oauthError(status: number, error: string, description: string): Response { + return oauthJson({ error, error_description: description }, status); +} + +export function oauthDisabled(): Response { + return new Response('Not found', { status: 404 }); +} + +export function oauthPreflight(): Response { + if (!oauthService.isEnabled()) return oauthDisabled(); + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} + +/** Form-encoded (the standard) or JSON body as a flat string map; `null` when it is neither. */ +export async function readOAuthBody(request: Request): Promise | null> { + const type = request.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase(); + try { + if (type === 'application/json') { + const body: unknown = await request.json(); + if (!body || typeof body !== 'object' || Array.isArray(body)) return null; + return Object.fromEntries( + Object.entries(body).filter(([, value]) => typeof value === 'string'), + ) as Record; + } + if (type === 'application/x-www-form-urlencoded') { + return Object.fromEntries(new URLSearchParams(await request.text())); + } + } catch { + return null; + } + return null; +} diff --git a/src/lib/server/return-to.ts b/src/lib/server/return-to.ts index 8bba2917..b4d0bbad 100644 --- a/src/lib/server/return-to.ts +++ b/src/lib/server/return-to.ts @@ -1,10 +1,11 @@ import type { Cookies } from '@sveltejs/kit'; -/** Where to land after signing in, for links that need a session (`/gitops login`). */ +/** Where to land after signing in, for links that need a session (`/gitops login`, the OAuth consent). */ export const RETURN_TO_COOKIE = 'gitops_return_to'; const RETURN_TO_TTL_SECONDS = 10 * 60; /** Only these pages ask to come back after the login; everything else lands on `/` as always. */ -const RETURNABLE_PATHS = ['/notifications/slack/link']; +export const OAUTH_AUTHORIZE_PATH = '/oauth/authorize'; +const RETURNABLE_PATHS = ['/notifications/slack/link', OAUTH_AUTHORIZE_PATH]; /** A same-origin path of `RETURNABLE_PATHS` (with its query), or `null`. */ export function safeReturnPath(value: string | undefined | null): string | null { diff --git a/src/modules/auth/application/apikeys.service.ts b/src/modules/auth/application/apikeys.service.ts index aff13939..ef54e18c 100644 --- a/src/modules/auth/application/apikeys.service.ts +++ b/src/modules/auth/application/apikeys.service.ts @@ -20,6 +20,21 @@ function generateToken(): { token: string; keyPrefix: string; keyHash: string } return { token, keyPrefix: token.slice(0, PREFIX_LENGTH), keyHash: hashApiKey(token) }; } +const REFRESH_PREFIX = 'gvr_'; + +function generateRefreshToken(): { refreshToken: string; refreshHash: string } { + const refreshToken = `${REFRESH_PREFIX}${crypto.randomBytes(32).toString('hex')}`; + return { refreshToken, refreshHash: hashApiKey(refreshToken) }; +} + +export type OAuthKeyResult = { + /** Clear-text access token (`gvs_…`), only returned here. */ + token: string; + /** Clear-text refresh token (`gvr_…`), only returned here. */ + refreshToken: string; + key: ApiKeyView; +}; + type RoleLookup = { findById(id: string): Promise; }; @@ -104,6 +119,7 @@ export class ApiKeysService { userId: key.userId, role: role ? (role.toJson() as SessionRole) : null, audience: key.audience, + oauth: Boolean(key.oauthClientId), }; } @@ -144,6 +160,93 @@ export class ApiKeysService { }); } + /** + * Creates the key behind an OAuth grant (ADR 0006): a personal `mcp` key with a short life and a + * refresh token (only its hash is stored). Goes through `persist`, so `api_key.created` is + * published like for any key. + */ + async createOAuthApiKey(input: { + userId: string; + oauthClientId: string; + name: string; + expiresAt: string; + refreshExpiresAt: string; + }): Promise { + const { refreshToken, refreshHash } = generateRefreshToken(); + const { token, key } = await this.persist({ + audience: 'mcp', + userId: input.userId, + projectId: null, + roleId: null, + createdByUserId: input.userId, + name: input.name, + expiresAt: input.expiresAt, + oauth: { + clientId: input.oauthClientId, + refreshHash, + refreshExpiresAt: input.refreshExpiresAt, + }, + }); + return { token, refreshToken, key }; + } + + /** The OAuth key a refresh token belongs to, whatever its state (revoked, expired…). */ + async findOAuthKeyByRefreshToken(refreshToken: string): Promise { + const normalized = refreshToken.trim(); + if (!normalized.startsWith(REFRESH_PREFIX)) return null; + const key = await this.apiKeyRepository.findByRefreshHash(hashApiKey(normalized)); + return key?.oauthClientId ? key : null; + } + + /** + * Rotates both tokens of an OAuth key in a single write: the previous access and refresh tokens + * stop working at once. The sliding refresh window restarts. + */ + async rotateOAuthKey( + existing: ApiKeyView, + input: { expiresAt: string; refreshExpiresAt: string }, + ): Promise { + if (!existing.oauthClientId) throw new Error('Not an OAuth key'); + const { token, keyPrefix, keyHash } = generateToken(); + const { refreshToken, refreshHash } = generateRefreshToken(); + + await this.apiKeyRepository.updateKeyMaterial(existing.id, { + keyPrefix, + keyHash, + expiresAt: input.expiresAt, + refreshHash, + refreshExpiresAt: input.refreshExpiresAt, + }); + + return { + token, + refreshToken, + key: { + ...existing, + keyPrefix: keyPrefix.slice(0, 6), + expiresAt: input.expiresAt, + refreshExpiresAt: input.refreshExpiresAt, + lastUsedAt: null, + revokedAt: null, + }, + }; + } + + /** + * RFC 7009: revokes the OAuth key an access or refresh token belongs to. Unknown tokens, manual + * keys and keys already revoked are ignored, so the caller can always answer 200. + */ + async revokeOAuthToken(token: string): Promise { + const normalized = token.trim(); + const key = normalized.startsWith(REFRESH_PREFIX) + ? await this.apiKeyRepository.findByRefreshHash(hashApiKey(normalized)) + : await this.apiKeyRepository.findByHashAny(hashApiKey(normalized)); + if (!key?.oauthClientId || key.revokedAt) return; + + await this.apiKeyRepository.revokeAny(key.id); + await this.publishKeyEvent('api_key.revoked', key); + } + async revokeApiKey(userId: string, keyId: string): Promise { const existing = await this.apiKeyRepository.findById(userId, keyId); @@ -204,6 +307,11 @@ export class ApiKeysService { throw new Error('API key is revoked'); } + // an OAuth key is renewed by its refresh token; its owner can only revoke it + if (existing.oauthClientId) { + throw new Error('OAuth keys cannot be regenerated'); + } + return this.rotate(existing); } @@ -249,6 +357,7 @@ export class ApiKeysService { name: string; expiresAt: string | null; audience?: 'api' | 'mcp'; + oauth?: { clientId: string; refreshHash: string; refreshExpiresAt: string }; }): Promise<{ token: string; key: ApiKeyView }> { const name = input.name.trim(); if (!name) { @@ -273,6 +382,13 @@ export class ApiKeysService { keyHash, expiresAt: input.expiresAt, audience: input.audience ?? 'api', + ...(input.oauth + ? { + oauthClientId: input.oauth.clientId, + refreshHash: input.oauth.refreshHash, + refreshExpiresAt: input.oauth.refreshExpiresAt, + } + : {}), }); await this.publishKeyEvent('api_key.created', { @@ -297,6 +413,8 @@ export class ApiKeysService { lastUsedAt: null, revokedAt: null, audience: input.audience ?? 'api', + oauthClientId: input.oauth?.clientId ?? null, + refreshExpiresAt: input.oauth?.refreshExpiresAt ?? null, createdAt: new Date().toISOString(), }, }; diff --git a/src/modules/auth/application/oauth.service.test.ts b/src/modules/auth/application/oauth.service.test.ts new file mode 100644 index 00000000..c374238a --- /dev/null +++ b/src/modules/auth/application/oauth.service.test.ts @@ -0,0 +1,470 @@ +import crypto from 'crypto'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + ACCESS_TOKEN_TTL_MS, + OAuthService, + OAuthTokenError, + REFRESH_TOKEN_TTL_MS, +} from './oauth.service'; +import { ApiKeysService } from './apikeys.service'; +import { OAuthRegistrationError, type OAuthClient } from '../domain/oauth.domain'; +import type { ApiKeyView } from '../domain/entities'; +import { RecordingEventBus } from '#lib/server/events/testing'; + +const RESOURCE = 'https://mcp.example.com/mcp'; +const REDIRECT = 'https://claude.ai/api/mcp/auth_callback'; +const VERIFIER = 'a'.repeat(64); +const CHALLENGE = crypto.createHash('sha256').update(VERIFIER).digest('base64url'); + +type Row = ApiKeyView & { keyHash: string; refreshHash: string | null }; + +/** In-memory ApiKeyRepository: just enough of it for the OAuth paths of ApiKeysService. */ +function createKeyRepository() { + const rows = new Map(); + return { + rows, + create: vi.fn(async (input: any) => { + rows.set(input.id, { + id: input.id, + name: input.name, + keyPrefix: input.keyPrefix, + userId: input.userId, + projectId: input.projectId, + roleId: input.roleId, + createdByUserId: input.createdByUserId, + expiresAt: input.expiresAt, + lastUsedAt: null, + revokedAt: null, + audience: input.audience, + oauthClientId: input.oauthClientId ?? null, + refreshExpiresAt: input.refreshExpiresAt ?? null, + createdAt: new Date().toISOString(), + keyHash: input.keyHash, + refreshHash: input.refreshHash ?? null, + }); + }), + findByRefreshHash: vi.fn(async (hash: string) => + [...rows.values()].find((row) => row.refreshHash === hash), + ), + findByHashAny: vi.fn(async (hash: string) => + [...rows.values()].find((row) => row.keyHash === hash), + ), + findValidByHash: vi.fn(async (hash: string) => { + const row = [...rows.values()].find((candidate) => candidate.keyHash === hash); + return row && !row.revokedAt ? row : null; + }), + revokeAny: vi.fn(async (id: string) => { + rows.get(id)!.revokedAt = new Date().toISOString(); + }), + updateKeyMaterial: vi.fn(async (id: string, input: any) => { + const row = rows.get(id)!; + row.keyHash = input.keyHash; + row.expiresAt = input.expiresAt; + row.refreshHash = input.refreshHash ?? row.refreshHash; + row.refreshExpiresAt = input.refreshExpiresAt ?? row.refreshExpiresAt; + }), + }; +} + +function setup(options: { resources?: string[]; user?: any } = {}) { + let now = Date.parse('2026-11-30T10:00:00.000Z'); + const keyRepository = createKeyRepository(); + const events = new RecordingEventBus(); + const user = { value: options.user ?? { disabled: false, status: 'active' } }; + const apiKeys = new ApiKeysService(keyRepository as any, undefined, undefined, events); + const clients = new Map(); + const clientStore = { + findByClientId: vi.fn(async (clientId: string) => clients.get(clientId) ?? null), + create: vi.fn(async (input: any) => { + const client = { ...input, createdAt: new Date(now).toISOString(), lastUsedAt: null }; + clients.set(input.clientId, client); + return client as OAuthClient; + }), + touchLastUsed: vi.fn(async () => {}), + }; + const service = new OAuthService({ + clients: clientStore, + keys: apiKeys, + users: { findById: vi.fn(async () => user.value) }, + secret: () => 'test-secret', + resources: () => options.resources ?? [RESOURCE], + now: () => now, + }); + return { + service, + keyRepository, + clientStore, + events, + user, + advance: (ms: number) => { + now += ms; + }, + }; +} + +async function registered(ctx: ReturnType) { + return ctx.service.register({ redirect_uris: [REDIRECT], client_name: 'Claude' }); +} + +function code(ctx: ReturnType, client: OAuthClient, overrides: any = {}) { + return ctx.service.issueCode({ + userId: 'user-1', + clientId: client.clientId, + redirectUri: REDIRECT, + codeChallenge: CHALLENGE, + resource: RESOURCE, + ...overrides, + }); +} + +function exchange( + ctx: ReturnType, + client: OAuthClient, + authCode: string, + extra = {}, +) { + return ctx.service.exchangeCode({ + code: authCode, + redirectUri: REDIRECT, + clientId: client.clientId, + codeVerifier: VERIFIER, + ...extra, + }); +} + +async function rejection(promise: Promise): Promise { + try { + await promise; + } catch (error) { + expect(error).toBeInstanceOf(OAuthTokenError); + return error as OAuthTokenError; + } + throw new Error('expected a rejection'); +} + +describe('OAuthService registration', () => { + const service = () => setup().service; + + it('registers a public client with a goc_ id and the default name', async () => { + const client = await service().register({ redirect_uris: [REDIRECT] }); + expect(client.clientId).toMatch(/^goc_[0-9a-f]{32}$/); + expect(client.clientName).toBe('MCP client'); + }); + + it('accepts http only on loopback', async () => { + for (const host of ['localhost', '127.0.0.1', '[::1]']) { + await expect( + service().register({ redirect_uris: [`http://${host}:8080/cb`] }), + ).resolves.toBeDefined(); + } + await expect( + service().register({ redirect_uris: ['http://example.com/cb'] }), + ).rejects.toMatchObject({ code: 'invalid_redirect_uri' }); + }); + + it.each([ + ['a fragment', { redirect_uris: ['https://example.com/cb#x'] }, 'invalid_redirect_uri'], + ['no redirect_uris', {}, 'invalid_redirect_uri'], + ['an empty list', { redirect_uris: [] }, 'invalid_redirect_uri'], + [ + 'more than 5 URIs', + { redirect_uris: Array.from({ length: 6 }, (_, i) => `https://example.com/${i}`) }, + 'invalid_redirect_uri', + ], + ['a non-URL', { redirect_uris: ['nope'] }, 'invalid_redirect_uri'], + [ + 'a confidential auth method', + { redirect_uris: [REDIRECT], token_endpoint_auth_method: 'client_secret_basic' }, + 'invalid_client_metadata', + ], + [ + 'a long name', + { redirect_uris: [REDIRECT], client_name: 'x'.repeat(101) }, + 'invalid_client_metadata', + ], + ])('rejects %s', async (_label, body, code) => { + const error = await service() + .register(body) + .catch((e) => e); + expect(error).toBeInstanceOf(OAuthRegistrationError); + expect(error.code).toBe(code); + }); + + it('trims the name and accepts auth method none', async () => { + const client = await service().register({ + redirect_uris: [REDIRECT], + client_name: ' Claude ', + token_endpoint_auth_method: 'none', + }); + expect(client.clientName).toBe('Claude'); + }); +}); + +describe('OAuthService authorize request', () => { + let ctx: ReturnType; + let client: OAuthClient; + const base = () => ({ + response_type: 'code', + client_id: client.clientId, + redirect_uri: REDIRECT, + code_challenge: CHALLENGE, + code_challenge_method: 'S256', + state: 'xyz', + }); + + beforeEach(async () => { + ctx = setup(); + client = await registered(ctx); + }); + + it('accepts a valid request and defaults the resource to the first allowed', async () => { + const result = await ctx.service.validateAuthorizeRequest(base()); + expect(result).toMatchObject({ ok: true, resource: RESOURCE, state: 'xyz' }); + }); + + it('shows a page, never redirects, for an unknown client or another redirect_uri', async () => { + await expect( + ctx.service.validateAuthorizeRequest({ ...base(), client_id: 'goc_nope' }), + ).resolves.toMatchObject({ ok: false, kind: 'page' }); + await expect( + ctx.service.validateAuthorizeRequest({ ...base(), redirect_uri: 'https://evil.example/cb' }), + ).resolves.toMatchObject({ ok: false, kind: 'page' }); + }); + + it.each([ + ['response_type', { response_type: 'token' }, 'unsupported_response_type'], + ['PKCE method', { code_challenge_method: 'plain' }, 'invalid_request'], + ['missing challenge', { code_challenge: undefined }, 'invalid_request'], + ['scope', { scope: 'mcp admin' }, 'invalid_scope'], + ['resource', { resource: 'https://other.example/mcp' }, 'invalid_target'], + ])('redirects the error for a bad %s', async (_label, patch, error) => { + const result = await ctx.service.validateAuthorizeRequest({ ...base(), ...patch }); + expect(result).toMatchObject({ ok: false, kind: 'redirect', redirectUri: REDIRECT, error }); + }); + + it('accepts the resource with a trailing slash', async () => { + await expect( + ctx.service.validateAuthorizeRequest({ ...base(), resource: `${RESOURCE}/`, scope: 'mcp' }), + ).resolves.toMatchObject({ ok: true, resource: RESOURCE }); + }); +}); + +describe('OAuthService authorization_code', () => { + let ctx: ReturnType; + let client: OAuthClient; + + beforeEach(async () => { + ctx = setup(); + client = await registered(ctx); + }); + + it('exchanges a code for an mcp key with a refresh token', async () => { + const response = await exchange(ctx, client, code(ctx, client), { resource: RESOURCE }); + + expect(response).toMatchObject({ token_type: 'Bearer', expires_in: 3600, scope: 'mcp' }); + expect(response.access_token).toMatch(/^gvs_/); + expect(response.refresh_token).toMatch(/^gvr_/); + + const [row] = [...ctx.keyRepository.rows.values()]; + expect(row).toMatchObject({ + audience: 'mcp', + userId: 'user-1', + projectId: null, + name: 'Claude (OAuth)', + oauthClientId: client.clientId, + }); + expect(row.expiresAt).toBe( + new Date(Date.parse('2026-11-30T10:00:00.000Z') + ACCESS_TOKEN_TTL_MS).toISOString(), + ); + expect(row.refreshExpiresAt).toBe( + new Date(Date.parse('2026-11-30T10:00:00.000Z') + REFRESH_TOKEN_TTL_MS).toISOString(), + ); + // only the hash of the refresh token is stored + expect(row.refreshHash).not.toContain('gvr_'); + expect(ctx.events.types()).toContain('api_key.created'); + expect(ctx.clientStore.touchLastUsed).toHaveBeenCalledTimes(1); + }); + + it('rejects a wrong PKCE verifier', async () => { + const error = await rejection( + exchange(ctx, client, code(ctx, client), { codeVerifier: 'b'.repeat(64) }), + ); + expect(error).toMatchObject({ code: 'invalid_grant', status: 400 }); + expect(ctx.keyRepository.rows.size).toBe(0); + }); + + it('rejects an expired code', async () => { + const authCode = code(ctx, client); + ctx.advance(61_000); + expect((await rejection(exchange(ctx, client, authCode))).code).toBe('invalid_grant'); + }); + + it('rejects a tampered code', async () => { + const authCode = code(ctx, client); + const tampered = `${authCode.slice(0, -2)}xx`; + expect((await rejection(exchange(ctx, client, tampered))).code).toBe('invalid_grant'); + }); + + it('rejects a reused code', async () => { + const authCode = code(ctx, client); + await exchange(ctx, client, authCode); + const error = await rejection(exchange(ctx, client, authCode)); + expect(error.code).toBe('invalid_grant'); + expect(ctx.keyRepository.rows.size).toBe(1); + }); + + it('rejects another redirect_uri', async () => { + const error = await rejection( + exchange(ctx, client, code(ctx, client), { redirectUri: 'https://evil.example/cb' }), + ); + expect(error.code).toBe('invalid_grant'); + }); + + it('rejects a resource that does not match the code, or is no longer allowed', async () => { + const mismatch = await rejection( + exchange(ctx, client, code(ctx, client), { resource: 'https://other.example/mcp' }), + ); + expect(mismatch.code).toBe('invalid_grant'); + + const stale = await rejection( + exchange(ctx, client, code(ctx, client, { resource: 'https://old.example/mcp' })), + ); + expect(stale.code).toBe('invalid_grant'); + }); + + it('rejects a code issued to another client', async () => { + const other = await registered(ctx); + const error = await rejection(exchange(ctx, other, code(ctx, client))); + expect(error.code).toBe('invalid_grant'); + }); + + it('answers invalid_client (401) for an unknown client and invalid_request when incomplete', async () => { + const unknown = await rejection( + ctx.service.exchangeCode({ + code: 'x', + redirectUri: REDIRECT, + clientId: 'goc_nope', + codeVerifier: VERIFIER, + }), + ); + expect(unknown).toMatchObject({ code: 'invalid_client', status: 401 }); + const incomplete = await rejection(ctx.service.exchangeCode({ code: 'x' })); + expect(incomplete.code).toBe('invalid_request'); + }); + + it.each([ + ['disabled', { disabled: true, status: 'active' }], + ['invited', { disabled: false, status: 'invited' }], + ['missing', null], + ])('rejects a %s user', async (_label, user) => { + ctx.user.value = user; + const error = await rejection(exchange(ctx, client, code(ctx, client))); + expect(error.code).toBe('invalid_grant'); + expect(ctx.keyRepository.rows.size).toBe(0); + }); +}); + +describe('OAuthService refresh and revoke', () => { + let ctx: ReturnType; + let client: OAuthClient; + let tokens: Awaited>; + + beforeEach(async () => { + ctx = setup(); + client = await registered(ctx); + tokens = await exchange(ctx, client, code(ctx, client)); + }); + + it('rotates both tokens with one write, and the old refresh token stops working', async () => { + ctx.advance(30 * 60 * 1000); + const next = await ctx.service.refresh({ + refreshToken: tokens.refresh_token, + clientId: client.clientId, + }); + + expect(next.access_token).not.toBe(tokens.access_token); + expect(next.refresh_token).not.toBe(tokens.refresh_token); + expect(ctx.keyRepository.updateKeyMaterial).toHaveBeenCalledTimes(1); + expect(ctx.keyRepository.rows.size).toBe(1); + + const [row] = [...ctx.keyRepository.rows.values()]; + expect(Date.parse(row.expiresAt!)).toBe(Date.parse('2026-11-30T11:30:00.000Z')); + expect(Date.parse(row.refreshExpiresAt!)).toBe( + Date.parse('2026-11-30T10:30:00.000Z') + REFRESH_TOKEN_TTL_MS, + ); + + const reused = await rejection( + ctx.service.refresh({ refreshToken: tokens.refresh_token, clientId: client.clientId }), + ); + expect(reused.code).toBe('invalid_grant'); + }); + + it('fails for a revoked key', async () => { + await ctx.service.revoke(tokens.access_token); + const error = await rejection( + ctx.service.refresh({ refreshToken: tokens.refresh_token, clientId: client.clientId }), + ); + expect(error.code).toBe('invalid_grant'); + }); + + it('fails for another client_id', async () => { + const other = await registered(ctx); + const error = await rejection( + ctx.service.refresh({ refreshToken: tokens.refresh_token, clientId: other.clientId }), + ); + expect(error.code).toBe('invalid_grant'); + }); + + it('fails when the refresh window is over', async () => { + ctx.advance(REFRESH_TOKEN_TTL_MS + 1000); + const error = await rejection( + ctx.service.refresh({ refreshToken: tokens.refresh_token, clientId: client.clientId }), + ); + expect(error.code).toBe('invalid_grant'); + }); + + it('fails for a disabled user and an unknown refresh token', async () => { + ctx.user.value = { disabled: true, status: 'active' }; + expect( + ( + await rejection( + ctx.service.refresh({ refreshToken: tokens.refresh_token, clientId: client.clientId }), + ) + ).code, + ).toBe('invalid_grant'); + expect( + ( + await rejection( + ctx.service.refresh({ refreshToken: 'gvr_unknown', clientId: client.clientId }), + ) + ).code, + ).toBe('invalid_grant'); + }); + + it('revokes by access token or refresh token, once, and ignores unknown tokens', async () => { + await ctx.service.revoke('gvs_unknown'); + await ctx.service.revoke(''); + expect(ctx.keyRepository.revokeAny).not.toHaveBeenCalled(); + + await ctx.service.revoke(tokens.refresh_token); + await ctx.service.revoke(tokens.access_token); + expect(ctx.keyRepository.revokeAny).toHaveBeenCalledTimes(1); + expect(ctx.events.types()).toEqual(['api_key.created', 'api_key.revoked']); + }); + + it('cannot regenerate an OAuth key', async () => { + const apiKeys = new ApiKeysService(ctx.keyRepository as any); + const [row] = [...ctx.keyRepository.rows.values()]; + (ctx.keyRepository as any).findById = vi.fn(async () => row); + await expect(apiKeys.regenerateApiKey('user-1', row.id)).rejects.toThrow( + /cannot be regenerated/, + ); + }); +}); + +describe('OAuthService enablement', () => { + it('is disabled without resources', () => { + expect(setup({ resources: [] }).service.isEnabled()).toBe(false); + expect(setup().service.isEnabled()).toBe(true); + }); +}); diff --git a/src/modules/auth/application/oauth.service.ts b/src/modules/auth/application/oauth.service.ts new file mode 100644 index 00000000..ef37ec2b --- /dev/null +++ b/src/modules/auth/application/oauth.service.ts @@ -0,0 +1,344 @@ +import crypto from 'crypto'; +import { + generateClientId, + normalizeResource, + OAUTH_SCOPE, + validateRegistration, + verifyPkceS256, + type OAuthClient, +} from '../domain/oauth.domain'; +import type { ApiKeyView } from '../domain/entities'; +import type { OAuthKeyResult } from './apikeys.service'; +import { signToken, verifySignedToken } from '#lib/server/infra/tokens'; + +/** ADR 0006: GitOps as an OAuth 2.1 Authorization Server for the MCP connector of Claude.ai. */ + +export const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000; +export const REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000; +export const AUTHORIZATION_CODE_TTL_MS = 60 * 1000; +const CODE_PURPOSE = 'oauth-code'; + +type ClientStore = { + findByClientId(clientId: string): Promise; + create(input: { + id: string; + clientId: string; + clientName: string; + redirectUris: string[]; + }): Promise; + touchLastUsed(id: string): Promise; +}; + +type KeyStore = { + createOAuthApiKey(input: { + userId: string; + oauthClientId: string; + name: string; + expiresAt: string; + refreshExpiresAt: string; + }): Promise; + findOAuthKeyByRefreshToken(refreshToken: string): Promise; + rotateOAuthKey( + existing: ApiKeyView, + input: { expiresAt: string; refreshExpiresAt: string }, + ): Promise; + revokeOAuthToken(token: string): Promise; +}; + +type UserLookup = { + findById(id: string): Promise<{ disabled?: boolean; status?: string } | null>; +}; + +export type OAuthServiceDeps = { + clients: ClientStore; + keys: KeyStore; + users: UserLookup; + /** Server secret the authorization codes are signed with (the one that signs sessions). */ + secret: () => string; + /** Allowed MCP resource URLs (`MCP_OAUTH_RESOURCES`); empty means OAuth is disabled. */ + resources: () => string[]; + now?: () => number; +}; + +export type TokenErrorCode = + 'invalid_request' | 'invalid_grant' | 'invalid_client' | 'unsupported_grant_type'; + +/** RFC 6749 error of the token endpoint; `invalid_client` is a 401, the rest a 400. */ +export class OAuthTokenError extends Error { + constructor( + readonly code: TokenErrorCode, + description: string, + ) { + super(description); + } + + get status(): number { + return this.code === 'invalid_client' ? 401 : 400; + } +} + +export type AuthorizeParams = { + response_type?: string | null; + client_id?: string | null; + redirect_uri?: string | null; + code_challenge?: string | null; + code_challenge_method?: string | null; + state?: string | null; + resource?: string | null; + scope?: string | null; +}; + +export type AuthorizeRequest = { + client: OAuthClient; + redirectUri: string; + codeChallenge: string; + resource: string; + state: string | null; +}; + +export type AuthorizeValidation = + /** The client or the redirect URI cannot be trusted: show an error page, never redirect. */ + | { ok: false; kind: 'page'; description: string } + /** The redirect URI is trusted: send the error back to it. */ + | { + ok: false; + kind: 'redirect'; + redirectUri: string; + error: string; + description: string; + state: string | null; + } + | ({ ok: true } & AuthorizeRequest); + +export type TokenResponse = { + access_token: string; + token_type: 'Bearer'; + expires_in: number; + refresh_token: string; + scope: string; +}; + +type CodePayload = { + userId: string; + clientId: string; + redirectUri: string; + codeChallenge: string; + resource: string; + jti: string; +}; + +export class OAuthService { + /** + * `jti` of the authorization codes already redeemed, with their expiry. Per process, like every + * other in-memory guard: with several replicas a code could be redeemed once on each one within + * its 60 seconds, still bound to its PKCE verifier. Expired entries are pruned on use. + */ + private readonly usedCodes = new Map(); + + constructor(private readonly deps: OAuthServiceDeps) {} + + private now(): number { + return this.deps.now?.() ?? Date.now(); + } + + /** OAuth is on only when `MCP_OAUTH_RESOURCES` lists at least one resource. */ + isEnabled(): boolean { + return this.deps.resources().length > 0; + } + + async register(body: unknown): Promise { + const { clientName, redirectUris } = validateRegistration(body); + return this.deps.clients.create({ + id: crypto.randomUUID(), + clientId: generateClientId(), + clientName, + redirectUris, + }); + } + + /** The allowed resource for a request: the one asked for, or the first configured; `null` if not allowed. */ + resolveResource(requested?: string | null): string | null { + const allowed = this.deps.resources(); + if (!requested?.trim()) return allowed[0] ?? null; + const wanted = normalizeResource(requested); + return allowed.find((candidate) => candidate === wanted) ?? null; + } + + async validateAuthorizeRequest(params: AuthorizeParams): Promise { + const clientId = params.client_id?.trim(); + const client = clientId ? await this.deps.clients.findByClientId(clientId) : null; + if (!client) return { ok: false, kind: 'page', description: 'unknown_client' }; + + const redirectUri = params.redirect_uri ?? ''; + if (!client.redirectUris.includes(redirectUri)) { + return { ok: false, kind: 'page', description: 'invalid_redirect_uri' }; + } + + const state = params.state ?? null; + const fail = (error: string, description: string): AuthorizeValidation => ({ + ok: false, + kind: 'redirect', + redirectUri, + error, + description, + state, + }); + + if (params.response_type !== 'code') { + return fail('unsupported_response_type', 'response_type must be "code"'); + } + const codeChallenge = params.code_challenge ?? ''; + if (!/^[A-Za-z0-9\-._~]{43,128}$/.test(codeChallenge)) { + return fail('invalid_request', 'A valid code_challenge is required (PKCE)'); + } + if (params.code_challenge_method !== 'S256') { + return fail('invalid_request', 'code_challenge_method must be S256'); + } + const scopes = (params.scope ?? '').split(/\s+/).filter(Boolean); + if (scopes.some((scope) => scope !== OAUTH_SCOPE)) { + return fail('invalid_scope', `The only supported scope is "${OAUTH_SCOPE}"`); + } + const resource = this.resolveResource(params.resource); + if (!resource) return fail('invalid_target', 'The resource is not allowed'); + + return { ok: true, client, redirectUri, codeChallenge, resource, state }; + } + + /** A signed, stateless, one-minute authorization code. Nothing is written to GitDB. */ + issueCode(input: Omit & { jti?: string }): string { + const payload: CodePayload = { ...input, jti: input.jti ?? crypto.randomUUID() }; + return signToken(CODE_PURPOSE, payload, { + secret: this.deps.secret(), + ttlMs: AUTHORIZATION_CODE_TTL_MS, + now: this.now(), + }); + } + + async exchangeCode(input: { + code?: string | null; + redirectUri?: string | null; + clientId?: string | null; + codeVerifier?: string | null; + resource?: string | null; + }): Promise { + const { code, redirectUri, clientId, codeVerifier } = input; + if (!code || !redirectUri || !clientId || !codeVerifier) { + throw new OAuthTokenError( + 'invalid_request', + 'code, redirect_uri, client_id and code_verifier are required', + ); + } + const client = await this.requireClient(clientId); + + const payload = verifySignedToken(CODE_PURPOSE, code, { + secret: this.deps.secret(), + now: this.now(), + }); + if (!payload) throw new OAuthTokenError('invalid_grant', 'The code is invalid or expired'); + // single use: redeemed on the first presentation, whatever happens next + if (!this.markUsed(payload.jti, payload.exp * 1000)) { + throw new OAuthTokenError('invalid_grant', 'The code was already used'); + } + + if (payload.clientId !== client.clientId) { + throw new OAuthTokenError('invalid_grant', 'The code was issued to another client'); + } + if (payload.redirectUri !== redirectUri) { + throw new OAuthTokenError('invalid_grant', 'redirect_uri does not match the authorization'); + } + if (input.resource?.trim()) { + if (normalizeResource(input.resource) !== payload.resource) { + throw new OAuthTokenError('invalid_grant', 'resource does not match the authorization'); + } + } + if (this.resolveResource(payload.resource) === null) { + throw new OAuthTokenError('invalid_grant', 'The resource is not allowed'); + } + if (!verifyPkceS256(codeVerifier, payload.codeChallenge)) { + throw new OAuthTokenError('invalid_grant', 'code_verifier does not match the challenge'); + } + await this.requireActiveUser(payload.userId); + + const now = this.now(); + const result = await this.deps.keys.createOAuthApiKey({ + userId: payload.userId, + oauthClientId: client.clientId, + name: `${client.clientName} (OAuth)`, + expiresAt: new Date(now + ACCESS_TOKEN_TTL_MS).toISOString(), + refreshExpiresAt: new Date(now + REFRESH_TOKEN_TTL_MS).toISOString(), + }); + await this.deps.clients.touchLastUsed(client.id); + return tokenResponse(result); + } + + async refresh(input: { + refreshToken?: string | null; + clientId?: string | null; + }): Promise { + const { refreshToken, clientId } = input; + if (!refreshToken || !clientId) { + throw new OAuthTokenError('invalid_request', 'refresh_token and client_id are required'); + } + const client = await this.requireClient(clientId); + + const key = await this.deps.keys.findOAuthKeyByRefreshToken(refreshToken); + const now = this.now(); + if ( + !key || + key.revokedAt || + !key.refreshExpiresAt || + Date.parse(key.refreshExpiresAt) <= now || + key.oauthClientId !== client.clientId + ) { + throw new OAuthTokenError('invalid_grant', 'The refresh token is invalid or expired'); + } + if (!key.userId) throw new OAuthTokenError('invalid_grant', 'The grant is no longer valid'); + await this.requireActiveUser(key.userId); + + const result = await this.deps.keys.rotateOAuthKey(key, { + expiresAt: new Date(now + ACCESS_TOKEN_TTL_MS).toISOString(), + refreshExpiresAt: new Date(now + REFRESH_TOKEN_TTL_MS).toISOString(), + }); + return tokenResponse(result); + } + + /** RFC 7009: never reveals whether the token existed. */ + async revoke(token: string | null | undefined): Promise { + if (!token?.trim()) return; + await this.deps.keys.revokeOAuthToken(token); + } + + private async requireClient(clientId: string): Promise { + const client = await this.deps.clients.findByClientId(clientId.trim()); + if (!client) throw new OAuthTokenError('invalid_client', 'Unknown client_id'); + return client; + } + + private async requireActiveUser(userId: string): Promise { + const user = await this.deps.users.findById(userId); + if (!user || user.disabled || user.status !== 'active') { + throw new OAuthTokenError('invalid_grant', 'The user is no longer active'); + } + } + + /** `false` when `jti` was already redeemed. */ + private markUsed(jti: string, expiresAtMs: number): boolean { + const now = this.now(); + for (const [id, exp] of this.usedCodes) { + if (exp <= now) this.usedCodes.delete(id); + } + if (this.usedCodes.has(jti)) return false; + this.usedCodes.set(jti, expiresAtMs); + return true; + } +} + +function tokenResponse(result: OAuthKeyResult): TokenResponse { + return { + access_token: result.token, + token_type: 'Bearer', + expires_in: ACCESS_TOKEN_TTL_MS / 1000, + refresh_token: result.refreshToken, + scope: OAUTH_SCOPE, + }; +} diff --git a/src/modules/auth/domain/entities.ts b/src/modules/auth/domain/entities.ts index 23112ae5..8653e44d 100644 --- a/src/modules/auth/domain/entities.ts +++ b/src/modules/auth/domain/entities.ts @@ -78,6 +78,10 @@ export type ApiKeyView = { rotatedAt?: string | null; /** 'mcp' keys are personal, act with their user's permissions and never reach the vault. */ audience: 'api' | 'mcp'; + /** Client that obtained this key through OAuth (ADR 0006); null for manual keys. */ + oauthClientId?: string | null; + /** When the refresh token of an OAuth key stops being valid (sliding window). */ + refreshExpiresAt?: string | null; createdAt: string; }; @@ -92,4 +96,6 @@ export type AuthenticatedApiKey = { role: SessionRole | null; /** Absent means 'api'. */ audience?: 'api' | 'mcp'; + /** True when the key was issued through OAuth (ADR 0006). */ + oauth?: boolean; }; diff --git a/src/modules/auth/domain/oauth.domain.ts b/src/modules/auth/domain/oauth.domain.ts new file mode 100644 index 00000000..6fadefc5 --- /dev/null +++ b/src/modules/auth/domain/oauth.domain.ts @@ -0,0 +1,139 @@ +import crypto from 'crypto'; + +/** A public OAuth client registered dynamically (RFC 7591). */ +export type OAuthClient = { + id: string; + clientId: string; + clientName: string; + redirectUris: string[]; + createdAt: string; + lastUsedAt: string | null; +}; + +export const OAUTH_SCOPE = 'mcp'; +export const MAX_REDIRECT_URIS = 5; +export const MAX_CLIENT_NAME_LENGTH = 100; +export const DEFAULT_CLIENT_NAME = 'MCP client'; + +export type RegistrationErrorCode = 'invalid_redirect_uri' | 'invalid_client_metadata'; + +export class OAuthRegistrationError extends Error { + constructor( + readonly code: RegistrationErrorCode, + description: string, + ) { + super(description); + } +} + +const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']); + +/** `https:` anywhere, `http:` only on loopback, never with a fragment. */ +export function isValidRedirectUri(value: unknown): value is string { + if (typeof value !== 'string' || value.length > 2000) return false; + let url: URL; + try { + url = new URL(value); + } catch { + return false; + } + if (url.hash || value.includes('#')) return false; + if (url.username || url.password) return false; + if (url.protocol === 'https:') return true; + return url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname); +} + +export type ValidatedRegistration = { clientName: string; redirectUris: string[] }; + +/** Validates an RFC 7591 registration body for a public client. Throws `OAuthRegistrationError`. */ +export function validateRegistration(body: unknown): ValidatedRegistration { + if (!body || typeof body !== 'object' || Array.isArray(body)) { + throw new OAuthRegistrationError('invalid_client_metadata', 'The body must be a JSON object'); + } + const input = body as Record; + + const uris = input.redirect_uris; + if (!Array.isArray(uris) || uris.length === 0) { + throw new OAuthRegistrationError('invalid_redirect_uri', 'redirect_uris is required'); + } + if (uris.length > MAX_REDIRECT_URIS) { + throw new OAuthRegistrationError( + 'invalid_redirect_uri', + `At most ${MAX_REDIRECT_URIS} redirect_uris are allowed`, + ); + } + for (const uri of uris) { + if (!isValidRedirectUri(uri)) { + throw new OAuthRegistrationError( + 'invalid_redirect_uri', + 'Each redirect URI must be https (http only for localhost) and have no fragment', + ); + } + } + + const method = input.token_endpoint_auth_method; + if (method !== undefined && method !== 'none') { + throw new OAuthRegistrationError( + 'invalid_client_metadata', + 'Only token_endpoint_auth_method "none" is supported', + ); + } + + let clientName = DEFAULT_CLIENT_NAME; + if (input.client_name !== undefined && input.client_name !== null) { + if (typeof input.client_name !== 'string') { + throw new OAuthRegistrationError('invalid_client_metadata', 'client_name must be a string'); + } + // control characters would break the consent screen and the logs + const trimmed = [...input.client_name] + .filter((char) => char.charCodeAt(0) > 31 && char.charCodeAt(0) !== 127) + .join('') + .trim(); + if (trimmed.length > MAX_CLIENT_NAME_LENGTH) { + throw new OAuthRegistrationError( + 'invalid_client_metadata', + `client_name is at most ${MAX_CLIENT_NAME_LENGTH} characters`, + ); + } + if (trimmed) clientName = trimmed; + } + + return { clientName, redirectUris: [...new Set(uris as string[])] }; +} + +/** PKCE S256: base64url(sha256(verifier)) equals the challenge, in constant time. */ +export function verifyPkceS256(codeVerifier: string, codeChallenge: string): boolean { + // RFC 7636: the verifier is 43-128 characters of [A-Za-z0-9-._~] + if (!/^[A-Za-z0-9\-._~]{43,128}$/.test(codeVerifier)) return false; + const expected = Buffer.from( + crypto.createHash('sha256').update(codeVerifier).digest('base64url'), + ); + const received = Buffer.from(codeChallenge); + return expected.length === received.length && crypto.timingSafeEqual(expected, received); +} + +/** Resource URIs compare without a trailing slash. */ +export function normalizeResource(value: string): string { + return value.trim().replace(/\/+$/, ''); +} + +/** Parses `MCP_OAUTH_RESOURCES`: comma-separated absolute URLs; anything else is dropped. */ +export function parseOAuthResources(value: string | undefined | null): string[] { + const resources: string[] = []; + for (const part of (value ?? '').split(',')) { + const candidate = normalizeResource(part); + if (!candidate) continue; + try { + const url = new URL(candidate); + if (url.protocol !== 'https:' && url.protocol !== 'http:') continue; + } catch { + continue; + } + if (!resources.includes(candidate)) resources.push(candidate); + } + return resources; +} + +export function generateClientId(): string { + return `goc_${crypto.randomBytes(16).toString('hex')}`; +} diff --git a/src/modules/auth/index.ts b/src/modules/auth/index.ts index 21b7a778..bad244e2 100644 --- a/src/modules/auth/index.ts +++ b/src/modules/auth/index.ts @@ -10,10 +10,13 @@ import { PasswordResetService } from './application/password-reset.service'; import { CanCanService } from './application/cancan.service'; import { RoleService } from './application/role.service'; import { SsoService } from './application/sso.service'; +import { OAuthService } from './application/oauth.service'; import { UserRepository } from './infrastructure/repositories/user.repository'; import { RoleRepository } from './infrastructure/repositories/role.repository'; import { ApiKeyRepository } from './infrastructure/repositories/apikey.repository'; +import { OAuthClientRepository } from './infrastructure/repositories/oauth-client.repository'; import { UserAccessRepository } from './infrastructure/repositories/user-access.repository'; +import { readOAuthResources } from './infrastructure/config/oauth.config'; import { readGoogleSsoConfig } from './infrastructure/config/google-sso.config'; import { GoogleOidcClient } from './infrastructure/oidc/google-oidc.client'; import { InvitationNotifier } from './infrastructure/notifications/invitation.notifier'; @@ -40,6 +43,20 @@ export const apiKeysService = new ApiKeysService( userRepository, ); +export const oauthService = new OAuthService({ + clients: new OAuthClientRepository(), + keys: apiKeysService, + users: userRepository, + secret: () => passwordService.ensureEncryptionKey(), + resources: readOAuthResources, +}); +export { + OAuthTokenError, + type AuthorizeValidation, + type TokenResponse, +} from './application/oauth.service'; +export { OAuthRegistrationError } from './domain/oauth.domain'; + export const authService = new AuthService( userRepository, roleRepository, diff --git a/src/modules/auth/infrastructure/config/oauth.config.ts b/src/modules/auth/infrastructure/config/oauth.config.ts new file mode 100644 index 00000000..84510dcc --- /dev/null +++ b/src/modules/auth/infrastructure/config/oauth.config.ts @@ -0,0 +1,7 @@ +import * as env from '$app/env/private'; +import { parseOAuthResources } from '../../domain/oauth.domain'; + +/** MCP resource URLs allowed by `MCP_OAUTH_RESOURCES`; empty means OAuth is off. Read on every call. */ +export function readOAuthResources(): string[] { + return parseOAuthResources(env.MCP_OAUTH_RESOURCES); +} diff --git a/src/modules/auth/infrastructure/repositories/apikey.repository.test.ts b/src/modules/auth/infrastructure/repositories/apikey.repository.test.ts new file mode 100644 index 00000000..339a1901 --- /dev/null +++ b/src/modules/auth/infrastructure/repositories/apikey.repository.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it, vi } from 'vitest'; + +const set = vi.hoisted(() => vi.fn()); + +vi.mock('#lib/server/gitdb', () => ({ + getGitDb: () => ({ + update: () => ({ set: (values: unknown) => (set(values), { where: async () => {} }) }), + }), +})); + +import { ApiKeyRepository } from './apikey.repository'; + +const material = { keyPrefix: 'gvs_abc', keyHash: 'h', expiresAt: null }; + +describe('ApiKeyRepository.updateKeyMaterial', () => { + it('does not touch revokedAt when rotating an OAuth key, so a revocation survives', async () => { + set.mockClear(); + await new ApiKeyRepository().updateKeyMaterial('k', { + ...material, + refreshHash: 'r', + refreshExpiresAt: '2026-12-30T00:00:00.000Z', + }); + expect(set.mock.calls[0][0]).not.toHaveProperty('revokedAt'); + expect(set.mock.calls[0][0]).toMatchObject({ refreshHash: 'r' }); + }); + + it('still clears revokedAt on a manual regenerate', async () => { + set.mockClear(); + await new ApiKeyRepository().updateKeyMaterial('k', material); + expect(set.mock.calls[0][0]).toMatchObject({ revokedAt: null }); + }); +}); diff --git a/src/modules/auth/infrastructure/repositories/apikey.repository.ts b/src/modules/auth/infrastructure/repositories/apikey.repository.ts index cca7dbd0..1eb1edc3 100644 --- a/src/modules/auth/infrastructure/repositories/apikey.repository.ts +++ b/src/modules/auth/infrastructure/repositories/apikey.repository.ts @@ -16,6 +16,9 @@ type ApiKeyRow = { revokedAt: string | null; rotatedAt?: string | null; audience?: string | null; + oauthClientId?: string | null; + refreshHash?: string | null; + refreshExpiresAt?: string | null; createdAt: string; }; @@ -79,6 +82,20 @@ export class ApiKeyRepository extends Repository { return this.toJSON(row); } + /** Any key (revoked or expired included) by the hash of its access token. */ + async findByHashAny(keyHash: string): Promise { + const result = await this.db.select().from(ApiKeyEntity).where({ keyHash }).limit(1); + const row = result.rows[0] as ApiKeyRow | undefined; + return row ? this.toJSON(row) : null; + } + + /** The key a refresh token (by its hash) belongs to, whatever its state; the service decides. */ + async findByRefreshHash(refreshHash: string): Promise { + const result = await this.db.select().from(ApiKeyEntity).where({ refreshHash }).limit(1); + const row = result.rows[0] as ApiKeyRow | undefined; + return row ? this.toJSON(row) : null; + } + async create(input: { id: string; userId: string | null; @@ -90,6 +107,9 @@ export class ApiKeyRepository extends Repository { keyHash: string; expiresAt: string | null; audience?: 'api' | 'mcp'; + oauthClientId?: string | null; + refreshHash?: string | null; + refreshExpiresAt?: string | null; }): Promise { await this.db.insert(ApiKeyEntity).values({ id: input.id, @@ -102,6 +122,13 @@ export class ApiKeyRepository extends Repository { keyHash: input.keyHash, expiresAt: input.expiresAt, audience: input.audience ?? 'api', + ...(input.oauthClientId + ? { + oauthClientId: input.oauthClientId, + refreshHash: input.refreshHash ?? null, + refreshExpiresAt: input.refreshExpiresAt ?? null, + } + : {}), lastUsedAt: null, revokedAt: null, createdAt: new Date().toISOString(), @@ -135,6 +162,9 @@ export class ApiKeyRepository extends Repository { keyPrefix: string; keyHash: string; expiresAt: string | null; + /** OAuth keys only: the new refresh token and its sliding expiry, in the same write. */ + refreshHash?: string; + refreshExpiresAt?: string; }, ): Promise { await this.db @@ -143,9 +173,14 @@ export class ApiKeyRepository extends Repository { keyPrefix: input.keyPrefix, keyHash: input.keyHash, expiresAt: input.expiresAt, - revokedAt: null, + // a manual regenerate revives the key; an OAuth rotation (refresh token) must never + // undo a revocation that landed after the caller checked it + ...(input.refreshHash ? {} : { revokedAt: null }), lastUsedAt: null, rotatedAt: new Date().toISOString(), + ...(input.refreshHash + ? { refreshHash: input.refreshHash, refreshExpiresAt: input.refreshExpiresAt ?? null } + : {}), }) .where({ id: keyId }); } @@ -164,6 +199,8 @@ export class ApiKeyRepository extends Repository { revokedAt: row.revokedAt, rotatedAt: row.rotatedAt ?? null, audience: row.audience === 'mcp' ? 'mcp' : 'api', + oauthClientId: row.oauthClientId ?? null, + refreshExpiresAt: row.refreshExpiresAt ?? null, createdAt: row.createdAt, }; } diff --git a/src/modules/auth/infrastructure/repositories/oauth-client.repository.ts b/src/modules/auth/infrastructure/repositories/oauth-client.repository.ts new file mode 100644 index 00000000..1faf7929 --- /dev/null +++ b/src/modules/auth/infrastructure/repositories/oauth-client.repository.ts @@ -0,0 +1,49 @@ +import { Repository } from './repository'; +import { OAuthClientEntity } from '#lib/database/schemas'; +import type { OAuthClient } from '../../domain/oauth.domain'; + +type OAuthClientRow = { + id: string; + clientId: string; + clientName: string; + redirectUris: unknown; + createdAt: string; + lastUsedAt: string | null; +}; + +export class OAuthClientRepository extends Repository { + async findByClientId(clientId: string): Promise { + const result = await this.db.select().from(OAuthClientEntity).where({ clientId }).limit(1); + const row = result.rows[0] as OAuthClientRow | undefined; + return row ? this.toJSON(row) : null; + } + + async create(input: { + id: string; + clientId: string; + clientName: string; + redirectUris: string[]; + }): Promise { + const createdAt = new Date().toISOString(); + await this.db.insert(OAuthClientEntity).values({ ...input, createdAt, lastUsedAt: null }); + return { ...input, createdAt, lastUsedAt: null }; + } + + async touchLastUsed(id: string): Promise { + await this.db + .update(OAuthClientEntity) + .set({ lastUsedAt: new Date().toISOString() }) + .where({ id }); + } + + protected override toJSON(row: OAuthClientRow): OAuthClient { + return { + id: row.id, + clientId: row.clientId, + clientName: row.clientName, + redirectUris: Array.isArray(row.redirectUris) ? (row.redirectUris as string[]) : [], + createdAt: row.createdAt, + lastUsedAt: row.lastUsedAt ?? null, + }; + } +} diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index ec021b24..8ada172b 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -43,6 +43,7 @@ pathname.startsWith('/auth/') || pathname.startsWith('/bootstrap') || pathname.startsWith('/notifications/') || + pathname.startsWith('/oauth/') || pathname === '/brand', ); diff --git a/src/routes/.well-known/oauth-authorization-server/+server.ts b/src/routes/.well-known/oauth-authorization-server/+server.ts new file mode 100644 index 00000000..32225cb4 --- /dev/null +++ b/src/routes/.well-known/oauth-authorization-server/+server.ts @@ -0,0 +1,26 @@ +import { oauthService } from '#modules/auth'; +import { oauthDisabled, oauthIssuer, oauthJson, oauthPreflight } from '#lib/server/oauth/http'; + +// GET /.well-known/oauth-authorization-server: RFC 8414 metadata (ADR 0006) +export const GET = ({ url }) => { + if (!oauthService.isEnabled()) return oauthDisabled(); + const issuer = oauthIssuer(url); + return oauthJson( + { + issuer, + authorization_endpoint: `${issuer}/oauth/authorize`, + token_endpoint: `${issuer}/oauth/token`, + registration_endpoint: `${issuer}/oauth/register`, + revocation_endpoint: `${issuer}/oauth/revoke`, + response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token'], + code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['none'], + scopes_supported: ['mcp'], + }, + 200, + { 'cache-control': 'public, max-age=3600' }, + ); +}; + +export const OPTIONS = () => oauthPreflight(); diff --git a/src/routes/api/whoami/+server.ts b/src/routes/api/whoami/+server.ts new file mode 100644 index 00000000..1442ca76 --- /dev/null +++ b/src/routes/api/whoami/+server.ts @@ -0,0 +1,16 @@ +import { apiError, ok } from '#lib/server/api'; + +// GET /api/whoami: who the credential is, cheaply. gitops-mcp calls it to validate a token and +// answer HTTP 401 so that the client refreshes it (ADR 0006) +export const GET = ({ locals }) => { + if (locals.apiKey) { + return ok({ + type: 'api_key', + audience: locals.apiKey.audience ?? 'api', + name: locals.apiKey.name, + oauth: locals.apiKey.oauth === true, + }); + } + if (locals.user) return ok({ type: 'user', userId: locals.user.id }); + return apiError(401, 'unauthorized', 'Authentication required'); +}; diff --git a/src/routes/api/whoami/server.test.ts b/src/routes/api/whoami/server.test.ts new file mode 100644 index 00000000..f3f73c64 --- /dev/null +++ b/src/routes/api/whoami/server.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { GET } from './+server'; + +const call = (locals: object) => GET({ locals } as any); + +describe('GET /api/whoami', () => { + it('describes a manual MCP key', async () => { + const response = await call({ apiKey: { id: 'k', name: 'Laptop', audience: 'mcp' } }); + expect(await response.json()).toEqual({ + type: 'api_key', + audience: 'mcp', + name: 'Laptop', + oauth: false, + }); + }); + + it('flags an OAuth key', async () => { + const response = await call({ + apiKey: { id: 'k', name: 'Claude (OAuth)', audience: 'mcp', oauth: true }, + }); + expect(await response.json()).toMatchObject({ audience: 'mcp', oauth: true }); + }); + + it('defaults the audience of a plain key to api', async () => { + const response = await call({ apiKey: { id: 'k', name: 'CI' } }); + expect(await response.json()).toMatchObject({ audience: 'api', oauth: false }); + }); + + it('describes a session', async () => { + const response = await call({ user: { id: 'user-1' } }); + expect(await response.json()).toEqual({ type: 'user', userId: 'user-1' }); + }); + + it('is 401 without authentication', async () => { + expect((await call({})).status).toBe(401); + }); +}); diff --git a/src/routes/oauth/authorize/+page.server.ts b/src/routes/oauth/authorize/+page.server.ts new file mode 100644 index 00000000..c192c999 --- /dev/null +++ b/src/routes/oauth/authorize/+page.server.ts @@ -0,0 +1,103 @@ +import { error, redirect } from '@sveltejs/kit'; +import { oauthService, type AuthorizeValidation } from '#modules/auth'; +import { oauthIssuer } from '#lib/server/oauth/http'; + +// GET /oauth/authorize: consent screen of the OAuth flow of the MCP connector (ADR 0006). The +// session is required (the auth guard sends the user to /auth/login and back with the same query). + +const PARAMS = [ + 'response_type', + 'client_id', + 'redirect_uri', + 'code_challenge', + 'code_challenge_method', + 'state', + 'resource', + 'scope', +] as const; + +function readParams(source: URLSearchParams | FormData) { + const params: Record = {}; + for (const name of PARAMS) { + const value = source.get(name); + params[name] = typeof value === 'string' ? value : null; + } + return params; +} + +/** `redirect_uri` plus the given response parameters; the client's own query is kept. */ +function callbackUrl( + redirectUri: string, + issuer: string, + state: string | null, + values: Record, +): string { + const target = new URL(redirectUri); + for (const [name, value] of Object.entries(values)) target.searchParams.set(name, value); + if (state !== null) target.searchParams.set('state', state); + target.searchParams.set('iss', issuer); + return target.toString(); +} + +function errorRedirect( + validation: Extract, + issuer: string, +) { + return callbackUrl(validation.redirectUri, issuer, validation.state, { + error: validation.error, + error_description: validation.description, + }); +} + +export async function load({ url, setHeaders }) { + if (!oauthService.isEnabled()) throw error(404, 'Not found'); + // the consent screen must not be framed (clickjacking on "Allow") + setHeaders({ 'x-frame-options': 'DENY', 'content-security-policy': "frame-ancestors 'none'" }); + + const validation = await oauthService.validateAuthorizeRequest(readParams(url.searchParams)); + if (!validation.ok) { + if (validation.kind === 'page') return { invalid: validation.description }; + throw redirect(303, errorRedirect(validation, oauthIssuer(url))); + } + + return { + invalid: null, + clientName: validation.client.clientName, + redirectHost: new URL(validation.redirectUri).host, + params: { ...readParams(url.searchParams), resource: validation.resource }, + }; +} + +export const actions = { + decision: async ({ request, locals, url }) => { + if (!locals.user) throw redirect(302, '/auth/login'); + if (!oauthService.isEnabled()) throw error(404, 'Not found'); + + const form = await request.formData(); + const validation = await oauthService.validateAuthorizeRequest(readParams(form)); + if (!validation.ok) { + if (validation.kind === 'page') throw error(400, validation.description); + throw redirect(303, errorRedirect(validation, oauthIssuer(url))); + } + + const issuer = oauthIssuer(url); + if (form.get('decision') !== 'allow') { + throw redirect( + 303, + callbackUrl(validation.redirectUri, issuer, validation.state, { + error: 'access_denied', + error_description: 'The user denied the request', + }), + ); + } + + const code = oauthService.issueCode({ + userId: locals.user.id, + clientId: validation.client.clientId, + redirectUri: validation.redirectUri, + codeChallenge: validation.codeChallenge, + resource: validation.resource, + }); + throw redirect(303, callbackUrl(validation.redirectUri, issuer, validation.state, { code })); + }, +}; diff --git a/src/routes/oauth/authorize/+page.svelte b/src/routes/oauth/authorize/+page.svelte new file mode 100644 index 00000000..ce0a4bc6 --- /dev/null +++ b/src/routes/oauth/authorize/+page.svelte @@ -0,0 +1,84 @@ + + + + + {$_('oauth.title')} - GitOps + + +{#if data.invalid !== null} + + + {data.invalid === 'invalid_redirect_uri' + ? $_('oauth.errorInvalidRedirect') + : $_('oauth.errorUnknownClient')} + + {$_('oauth.backToGitops')} + +{:else} + +
+
+
{$_('oauth.clientName')}
+
{data.clientName}
+
{$_('oauth.clientNameNote')}
+
+
+
{$_('oauth.redirectsTo')}
+
+ {data.redirectHost} +
+
+ {#if data.user} +
+
{$_('oauth.signedInAs')}
+
+ {data.user.username}{data.user.email ? ` (${data.user.email})` : ''} +
+
+ {/if} +
+ +
+ +

{$_('oauth.warning')}

+
+ +
+ {#each Object.entries(data.params) as [name, value] (name)} + {#if value !== null}{/if} + {/each} + + +
+
+{/if} diff --git a/src/routes/oauth/register/+server.ts b/src/routes/oauth/register/+server.ts new file mode 100644 index 00000000..996cf739 --- /dev/null +++ b/src/routes/oauth/register/+server.ts @@ -0,0 +1,58 @@ +import { OAuthRegistrationError, oauthService } from '#modules/auth'; +import { RateLimiter } from '#lib/server/infra/rate-limit'; +import { oauthDisabled, oauthError, oauthJson, oauthPreflight } from '#lib/server/oauth/http'; + +// POST /oauth/register: RFC 7591 dynamic registration of public clients (ADR 0006). Every client +// is a GitDB commit, so it is limited per address (per process, like the other limiters). +const registrationLimiter = new RateLimiter({ limit: 20, windowMs: 60 * 60 * 1000 }); + +function clientAddress(event: { getClientAddress(): string }): string { + try { + return event.getClientAddress(); + } catch { + return 'unknown'; + } +} + +export const POST = async (event) => { + if (!oauthService.isEnabled()) return oauthDisabled(); + + const decision = registrationLimiter.consume(clientAddress(event)); + if (!decision.allowed) { + return oauthJson( + { error: 'invalid_client_metadata', error_description: 'Too many registrations' }, + 429, + { 'retry-after': String(Math.max(1, Math.ceil(decision.retryAfterMs / 1000))) }, + ); + } + + let body: unknown; + try { + body = await event.request.json(); + } catch { + return oauthError(400, 'invalid_client_metadata', 'The body must be JSON'); + } + + try { + const client = await oauthService.register(body); + return oauthJson( + { + client_id: client.clientId, + client_id_issued_at: Math.floor(Date.parse(client.createdAt) / 1000), + client_name: client.clientName, + redirect_uris: client.redirectUris, + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'none', + }, + 201, + ); + } catch (error) { + if (error instanceof OAuthRegistrationError) { + return oauthError(400, error.code, error.message); + } + throw error; + } +}; + +export const OPTIONS = () => oauthPreflight(); diff --git a/src/routes/oauth/revoke/+server.ts b/src/routes/oauth/revoke/+server.ts new file mode 100644 index 00000000..f9e2b6ba --- /dev/null +++ b/src/routes/oauth/revoke/+server.ts @@ -0,0 +1,12 @@ +import { oauthService } from '#modules/auth'; +import { oauthDisabled, oauthJson, oauthPreflight, readOAuthBody } from '#lib/server/oauth/http'; + +// POST /oauth/revoke: RFC 7009. Always 200, so it never says whether the token existed (ADR 0006) +export const POST = async ({ request }) => { + if (!oauthService.isEnabled()) return oauthDisabled(); + const body = await readOAuthBody(request); + await oauthService.revoke(body?.token); + return oauthJson({}); +}; + +export const OPTIONS = () => oauthPreflight(); diff --git a/src/routes/oauth/server.test.ts b/src/routes/oauth/server.test.ts new file mode 100644 index 00000000..52b91568 --- /dev/null +++ b/src/routes/oauth/server.test.ts @@ -0,0 +1,274 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const state = vi.hoisted(() => ({ enabled: true })); +const service = vi.hoisted(() => ({ + isEnabled: vi.fn(() => state.enabled), + register: vi.fn(), + exchangeCode: vi.fn(), + refresh: vi.fn(), + revoke: vi.fn(async () => {}), +})); + +vi.mock('$app/env/private', () => ({ ORIGIN: undefined })); +vi.mock('#modules/auth', async () => { + const { OAuthRegistrationError } = await import('#modules/auth/domain/oauth.domain'); + const { OAuthTokenError } = await import('#modules/auth/application/oauth.service'); + return { oauthService: service, OAuthRegistrationError, OAuthTokenError }; +}); + +import { OAuthRegistrationError } from '#modules/auth/domain/oauth.domain'; +import { OAuthTokenError } from '#modules/auth/application/oauth.service'; +import { + GET as metadata, + OPTIONS as metadataOptions, +} from '../.well-known/oauth-authorization-server/+server'; +import { POST as register } from './register/+server'; +import { POST as token, OPTIONS as tokenOptions } from './token/+server'; +import { POST as revoke } from './revoke/+server'; +import { isCsrfForbidden } from '#lib/server/csrf'; +import { isOAuthPublicPath } from '#lib/server/oauth/http'; +import { safeReturnPath } from '#lib/server/return-to'; + +const ORIGIN = 'https://gitops.example.com'; + +function event(path: string, init: RequestInit = {}, address = '10.0.0.1') { + const url = new URL(`${ORIGIN}${path}`); + return { + url, + request: new Request(url, init), + getClientAddress: () => address, + } as any; +} + +function form(path: string, body: Record) { + return event(path, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams(body).toString(), + }); +} + +beforeEach(() => { + state.enabled = true; + vi.clearAllMocks(); +}); + +describe('GET /.well-known/oauth-authorization-server', () => { + it('publishes the RFC 8414 metadata for the public origin', async () => { + const response = await metadata(event('/.well-known/oauth-authorization-server')); + expect(response.status).toBe(200); + expect(response.headers.get('access-control-allow-origin')).toBe('*'); + expect(await response.json()).toEqual({ + issuer: ORIGIN, + authorization_endpoint: `${ORIGIN}/oauth/authorize`, + token_endpoint: `${ORIGIN}/oauth/token`, + registration_endpoint: `${ORIGIN}/oauth/register`, + revocation_endpoint: `${ORIGIN}/oauth/revoke`, + response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token'], + code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['none'], + scopes_supported: ['mcp'], + }); + }); + + it('is 404 with OAuth disabled, like every other endpoint', async () => { + state.enabled = false; + expect((await metadata(event('/.well-known/oauth-authorization-server'))).status).toBe(404); + expect((await metadataOptions()).status).toBe(404); + expect((await register(event('/oauth/register', { method: 'POST' }))).status).toBe(404); + expect((await token(form('/oauth/token', {}))).status).toBe(404); + expect((await revoke(form('/oauth/revoke', { token: 'x' }))).status).toBe(404); + expect(service.revoke).not.toHaveBeenCalled(); + }); +}); + +describe('CORS and CSRF of the public endpoints', () => { + it('answers OPTIONS with 204 and the allowed methods and headers', async () => { + const response = await tokenOptions(); + expect(response.status).toBe(204); + expect(response.headers.get('access-control-allow-origin')).toBe('*'); + expect(response.headers.get('access-control-allow-methods')).toContain('POST'); + expect(response.headers.get('access-control-allow-headers')).toBe( + 'Content-Type, Authorization', + ); + }); + + it('exempts only the three POST endpoints from the CSRF check', () => { + const post = (path: string) => { + const url = new URL(`${ORIGIN}${path}`); + const request = new Request(url, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + }); + return isCsrfForbidden(request, url); + }; + for (const path of ['/oauth/register', '/oauth/token', '/oauth/revoke']) { + expect(post(path)).toBe(false); + } + // the consent form uses the session cookie + expect(post('/oauth/authorize')).toBe(true); + }); + + it('lets the four public paths through without a session, and not the consent page', () => { + for (const path of [ + '/.well-known/oauth-authorization-server', + '/oauth/register', + '/oauth/token', + '/oauth/revoke', + ]) { + expect(isOAuthPublicPath(path)).toBe(true); + } + expect(isOAuthPublicPath('/oauth/authorize')).toBe(false); + }); + + it('keeps the whole authorize query when it comes back after the login', () => { + const path = + '/oauth/authorize?response_type=code&client_id=goc_1&redirect_uri=https%3A%2F%2Fa.example%2Fcb&state=s'; + expect(safeReturnPath(path)).toBe(path); + expect(safeReturnPath('/oauth/token')).toBeNull(); + }); +}); + +describe('POST /oauth/register', () => { + const json = (body: unknown, address?: string) => + event( + '/oauth/register', + { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }, + address, + ); + + it('answers 201 with the client', async () => { + service.register.mockResolvedValue({ + clientId: 'goc_1', + clientName: 'Claude', + redirectUris: ['https://claude.ai/cb'], + createdAt: '2026-11-30T10:00:00.000Z', + }); + const response = await register(json({ redirect_uris: ['https://claude.ai/cb'] })); + expect(response.status).toBe(201); + expect(response.headers.get('access-control-allow-origin')).toBe('*'); + expect(await response.json()).toEqual({ + client_id: 'goc_1', + client_id_issued_at: Date.parse('2026-11-30T10:00:00.000Z') / 1000, + client_name: 'Claude', + redirect_uris: ['https://claude.ai/cb'], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'none', + }); + }); + + it('answers 400 with the OAuth error', async () => { + service.register.mockRejectedValue(new OAuthRegistrationError('invalid_redirect_uri', 'nope')); + const response = await register(json({})); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: 'invalid_redirect_uri', + error_description: 'nope', + }); + }); + + it('answers 400 for a body that is not JSON', async () => { + const response = await register( + event('/oauth/register', { + method: 'POST', + body: 'x', + headers: { 'content-type': 'text/plain' }, + }), + ); + expect(response.status).toBe(400); + }); + + it('limits registrations per address to 20 per hour', async () => { + service.register.mockResolvedValue({ + clientId: 'goc_1', + clientName: 'c', + redirectUris: [], + createdAt: '2026-11-30T10:00:00.000Z', + }); + const statuses: number[] = []; + for (let i = 0; i < 21; i += 1) { + statuses.push((await register(json({}, '10.9.9.9'))).status); + } + expect(statuses.slice(0, 20).every((status) => status === 201)).toBe(true); + expect(statuses[20]).toBe(429); + }); +}); + +describe('POST /oauth/token', () => { + it('exchanges an authorization code, with no-store', async () => { + service.exchangeCode.mockResolvedValue({ access_token: 'gvs_a', token_type: 'Bearer' }); + const response = await token( + form('/oauth/token', { + grant_type: 'authorization_code', + code: 'c', + redirect_uri: 'https://claude.ai/cb', + client_id: 'goc_1', + code_verifier: 'v', + resource: 'https://mcp.example.com/mcp', + }), + ); + expect(response.status).toBe(200); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(service.exchangeCode).toHaveBeenCalledWith({ + code: 'c', + redirectUri: 'https://claude.ai/cb', + clientId: 'goc_1', + codeVerifier: 'v', + resource: 'https://mcp.example.com/mcp', + }); + }); + + it('accepts JSON for the refresh grant', async () => { + service.refresh.mockResolvedValue({ access_token: 'gvs_b' }); + const response = await token( + event('/oauth/token', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + grant_type: 'refresh_token', + refresh_token: 'gvr_x', + client_id: 'goc_1', + }), + }), + ); + expect(response.status).toBe(200); + expect(service.refresh).toHaveBeenCalledWith({ refreshToken: 'gvr_x', clientId: 'goc_1' }); + }); + + it('maps grant errors to 400 and invalid_client to 401', async () => { + service.exchangeCode.mockRejectedValueOnce(new OAuthTokenError('invalid_grant', 'bad code')); + const bad = await token(form('/oauth/token', { grant_type: 'authorization_code' })); + expect(bad.status).toBe(400); + expect(await bad.json()).toEqual({ error: 'invalid_grant', error_description: 'bad code' }); + + service.refresh.mockRejectedValueOnce( + new OAuthTokenError('invalid_client', 'Unknown client_id'), + ); + const unknown = await token(form('/oauth/token', { grant_type: 'refresh_token' })); + expect(unknown.status).toBe(401); + }); + + it('rejects unsupported grants and unreadable bodies', async () => { + const grant = await token(form('/oauth/token', { grant_type: 'password' })); + expect(grant.status).toBe(400); + expect((await grant.json()).error).toBe('unsupported_grant_type'); + + const empty = await token(event('/oauth/token', { method: 'POST' })); + expect(empty.status).toBe(400); + expect((await empty.json()).error).toBe('invalid_request'); + }); +}); + +describe('POST /oauth/revoke', () => { + it('always answers 200', async () => { + expect((await revoke(form('/oauth/revoke', { token: 'gvs_x' }))).status).toBe(200); + expect(service.revoke).toHaveBeenCalledWith('gvs_x'); + expect((await revoke(event('/oauth/revoke', { method: 'POST' }))).status).toBe(200); + }); +}); diff --git a/src/routes/oauth/token/+server.ts b/src/routes/oauth/token/+server.ts new file mode 100644 index 00000000..8aec703c --- /dev/null +++ b/src/routes/oauth/token/+server.ts @@ -0,0 +1,56 @@ +import { OAuthTokenError, oauthService } from '#modules/auth'; +import { + oauthDisabled, + oauthError, + oauthJson, + oauthPreflight, + readOAuthBody, +} from '#lib/server/oauth/http'; + +// POST /oauth/token: authorization_code (PKCE) and refresh_token grants for public clients (ADR 0006) +export const POST = async ({ request }) => { + if (!oauthService.isEnabled()) return oauthDisabled(); + + const body = await readOAuthBody(request); + if (!body) { + return oauthError( + 400, + 'invalid_request', + 'Send application/x-www-form-urlencoded (or JSON) parameters', + ); + } + + try { + if (body.grant_type === 'authorization_code') { + return oauthJson( + await oauthService.exchangeCode({ + code: body.code, + redirectUri: body.redirect_uri, + clientId: body.client_id, + codeVerifier: body.code_verifier, + resource: body.resource, + }), + ); + } + if (body.grant_type === 'refresh_token') { + return oauthJson( + await oauthService.refresh({ + refreshToken: body.refresh_token, + clientId: body.client_id, + }), + ); + } + return oauthError( + 400, + 'unsupported_grant_type', + 'grant_type must be authorization_code or refresh_token', + ); + } catch (error) { + if (error instanceof OAuthTokenError) { + return oauthError(error.status, error.code, error.message); + } + throw error; + } +}; + +export const OPTIONS = () => oauthPreflight(); diff --git a/src/routes/profile/+page.server.ts b/src/routes/profile/+page.server.ts index 45babd41..a43919ec 100644 --- a/src/routes/profile/+page.server.ts +++ b/src/routes/profile/+page.server.ts @@ -129,6 +129,17 @@ export const actions = { return fail(400, { section: 'apiKeys', message: 'Key id is required.' }); } + // an OAuth key renews itself with its refresh token (ADR 0006): it can only be revoked + const own = (await apiKeysService.listActiveApiKeys(locals.user.id)).find( + (key) => key.id === keyId, + ); + if (own?.oauthClientId) { + return fail(400, { + section: 'apiKeys', + message: 'OAuth keys cannot be regenerated; revoke the connection and connect again.', + }); + } + const { token, key } = await apiKeysService.regenerateApiKey(locals.user.id, keyId); return { diff --git a/src/routes/profile/+page.svelte b/src/routes/profile/+page.svelte index 8cd5716c..400c2a88 100644 --- a/src/routes/profile/+page.svelte +++ b/src/routes/profile/+page.svelte @@ -32,6 +32,8 @@ lastUsedAt: string | null; createdAt: string; audience: 'api' | 'mcp'; + oauthClientId?: string | null; + refreshExpiresAt?: string | null; }; let { @@ -387,22 +389,32 @@

{key.name} - {#if key.audience === 'mcp'}{$_('profile.mcpBadge')}{$_('profile.oauthBadge')}{:else if key.audience === 'mcp'}{$_('profile.mcpBadge')}{/if}

- {key.keyPrefix}… · {$_('profile.expires')} - {formatDate(key.expiresAt)} · {$_('profile.lastUsed')} - {formatDate(key.lastUsedAt)} + {#if key.oauthClientId} + {$_('profile.oauthConnectedUntil')} + {formatDate(key.refreshExpiresAt ?? null)} · {$_('profile.lastUsed')} + {formatDate(key.lastUsedAt)} + {:else} + {key.keyPrefix}… · {$_('profile.expires')} + {formatDate(key.expiresAt)} · {$_('profile.lastUsed')} + {formatDate(key.lastUsedAt)} + {/if}

-
- - -
+ {#if !key.oauthClientId} +
+ + +
+ {/if}