From bec45771d3a066428cd01a1013f7c9849685eb5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:02:08 +0000 Subject: [PATCH 01/13] fix(security): one owner per GCP workload identity pool A stored GCP WIF credential could name any (project number, pool). SAM signed an identity token for it, the user-level provider checked only SAM's issuer, and its pool/* binding let one user impersonate another user's (or the installation's) service account. Worker side (no GCP change needed): - gcp-wif-pool-ownership: a credential may name a pool only when no credential of a different owner (another user, or the installation) names it. Enforced at save (409) and before signing any token. - gcp_wif_pool_index (migration 0262) indexes the pool each encrypted credential names, keyed by IV, reconciled in the same D1 batch as the owner read: writer-independent, one round trip per check, per-row fault isolation, fail-closed time budget. - Token exchange takes an explicit requester; project credentials use the stored row's owner. GCP side: - User-level setup scopes the provider to assertion.user_id and binds attribute.sam_user/; re-running setup narrows an existing provider and removes the pool/* member. No issuer-only scope remains. - Guided setup checks the pool before changing anything in Google. Production audit (counts only): every GCP credential belongs to one owner, so no existing connection is refused. Co-Authored-By: Claude Opus 5.5 --- .../db/migrations/0262_gcp_wif_pool_index.sql | 24 + .../src/routes/admin-platform-credentials.ts | 12 + apps/api/src/routes/composable-credentials.ts | 9 + apps/api/src/routes/gcp.ts | 32 +- apps/api/src/routes/project-deployment.ts | 321 +++++----- apps/api/src/routes/projects/credentials.ts | 9 + .../admin-settings-gcp-catalog-definitions.ts | 21 +- apps/api/src/services/gcp-credential-store.ts | 9 + apps/api/src/services/gcp-deploy-setup.ts | 9 +- apps/api/src/services/gcp-setup.ts | 21 +- apps/api/src/services/gcp-sts.ts | 32 +- apps/api/src/services/gcp-token-provider.ts | 36 +- .../src/services/gcp-wif-pool-ownership.ts | 388 ++++++++++++ apps/api/src/services/gcp-wif-setup.ts | 124 ++-- .../src/services/provider-credential-exact.ts | 19 +- apps/api/src/services/provider-credentials.ts | 40 +- apps/api/tests/unit/gcp-deploy-setup.test.ts | 11 +- apps/api/tests/unit/routes/gcp.test.ts | 4 +- .../unit/services/gcp-api-health.test.ts | 5 +- .../services/gcp-live-catalog-build.test.ts | 21 +- .../unit/services/gcp-price-table.test.ts | 30 +- .../gcp-provider-cancellation-slice.test.ts | 12 +- .../unit/services/gcp-service-account.test.ts | 63 +- .../gcp-wif-installation-isolation.test.ts | 10 +- .../services/gcp-wif-pool-ownership.test.ts | 551 ++++++++++++++++++ .../unit/services/gcp-wif-scoping.test.ts | 386 ++++++------ .../services/gcp-wif-shared-project.test.ts | 17 +- .../docs/docs/architecture/security.md | 12 + .../docs/docs/guides/admin-settings.md | 2 + .../content/docs/docs/guides/google-cloud.md | 4 +- .../content/docs/docs/guides/self-hosting.mdx | 4 + packages/worker-core/src/schema.ts | 29 + ...-gcp-wif-cross-owner-pool-impersonation.md | 46 ++ 33 files changed, 1842 insertions(+), 471 deletions(-) create mode 100644 apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql create mode 100644 apps/api/src/services/gcp-wif-pool-ownership.ts create mode 100644 apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts create mode 100644 tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md diff --git a/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql b/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql new file mode 100644 index 0000000000..741c66769b --- /dev/null +++ b/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql @@ -0,0 +1,24 @@ +-- Which Google Cloud workload identity pool each stored cloud credential names, so a pool can be +-- held by one owner (one SAM user, or the installation). See services/gcp-wif-pool-ownership.ts. +-- Pool identities live inside encrypted payloads, so the Worker fills this table itself: every +-- ownership check indexes rows whose IV it has not seen, and reads owners only through rows whose +-- source credential still has the indexed IV. Existing credentials are indexed on the first check +-- after deploy; nothing here can decrypt them. No secret material is stored: the IV identifies a +-- ciphertext generation, the pool key is `/`. +-- No foreign keys: a row references one of three tables, and deletions drop out of the owner read. +CREATE TABLE IF NOT EXISTS gcp_wif_pool_index ( + source_table TEXT NOT NULL CHECK (source_table IN ('credentials', 'platform_credentials', 'cc_credentials')), + source_id TEXT NOT NULL, + iv TEXT NOT NULL, + owner_kind TEXT NOT NULL CHECK (owner_kind IN ('user', 'platform')), + owner_user_id TEXT, + pool_key TEXT, + indexed_at TEXT NOT NULL, + PRIMARY KEY (source_table, source_id), + CHECK ((owner_kind = 'user' AND owner_user_id IS NOT NULL) OR (owner_kind = 'platform' AND owner_user_id IS NULL)) +) WITHOUT ROWID; +CREATE INDEX IF NOT EXISTS idx_gcp_wif_pool_index_pool + ON gcp_wif_pool_index (pool_key) WHERE pool_key IS NOT NULL; +-- Deployment credentials store their pool in plaintext; the ownership check reads them directly. +CREATE INDEX IF NOT EXISTS idx_project_deployment_creds_gcp_project_number + ON project_deployment_credentials (gcp_project_number); diff --git a/apps/api/src/routes/admin-platform-credentials.ts b/apps/api/src/routes/admin-platform-credentials.ts index 49dfe9d961..6015a5a4a5 100644 --- a/apps/api/src/routes/admin-platform-credentials.ts +++ b/apps/api/src/routes/admin-platform-credentials.ts @@ -25,6 +25,7 @@ import { import { reconcileCapacityPoolsForCredentialMutation } from '../services/capacity-pool-credential-lifecycle'; import { decrypt, encrypt } from '../services/encryption'; import { deleteGcpApiHealthSafely } from '../services/gcp-api-health'; +import { assertGcpWifPayloadOwnership } from '../services/gcp-wif-pool-ownership'; import { buildProviderConfig } from '../services/provider-credentials'; import { CredentialValidator } from '../services/validation'; @@ -124,6 +125,17 @@ adminPlatformCredentialRoutes.post( } } + if (body.credentialType === 'cloud-provider' && body.provider === 'gcp') { + // The installation owns platform credentials: a pool a user's credential names is not + // available to them, and the reverse is refused when users save. + await assertGcpWifPayloadOwnership( + c.env, + body.credential, + { kind: 'platform' }, + 'save_platform_credential' + ); + } + // Encrypt and store const encryptionKey = getCredentialEncryptionKey(c.env); const { ciphertext, iv } = await encrypt(body.credential, encryptionKey); diff --git a/apps/api/src/routes/composable-credentials.ts b/apps/api/src/routes/composable-credentials.ts index 9ccc22fcce..cf7381ed50 100644 --- a/apps/api/src/routes/composable-credentials.ts +++ b/apps/api/src/routes/composable-credentials.ts @@ -24,6 +24,7 @@ import { getUserId } from '../middleware/auth'; import { errors } from '../middleware/error'; import { reconcileCapacityPoolsForCredentialMutation } from '../services/capacity-pool-credential-lifecycle'; import { encrypt } from '../services/encryption'; +import { assertGcpWifPayloadOwnership } from '../services/gcp-wif-pool-ownership'; import { registerCCAttachmentRoutes, uniqueProjectIds } from './composable-credentials-attachments'; import { registerCCProfileAttachmentRoutes } from './composable-credentials-profile-attachments'; @@ -186,6 +187,14 @@ ccRoutes.post('/credentials', async (c) => { const encryptionKey = getCredentialEncryptionKey(c.env); const tokenToEncrypt = typeof secret === 'string' ? secret : JSON.stringify(secret); + if (kind === 'cloud-provider') { + await assertGcpWifPayloadOwnership( + c.env, + tokenToEncrypt, + { kind: 'user', userId }, + 'save_composable_credential' + ); + } const { ciphertext, iv } = await encrypt(tokenToEncrypt, encryptionKey); const id = `cc-cred-${ulid()}`; diff --git a/apps/api/src/routes/gcp.ts b/apps/api/src/routes/gcp.ts index d6b9b4750b..14819b4393 100644 --- a/apps/api/src/routes/gcp.ts +++ b/apps/api/src/routes/gcp.ts @@ -39,14 +39,24 @@ import { import { listGcpProjects, runGcpSetup } from '../services/gcp-setup'; import { clearGcpAccessTokenCache, + type GcpTokenRequester, getGcpAccessToken, verifyGcpOidcSetup, } from '../services/gcp-sts'; +import { + assertGcpWifPoolOwnership, + isGcpWifPoolOwnershipError, +} from '../services/gcp-wif-pool-ownership'; import { getGoogleInfraOAuthConfig } from '../services/platform-config'; import { parseGcpCredential } from '../services/provider-credentials'; const gcpRoutes = new Hono<{ Bindings: Env }>(); +/** A user acting on their own user-level GCP credential. */ +function userTokenRequester(userId: string): GcpTokenRequester { + return { tokenUserId: userId, poolOwner: { kind: 'user', userId } }; +} + gcpRoutes.use('*', requireAuth(), requireApproved()); async function resolveOAuthToken(handle: string, kv: KVNamespace): Promise { @@ -171,7 +181,7 @@ gcpRoutes.put( try { const accessToken = await getGcpAccessToken( - userId, + userTokenRequester(userId), 'service-account-setup', credential, c.env @@ -212,8 +222,15 @@ gcpRoutes.post('/setup', jsonValidator(GcpSetupSchema), async (c) => { const previous = await getStoredGcpCredential(c.env, userId).catch(() => null); let credential: Awaited>; try { - credential = await runGcpSetup(oauthToken, body.gcpProjectId, body.defaultZone, c.env); + credential = await runGcpSetup(oauthToken, body.gcpProjectId, body.defaultZone, c.env, { + userId, + // Runs once the project number is known and before SAM creates or changes anything in + // Google: a pool another owner already uses must not be re-pointed at this user. + assertPoolAvailable: (pool) => + assertGcpWifPoolOwnership(c.env, pool, { kind: 'user', userId }, 'gcp_setup'), + }); } catch (err) { + if (isGcpWifPoolOwnershipError(err)) throw err; throw toSanitizedAppError(err, 'gcp-setup'); } @@ -224,7 +241,7 @@ gcpRoutes.post('/setup', jsonValidator(GcpSetupSchema), async (c) => { await reconcileCapacityPoolsForCredentialMutation(c.env, { scope: 'user', userId }); try { - await verifyGcpOidcSetup(userId, 'setup-verification', credential, c.env); + await verifyGcpOidcSetup(userTokenRequester(userId), 'setup-verification', credential, c.env); } catch (verifyErr) { log.warn('gcp.oidc_verification_failed', { error: verifyErr instanceof Error ? verifyErr.message : String(verifyErr), @@ -272,10 +289,15 @@ gcpRoutes.post('/verify', async (c) => { try { if (gcpCredential.authType === 'service-account-key') { - const token = await getGcpAccessToken(userId, 'verification', gcpCredential, c.env); + const token = await getGcpAccessToken( + userTokenRequester(userId), + 'verification', + gcpCredential, + c.env + ); await verifyGcpServiceAccountAccess(gcpCredential, token, c.env); } else { - await verifyGcpOidcSetup(userId, 'verification', gcpCredential, c.env); + await verifyGcpOidcSetup(userTokenRequester(userId), 'verification', gcpCredential, c.env); } } catch (err) { return c.json({ diff --git a/apps/api/src/routes/project-deployment.ts b/apps/api/src/routes/project-deployment.ts index 22b257823b..3cf318699c 100644 --- a/apps/api/src/routes/project-deployment.ts +++ b/apps/api/src/routes/project-deployment.ts @@ -73,11 +73,9 @@ projectDeploymentRoutes.get( const stateTtl = c.env.GCP_DEPLOY_OAUTH_STATE_TTL_SECONDS ? parseInt(c.env.GCP_DEPLOY_OAUTH_STATE_TTL_SECONDS, 10) : DEFAULT_GCP_DEPLOY_OAUTH_STATE_TTL_SECONDS; - await c.env.KV.put( - `gcp-deploy-oauth-state:${state}`, - JSON.stringify({ projectId, userId }), - { expirationTtl: stateTtl }, - ); + await c.env.KV.put(`gcp-deploy-oauth-state:${state}`, JSON.stringify({ projectId, userId }), { + expirationTtl: stateTtl, + }); const redirectUri = `https://api.${c.env.BASE_DOMAIN}/api/deployment/gcp/callback`; const params = new URLSearchParams({ @@ -92,7 +90,7 @@ projectDeploymentRoutes.get( }); return c.redirect(`${GOOGLE_AUTH_URL}?${params.toString()}`); - }, + } ); // OAuth callback moved to gcpDeployCallbackRoute — see below @@ -116,7 +114,9 @@ projectDeploymentRoutes.get( const kvKey = `gcp-deploy-oauth-result:${userId}:${projectId}`; const handle = await c.env.KV.get(kvKey); if (!handle) { - throw errors.notFound('No pending OAuth result — it may have expired or already been retrieved'); + throw errors.notFound( + 'No pending OAuth result — it may have expired or already been retrieved' + ); } // One-time use: delete after retrieval. @@ -125,7 +125,7 @@ projectDeploymentRoutes.get( await c.env.KV.delete(kvKey); return c.json({ handle }); - }, + } ); // ─── Setup + management (user session auth) ───────────────────────────── @@ -159,7 +159,7 @@ projectDeploymentRoutes.post( } catch (err) { throw toSanitizedAppError(err, 'deploy-list-projects'); } - }, + } ); /** @@ -187,7 +187,7 @@ projectDeploymentRoutes.post( let result; try { - result = await runGcpDeploySetup(oauthToken, body.gcpProjectId, c.env, undefined, projectId); + result = await runGcpDeploySetup(oauthToken, body.gcpProjectId, c.env, projectId); } catch (err) { throw toSanitizedAppError(err, 'deploy-setup'); } @@ -203,8 +203,8 @@ projectDeploymentRoutes.post( .where( and( eq(schema.projectDeploymentCredentials.projectId, projectId), - eq(schema.projectDeploymentCredentials.provider, 'gcp'), - ), + eq(schema.projectDeploymentCredentials.provider, 'gcp') + ) ) .limit(1); @@ -246,48 +246,43 @@ projectDeploymentRoutes.post( createdAt: now, }, }); - }, + } ); /** * GET /api/projects/:id/deployment/gcp * Get deployment credential config for a project. */ -projectDeploymentRoutes.get( - '/:id/deployment/gcp', - requireAuth(), - requireApproved(), - async (c) => { - const projectId = c.req.param('id'); - const userId = getUserId(c); - const db = drizzle(c.env.DATABASE, { schema }); - await requireProjectCapability(db, projectId, userId, 'infra:manage'); +projectDeploymentRoutes.get('/:id/deployment/gcp', requireAuth(), requireApproved(), async (c) => { + const projectId = c.req.param('id'); + const userId = getUserId(c); + const db = drizzle(c.env.DATABASE, { schema }); + await requireProjectCapability(db, projectId, userId, 'infra:manage'); - const rows = await db - .select() - .from(schema.projectDeploymentCredentials) - .where( - and( - eq(schema.projectDeploymentCredentials.projectId, projectId), - eq(schema.projectDeploymentCredentials.provider, 'gcp'), - ), + const rows = await db + .select() + .from(schema.projectDeploymentCredentials) + .where( + and( + eq(schema.projectDeploymentCredentials.projectId, projectId), + eq(schema.projectDeploymentCredentials.provider, 'gcp') ) - .limit(1); + ) + .limit(1); - const cred = rows[0]; - if (!cred) { - return c.json({ connected: false }); - } + const cred = rows[0]; + if (!cred) { + return c.json({ connected: false }); + } - return c.json({ - connected: true, - provider: 'gcp' as const, - gcpProjectId: cred.gcpProjectId, - serviceAccountEmail: cred.serviceAccountEmail, - createdAt: cred.createdAt, - }); - }, -); + return c.json({ + connected: true, + provider: 'gcp' as const, + gcpProjectId: cred.gcpProjectId, + serviceAccountEmail: cred.serviceAccountEmail, + createdAt: cred.createdAt, + }); +}); /** * DELETE /api/projects/:id/deployment/gcp @@ -308,12 +303,12 @@ projectDeploymentRoutes.delete( .where( and( eq(schema.projectDeploymentCredentials.projectId, projectId), - eq(schema.projectDeploymentCredentials.provider, 'gcp'), - ), + eq(schema.projectDeploymentCredentials.provider, 'gcp') + ) ); return c.json({ success: true }); - }, + } ); // ─── Identity token endpoint (MCP token auth only) ────────────────────── @@ -365,8 +360,8 @@ deploymentIdentityTokenRoute.get('/:id/deployment-identity-token', async (c) => .where( and( eq(schema.projectDeploymentCredentials.projectId, projectId), - eq(schema.projectDeploymentCredentials.provider, 'gcp'), - ), + eq(schema.projectDeploymentCredentials.provider, 'gcp') + ) ) .limit(1); @@ -380,7 +375,8 @@ deploymentIdentityTokenRoute.get('/:id/deployment-identity-token', async (c) => // for identity tokens. The STS `audience` field in the credential config (deployment-tools.ts) // uses the protocol-relative `//` format. Both forms are intentionally different per GCP WIF spec. const poolId = cred.wifPoolId || c.env.GCP_DEPLOY_WIF_POOL_ID || DEFAULT_GCP_DEPLOY_WIF_POOL_ID; - const providerId = cred.wifProviderId || c.env.GCP_DEPLOY_WIF_PROVIDER_ID || DEFAULT_GCP_DEPLOY_WIF_PROVIDER_ID; + const providerId = + cred.wifProviderId || c.env.GCP_DEPLOY_WIF_PROVIDER_ID || DEFAULT_GCP_DEPLOY_WIF_PROVIDER_ID; const audience = `https://iam.googleapis.com/projects/${cred.gcpProjectNumber}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`; const expirySeconds = c.env.GCP_DEPLOY_IDENTITY_TOKEN_EXPIRY_SECONDS @@ -407,7 +403,7 @@ deploymentIdentityTokenRoute.get('/:id/deployment-identity-token', async (c) => c.env.KV, rlKey, rateLimitMax, - rateLimitWindowSeconds, + rateLimitWindowSeconds ); c.header('X-RateLimit-Limit', rateLimitMax.toString()); @@ -428,7 +424,7 @@ deploymentIdentityTokenRoute.get('/:id/deployment-identity-token', async (c) => audience, }, c.env, - expirySeconds, + expirySeconds ); // Cache the signed token with TTL = expiry - buffer (min floor) @@ -464,131 +460,136 @@ const gcpDeployCallbackRoute = new Hono<{ Bindings: Env }>(); * Project context comes from the KV state token, NOT the URL. * This allows a single static redirect URI in Google Cloud Console. */ -gcpDeployCallbackRoute.get( - '/gcp/callback', - requireAuth(), - requireApproved(), - async (c) => { - const sessionUserId = getUserId(c); - const appBaseUrl = `https://app.${c.env.BASE_DOMAIN}`; +gcpDeployCallbackRoute.get('/gcp/callback', requireAuth(), requireApproved(), async (c) => { + const sessionUserId = getUserId(c); + const appBaseUrl = `https://app.${c.env.BASE_DOMAIN}`; - const googleOAuth = await getGoogleInfraOAuthConfig(c.env); - if (!googleOAuth) { - throw errors.badRequest('Google OAuth is not configured'); - } - - const code = c.req.query('code'); - const state = c.req.query('state'); - const error = c.req.query('error'); - - if (error) { - // No project context yet — redirect to dashboard with error - return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent(error)}`); - } + const googleOAuth = await getGoogleInfraOAuthConfig(c.env); + if (!googleOAuth) { + throw errors.badRequest('Google OAuth is not configured'); + } - if (!code || !state) { - return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Missing authorization code or state')}`); - } + const code = c.req.query('code'); + const state = c.req.query('state'); + const error = c.req.query('error'); - // Validate state format before KV lookup (state is always a UUID) - const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (!UUID_RE.test(state)) { - return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid OAuth state')}`); - } + if (error) { + // No project context yet — redirect to dashboard with error + return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent(error)}`); + } - // Validate CSRF state and extract project context - const storedStateRaw = await c.env.KV.get(`gcp-deploy-oauth-state:${state}`); - if (!storedStateRaw) { - return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid or expired OAuth state')}`); - } + if (!code || !state) { + return c.redirect( + `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Missing authorization code or state')}` + ); + } - let storedState: { projectId: string; userId: string }; - try { - const parsed = expectJsonRecord(JSON.parse(storedStateRaw), 'gcp_deploy_oauth.state'); - if (typeof parsed.projectId !== 'string' || typeof parsed.userId !== 'string') { - throw new Error('Invalid state structure'); - } - storedState = { projectId: parsed.projectId, userId: parsed.userId }; - } catch { - await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); - return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid OAuth state format')}`); - } + // Validate state format before KV lookup (state is always a UUID) + const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + if (!UUID_RE.test(state)) { + return c.redirect( + `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid OAuth state')}` + ); + } - if (!storedState.projectId || !storedState.userId) { - await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); - return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Incomplete OAuth state')}`); - } + // Validate CSRF state and extract project context + const storedStateRaw = await c.env.KV.get(`gcp-deploy-oauth-state:${state}`); + if (!storedStateRaw) { + return c.redirect( + `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid or expired OAuth state')}` + ); + } - // Validate user identity BEFORE consuming the state token — if the user doesn't - // match, the state remains valid for the legitimate user to retry - if (storedState.userId !== sessionUserId) { - return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('OAuth state user mismatch')}`); + let storedState: { projectId: string; userId: string }; + try { + const parsed = expectJsonRecord(JSON.parse(storedStateRaw), 'gcp_deploy_oauth.state'); + if (typeof parsed.projectId !== 'string' || typeof parsed.userId !== 'string') { + throw new Error('Invalid state structure'); } - - // All validation passed — consume the state token (one-time use) + storedState = { projectId: parsed.projectId, userId: parsed.userId }; + } catch { await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); + return c.redirect( + `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid OAuth state format')}` + ); + } - const projectId = storedState.projectId; + if (!storedState.projectId || !storedState.userId) { + await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); + return c.redirect( + `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Incomplete OAuth state')}` + ); + } - // Defense-in-depth: verify the session user can still manage project - // infrastructure, even though the KV state was created by an authenticated - // actor at authorize time. - const db = drizzle(c.env.DATABASE, { schema }); - await requireProjectCapability(db, projectId, sessionUserId, 'infra:manage'); + // Validate user identity BEFORE consuming the state token — if the user doesn't + // match, the state remains valid for the legitimate user to retry + if (storedState.userId !== sessionUserId) { + return c.redirect( + `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('OAuth state user mismatch')}` + ); + } - const appUrl = `https://app.${c.env.BASE_DOMAIN}/projects/${projectId}/settings/deploy`; + // All validation passed — consume the state token (one-time use) + await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); - // Exchange auth code for access token - const redirectUri = `https://api.${c.env.BASE_DOMAIN}/api/deployment/gcp/callback`; - const tokenResponse = await fetch(GOOGLE_TOKEN_URL, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - code, - client_id: googleOAuth.clientId, - client_secret: googleOAuth.clientSecret, - redirect_uri: redirectUri, - grant_type: 'authorization_code', - }), - }); + const projectId = storedState.projectId; - if (!tokenResponse.ok) { - const errPayload: unknown = await tokenResponse.json().catch(() => ({})); - const errBody = maybeJsonRecord(errPayload) ?? {}; - log.error('project_deployment.google_token_exchange_failed', { - status: tokenResponse.status, - error: typeof errBody.error === 'string' ? errBody.error : 'unknown', - }); - return c.redirect(`${appUrl}?gcp_deploy_error=token_exchange_failed`); - } + // Defense-in-depth: verify the session user can still manage project + // infrastructure, even though the KV state was created by an authenticated + // actor at authorize time. + const db = drizzle(c.env.DATABASE, { schema }); + await requireProjectCapability(db, projectId, sessionUserId, 'infra:manage'); - const tokenData = await readResponseJson( - tokenResponse, - googleDeployTokenResponseSchema, - 'project_deployment.google_token_response', - ); + const appUrl = `https://app.${c.env.BASE_DOMAIN}/projects/${projectId}/settings/deploy`; - // Store token in KV with opaque handle (for subsequent API calls) - const handle = crypto.randomUUID(); - const tokenHandleTtl = c.env.GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS - ? parseInt(c.env.GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS, 10) - : DEFAULT_GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS; - await c.env.KV.put(`gcp-deploy-oauth-token:${handle}`, tokenData.access_token, { - expirationTtl: tokenHandleTtl, + // Exchange auth code for access token + const redirectUri = `https://api.${c.env.BASE_DOMAIN}/api/deployment/gcp/callback`; + const tokenResponse = await fetch(GOOGLE_TOKEN_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + code, + client_id: googleOAuth.clientId, + client_secret: googleOAuth.clientSecret, + redirect_uri: redirectUri, + grant_type: 'authorization_code', + }), + }); + + if (!tokenResponse.ok) { + const errPayload: unknown = await tokenResponse.json().catch(() => ({})); + const errBody = maybeJsonRecord(errPayload) ?? {}; + log.error('project_deployment.google_token_exchange_failed', { + status: tokenResponse.status, + error: typeof errBody.error === 'string' ? errBody.error : 'unknown', }); + return c.redirect(`${appUrl}?gcp_deploy_error=token_exchange_failed`); + } - // Store the handle reference in a user+project-scoped KV key so the frontend - // can retrieve it via an authenticated API call instead of from the URL. - // This prevents the handle from leaking in browser history, Referer headers, and logs. - await c.env.KV.put( - `gcp-deploy-oauth-result:${sessionUserId}:${projectId}`, - handle, - { expirationTtl: tokenHandleTtl }, - ); + const tokenData = await readResponseJson( + tokenResponse, + googleDeployTokenResponseSchema, + 'project_deployment.google_token_response' + ); - // Redirect with only a flag — no sensitive token in the URL - return c.redirect(`${appUrl}?gcp_deploy_setup=ready`); - }, -); + // Store token in KV with opaque handle (for subsequent API calls) + const handle = crypto.randomUUID(); + const tokenHandleTtl = c.env.GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS + ? parseInt(c.env.GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS, 10) + : DEFAULT_GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS; + await c.env.KV.put(`gcp-deploy-oauth-token:${handle}`, tokenData.access_token, { + expirationTtl: tokenHandleTtl, + }); + + // Store the handle reference in a user+project-scoped KV key so the frontend + // can retrieve it via an authenticated API call instead of from the URL. + // This prevents the handle from leaking in browser history, Referer headers, and logs. + await c.env.KV.put(`gcp-deploy-oauth-result:${sessionUserId}:${projectId}`, handle, { + expirationTtl: tokenHandleTtl, + }); + + // Redirect with only a flag — no sensitive token in the URL + return c.redirect(`${appUrl}?gcp_deploy_setup=ready`); +}); -export { deploymentIdentityTokenRoute,gcpDeployCallbackRoute, projectDeploymentRoutes }; +export { deploymentIdentityTokenRoute, gcpDeployCallbackRoute, projectDeploymentRoutes }; diff --git a/apps/api/src/routes/projects/credentials.ts b/apps/api/src/routes/projects/credentials.ts index 971f061913..bd4655bce3 100644 --- a/apps/api/src/routes/projects/credentials.ts +++ b/apps/api/src/routes/projects/credentials.ts @@ -53,6 +53,7 @@ import { import { decrypt, encrypt } from '../../services/encryption'; import { getTimeoutMs } from '../../services/fetch-timeout'; import { deleteGcpApiHealthSafely } from '../../services/gcp-api-health'; +import { assertGcpWifPayloadOwnership } from '../../services/gcp-wif-pool-ownership'; import { serializeCredentialToken } from '../../services/provider-credentials'; import { CredentialValidator, @@ -299,6 +300,14 @@ projectCredentialsRoutes.put( const requestBody = c.req.valid('json'); const { providerName, tokenToValidate: tokenToEncrypt } = getCloudCredentialFields(requestBody); const validation = await validateCloudCredentialRequest(requestBody, c.env); + // Same owner as the user's own credentials: a user may reuse their pool per project, but + // never name a pool another user or the installation uses. + await assertGcpWifPayloadOwnership( + c.env, + tokenToEncrypt, + { kind: 'user', userId }, + 'save_project_cloud_credential' + ); const { ciphertext, iv } = await encrypt(tokenToEncrypt, getCredentialEncryptionKey(c.env)); const existing = await db diff --git a/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts index c7beb44a41..61deb0a1d6 100644 --- a/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts +++ b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts @@ -18,7 +18,9 @@ export type GcpCatalogSettingName = | 'gcpCatalog.priceRefreshBudgetMs' | 'gcpCatalog.apiIssueTtlMinutes' | 'gcpCatalog.bootDiskGbPerVcpu' - | 'gcpCatalog.bootDiskMinGb'; + | 'gcpCatalog.bootDiskMinGb' + | 'gcpWif.poolIndexPageSize' + | 'gcpWif.poolIndexBudgetMs'; /** * General-purpose shapes SAM offers from Google Cloud by default: shared-core e2-medium, and the @@ -123,4 +125,21 @@ export const GCP_CATALOG_SETTINGS: readonly AdminSettingDefinition[] = [ 'Smallest boot disk, in GB, SAM gives a new Google Cloud VM, whatever its vCPU count.', { min: GCP_BOOT_DISK_FLOOR_GB, max: GCP_BOOT_DISK_MAX_GB } ), + // Workload identity pool ownership (`gcp-wif-pool-ownership.ts`). Indexing runs only for + // credentials added or re-encrypted since the last check; a check that cannot finish inside the + // budget refuses rather than trusting a partial index. + integerDefinition( + 'gcpWif.poolIndexPageSize', + 100, + 'Operations', + 'Stored cloud credentials SAM decrypts per step when indexing which Google Cloud workload identity pool each one names.', + { min: 10, max: 100 } + ), + integerDefinition( + 'gcpWif.poolIndexBudgetMs', + 10_000, + 'Operations', + 'Most milliseconds one Google Cloud token exchange or credential save may spend indexing newly saved credentials before it refuses and asks to retry.', + { min: 1_000, max: 25_000 } + ), ]; diff --git a/apps/api/src/services/gcp-credential-store.ts b/apps/api/src/services/gcp-credential-store.ts index abecd537d0..c0ca401adc 100644 --- a/apps/api/src/services/gcp-credential-store.ts +++ b/apps/api/src/services/gcp-credential-store.ts @@ -4,6 +4,7 @@ import type { Env } from '../env'; import { getCredentialEncryptionKey } from '../lib/secrets'; import { ulid } from '../lib/ulid'; import { encrypt } from './encryption'; +import { assertGcpWifPoolOwnership } from './gcp-wif-pool-ownership'; import { serializeGcpCredential } from './provider-credentials'; export interface StoredGcpCredentialResult { @@ -110,6 +111,14 @@ export async function replaceUserGcpCredential( if (typeof env.DATABASE.batch !== 'function') { throw new Error('Atomic credential replacement is unavailable'); } + if (credential.authType === 'workload-identity') { + await assertGcpWifPoolOwnership( + env, + credential, + { kind: 'user', userId }, + 'save_user_gcp_credential' + ); + } const now = new Date().toISOString(); const legacyId = ulid(); const ccCredentialId = `cc-cred-${ulid()}`; diff --git a/apps/api/src/services/gcp-deploy-setup.ts b/apps/api/src/services/gcp-deploy-setup.ts index df7181603f..44846f1364 100644 --- a/apps/api/src/services/gcp-deploy-setup.ts +++ b/apps/api/src/services/gcp-deploy-setup.ts @@ -48,9 +48,10 @@ export async function runGcpDeploySetup( oauthToken: string, gcpProjectId: string, env: Env, - onProgress?: SetupProgressCallback, - samProjectId?: string + samProjectId: string, + onProgress?: SetupProgressCallback ): Promise> { + const trustScope = { kind: 'project', samProjectId } as const; const timeoutMs = env.GCP_API_TIMEOUT_MS ? parseInt(env.GCP_API_TIMEOUT_MS, 10) : DEFAULT_GCP_API_TIMEOUT_MS; @@ -85,7 +86,7 @@ export async function runGcpDeploySetup( providerId, issuerUri, timeoutMs, - samProjectId + trustScope ); onProgress?.('create_oidc_provider', 'done'); @@ -110,7 +111,7 @@ export async function runGcpDeploySetup( saEmail, poolId, timeoutMs, - samProjectId + trustScope ); onProgress?.('grant_wif_user', 'done'); diff --git a/apps/api/src/services/gcp-setup.ts b/apps/api/src/services/gcp-setup.ts index 40b090a920..4f8303ddd2 100644 --- a/apps/api/src/services/gcp-setup.ts +++ b/apps/api/src/services/gcp-setup.ts @@ -354,18 +354,30 @@ export async function grantProjectRoles( } } +/** The SAM user a user-level guided setup is for. */ +export interface GcpUserSetupScope { + userId: string; + /** + * Called with the pool once the project number is known, before SAM creates or changes any + * Google resource. Throws to stop a setup that would take over another owner's pool. + */ + assertPoolAvailable?: (pool: { gcpProjectNumber: string; wifPoolId: string }) => Promise; +} + /** * Full GCP OIDC setup orchestrator. * Takes a Google OAuth access token and project ID, then configures all GCP resources. + * The provider and service-account binding admit only tokens SAM signs for `scope.userId`. */ export async function runGcpSetup( oauthToken: string, gcpProjectId: string, defaultZone: string, env: Env, - onProgress?: SetupProgressCallback, - samProjectId?: string + scope: GcpUserSetupScope, + onProgress?: SetupProgressCallback ): Promise { + const trustScope = { kind: 'user', userId: scope.userId } as const; const timeoutMs = env.GCP_API_TIMEOUT_MS ? parseInt(env.GCP_API_TIMEOUT_MS, 10) : DEFAULT_GCP_API_TIMEOUT_MS; @@ -379,6 +391,7 @@ export async function runGcpSetup( onProgress?.('get_project_number', 'in_progress'); const projectNumber = await getProjectNumber(oauthToken, gcpProjectId, timeoutMs); onProgress?.('get_project_number', 'done'); + await scope.assertPoolAvailable?.({ gcpProjectNumber: projectNumber, wifPoolId: poolId }); // Step 2: Enable APIs onProgress?.('enable_apis', 'in_progress'); @@ -399,7 +412,7 @@ export async function runGcpSetup( providerId, issuerUri, timeoutMs, - samProjectId + trustScope ); onProgress?.('create_oidc_provider', 'done'); @@ -417,7 +430,7 @@ export async function runGcpSetup( saEmail, poolId, timeoutMs, - samProjectId + trustScope ); onProgress?.('grant_wif_user', 'done'); diff --git a/apps/api/src/services/gcp-sts.ts b/apps/api/src/services/gcp-sts.ts index 77b99a222d..a06add8d01 100644 --- a/apps/api/src/services/gcp-sts.ts +++ b/apps/api/src/services/gcp-sts.ts @@ -23,8 +23,20 @@ import { exchangeGcpServiceAccountAccessToken, type GcpAccessTokenResult, } from './gcp-service-account'; +import { assertGcpWifPoolOwnership, type GcpWifPoolOwner } from './gcp-wif-pool-ownership'; import { signIdentityToken } from './jwt'; +/** Who a GCP access token is minted for. */ +export interface GcpTokenRequester { + /** + * The identity SAM asserts as the token's `user_id` claim and keys the token cache on: the + * user id, `project::` or `platform:`. + */ + tokenUserId: string; + /** The owner of the stored credential, which must own the workload identity pool it names. */ + poolOwner: GcpWifPoolOwner; +} + interface StsTokenResponse { access_token: string; token_type: string; @@ -129,7 +141,7 @@ export interface GcpAccessTokenOptions { * encrypted D1 storage. */ export async function getGcpAccessToken( - userId: string, + requester: GcpTokenRequester, projectId: string, credential: GcpCredential, env: Env, @@ -137,6 +149,7 @@ export async function getGcpAccessToken( options: GcpAccessTokenOptions = {} ): Promise { throwIfProviderRequestAborted(context); + const userId = requester.tokenUserId; // A token minted for different scopes is a different token; the suffix keeps the shared // prefix, so clearGcpAccessTokenCache still removes it. const cacheKey = options.scopes @@ -149,7 +162,7 @@ export async function getGcpAccessToken( const result = credential.authType === 'service-account-key' ? await exchangeGcpServiceAccountAccessToken(credential, env, context) - : await exchangeGcpWifAccessToken(userId, projectId, credential, env, context, options); + : await exchangeGcpWifAccessToken(requester, projectId, credential, env, context, options); throwIfProviderRequestAborted(context); const configuredTtl = positiveInteger( @@ -168,7 +181,7 @@ export async function getGcpAccessToken( } async function exchangeGcpWifAccessToken( - userId: string, + requester: GcpTokenRequester, projectId: string, credential: GcpOidcCredential, env: Env, @@ -188,7 +201,14 @@ async function exchangeGcpWifAccessToken( const wifResourcePath = `projects/${credential.gcpProjectNumber}/locations/global/workloadIdentityPools/${credential.wifPoolId}/providers/${credential.wifProviderId}`; const jwtAudience = `https://iam.googleapis.com/${wifResourcePath}`; const stsAudience = `//iam.googleapis.com/${wifResourcePath}`; - const identityToken = await signIdentityToken({ userId, projectId, audience: jwtAudience }, env); + // Refuse before signing: a provider that trusts only SAM's issuer would accept any token SAM + // signs, so naming another owner's pool must never produce one. + await assertGcpWifPoolOwnership(env, credential, requester.poolOwner, 'token_exchange'); + throwIfProviderRequestAborted(context); + const identityToken = await signIdentityToken( + { userId: requester.tokenUserId, projectId, audience: jwtAudience }, + env + ); const stsResponse = await fetchWithTimeout( gcpStsUrl, @@ -272,12 +292,12 @@ async function exchangeGcpWifAccessToken( /** Verify the existing WIF path with a full exchange. */ export async function verifyGcpOidcSetup( - userId: string, + requester: GcpTokenRequester, projectId: string, credential: GcpOidcCredential, env: Env, context?: ProviderRequestContext ): Promise { - await getGcpAccessToken(userId, projectId, credential, env, context); + await getGcpAccessToken(requester, projectId, credential, env, context); return true; } diff --git a/apps/api/src/services/gcp-token-provider.ts b/apps/api/src/services/gcp-token-provider.ts index d4aa090c31..bc58da2c9d 100644 --- a/apps/api/src/services/gcp-token-provider.ts +++ b/apps/api/src/services/gcp-token-provider.ts @@ -2,7 +2,7 @@ import type { GcpTokenProvider, ProviderRequestContext } from '@simple-agent-man import type { CredentialSource, GcpCredential } from '@simple-agent-manager/shared'; import type { Env } from '../env'; -import type { GcpAccessTokenOptions } from './gcp-sts'; +import type { GcpAccessTokenOptions, GcpTokenRequester } from './gcp-sts'; /** Who a GCP token is minted for: the credential's owner and the SAM project it serves. */ export interface GcpTokenOwner { @@ -10,6 +10,29 @@ export interface GcpTokenOwner { userId: string; /** The SAM project the token acts for; null when the credential is not project-scoped. */ projectId: string | null; + /** + * The user who stored the credential, when it differs from `userId`: a project-scoped + * credential one member saved and another member's run uses. Defaults to `userId`. + * Ignored for platform credentials, which the installation owns. + */ + credentialOwnerUserId?: string; +} + +/** The token identity and pool owner for a credential resolved for `owner`. */ +export function gcpTokenRequester(owner: GcpTokenOwner): GcpTokenRequester { + const tokenUserId = + owner.credentialSource === 'platform' + ? `platform:${owner.userId}` + : owner.credentialSource === 'project' && owner.projectId + ? `project:${owner.projectId}:${owner.userId}` + : owner.userId; + return { + tokenUserId, + poolOwner: + owner.credentialSource === 'platform' + ? { kind: 'platform' } + : { kind: 'user', userId: owner.credentialOwnerUserId ?? owner.userId }, + }; } /** @@ -24,17 +47,12 @@ export function createGcpTokenProvider( env: Env, options: GcpAccessTokenOptions = {} ): GcpTokenProvider { - const cacheUserId = - owner.credentialSource === 'platform' - ? `platform:${owner.userId}` - : owner.credentialSource === 'project' && owner.projectId - ? `project:${owner.projectId}:${owner.userId}` - : owner.userId; + const requester = gcpTokenRequester(owner); const cacheProjectId = owner.projectId ?? credential.gcpProjectId; return async (context?: ProviderRequestContext) => { const { getGcpAccessToken } = await import('./gcp-sts'); return options.scopes - ? getGcpAccessToken(cacheUserId, cacheProjectId, credential, env, context, options) - : getGcpAccessToken(cacheUserId, cacheProjectId, credential, env, context); + ? getGcpAccessToken(requester, cacheProjectId, credential, env, context, options) + : getGcpAccessToken(requester, cacheProjectId, credential, env, context); }; } diff --git a/apps/api/src/services/gcp-wif-pool-ownership.ts b/apps/api/src/services/gcp-wif-pool-ownership.ts new file mode 100644 index 0000000000..008d093577 --- /dev/null +++ b/apps/api/src/services/gcp-wif-pool-ownership.ts @@ -0,0 +1,388 @@ +/** + * One owner per Google Cloud workload identity pool. + * + * SAM signs an identity token for whatever pool a stored GCP credential names. A pool whose + * provider checks only SAM's issuer, with a `pool/*` binding (the user-level guided setup before + * this module existed), accepts any token SAM signs. So user B could save a credential naming + * user A's pool and impersonate A's service account. This module refuses that on the Worker side: + * a credential may name a `(gcpProjectNumber, wifPoolId)` only when no credential belonging to a + * different owner names it. Owners are one SAM user (user-level and project-scoped credentials of + * the same user may share a pool) or the installation (platform credentials). + * + * Pool identities live inside encrypted credential payloads, so they are indexed in + * `gcp_wif_pool_index`, one row per stored credential, keyed by the row's IV. Writers do not + * maintain the index: every check first indexes rows whose IV the index has not seen (a new or + * re-encrypted row), then reads owners only through index rows whose source row still exists with + * the same IV. A writer that forgets the index, a deleted credential, or a rotation therefore + * cannot leave the check reading stale data. Deployment credentials store their pool in plaintext + * and are read directly. + * + * Per check: one D1 round trip (the unindexed-row probe and the owner lookup run as one batch). + * Only when a credential was added or re-encrypted since the last check does it decrypt those + * rows, page by page, inside a time budget, and run the owner lookup again. + */ +import type { Env } from '../env'; +import { log } from '../lib/logger'; +import { getCredentialEncryptionKey } from '../lib/secrets'; +import { AppError } from '../middleware/error'; +import { resolveAdminSetting } from './admin-settings-resolution'; +import { decrypt } from './encryption'; +import { extractCloudProviderToken, parseGcpCredential } from './provider-credential-codecs'; + +/** Who a stored GCP credential belongs to, for pool ownership. */ +export type GcpWifPoolOwner = { kind: 'platform' } | { kind: 'user'; userId: string }; + +/** The pool a workload-identity credential names, in comparable form. */ +export interface GcpWifPoolIdentity { + gcpProjectNumber: string; + wifPoolId: string; + /** `/`, the index key. */ + key: string; +} + +const PROJECT_NUMBER_PATTERN = /^\d{1,20}$/; +const POOL_ID_PATTERN = /^[a-z0-9-]{1,63}$/; + +/** + * Normalize a pool identity, or return null when the values cannot name a real pool. Google + * resource IDs are lowercase and STS audiences use the project number, so a value that differs + * only in case or whitespace is the same pool. + */ +export function gcpWifPoolIdentity( + gcpProjectNumber: string, + wifPoolId: string +): GcpWifPoolIdentity | null { + const projectNumber = gcpProjectNumber.trim(); + const poolId = wifPoolId.trim().toLowerCase(); + if (!PROJECT_NUMBER_PATTERN.test(projectNumber) || !POOL_ID_PATTERN.test(poolId)) return null; + return { gcpProjectNumber: projectNumber, wifPoolId: poolId, key: `${projectNumber}/${poolId}` }; +} + +/** + * The pool a decrypted cloud-provider payload names, or null when it is not a GCP + * workload-identity credential. Never throws: stored payloads come in several encodings + * (raw tokens for other providers, `{provider, token}` wrappers, GCP JSON), and a payload this + * cannot read must not break the check for every other credential (rule 41). + */ +export function gcpWifPoolFromDecryptedPayload(decrypted: string): GcpWifPoolIdentity | null { + try { + const credential = parseGcpCredential(extractCloudProviderToken('gcp', decrypted)); + if (credential.authType !== 'workload-identity') return null; + return gcpWifPoolIdentity(credential.gcpProjectNumber, credential.wifPoolId); + } catch { + return null; + } +} + +export class GcpWifPoolOwnedByAnotherOwnerError extends AppError { + constructor() { + super( + 409, + 'GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER', + 'This Google Cloud workload identity pool is already used by a credential that belongs to a different SAM owner. Each SAM user, and the installation itself, must use its own pool.' + ); + this.name = 'GcpWifPoolOwnedByAnotherOwnerError'; + } +} + +export class GcpWifPoolInvalidError extends AppError { + constructor() { + super( + 400, + 'GCP_WIF_POOL_INVALID', + 'The Google Cloud project number must be digits and the workload identity pool ID may contain only lowercase letters, digits and hyphens.' + ); + this.name = 'GcpWifPoolInvalidError'; + } +} + +export class GcpWifPoolIndexUnavailableError extends AppError { + constructor() { + super( + 503, + 'GCP_WIF_POOL_INDEX_UNAVAILABLE', + 'SAM could not confirm who owns this Google Cloud workload identity pool. Try again shortly.' + ); + this.name = 'GcpWifPoolIndexUnavailableError'; + } +} + +/** True for the refusals this module raises, which callers must surface unchanged. */ +export function isGcpWifPoolOwnershipError(err: unknown): boolean { + return ( + err instanceof GcpWifPoolOwnedByAnotherOwnerError || + err instanceof GcpWifPoolInvalidError || + err instanceof GcpWifPoolIndexUnavailableError + ); +} + +type SourceTable = 'credentials' | 'platform_credentials' | 'cc_credentials'; + +interface UnindexedRow { + sourceTable: SourceTable; + sourceId: string; + ownerKind: 'user' | 'platform'; + ownerUserId: string | null; + encryptedToken: string; + iv: string; +} + +interface PoolOwnerRow { + sourceTable: string; + sourceId: string; + ownerKind: 'user' | 'platform'; + ownerUserId: string | null; +} + +// Every stored row that can be exchanged as a GCP credential. Composable credentials do not +// record their provider in plaintext, so every cloud-provider row is indexed once (a non-GCP row +// is stored with a NULL pool and is not decrypted again until it is re-encrypted). +const UNINDEXED_ROWS_SQL = ` +SELECT 'credentials' AS sourceTable, c.id AS sourceId, 'user' AS ownerKind, c.user_id AS ownerUserId, + c.encrypted_token AS encryptedToken, c.iv AS iv + FROM credentials c + WHERE c.provider = 'gcp' AND c.credential_type = 'cloud-provider' + AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i + WHERE i.source_table = 'credentials' AND i.source_id = c.id + AND i.iv = c.iv AND i.owner_kind = 'user' AND i.owner_user_id = c.user_id) +UNION ALL +SELECT 'platform_credentials', p.id, 'platform', NULL, p.encrypted_token, p.iv + FROM platform_credentials p + WHERE p.provider = 'gcp' AND p.credential_type = 'cloud-provider' + AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i + WHERE i.source_table = 'platform_credentials' AND i.source_id = p.id + AND i.iv = p.iv AND i.owner_kind = 'platform') +UNION ALL +SELECT 'cc_credentials', cc.id, 'user', cc.owner_id, cc.encrypted_token, cc.iv + FROM cc_credentials cc + WHERE cc.kind = 'cloud-provider' + AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i + WHERE i.source_table = 'cc_credentials' AND i.source_id = cc.id + AND i.iv = cc.iv AND i.owner_kind = 'user' AND i.owner_user_id = cc.owner_id) +LIMIT ?`; + +// Owners of one pool. Index rows of deleted credentials drop out through the existence checks. +// The read is used only when the unindexed-row probe in the same D1 batch (one transaction) +// returned nothing, so every remaining index row already matches its credential's current IV and +// owner. Inactive and disabled rows still count: they can be re-enabled, and the pool's binding +// in Google still trusts them. +const POOL_OWNERS_SQL = ` +SELECT i.source_table AS sourceTable, i.source_id AS sourceId, i.owner_kind AS ownerKind, + i.owner_user_id AS ownerUserId + FROM gcp_wif_pool_index i + WHERE i.pool_key = ? + AND ( + (i.source_table = 'credentials' AND EXISTS ( + SELECT 1 FROM credentials c WHERE c.id = i.source_id AND c.provider = 'gcp' + AND c.credential_type = 'cloud-provider')) + OR (i.source_table = 'platform_credentials' AND EXISTS ( + SELECT 1 FROM platform_credentials p WHERE p.id = i.source_id AND p.provider = 'gcp' + AND p.credential_type = 'cloud-provider')) + OR (i.source_table = 'cc_credentials' AND EXISTS ( + SELECT 1 FROM cc_credentials cc WHERE cc.id = i.source_id AND cc.kind = 'cloud-provider')) + ) +UNION ALL +SELECT 'project_deployment_credentials', d.id, 'user', d.user_id + FROM project_deployment_credentials d + WHERE d.provider = 'gcp' AND d.gcp_project_number = ? AND lower(trim(d.wif_pool_id)) = ?`; + +const UPSERT_INDEX_SQL = ` +INSERT INTO gcp_wif_pool_index + (source_table, source_id, iv, owner_kind, owner_user_id, pool_key, indexed_at) +VALUES (?, ?, ?, ?, ?, ?, ?) +ON CONFLICT (source_table, source_id) DO UPDATE SET + iv = excluded.iv, owner_kind = excluded.owner_kind, owner_user_id = excluded.owner_user_id, + pool_key = excluded.pool_key, indexed_at = excluded.indexed_at`; + +function isSourceTable(value: unknown): value is SourceTable { + return value === 'credentials' || value === 'platform_credentials' || value === 'cc_credentials'; +} + +function toUnindexedRow(row: Record): UnindexedRow | null { + const { sourceTable, sourceId, ownerKind, ownerUserId, encryptedToken, iv } = row; + if ( + !isSourceTable(sourceTable) || + typeof sourceId !== 'string' || + (ownerKind !== 'user' && ownerKind !== 'platform') || + (ownerUserId !== null && typeof ownerUserId !== 'string') || + typeof encryptedToken !== 'string' || + typeof iv !== 'string' + ) { + return null; + } + return { sourceTable, sourceId, ownerKind, ownerUserId, encryptedToken, iv }; +} + +function toPoolOwnerRow(row: Record): PoolOwnerRow | null { + const { sourceTable, sourceId, ownerKind, ownerUserId } = row; + if ( + typeof sourceTable !== 'string' || + typeof sourceId !== 'string' || + (ownerKind !== 'user' && ownerKind !== 'platform') || + (ownerUserId !== null && typeof ownerUserId !== 'string') + ) { + return null; + } + return { sourceTable, sourceId, ownerKind, ownerUserId }; +} + +function ownerLabel(owner: GcpWifPoolOwner): string { + return owner.kind === 'platform' ? 'platform' : `user:${owner.userId}`; +} + +function belongsToOwner(row: PoolOwnerRow, owner: GcpWifPoolOwner): boolean { + if (owner.kind === 'platform') return row.ownerKind === 'platform'; + return row.ownerKind === 'user' && row.ownerUserId === owner.userId; +} + +async function readIndexSettings(env: Env): Promise<{ pageSize: number; budgetMs: number }> { + const [pageSize, budgetMs] = await Promise.all([ + resolveAdminSetting(env, 'gcpWif.poolIndexPageSize'), + resolveAdminSetting(env, 'gcpWif.poolIndexBudgetMs'), + ]); + return { pageSize: Number(pageSize), budgetMs: Number(budgetMs) }; +} + +/** Decrypt and index one page of unindexed rows. A row that fails is indexed with no pool. */ +async function indexRows(env: Env, rows: UnindexedRow[]): Promise { + const key = getCredentialEncryptionKey(env); + const now = new Date().toISOString(); + const statements: D1PreparedStatement[] = []; + for (const row of rows) { + let poolKey: string | null = null; + try { + const decrypted = await decrypt(row.encryptedToken, row.iv, key); + poolKey = gcpWifPoolFromDecryptedPayload(decrypted)?.key ?? null; + } catch (err) { + // An unreadable row cannot be exchanged either, so it owns no pool. Recording it stops + // it being decrypted again on every check until it is re-encrypted (rule 41, rule 47). + log.error('gcp_wif_pool_index.row_unreadable', { + sourceTable: row.sourceTable, + sourceId: row.sourceId, + error: err instanceof Error ? err.message : String(err), + action: 'indexed_without_pool', + }); + } + statements.push( + env.DATABASE.prepare(UPSERT_INDEX_SQL).bind( + row.sourceTable, + row.sourceId, + row.iv, + row.ownerKind, + row.ownerKind === 'platform' ? null : row.ownerUserId, + poolKey, + now + ) + ); + } + if (statements.length > 0) await env.DATABASE.batch(statements); +} + +function parseRows( + results: Record[] | undefined, + parse: (row: Record) => T | null, + context: string +): T[] { + const parsed: T[] = []; + for (const row of results ?? []) { + const value = parse(row); + if (value) parsed.push(value); + else log.error('gcp_wif_pool_index.row_skipped', { context, action: 'skipped' }); + } + return parsed; +} + +/** + * Bring the index up to date, then return every live credential that names `pool`. + * Throws GcpWifPoolIndexUnavailableError when unindexed rows remain after the time budget, + * because an incomplete index cannot prove that no other owner names the pool. + */ +async function listPoolOwners(env: Env, pool: GcpWifPoolIdentity): Promise { + const { pageSize, budgetMs } = await readIndexSettings(env); + const deadline = Date.now() + budgetMs; + const ownersStatement = env.DATABASE.prepare(POOL_OWNERS_SQL).bind( + pool.key, + pool.gcpProjectNumber, + pool.wifPoolId + ); + let indexedAny = false; + for (;;) { + const [unindexedResult, ownersResult] = await env.DATABASE.batch>([ + env.DATABASE.prepare(UNINDEXED_ROWS_SQL).bind(pageSize), + ownersStatement, + ]); + const unindexed = parseRows(unindexedResult?.results, toUnindexedRow, 'unindexed'); + if (unindexed.length === 0) { + const owners = parseRows(ownersResult?.results, toPoolOwnerRow, 'owners'); + if (indexedAny) { + log.info('gcp_wif_pool_index.reconciled', { poolKey: pool.key, owners: owners.length }); + } + return owners; + } + if (Date.now() >= deadline) { + log.error('gcp_wif_pool_index.budget_exhausted', { + poolKey: pool.key, + budgetMs, + remainingPage: unindexed.length, + action: 'refused', + }); + throw new GcpWifPoolIndexUnavailableError(); + } + await indexRows(env, unindexed); + indexedAny = true; + } +} + +/** + * Refuse when a credential belonging to a different owner names `pool`. + * `context` names the caller (save route or token exchange) for the structured log line. + */ +export async function assertGcpWifPoolOwnership( + env: Env, + pool: { gcpProjectNumber: string; wifPoolId: string }, + owner: GcpWifPoolOwner, + context: string +): Promise { + const identity = gcpWifPoolIdentity(pool.gcpProjectNumber, pool.wifPoolId); + if (!identity) { + log.error('gcp_wif_pool.invalid_identity', { + context, + owner: ownerLabel(owner), + action: 'refused', + }); + throw new GcpWifPoolInvalidError(); + } + const owners = await listPoolOwners(env, identity); + const foreign = owners.filter((row) => !belongsToOwner(row, owner)); + if (foreign.length === 0) return; + log.error('gcp_wif_pool.cross_owner_refused', { + context, + poolKey: identity.key, + owner: ownerLabel(owner), + conflictingCredentials: foreign.map((row) => `${row.sourceTable}:${row.sourceId}`), + conflictingOwnerKinds: [...new Set(foreign.map((row) => row.ownerKind))], + action: 'refused', + }); + throw new GcpWifPoolOwnedByAnotherOwnerError(); +} + +/** + * Save-time form of the check for a decrypted or about-to-be-encrypted cloud-provider payload. + * Payloads that are not GCP workload-identity credentials pass through untouched. + */ +export async function assertGcpWifPayloadOwnership( + env: Env, + payload: string, + owner: GcpWifPoolOwner, + context: string +): Promise { + const credential = (() => { + try { + return parseGcpCredential(extractCloudProviderToken('gcp', payload)); + } catch { + return null; + } + })(); + if (credential?.authType !== 'workload-identity') return; + await assertGcpWifPoolOwnership(env, credential, owner, context); +} diff --git a/apps/api/src/services/gcp-wif-setup.ts b/apps/api/src/services/gcp-wif-setup.ts index b9124d98c4..a5266dbdad 100644 --- a/apps/api/src/services/gcp-wif-setup.ts +++ b/apps/api/src/services/gcp-wif-setup.ts @@ -17,16 +17,65 @@ const serviceAccountPolicySchema = v.object({ }); /** - * Validate a value is safe for interpolation into a GCP CEL attribute condition. - * SAM project IDs are ULIDs (alphanumeric), but this guard enforces the invariant - * at the function boundary to prevent injection if a non-ULID value is ever passed. + * Validate a value is safe for interpolation into a GCP CEL attribute condition or an IAM + * principal path. SAM project and user IDs are alphanumeric, but this guard enforces the + * invariant at the function boundary to prevent injection if another value is ever passed. */ function assertSafeCelValue(value: string, fieldName: string): void { - if (!/^[a-zA-Z0-9_:.-]+$/.test(value)) { + if (typeof value !== 'string' || !/^[a-zA-Z0-9_:.-]+$/.test(value)) { throw new Error(`${fieldName} contains characters unsafe for CEL interpolation`); } } +/** + * Whose tokens a workload identity provider and its service-account binding accept. + * - `project`: one SAM project (deployment setup). Tokens carry `project_id` and + * `sub = project:`. + * - `user`: one SAM user (user-level guided setup). Tokens carry `user_id`, mapped to + * `attribute.sam_user`. + * There is no issuer-only scope: a provider that checks only SAM's issuer accepts a token SAM + * signs for any user, so any user could name the pool and impersonate its service account. + */ +export type WifTrustScope = + { kind: 'project'; samProjectId: string } | { kind: 'user'; userId: string }; + +function assertSafeTrustScope(scope: WifTrustScope): void { + if (scope.kind === 'project') assertSafeCelValue(scope.samProjectId, 'samProjectId'); + else assertSafeCelValue(scope.userId, 'userId'); +} + +/** The provider's attribute condition: SAM's issuer plus the scope's own claim. */ +export function wifAttributeCondition(issuerUri: string, scope: WifTrustScope): string { + assertSafeTrustScope(scope); + return scope.kind === 'project' + ? `assertion.iss == '${issuerUri}' && assertion.project_id == '${scope.samProjectId}'` + : `assertion.iss == '${issuerUri}' && assertion.user_id == '${scope.userId}'`; +} + +function poolPrincipalPrefix(projectNumber: string, poolId: string): string { + return `iam.googleapis.com/projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}`; +} + +/** The service-account binding member that admits exactly the scope's tokens. */ +export function wifServiceAccountMember( + projectNumber: string, + poolId: string, + scope: WifTrustScope +): string { + assertSafeTrustScope(scope); + const pool = poolPrincipalPrefix(projectNumber, poolId); + // A project token's `sub` is `project:`; a user token's `user_id` is mapped + // to `attribute.sam_user`. + return scope.kind === 'project' + ? `principal://${pool}/subject/project:${scope.samProjectId}` + : `principalSet://${pool}/attribute.sam_user/${scope.userId}`; +} + +/** The pool-wide member earlier user-level setups granted. Re-running setup removes it. */ +export function legacyPoolWideMember(projectNumber: string, poolId: string): string { + return `principalSet://${poolPrincipalPrefix(projectNumber, poolId)}/*`; +} + /** Google allows 4-32 characters of [a-z0-9-] for a provider ID and reserves the "gcp-" prefix. */ const WIF_PROVIDER_ID_MAX_LENGTH = 32; const WIF_PROVIDER_ID_PREFIX = 'sam-'; @@ -122,20 +171,14 @@ export async function createOidcProvider( providerId: string, issuerUri: string, timeoutMs: number, - samProjectId?: string + scope: WifTrustScope ): Promise { // The OIDC provider's allowedAudiences must match the JWT aud claim (https:// scheme). // GCP STS uses the protocol-relative format (//iam.googleapis.com/...) separately in gcp-sts.ts. const wifAudience = `https://iam.googleapis.com/projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`; - // Enforce both issuer and SAM project ID in the attribute condition to prevent - // cross-project impersonation within the same WIF pool. - if (samProjectId) { - assertSafeCelValue(samProjectId, 'samProjectId'); - } - const attributeCondition = samProjectId - ? `assertion.iss == '${issuerUri}' && assertion.project_id == '${samProjectId}'` - : `assertion.iss == '${issuerUri}'`; + // Issuer plus the scope's own claim, so a token SAM signs for anyone else is refused. + const attributeCondition = wifAttributeCondition(issuerUri, scope); const url = `${IAM_URL}/projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/providers?workloadIdentityPoolProviderId=${providerId}`; const res = await fetchWithTimeout( @@ -173,7 +216,7 @@ export async function createOidcProvider( providerId, issuerUri, timeoutMs, - samProjectId + scope ); return; } @@ -238,16 +281,13 @@ export async function updateOidcProvider( providerId: string, issuerUri: string, timeoutMs: number, - samProjectId?: string + scope: WifTrustScope ): Promise { const wifAudience = `https://iam.googleapis.com/projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`; - if (samProjectId) { - assertSafeCelValue(samProjectId, 'samProjectId'); - } - const attributeCondition = samProjectId - ? `assertion.iss == '${issuerUri}' && assertion.project_id == '${samProjectId}'` - : `assertion.iss == '${issuerUri}'`; + // Re-running setup rewrites an existing provider's condition, so a provider created by an + // earlier issuer-only setup is narrowed to the scope here. + const attributeCondition = wifAttributeCondition(issuerUri, scope); const name = `projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`; await requireOidcProviderIssuer(oauthToken, name, issuerUri, timeoutMs); @@ -302,12 +342,11 @@ export async function grantWifUserOnSa( saEmail: string, poolId: string, timeoutMs: number, - samProjectId?: string + scope: WifTrustScope ): Promise { // Validate early, before any network calls (fail-fast pattern). - if (samProjectId) { - assertSafeCelValue(samProjectId, 'samProjectId'); - } + const member = wifServiceAccountMember(projectNumber, poolId, scope); + const legacyMember = legacyPoolWideMember(projectNumber, poolId); const saResource = `projects/${projectId}/serviceAccounts/${saEmail}`; @@ -342,27 +381,28 @@ export async function grantWifUserOnSa( 'gcp.iam.service_account_policy' ); - // Use subject-scoped principal to prevent cross-project impersonation. - // The `sub` claim in the identity token is `project:${samProjectId}`, so the principal - // matches only tokens issued for this specific SAM project. - const member = samProjectId - ? `principal://iam.googleapis.com/projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/subject/project:${samProjectId}` - : `principalSet://iam.googleapis.com/projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/*`; const role = 'roles/iam.workloadIdentityUser'; - // Check if binding already exists - const existingBinding = (policy.bindings || []).find((b) => b.role === role); - if (existingBinding?.members?.includes(member)) { - return; // Already granted + // Grant the scoped member and drop the pool-wide member an earlier user-level setup granted: + // while `pool/*` stays, any provider in the pool that still trusts SAM's issuer alone lets + // every SAM user impersonate this service account. + const roleBindings = (policy.bindings || []).filter((b) => b.role === role); + const granted = roleBindings.some((b) => b.members.includes(member)); + const legacyPresent = roleBindings.some((b) => b.members.includes(legacyMember)); + if (granted && !legacyPresent) { + return; // Already granted, nothing to remove } - // Add our binding - const bindings = [...(policy.bindings || [])]; - if (existingBinding) { - existingBinding.members.push(member); - } else { - bindings.push({ role, members: [member] }); + const bindings = (policy.bindings || []).map((b) => + b.role === role ? { ...b, members: b.members.filter((m) => m !== legacyMember) } : b + ); + if (!granted) { + const target = bindings.find((b) => b.role === role); + if (target) target.members.push(member); + else bindings.push({ role, members: [member] }); } + // A binding left with no members after removing `pool/*` is dropped rather than sent empty. + const nonEmptyBindings = bindings.filter((b) => b.members.length > 0); // Write updated policy const setUrl = `${IAM_URL}/${saResource}:setIamPolicy`; @@ -374,7 +414,7 @@ export async function grantWifUserOnSa( Authorization: `Bearer ${oauthToken}`, 'Content-Type': 'application/json', }, - body: JSON.stringify({ policy: { bindings, etag: policy.etag } }), + body: JSON.stringify({ policy: { bindings: nonEmptyBindings, etag: policy.etag } }), }, timeoutMs ); diff --git a/apps/api/src/services/provider-credential-exact.ts b/apps/api/src/services/provider-credential-exact.ts index adc5db8ea6..b2ba37b1cc 100644 --- a/apps/api/src/services/provider-credential-exact.ts +++ b/apps/api/src/services/provider-credential-exact.ts @@ -1,7 +1,5 @@ import type { Provider } from '@simple-agent-manager/providers'; -import { - timestampVersion, -} from '@simple-agent-manager/scheduler-core'; +import { timestampVersion } from '@simple-agent-manager/scheduler-core'; import type { CredentialProvider, CredentialSource } from '@simple-agent-manager/shared'; import { and, eq, isNull } from 'drizzle-orm'; import { type drizzle } from 'drizzle-orm/d1'; @@ -47,7 +45,9 @@ type ProviderFactory = ( credentialSource: CredentialSource, userId: string, projectId: string | null, - env: TEnv + env: TEnv, + /** The user who stored the credential, when a project member uses another member's row. */ + credentialOwnerUserId?: string ) => Promise; export function parseProviderCredentialReference( @@ -73,7 +73,9 @@ export function parseProviderCredentialReference( return null; } -export function isExactCredentialSource(value: string | null | undefined): value is CredentialSource { +export function isExactCredentialSource( + value: string | null | undefined +): value is CredentialSource { return value === 'user' || value === 'project' || value === 'platform'; } @@ -323,7 +325,8 @@ export async function createProviderForExactCredential( 'project', userId, projectId, - env + env, + cred.userId ); return { ...result, @@ -363,6 +366,7 @@ async function createProviderForExactComposableCredential( const [row] = await db .select({ + ownerId: schema.ccCredentials.ownerId, encryptedToken: schema.ccCredentials.encryptedToken, iv: schema.ccCredentials.iv, createdAt: schema.ccCredentials.createdAt, @@ -401,7 +405,8 @@ async function createProviderForExactComposableCredential( credentialSource, userId, projectId, - env + env, + row.ownerId ); return { ...result, diff --git a/apps/api/src/services/provider-credentials.ts b/apps/api/src/services/provider-credentials.ts index 4e2b306b09..b9767d4d1e 100644 --- a/apps/api/src/services/provider-credentials.ts +++ b/apps/api/src/services/provider-credentials.ts @@ -16,6 +16,7 @@ import { lazyBackfillIfNeeded } from './composable-credentials/lazy-backfill'; import { resolveForConsumer } from './composable-credentials/resolve'; import { decrypt } from './encryption'; import { createGcpProviderForEnv } from './gcp-provider-factory'; +import type { GcpTokenRequester } from './gcp-sts'; import { createGcpTokenProvider } from './gcp-token-provider'; import { buildProviderConfigForEnv } from './infomaniak-provider-settings'; import { getPlatformCloudCredential } from './platform-credentials'; @@ -163,13 +164,14 @@ async function createProviderFromDecryptedToken( credentialSource: CredentialSource, userId: string, projectId: string | null, - env: Env & Partial + env: Env & Partial, + credentialOwnerUserId?: string ): Promise { if (providerName === 'gcp') { const gcpCred = parseGcpCredential(decryptedToken); const tokenProvider = createGcpTokenProvider( gcpCred, - { credentialSource, userId, projectId }, + { credentialSource, userId, projectId, credentialOwnerUserId }, env ); return { @@ -266,10 +268,12 @@ async function createProviderFromComposableConfig( if (providerName === 'gcp') { const gcpCred = parseGcpCredential(token); const { getGcpAccessToken } = await import('./gcp-sts'); - const cacheUserId = isPlatform ? `platform:${userId}` : userId; + const requester: GcpTokenRequester = isPlatform + ? { tokenUserId: `platform:${userId}`, poolOwner: { kind: 'platform' } } + : { tokenUserId: userId, poolOwner: { kind: 'user', userId } }; const cacheProjectId = projectId ?? gcpCred.gcpProjectId; const tokenProvider = (context?: ProviderRequestContext) => - getGcpAccessToken(cacheUserId, cacheProjectId, gcpCred, env, context); + getGcpAccessToken(requester, cacheProjectId, gcpCred, env, context); return { provider: await createGcpProviderForEnv(env, gcpCred, tokenProvider), providerName, @@ -411,7 +415,17 @@ async function createProviderForUserLegacy( const gcpCred = parseGcpCredential(decryptedToken); const { getGcpAccessToken } = await import('./gcp-sts'); const tokenProvider = (context?: ProviderRequestContext) => - getGcpAccessToken(`project:${projectId}:${userId}`, projectId, gcpCred, env, context); + getGcpAccessToken( + { + tokenUserId: `project:${projectId}:${userId}`, + // The project credential may have been saved by another member of the project. + poolOwner: { kind: 'user', userId: projectCred.userId }, + }, + projectId, + gcpCred, + env, + context + ); const provider = await createGcpProviderForEnv(env, gcpCred, tokenProvider); return { @@ -475,7 +489,13 @@ async function createProviderForUserLegacy( const { getGcpAccessToken } = await import('./gcp-sts'); const cacheProjectId = projectId ?? gcpCred.gcpProjectId; const tokenProvider = (context?: ProviderRequestContext) => - getGcpAccessToken(userId, cacheProjectId, gcpCred, env, context); + getGcpAccessToken( + { tokenUserId: userId, poolOwner: { kind: 'user', userId } }, + cacheProjectId, + gcpCred, + env, + context + ); const provider = await createGcpProviderForEnv(env, gcpCred, tokenProvider); return { @@ -524,7 +544,13 @@ async function createProviderForUserLegacy( const { getGcpAccessToken } = await import('./gcp-sts'); const cacheProjectId = projectId ?? gcpCred.gcpProjectId; const tokenProvider = (context?: ProviderRequestContext) => - getGcpAccessToken(`platform:${userId}`, cacheProjectId, gcpCred, env, context); + getGcpAccessToken( + { tokenUserId: `platform:${userId}`, poolOwner: { kind: 'platform' } }, + cacheProjectId, + gcpCred, + env, + context + ); const provider = await createGcpProviderForEnv(env, gcpCred, tokenProvider); return { diff --git a/apps/api/tests/unit/gcp-deploy-setup.test.ts b/apps/api/tests/unit/gcp-deploy-setup.test.ts index 62950114e2..63ee073374 100644 --- a/apps/api/tests/unit/gcp-deploy-setup.test.ts +++ b/apps/api/tests/unit/gcp-deploy-setup.test.ts @@ -67,8 +67,8 @@ describe('runGcpDeploySetup', () => { 'fake-oauth-token', 'my-project', mockEnv(), - (step, status) => progressSteps.push({ step, status }), - 'sam-project-123' + 'sam-project-123', + (step, status) => progressSteps.push({ step, status }) ); // Verify result @@ -154,7 +154,8 @@ describe('runGcpDeploySetup', () => { GCP_DEPLOY_WIF_POOL_ID: 'custom-pool', GCP_DEPLOY_WIF_PROVIDER_ID: 'custom-provider', GCP_DEPLOY_SERVICE_ACCOUNT_ID: 'custom', - }) + }), + 'sam-project-123' ); expect(result.wifPoolId).toBe('custom-pool'); @@ -170,7 +171,7 @@ describe('runGcpDeploySetup', () => { mockFetch.mockResolvedValueOnce(mockGcpResponse(JSON.parse(rawBody), 403)); try { - await runGcpDeploySetup('fake-token', 'my-project', mockEnv()); + await runGcpDeploySetup('fake-token', 'my-project', mockEnv(), 'sam-project-123'); expect.fail('Should have thrown'); } catch (err) { expect(err).toBeInstanceOf(GcpApiError); @@ -202,7 +203,7 @@ describe('runGcpDeploySetup', () => { mockFetch.mockResolvedValueOnce(mockGcpResponse(JSON.parse(rawBody), 403)); try { - await runGcpDeploySetup('fake-token', 'p1', mockEnv()); + await runGcpDeploySetup('fake-token', 'p1', mockEnv(), 'sam-project-123'); expect.fail('Should have thrown'); } catch (err) { expect(err).toBeInstanceOf(GcpApiError); diff --git a/apps/api/tests/unit/routes/gcp.test.ts b/apps/api/tests/unit/routes/gcp.test.ts index 3d5132059f..b31486a47a 100644 --- a/apps/api/tests/unit/routes/gcp.test.ts +++ b/apps/api/tests/unit/routes/gcp.test.ts @@ -159,7 +159,7 @@ describe('GCP routes', () => { expect(res.status).toBe(200); expect(mocks.replaceUserGcpCredential).toHaveBeenCalledWith(env, 'test-user-id', wifCredential); expect(mocks.verifyGcpOidcSetup).toHaveBeenCalledWith( - 'test-user-id', + { tokenUserId: 'test-user-id', poolOwner: { kind: 'user', userId: 'test-user-id' } }, 'setup-verification', wifCredential, env @@ -197,7 +197,7 @@ describe('GCP routes', () => { ); expect(mocks.parseServiceAccountJson).toHaveBeenCalledWith(uploadedJson, 'us-central1-a'); expect(mocks.getGcpAccessToken).toHaveBeenCalledWith( - 'test-user-id', + { tokenUserId: 'test-user-id', poolOwner: { kind: 'user', userId: 'test-user-id' } }, 'service-account-setup', serviceAccountCredential, env diff --git a/apps/api/tests/unit/services/gcp-api-health.test.ts b/apps/api/tests/unit/services/gcp-api-health.test.ts index f52c02df31..012a3b5152 100644 --- a/apps/api/tests/unit/services/gcp-api-health.test.ts +++ b/apps/api/tests/unit/services/gcp-api-health.test.ts @@ -313,7 +313,8 @@ describe('runGcpSetup', () => { 'oauth-token', 'owner-project', 'us-central1-a', - setupEnv + setupEnv, + { userId: 'user-1' } ); expect(enabledServices).toEqual([ALL_REQUIRED]); @@ -326,7 +327,7 @@ describe('runGcpSetup', () => { stubGoogleSetup(false, true); await expect( - runGcpSetup('oauth-token', 'owner-project', 'us-central1-a', setupEnv) + runGcpSetup('oauth-token', 'owner-project', 'us-central1-a', setupEnv, { userId: 'user-1' }) ).rejects.toMatchObject({ step: 'enable_apis' }); }); }); diff --git a/apps/api/tests/unit/services/gcp-live-catalog-build.test.ts b/apps/api/tests/unit/services/gcp-live-catalog-build.test.ts index be9b034fda..815df44d74 100644 --- a/apps/api/tests/unit/services/gcp-live-catalog-build.test.ts +++ b/apps/api/tests/unit/services/gcp-live-catalog-build.test.ts @@ -18,10 +18,13 @@ import type { ProviderCatalogCredentialSeed } from '../../../src/services/provid import { serializeGcpCredential } from '../../../src/services/provider-credential-codecs'; import { createAllSchemaTables, createMemoryKv, createSqliteD1 } from '../../helpers/sqlite-d1'; -const tokenCalls: Array<{ userId: string; projectId: string }> = []; +const tokenCalls: Array<{ userId: string; poolOwner: unknown; projectId: string }> = []; vi.mock('../../../src/services/gcp-sts', () => ({ - getGcpAccessToken: async (userId: string, projectId: string) => { - tokenCalls.push({ userId, projectId }); + getGcpAccessToken: async ( + requester: { tokenUserId: string; poolOwner: unknown }, + projectId: string + ) => { + tokenCalls.push({ userId: requester.tokenUserId, poolOwner: requester.poolOwner, projectId }); return 'gcp-token'; }, })); @@ -139,7 +142,9 @@ describe('GCP live catalog build', () => { price: 'Price unavailable', }); // A user-level credential is bound to no SAM project, so its GCP project id is the identity. - expect(tokenCalls).toEqual([{ userId: 'user-1', projectId: 'my-vms' }]); + expect(tokenCalls).toEqual([ + { userId: 'user-1', poolOwner: { kind: 'user', userId: 'user-1' }, projectId: 'my-vms' }, + ]); }); it('mints a project-scoped credential for its SAM project', async () => { @@ -150,7 +155,13 @@ describe('GCP live catalog build', () => { seed: await seed({ credentialSource: 'project', ownerProjectId: 'project-9' }), }); - expect(tokenCalls).toEqual([{ userId: 'project:project-9:user-1', projectId: 'project-9' }]); + expect(tokenCalls).toEqual([ + { + userId: 'project:project-9:user-1', + poolOwner: { kind: 'user', userId: 'user-1' }, + projectId: 'project-9', + }, + ]); }); it('offers machine types unpriced when no price table has been stored yet', async () => { diff --git a/apps/api/tests/unit/services/gcp-price-table.test.ts b/apps/api/tests/unit/services/gcp-price-table.test.ts index 1f77111953..689b6ef48c 100644 --- a/apps/api/tests/unit/services/gcp-price-table.test.ts +++ b/apps/api/tests/unit/services/gcp-price-table.test.ts @@ -31,18 +31,28 @@ import { } from '../../helpers/google-api-errors'; import { createAllSchemaTables, createMemoryKv, createSqliteD1 } from '../../helpers/sqlite-d1'; -const tokenCalls: Array<{ userId: string; projectId: string; gcpProjectId: string }> = []; +const tokenCalls: Array<{ + userId: string; + poolOwner: unknown; + projectId: string; + gcpProjectId: string; +}> = []; const tokenScopes: Array = []; vi.mock('../../../src/services/gcp-sts', () => ({ getGcpAccessToken: async ( - userId: string, + requester: { tokenUserId: string; poolOwner: unknown }, projectId: string, credential: { gcpProjectId: string }, _env: unknown, _context: unknown, options?: { scopes?: readonly string[] } ) => { - tokenCalls.push({ userId, projectId, gcpProjectId: credential.gcpProjectId }); + tokenCalls.push({ + userId: requester.tokenUserId, + poolOwner: requester.poolOwner, + projectId, + gcpProjectId: credential.gcpProjectId, + }); tokenScopes.push(options?.scopes); return `token-for-${credential.gcpProjectId}`; }, @@ -212,7 +222,12 @@ describe('GCP price table', () => { expect(result).toMatchObject({ status: 'refreshed', credentialSource: 'platform', regions: 1 }); expect(fetchMock).toHaveBeenCalledTimes(1); expect(tokenCalls).toEqual([ - { userId: 'platform:admin-1', projectId: 'platform-gcp', gcpProjectId: 'platform-gcp' }, + { + userId: 'platform:admin-1', + poolOwner: { kind: 'platform' }, + projectId: 'platform-gcp', + gcpProjectId: 'platform-gcp', + }, ]); // The price read asks for read-only Cloud Billing alone; provisioning tokens never carry it. expect(tokenScopes).toEqual([['https://www.googleapis.com/auth/cloud-billing.readonly']]); @@ -233,7 +248,12 @@ describe('GCP price table', () => { await refreshGcpPriceTableIfDue(env, NOW); expect(tokenCalls).toEqual([ - { userId: 'project:project-9:user-1', projectId: 'project-9', gcpProjectId: 'project-gcp' }, + { + userId: 'project:project-9:user-1', + poolOwner: { kind: 'user', userId: 'user-1' }, + projectId: 'project-9', + gcpProjectId: 'project-gcp', + }, ]); }); diff --git a/apps/api/tests/unit/services/gcp-provider-cancellation-slice.test.ts b/apps/api/tests/unit/services/gcp-provider-cancellation-slice.test.ts index 40fc8c5f55..c3a09cb1d8 100644 --- a/apps/api/tests/unit/services/gcp-provider-cancellation-slice.test.ts +++ b/apps/api/tests/unit/services/gcp-provider-cancellation-slice.test.ts @@ -139,13 +139,13 @@ describe('GCP provider credential cancellation wiring', () => { mocks.resolveForConsumer.mockResolvedValue(composableGcpResolution()); return makeCredentialDbMock(); }, - expectedCacheUserId: USER_ID, + expectedRequester: { tokenUserId: USER_ID, poolOwner: { kind: 'user', userId: USER_ID } }, expectedSource: 'user', }, { name: 'legacy user credential', setup: () => makeCredentialDbMock(legacyGcpCredential()), - expectedCacheUserId: USER_ID, + expectedRequester: { tokenUserId: USER_ID, poolOwner: { kind: 'user', userId: USER_ID } }, expectedSource: 'user', }, { @@ -157,19 +157,19 @@ describe('GCP provider credential cancellation wiring', () => { }); return makeCredentialDbMock(); }, - expectedCacheUserId: `platform:${USER_ID}`, + expectedRequester: { tokenUserId: `platform:${USER_ID}`, poolOwner: { kind: 'platform' } }, expectedSource: 'platform', }, ])( 'forwards caller cancellation through the $name token closure', - async ({ setup, expectedCacheUserId, expectedSource }) => { + async ({ setup, expectedRequester, expectedSource }) => { const fetchMock = vi.fn(); const kvPut = vi.fn(); vi.stubGlobal('fetch', fetchMock); let receivedSignal: AbortSignal | undefined; mocks.getGcpAccessToken.mockImplementation( ( - _userId: string, + _requester: unknown, _projectId: string, _credential: unknown, _env: unknown, @@ -207,7 +207,7 @@ describe('GCP provider credential cancellation wiring', () => { expect(await validation).toBe(reason); expect(receivedSignal).toBe(caller.signal); expect(mocks.getGcpAccessToken).toHaveBeenCalledWith( - expectedCacheUserId, + expectedRequester, PROJECT_ID, expect.objectContaining({ provider: 'gcp' }), expect.any(Object), diff --git a/apps/api/tests/unit/services/gcp-service-account.test.ts b/apps/api/tests/unit/services/gcp-service-account.test.ts index 45f9292042..14e29e00a6 100644 --- a/apps/api/tests/unit/services/gcp-service-account.test.ts +++ b/apps/api/tests/unit/services/gcp-service-account.test.ts @@ -27,6 +27,13 @@ import { vi.mock('../../../src/services/jwt', () => ({ signIdentityToken: vi.fn().mockResolvedValue('sam-identity-token'), })); +// Pool ownership has its own real-SQL suite (gcp-wif-pool-ownership.test.ts); here it is a +// pass-through so these tests stay about cancellation and caching. +vi.mock('../../../src/services/gcp-wif-pool-ownership', () => ({ + assertGcpWifPoolOwnership: vi.fn().mockResolvedValue(undefined), +})); + +const USER_1 = { tokenUserId: 'user-1', poolOwner: { kind: 'user', userId: 'user-1' } } as const; let privateKey: string; @@ -201,7 +208,7 @@ describe('service-account verification and caching', () => { vi.stubGlobal('fetch', fetchMock); const request = getGcpAccessToken( - 'user-1', + USER_1, 'project-a', credential, { KV: kv.namespace } as Env, @@ -242,7 +249,7 @@ describe('service-account verification and caching', () => { vi.stubGlobal('fetch', fetchMock); const request = getGcpAccessToken( - 'user-1', + USER_1, 'project-a', credential, { KV: kv.namespace } as Env, @@ -272,6 +279,40 @@ describe('service-account verification and caching', () => { ); }); + it('checks pool ownership for the credential owner before signing, and refuses without signing', async () => { + const { assertGcpWifPoolOwnership } = + await import('../../../src/services/gcp-wif-pool-ownership'); + const { signIdentityToken } = await import('../../../src/services/jwt'); + const credential = workloadIdentityCredential(); + const kv = createKv(); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const refusal = new Error('pool belongs to another owner'); + vi.mocked(assertGcpWifPoolOwnership).mockRejectedValueOnce(refusal); + vi.mocked(signIdentityToken).mockClear(); + const env = { KV: kv.namespace } as Env; + + await expect( + getGcpAccessToken( + { tokenUserId: 'project:p-1:user-2', poolOwner: { kind: 'user', userId: 'user-9' } }, + 'p-1', + credential, + env + ) + ).rejects.toBe(refusal); + + expect(assertGcpWifPoolOwnership).toHaveBeenLastCalledWith( + env, + credential, + // The stored credential's owner, not the user whose run is asking. + { kind: 'user', userId: 'user-9' }, + 'token_exchange' + ); + expect(signIdentityToken).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(kv.namespace.put).not.toHaveBeenCalled(); + }); + it('cancels a pending WIF STS exchange without IAM impersonation or token caching', async () => { const credential = workloadIdentityCredential(); const kv = createKv(); @@ -286,7 +327,7 @@ describe('service-account verification and caching', () => { vi.stubGlobal('fetch', fetchMock); const request = getGcpAccessToken( - 'user-1', + USER_1, 'project-a', credential, { KV: kv.namespace } as Env, @@ -327,7 +368,7 @@ describe('service-account verification and caching', () => { vi.stubGlobal('fetch', fetchMock); const request = getGcpAccessToken( - 'user-1', + USER_1, 'project-a', credential, { KV: kv.namespace } as Env, @@ -363,13 +404,13 @@ describe('service-account verification and caching', () => { vi.stubGlobal('fetch', fetchMock); const env = { KV: kv.namespace } as Env; - await expect(getGcpAccessToken('user-1', 'project-a', credential, env)).resolves.toBe( + await expect(getGcpAccessToken(USER_1, 'project-a', credential, env)).resolves.toBe( 'short-lived-token' ); - await expect(getGcpAccessToken('user-1', 'project-a', credential, env)).resolves.toBe( + await expect(getGcpAccessToken(USER_1, 'project-a', credential, env)).resolves.toBe( 'short-lived-token' ); - await expect(getGcpAccessToken('user-1', 'project-b', credential, env)).resolves.toBe( + await expect(getGcpAccessToken(USER_1, 'project-b', credential, env)).resolves.toBe( 'short-lived-token' ); @@ -439,8 +480,8 @@ describe('WIF impersonation scopes', () => { const env = { KV: kv.namespace } as Env; const { impersonationScopes } = stubWifExchange(); - const provisioning = await getGcpAccessToken('user-1', 'project-a', credential, env); - const pricing = await getGcpAccessToken('user-1', 'project-a', credential, env, undefined, { + const provisioning = await getGcpAccessToken(USER_1, 'project-a', credential, env); + const pricing = await getGcpAccessToken(USER_1, 'project-a', credential, env, undefined, { scopes: ['https://www.googleapis.com/auth/cloud-billing.readonly'], }); @@ -451,7 +492,7 @@ describe('WIF impersonation scopes', () => { // Different scopes never share a cached token, in either order. expect(provisioning).toBe('token-1'); expect(pricing).toBe('token-2'); - expect(await getGcpAccessToken('user-1', 'project-a', credential, env)).toBe('token-1'); + expect(await getGcpAccessToken(USER_1, 'project-a', credential, env)).toBe('token-1'); expect(kv.puts.map((put) => put.key)).toEqual([ getGcpAccessTokenCacheKey('user-1', 'project-a', credential), expect.stringMatching(/:scopes:/), @@ -463,7 +504,7 @@ describe('WIF impersonation scopes', () => { const kv = createKv(); const env = { KV: kv.namespace } as Env; stubWifExchange(); - await getGcpAccessToken('user-1', 'project-a', credential, env, undefined, { + await getGcpAccessToken(USER_1, 'project-a', credential, env, undefined, { scopes: ['https://www.googleapis.com/auth/cloud-billing.readonly'], }); expect(kv.values.size).toBe(1); diff --git a/apps/api/tests/unit/services/gcp-wif-installation-isolation.test.ts b/apps/api/tests/unit/services/gcp-wif-installation-isolation.test.ts index 88fcef6234..bd049ea47c 100644 --- a/apps/api/tests/unit/services/gcp-wif-installation-isolation.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-installation-isolation.test.ts @@ -15,7 +15,10 @@ function existingProvider(body: unknown) { } async function create() { - return createOidcProvider('oauth-token', '123456', 'shared', 'sam-oidc', issuer, 5000); + return createOidcProvider('oauth-token', '123456', 'shared', 'sam-oidc', issuer, 5000, { + kind: 'user', + userId: 'user-1', + }); } beforeEach(() => { @@ -37,7 +40,10 @@ describe('OIDC provider conflicts preserve the other installation', () => { it('also protects a direct update caller from changing another issuer', async () => { existingProvider({ name, oidc: { issuerUri: 'https://api.secondary.example' } }); await expect( - updateOidcProvider('oauth-token', '123456', 'shared', 'sam-oidc', issuer, 5000) + updateOidcProvider('oauth-token', '123456', 'shared', 'sam-oidc', issuer, 5000, { + kind: 'user', + userId: 'user-1', + }) ).rejects.toMatchObject({ step: 'oidc_provider_issuer_mismatch' }); expect(fetchMock).toHaveBeenCalledTimes(1); }); diff --git a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts new file mode 100644 index 0000000000..759e5cfa9a --- /dev/null +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -0,0 +1,551 @@ +/** + * One owner per Google Cloud workload identity pool, on a real SQL engine. + * + * Attack: user B stores a GCP credential naming user A's (or the installation's) pool. Before + * this guard SAM signed an identity token for it, A's issuer-only provider accepted it, and the + * `pool/*` binding let B impersonate A's service account. Each attack case has an owner control, + * and each guard was deleted once to confirm its attack case goes red (see the PR). + */ +import { readFileSync } from 'node:fs'; + +import { GCP_CREDENTIAL_VERSION, type GcpOidcCredential } from '@simple-agent-manager/shared'; +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { encrypt } from '../../../src/services/encryption'; +import { createAllSchemaTables, createMemoryKv, createSqliteD1 } from '../../helpers/sqlite-d1'; + +const auth = vi.hoisted(() => ({ userId: 'user-a' })); +vi.mock('../../../src/middleware/auth', () => ({ + requireAuth: () => (_c: unknown, next: () => Promise) => next(), + requireApproved: () => (_c: unknown, next: () => Promise) => next(), + getUserId: () => auth.userId, +})); +vi.mock('../../../src/services/jwt', async (importOriginal) => ({ + ...(await importOriginal()), + signIdentityToken: vi.fn(async () => 'sam-identity-token'), +})); + +const { signIdentityToken } = await import('../../../src/services/jwt'); +const { getGcpAccessToken } = await import('../../../src/services/gcp-sts'); +const { replaceUserGcpCredential } = await import('../../../src/services/gcp-credential-store'); +const { credentialsRoutes } = await import('../../../src/routes/credentials'); +const { ccRoutes } = await import('../../../src/routes/composable-credentials'); +const { runGcpSetup } = await import('../../../src/services/gcp-setup'); +const { + assertGcpWifPayloadOwnership, + GcpWifPoolIndexUnavailableError, + GcpWifPoolInvalidError, + GcpWifPoolOwnedByAnotherOwnerError, +} = await import('../../../src/services/gcp-wif-pool-ownership'); +const { serializeCredentialToken } = await import('../../../src/services/provider-credentials'); + +const KEY = Buffer.from('0123456789abcdef0123456789abcdef').toString('base64'); +const NOW = '2026-11-19T00:00:00.000Z'; +const POOL_A = { gcpProjectNumber: '111111111111', wifPoolId: 'sam-pool' }; +const POOL_PLATFORM = { gcpProjectNumber: '222222222222', wifPoolId: 'sam-pool' }; +const POOL_B = { gcpProjectNumber: '333333333333', wifPoolId: 'sam-pool' }; + +let sqlite: Database.Database; +let env: Env; +let fetchMock: ReturnType; + +function wif( + pool: { gcpProjectNumber: string; wifPoolId: string }, + overrides: Partial = {} +): GcpOidcCredential { + return { + version: GCP_CREDENTIAL_VERSION, + provider: 'gcp', + authType: 'workload-identity', + gcpProjectId: `gcp-${pool.gcpProjectNumber}`, + gcpProjectNumber: pool.gcpProjectNumber, + serviceAccountEmail: `sam@gcp-${pool.gcpProjectNumber}.iam.gserviceaccount.com`, + wifPoolId: pool.wifPoolId, + wifProviderId: 'sam-provider', + defaultZone: 'us-central1-a', + ...overrides, + }; +} + +async function sealed(plaintext: string) { + return encrypt(plaintext, KEY); +} + +/** A legacy `credentials` row stored before the save-time check existed. */ +async function storeLegacyRow( + id: string, + userId: string, + credential: GcpOidcCredential, + projectId: string | null = null +) { + const { ciphertext, iv } = await sealed(JSON.stringify(credential)); + sqlite + .prepare( + `INSERT INTO credentials (id, user_id, project_id, provider, credential_type, credential_kind, + is_active, encrypted_token, iv, created_at, updated_at) + VALUES (?, ?, ?, 'gcp', 'cloud-provider', 'api-key', 1, ?, ?, ?, ?)` + ) + .run(id, userId, projectId, ciphertext, iv, NOW, NOW); +} + +async function storePlatformRow(id: string, credential: GcpOidcCredential) { + const { ciphertext, iv } = await sealed(JSON.stringify(credential)); + sqlite + .prepare( + `INSERT INTO platform_credentials (id, credential_type, provider, credential_kind, label, + encrypted_token, iv, is_enabled, created_by, created_at, updated_at) + VALUES (?, 'cloud-provider', 'gcp', 'api-key', 'GCP', ?, ?, 1, 'admin', ?, ?)` + ) + .run(id, ciphertext, iv, NOW, NOW); +} + +async function storeCcRow(id: string, ownerId: string, plaintext: string) { + const { ciphertext, iv } = await sealed(plaintext); + sqlite + .prepare( + `INSERT INTO cc_credentials (id, owner_id, name, kind, encrypted_token, iv, is_active, + created_at, updated_at) + VALUES (?, ?, 'cloud', 'cloud-provider', ?, ?, 1, ?, ?)` + ) + .run(id, ownerId, ciphertext, iv, NOW, NOW); +} + +function user(userId: string) { + return { tokenUserId: userId, poolOwner: { kind: 'user' as const, userId } }; +} + +function exchange( + requester: Parameters[0], + credential: GcpOidcCredential, + projectId = credential.gcpProjectId +) { + return getGcpAccessToken(requester, projectId, credential, env); +} + +function stubGoogleTokens() { + fetchMock = vi.fn(async (url: string) => { + if (String(url).includes('sts')) { + return Response.json({ access_token: 'federated', token_type: 'Bearer', expires_in: 3600 }); + } + return Response.json({ + accessToken: 'sa-token', + expireTime: new Date(Date.now() + 3_600_000).toISOString(), + }); + }); + vi.stubGlobal('fetch', fetchMock); +} + +function indexRows() { + return sqlite + .prepare( + 'SELECT source_table, source_id, owner_kind, owner_user_id, pool_key FROM gcp_wif_pool_index ORDER BY source_table, source_id' + ) + .all() as Array<{ + source_table: string; + source_id: string; + owner_kind: string; + owner_user_id: string | null; + pool_key: string | null; + }>; +} + +function testApp() { + const app = new Hono<{ Bindings: Env }>(); + app.onError((err, c) => { + const appError = err as { statusCode?: number; error?: string; message?: string }; + if (typeof appError.statusCode === 'number' && typeof appError.error === 'string') { + return c.json( + { error: appError.error, message: appError.message }, + appError.statusCode as 400 + ); + } + return c.json({ error: 'INTERNAL_ERROR', message: err.message }, 500); + }); + app.route('/api/credentials', credentialsRoutes); + app.route('/api/cc', ccRoutes); + return app; +} + +function postGcpCredential(credential: GcpOidcCredential) { + return testApp().request( + '/api/credentials', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + provider: 'gcp', + gcpProjectId: credential.gcpProjectId, + gcpProjectNumber: credential.gcpProjectNumber, + serviceAccountEmail: credential.serviceAccountEmail, + wifPoolId: credential.wifPoolId, + wifProviderId: credential.wifProviderId, + defaultZone: credential.defaultZone, + }), + }, + env + ); +} + +beforeEach(() => { + sqlite = new Database(':memory:'); + createAllSchemaTables(sqlite, schema); + // Exercise the real migration (its CHECK constraints and indexes), not only the drizzle shape. + sqlite.exec('DROP TABLE gcp_wif_pool_index'); + sqlite.exec( + readFileSync( + new URL('../../../src/db/migrations/0262_gcp_wif_pool_index.sql', import.meta.url), + 'utf8' + ) + ); + for (const id of ['user-a', 'user-b', 'user-m', 'admin']) { + sqlite + .prepare(`INSERT INTO users (id, email, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`) + .run(id, `${id}@example.com`, id, NOW, NOW); + } + sqlite + .prepare( + `INSERT INTO projects (id, user_id, name, created_at, updated_at) VALUES ('proj-a', 'user-a', 'A', ?, ?)` + ) + .run(NOW, NOW); + env = { + DATABASE: createSqliteD1(sqlite), + KV: createMemoryKv(), + ENCRYPTION_KEY: KEY, + BASE_DOMAIN: 'example.com', + } as unknown as Env; + auth.userId = 'user-a'; + vi.mocked(signIdentityToken).mockClear(); + stubGoogleTokens(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + sqlite.close(); +}); + +describe('token exchange refuses a pool another owner uses (rows that predate the save check)', () => { + it('owner control: user A exchanges with A’s own pool', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + + await expect(exchange(user('user-a'), wif(POOL_A))).resolves.toBe('sa-token'); + expect(signIdentityToken).toHaveBeenCalledTimes(1); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('attack: user B naming user A’s pool is refused before any token is signed', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + // B's row was saved before the save-time check existed. + await storeLegacyRow('cred-b', 'user-b', wif(POOL_A, { serviceAccountEmail: 'x@y.z' })); + + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + expect(signIdentityToken).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('attack: case and whitespace variants of A’s pool are the same pool', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + + await expect( + exchange( + user('user-b'), + wif({ gcpProjectNumber: ` ${POOL_A.gcpProjectNumber} `, wifPoolId: 'SAM-Pool' }) + ) + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + expect(signIdentityToken).not.toHaveBeenCalled(); + }); + + it('attack: a user credential cannot name the platform credential’s pool', async () => { + await storePlatformRow('plat-1', wif(POOL_PLATFORM)); + + await expect(exchange(user('user-b'), wif(POOL_PLATFORM))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + expect(fetchMock).not.toHaveBeenCalled(); + + // Owner control: the installation still exchanges with its own pool. + await expect( + exchange( + { tokenUserId: 'platform:user-b', poolOwner: { kind: 'platform' } }, + wif(POOL_PLATFORM) + ) + ).resolves.toBe('sa-token'); + }); + + it('attack: the platform credential cannot name a user’s pool', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + + await expect( + exchange({ tokenUserId: 'platform:user-b', poolOwner: { kind: 'platform' } }, wif(POOL_A)) + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('attack: a user credential cannot name another user’s deployment pool', async () => { + sqlite + .prepare( + `INSERT INTO project_deployment_credentials (id, project_id, user_id, provider, gcp_project_id, + gcp_project_number, service_account_email, wif_pool_id, wif_provider_id, created_at, updated_at) + VALUES ('dep-a', 'proj-a', 'user-a', 'gcp', 'gcp-a', ?, 'deployer@a', 'sam-deploy-pool', 'p', ?, ?)` + ) + .run(POOL_A.gcpProjectNumber, NOW, NOW); + const deployPool = { gcpProjectNumber: POOL_A.gcpProjectNumber, wifPoolId: 'sam-deploy-pool' }; + + await expect(exchange(user('user-b'), wif(deployPool))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + await expect(exchange(user('user-a'), wif(deployPool))).resolves.toBe('sa-token'); + }); + + it('owner control: the same user’s user-level, project-scoped and composable copies share a pool', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + await storeLegacyRow('cred-a-proj', 'user-a', wif(POOL_A), 'proj-a'); + await storeCcRow('cc-a', 'user-a', JSON.stringify(wif(POOL_A))); + + await expect( + exchange( + { tokenUserId: 'project:proj-a:user-a', poolOwner: { kind: 'user', userId: 'user-a' } }, + wif(POOL_A), + 'proj-a' + ) + ).resolves.toBe('sa-token'); + // Another project member's run uses A's project credential, so A owns the pool. + await expect( + exchange( + { tokenUserId: 'project:proj-a:user-m', poolOwner: { kind: 'user', userId: 'user-a' } }, + wif(POOL_A), + 'proj-a' + ) + ).resolves.toBe('sa-token'); + }); + + it('a deleted or re-pointed credential stops owning its old pool', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + + // A re-saves their credential for a different pool (new IV), then B may use the old one. + const repointed = await sealed(JSON.stringify(wif(POOL_B))); + sqlite + .prepare('UPDATE credentials SET encrypted_token = ?, iv = ? WHERE id = ?') + .run(repointed.ciphertext, repointed.iv, 'cred-a'); + await expect(exchange(user('user-b'), wif(POOL_A))).resolves.toBe('sa-token'); + await expect(exchange(user('user-b'), wif(POOL_B))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + + sqlite.prepare('DELETE FROM credentials WHERE id = ?').run('cred-a'); + await expect(exchange(user('user-b'), wif(POOL_B))).resolves.toBe('sa-token'); + }); + + it('deleted platform and composable credentials stop owning their pools', async () => { + await storePlatformRow('plat-1', wif(POOL_PLATFORM)); + await storeCcRow('cc-a', 'user-a', JSON.stringify(wif(POOL_A))); + await expect(exchange(user('user-b'), wif(POOL_PLATFORM))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + + sqlite.prepare('DELETE FROM platform_credentials WHERE id = ?').run('plat-1'); + sqlite.prepare('DELETE FROM cc_credentials WHERE id = ?').run('cc-a'); + await expect(exchange(user('user-b'), wif(POOL_PLATFORM))).resolves.toBe('sa-token'); + await expect(exchange(user('user-b'), wif(POOL_A))).resolves.toBe('sa-token'); + }); + + it('a bad row does not break the check for others (rule 41)', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + // Undecryptable ciphertext, a raw Hetzner token and a Scaleway JSON payload. + sqlite + .prepare( + `INSERT INTO cc_credentials (id, owner_id, name, kind, encrypted_token, iv, is_active, created_at, updated_at) + VALUES ('cc-broken', 'user-b', 'x', 'cloud-provider', 'bm90LWNpcGhlcnRleHQ=', 'AAAAAAAAAAAAAAAA', 1, ?, ?)` + ) + .run(NOW, NOW); + await storeCcRow('cc-hetzner', 'user-b', 'raw-hetzner-token'); + await storeCcRow('cc-scaleway', 'user-b', JSON.stringify({ secretKey: 's', projectId: 'p' })); + const errorLog = vi.spyOn(console, 'error').mockImplementation(() => {}); + + await expect(exchange(user('user-a'), wif(POOL_A))).resolves.toBe('sa-token'); + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + + const rows = indexRows(); + expect(rows.filter((row) => row.source_id.startsWith('cc-'))).toEqual([ + expect.objectContaining({ source_id: 'cc-broken', pool_key: null }), + expect.objectContaining({ source_id: 'cc-hetzner', pool_key: null }), + expect.objectContaining({ source_id: 'cc-scaleway', pool_key: null }), + ]); + expect(rows.find((row) => row.source_id === 'cred-a')?.pool_key).toBe('111111111111/sam-pool'); + expect(errorLog.mock.calls.some(([line]) => String(line).includes('row_unreadable'))).toBe( + true + ); + }); + + it('indexes more rows than one page in a single check, then reads the index without decrypting', async () => { + // 230 non-GCP rows (more than two pages at the default page size of 100) ahead of A's row. + for (let i = 0; i < 230; i++) { + await storeCcRow(`cc-other-${String(i).padStart(3, '0')}`, 'user-b', `token-${i}`); + } + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + expect(indexRows()).toHaveLength(231); + + const encryption = await import('../../../src/services/encryption'); + const decryptSpy = vi.spyOn(encryption, 'decrypt'); + await expect(exchange(user('user-a'), wif(POOL_A))).resolves.toBe('sa-token'); + expect(decryptSpy).not.toHaveBeenCalled(); + }); + + it('fails closed when unindexed rows remain after the time budget', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + // Every clock reading is 20 s after the previous one, so whichever reading sets the + // deadline (default budget 10 s), the next reading is already past it. + let clock = Date.now(); + vi.spyOn(Date, 'now').mockImplementation(() => (clock += 20_000)); + vi.spyOn(console, 'error').mockImplementation(() => {}); + + await expect(exchange(user('user-a'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolIndexUnavailableError + ); + expect(signIdentityToken).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refuses a credential whose project number cannot name a pool', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + await expect( + exchange(user('user-a'), wif({ gcpProjectNumber: 'my-project-id', wifPoolId: 'sam-pool' })) + ).rejects.toBeInstanceOf(GcpWifPoolInvalidError); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); + +describe('save time refuses a pool another owner uses', () => { + it('POST /api/credentials: B naming A’s pool gets 409 and nothing is stored; A can save', async () => { + auth.userId = 'user-a'; + const first = await postGcpCredential(wif(POOL_A)); + expect(first.status).toBe(201); + // Owner control: A re-saves the same pool. + expect((await postGcpCredential(wif(POOL_A))).status).toBe(200); + + auth.userId = 'user-b'; + const attack = await postGcpCredential(wif(POOL_A)); + expect(attack.status).toBe(409); + expect(await attack.json()).toMatchObject({ error: 'GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER' }); + const bRows = sqlite + .prepare(`SELECT count(*) AS n FROM credentials WHERE user_id = 'user-b'`) + .get() as { n: number }; + expect(bRows.n).toBe(0); + const bCc = sqlite + .prepare(`SELECT count(*) AS n FROM cc_credentials WHERE owner_id = 'user-b'`) + .get() as { n: number }; + expect(bCc.n).toBe(0); + }); + + it('POST /api/credentials: a user cannot save the platform credential’s pool', async () => { + await storePlatformRow('plat-1', wif(POOL_PLATFORM)); + auth.userId = 'user-b'; + + const attack = await postGcpCredential(wif(POOL_PLATFORM)); + expect(attack.status).toBe(409); + }); + + it('POST /api/cc/credentials: a composable cloud credential naming A’s pool gets 409', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + auth.userId = 'user-b'; + + const attack = await testApp().request( + '/api/cc/credentials', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'gcp', + kind: 'cloud-provider', + secret: { provider: 'gcp', token: JSON.stringify(wif(POOL_A)) }, + }), + }, + env + ); + expect(attack.status).toBe(409); + + // Owner control: A may store a composable copy of the same pool. + auth.userId = 'user-a'; + const own = await testApp().request( + '/api/cc/credentials', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: 'gcp', kind: 'cloud-provider', secret: wif(POOL_A) }), + }, + env + ); + expect(own.status).toBe(201); + }); + + it('project-scoped and platform payloads: refused for another owner, allowed for the owner', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + const projectPayload = serializeCredentialToken('gcp', { + ...wif(POOL_A), + } as unknown as Record); + + // The project credential route checks the saving user as the owner. + await expect( + assertGcpWifPayloadOwnership(env, projectPayload, { kind: 'user', userId: 'user-a' }, 't') + ).resolves.toBeUndefined(); + await expect( + assertGcpWifPayloadOwnership(env, projectPayload, { kind: 'user', userId: 'user-b' }, 't') + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + // The admin platform route checks the installation as the owner. + await expect( + assertGcpWifPayloadOwnership(env, projectPayload, { kind: 'platform' }, 't') + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + // Non-GCP payloads are not affected. + await expect( + assertGcpWifPayloadOwnership(env, 'raw-hetzner-token', { kind: 'platform' }, 't') + ).resolves.toBeUndefined(); + }); + + it('the user GCP store refuses before writing anything', async () => { + await storePlatformRow('plat-1', wif(POOL_PLATFORM)); + + await expect( + replaceUserGcpCredential(env, 'user-b', wif(POOL_PLATFORM)) + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + const rows = sqlite.prepare('SELECT count(*) AS n FROM credentials').get() as { n: number }; + expect(rows.n).toBe(0); + }); + + it('guided setup stops before changing anything in Google when the pool is taken', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + const google = vi.fn(async () => + Response.json({ projectNumber: POOL_A.gcpProjectNumber, projectId: 'gcp-a' }) + ); + vi.stubGlobal('fetch', google); + const { assertGcpWifPoolOwnership } = + await import('../../../src/services/gcp-wif-pool-ownership'); + + await expect( + runGcpSetup('oauth', 'gcp-a', 'us-central1-a', env, { + userId: 'user-b', + assertPoolAvailable: (pool) => + assertGcpWifPoolOwnership(env, pool, { kind: 'user', userId: 'user-b' }, 'gcp_setup'), + }) + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + // Only the project-number lookup ran: no API enablement, pool, provider or IAM change. + expect(google).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/tests/unit/services/gcp-wif-scoping.test.ts b/apps/api/tests/unit/services/gcp-wif-scoping.test.ts index ab7cb75c97..09331d2011 100644 --- a/apps/api/tests/unit/services/gcp-wif-scoping.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-scoping.test.ts @@ -1,9 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; /** - * Security tests for WIF pool IAM binding scoping. - * Verifies that identity tokens are scoped to specific SAM projects, - * preventing cross-project impersonation within the same WIF pool. + * Security tests for WIF provider conditions and service-account bindings. + * Every provider and binding is scoped to one SAM project (deployment setup) or one SAM user + * (user-level guided setup); there is no issuer-only scope, so a token SAM signs for one user + * or project cannot impersonate another's service account. */ const mockFetch = vi.fn(); @@ -11,6 +12,17 @@ vi.stubGlobal('fetch', mockFetch); const { createOidcProvider, updateOidcProvider, grantWifUserOnSa } = await import('../../../src/services/gcp-setup'); +const { wifAttributeCondition, wifServiceAccountMember, legacyPoolWideMember } = + await import('../../../src/services/gcp-wif-setup'); + +const ISSUER = 'https://api.example.com'; +const POOL_PATH = + 'iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/sam-pool'; +const PROVIDER_NAME = + 'projects/123456/locations/global/workloadIdentityPools/sam-pool/providers/sam-oidc'; +const USER_SCOPE = { kind: 'user', userId: 'user-a' } as const; +const PROJECT_SCOPE = { kind: 'project', samProjectId: 'proj-abc-123' } as const; +const WIF_ROLE = 'roles/iam.workloadIdentityUser'; function mockGcpResponse(body: unknown, status = 200) { return { @@ -21,59 +33,74 @@ function mockGcpResponse(body: unknown, status = 200) { }; } -describe('WIF pool scoping (cross-project impersonation prevention)', () => { +function requestBody(index: number): Record { + const call = mockFetch.mock.calls[index]; + return JSON.parse(call![1]!.body as string) as Record; +} + +interface PolicyBinding { + role: string; + members: string[]; +} + +function setPolicyBindings(index: number): PolicyBinding[] { + const body = requestBody(index) as { policy: { bindings: PolicyBinding[] } }; + return body.policy.bindings; +} + +describe('WIF trust scoping (cross-owner impersonation prevention)', () => { beforeEach(() => { mockFetch.mockReset(); }); - describe('createOidcProvider', () => { - it('enforces project-scoped attributeCondition when samProjectId is provided', async () => { - mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); - - await createOidcProvider( - 'token', - '123456', - 'sam-pool', - 'sam-oidc', - 'https://api.example.com', - 5000, - 'proj-abc-123' + describe('condition and member strings', () => { + it('scopes a user-level provider to the user_id claim', () => { + expect(wifAttributeCondition(ISSUER, USER_SCOPE)).toBe( + "assertion.iss == 'https://api.example.com' && assertion.user_id == 'user-a'" ); + }); - const call = mockFetch.mock.calls[0]; - const body = JSON.parse(call![1]!.body as string); - expect(body.attributeCondition).toBe( + it('scopes a deployment provider to the project_id claim', () => { + expect(wifAttributeCondition(ISSUER, PROJECT_SCOPE)).toBe( "assertion.iss == 'https://api.example.com' && assertion.project_id == 'proj-abc-123'" ); }); - it('uses issuer-only attributeCondition when samProjectId is not provided', async () => { - mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); - - await createOidcProvider( - 'token', - '123456', - 'sam-pool', - 'sam-oidc', - 'https://api.example.com', - 5000 + it('binds a user to attribute.sam_user and a project to its subject', () => { + expect(wifServiceAccountMember('123456', 'sam-pool', USER_SCOPE)).toBe( + `principalSet://${POOL_PATH}/attribute.sam_user/user-a` + ); + expect(wifServiceAccountMember('123456', 'sam-pool', PROJECT_SCOPE)).toBe( + `principal://${POOL_PATH}/subject/project:proj-abc-123` ); + expect(legacyPoolWideMember('123456', 'sam-pool')).toBe(`principalSet://${POOL_PATH}/*`); + }); - const call = mockFetch.mock.calls[0]; - const body = JSON.parse(call![1]!.body as string); - expect(body.attributeCondition).toBe("assertion.iss == 'https://api.example.com'"); + it('two users sharing a GCP project get non-overlapping members and conditions', () => { + const userB = { kind: 'user', userId: 'user-b' } as const; + expect(wifServiceAccountMember('123456', 'sam-pool', USER_SCOPE)).not.toBe( + wifServiceAccountMember('123456', 'sam-pool', userB) + ); + expect(wifAttributeCondition(ISSUER, USER_SCOPE)).not.toBe( + wifAttributeCondition(ISSUER, userB) + ); }); + }); - it('passes samProjectId to updateOidcProvider on 409 conflict', async () => { - // First call returns 409 (already exists) - mockFetch.mockResolvedValueOnce(mockGcpResponse({}, 409)); - mockFetch.mockResolvedValueOnce( - mockGcpResponse({ - name: 'projects/123456/locations/global/workloadIdentityPools/sam-pool/providers/sam-oidc', - oidc: { issuerUri: 'https://api.example.com' }, - }) + describe('createOidcProvider', () => { + it('creates a user-level provider with the user-scoped condition', async () => { + mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); + + await createOidcProvider('token', '123456', 'sam-pool', 'sam-oidc', ISSUER, 5000, USER_SCOPE); + + const body = requestBody(0); + expect(body.attributeCondition).toBe( + "assertion.iss == 'https://api.example.com' && assertion.user_id == 'user-a'" ); - // Third call is the PATCH update + expect(body.attributeMapping).toMatchObject({ 'attribute.sam_user': 'assertion.user_id' }); + }); + + it('creates a deployment provider with the project-scoped condition', async () => { mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); await createOidcProvider( @@ -81,78 +108,58 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { '123456', 'sam-pool', 'sam-oidc', - 'https://api.example.com', + ISSUER, 5000, - 'proj-abc-123' + PROJECT_SCOPE ); - // The update call (second fetch) should have project-scoped condition - const updateCall = mockFetch.mock.calls[2]; - const updateBody = JSON.parse(updateCall![1]!.body as string); - expect(updateBody.attributeCondition).toBe( + expect(requestBody(0).attributeCondition).toBe( "assertion.iss == 'https://api.example.com' && assertion.project_id == 'proj-abc-123'" ); }); - }); - describe('updateOidcProvider', () => { - it('enforces project-scoped attributeCondition when samProjectId is provided', async () => { + it('narrows an existing issuer-only provider to the user on a 409 re-run', async () => { + mockFetch.mockResolvedValueOnce(mockGcpResponse({}, 409)); mockFetch.mockResolvedValueOnce( - mockGcpResponse({ - name: 'projects/123456/locations/global/workloadIdentityPools/sam-pool/providers/sam-oidc', - oidc: { issuerUri: 'https://api.example.com' }, - }) + mockGcpResponse({ name: PROVIDER_NAME, oidc: { issuerUri: ISSUER } }) ); mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); - await updateOidcProvider( - 'token', - '123456', - 'sam-pool', - 'sam-oidc', - 'https://api.example.com', - 5000, - 'proj-xyz-789' - ); + await createOidcProvider('token', '123456', 'sam-pool', 'sam-oidc', ISSUER, 5000, USER_SCOPE); - const call = mockFetch.mock.calls[1]; - const body = JSON.parse(call![1]!.body as string); - expect(body.attributeCondition).toBe( - "assertion.iss == 'https://api.example.com' && assertion.project_id == 'proj-xyz-789'" + expect(mockFetch.mock.calls[2]![1]!.method).toBe('PATCH'); + expect(requestBody(2).attributeCondition).toBe( + "assertion.iss == 'https://api.example.com' && assertion.user_id == 'user-a'" ); }); + }); - it('uses issuer-only attributeCondition when samProjectId is not provided', async () => { + describe('updateOidcProvider', () => { + it.each([ + ['user', USER_SCOPE, "assertion.user_id == 'user-a'"], + ['project', PROJECT_SCOPE, "assertion.project_id == 'proj-abc-123'"], + ] as const)('patches the %s-scoped condition', async (_name, scope, claim) => { mockFetch.mockResolvedValueOnce( - mockGcpResponse({ - name: 'projects/123456/locations/global/workloadIdentityPools/sam-pool/providers/sam-oidc', - oidc: { issuerUri: 'https://api.example.com' }, - }) + mockGcpResponse({ name: PROVIDER_NAME, oidc: { issuerUri: ISSUER } }) ); mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); - await updateOidcProvider( - 'token', - '123456', - 'sam-pool', - 'sam-oidc', - 'https://api.example.com', - 5000 - ); + await updateOidcProvider('token', '123456', 'sam-pool', 'sam-oidc', ISSUER, 5000, scope); - const call = mockFetch.mock.calls[1]; - const body = JSON.parse(call![1]!.body as string); - expect(body.attributeCondition).toBe("assertion.iss == 'https://api.example.com'"); + expect(mockFetch.mock.calls[1]![1]!.method).toBe('PATCH'); + expect(requestBody(1).attributeCondition).toBe( + `assertion.iss == 'https://api.example.com' && ${claim}` + ); }); }); describe('grantWifUserOnSa', () => { - it('uses subject-scoped principal when samProjectId is provided', async () => { - // getIamPolicy - mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'abc' })); - // setIamPolicy + async function grant( + bindings: PolicyBinding[], + scope: typeof USER_SCOPE | typeof PROJECT_SCOPE = USER_SCOPE + ) { + mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings, etag: 'abc' })); mockFetch.mockResolvedValueOnce(mockGcpResponse({ etag: 'def' })); - await grantWifUserOnSa( 'token', 'my-gcp-project', @@ -160,27 +167,80 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sa@my-gcp-project.iam.gserviceaccount.com', 'sam-pool', 5000, - 'proj-abc-123' + scope ); + } - const setCall = mockFetch.mock.calls[1]; - const setBody = JSON.parse(setCall![1]!.body as string); - const binding = setBody.policy.bindings.find( - (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser' - ); + it('grants a user-level setup the sam_user member, never the pool-wide wildcard', async () => { + await grant([]); - // Must be subject-scoped principal, NOT pool-wide wildcard - expect(binding.members[0]).toBe( - 'principal://iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/sam-pool/subject/project:proj-abc-123' - ); - expect(binding.members[0]).not.toContain('/*'); + const binding = setPolicyBindings(1).find((b) => b.role === WIF_ROLE); + expect(binding?.members).toEqual([`principalSet://${POOL_PATH}/attribute.sam_user/user-a`]); }); - it('uses pool-wide wildcard when samProjectId is not provided (user-level setup)', async () => { - // getIamPolicy - mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'abc' })); - // setIamPolicy - mockFetch.mockResolvedValueOnce(mockGcpResponse({ etag: 'def' })); + it('grants a deployment setup the subject-scoped principal', async () => { + await grant([], PROJECT_SCOPE); + + const binding = setPolicyBindings(1).find((b) => b.role === WIF_ROLE); + expect(binding?.members).toEqual([`principal://${POOL_PATH}/subject/project:proj-abc-123`]); + }); + + it('re-running setup removes the pool-wide member an earlier setup granted', async () => { + const otherPoolWide = + 'principalSet://iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/other-pool/*'; + await grant([ + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/*`, otherPoolWide] }, + { role: 'roles/viewer', members: ['user:owner@example.com'] }, + ]); + + const bindings = setPolicyBindings(1); + expect(bindings.find((b) => b.role === WIF_ROLE)?.members).toEqual([ + // Only this pool's wildcard is removed; another pool's binding is not SAM's to change. + otherPoolWide, + `principalSet://${POOL_PATH}/attribute.sam_user/user-a`, + ]); + expect(bindings.find((b) => b.role === 'roles/viewer')?.members).toEqual([ + 'user:owner@example.com', + ]); + }); + + it('removes the pool-wide member even when the scoped member is already granted', async () => { + await grant([ + { + role: WIF_ROLE, + members: [ + `principalSet://${POOL_PATH}/*`, + `principalSet://${POOL_PATH}/attribute.sam_user/user-a`, + ], + }, + ]); + + expect(mockFetch).toHaveBeenCalledTimes(2); + expect(setPolicyBindings(1)).toEqual([ + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`] }, + ]); + }); + + it('drops a binding left empty after removing the pool-wide member', async () => { + await grant([ + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/*`] }, + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`] }, + ]); + + expect(setPolicyBindings(1)).toEqual([ + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`] }, + ]); + }); + + it('leaves the policy untouched when already scoped and no wildcard remains', async () => { + mockFetch.mockResolvedValueOnce( + mockGcpResponse({ + bindings: [ + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`] }, + ], + etag: 'abc', + }) + ); await grantWifUserOnSa( 'token', @@ -188,102 +248,60 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { '123456', 'sa@my-gcp-project.iam.gserviceaccount.com', 'sam-pool', - 5000 - ); - - const setCall = mockFetch.mock.calls[1]; - const setBody = JSON.parse(setCall![1]!.body as string); - const binding = setBody.policy.bindings.find( - (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser' - ); - - expect(binding.members[0]).toBe( - 'principalSet://iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/sam-pool/*' + 5000, + USER_SCOPE ); - }); - it('two projects sharing a GCP project get non-overlapping principals', async () => { - // Call grantWifUserOnSa for two different SAM projects and verify - // the IAM binding members are distinct (not wildcards). - const members: string[] = []; - - for (const projectId of ['project-a', 'project-b']) { - mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'abc' })); - mockFetch.mockResolvedValueOnce(mockGcpResponse({ etag: 'def' })); - - await grantWifUserOnSa( - 'token', - 'my-gcp-project', - '123456', - 'sa@my-gcp-project.iam.gserviceaccount.com', - 'sam-pool', - 5000, - projectId - ); - - const setCall = mockFetch.mock.calls.at(-1); - const setBody = JSON.parse(setCall![1]!.body as string); - const binding = setBody.policy.bindings.find( - (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser' - ); - members.push(binding.members[0]); - } - - // Principals must be different and neither must be a wildcard - expect(members[0]).not.toBe(members[1]); - expect(members[0]).not.toContain('/*'); - expect(members[1]).not.toContain('/*'); - // Each must contain the respective project ID in the subject - expect(members[0]).toContain('subject/project:project-a'); - expect(members[1]).toContain('subject/project:project-b'); + expect(mockFetch).toHaveBeenCalledTimes(1); }); }); describe('CEL injection prevention', () => { - it('rejects samProjectId with single quotes (CEL injection)', async () => { - mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); - + it('rejects a samProjectId with single quotes', async () => { await expect( - createOidcProvider( - 'token', - '123456', - 'sam-pool', - 'sam-oidc', - 'https://api.example.com', - 5000, - "x' || true || 'y" - ) + createOidcProvider('token', '123456', 'sam-pool', 'sam-oidc', ISSUER, 5000, { + kind: 'project', + samProjectId: "x' || true || 'y", + }) ).rejects.toThrow('unsafe for CEL interpolation'); + expect(mockFetch).not.toHaveBeenCalled(); }); - it('rejects samProjectId with spaces', async () => { + it('rejects a userId with single quotes before any request', async () => { + await expect( + createOidcProvider('token', '123456', 'sam-pool', 'sam-oidc', ISSUER, 5000, { + kind: 'user', + userId: "u' || true || 'v", + }) + ).rejects.toThrow('unsafe for CEL interpolation'); await expect( - grantWifUserOnSa( - 'token', - 'my-gcp-project', - '123456', - 'sa@x.com', - 'sam-pool', - 5000, - 'project with spaces' - ) + grantWifUserOnSa('token', 'p', '123456', 'sa@x.com', 'sam-pool', 5000, { + kind: 'user', + userId: 'user with spaces', + }) ).rejects.toThrow('unsafe for CEL interpolation'); + expect(mockFetch).not.toHaveBeenCalled(); }); - it('accepts valid ULID-format samProjectId', async () => { - mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); + it('rejects a missing scope value instead of interpolating "undefined"', () => { + expect(() => + wifAttributeCondition(ISSUER, { kind: 'user', userId: undefined as unknown as string }) + ).toThrow('unsafe for CEL interpolation'); + }); - // Should not throw — ULIDs are alphanumeric + it('accepts ULID and Better Auth id formats', async () => { + mockFetch.mockResolvedValue(mockGcpResponse({ name: 'op/1', done: true })); + await expect( + createOidcProvider('token', '123456', 'sam-pool', 'sam-oidc', ISSUER, 5000, { + kind: 'project', + samProjectId: '01KHRJGANBBWGDY1NZ0KVF0D4J', + }) + ).resolves.toBeUndefined(); await expect( - createOidcProvider( - 'token', - '123456', - 'sam-pool', - 'sam-oidc', - 'https://api.example.com', - 5000, - '01KHRJGANBBWGDY1NZ0KVF0D4J' - ) + createOidcProvider('token', '123456', 'sam-pool', 'sam-oidc', ISSUER, 5000, { + kind: 'user', + userId: '4bw1FJlXCOgSGq0TsQgpiMAhQKjGOSXx', + }) ).resolves.toBeUndefined(); }); }); diff --git a/apps/api/tests/unit/services/gcp-wif-shared-project.test.ts b/apps/api/tests/unit/services/gcp-wif-shared-project.test.ts index 15619d9181..c5cb1ca077 100644 --- a/apps/api/tests/unit/services/gcp-wif-shared-project.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-shared-project.test.ts @@ -80,7 +80,8 @@ async function connect(baseDomain: string, extra: Partial = {}) { 'oauth-token', 'sam-staging-infra', 'us-central1-a', - envFor(baseDomain, extra) + envFor(baseDomain, extra), + { userId: 'user-1' } ); } @@ -132,8 +133,18 @@ describe('installations sharing one Google Cloud project', () => { }); it('names deployment providers per installation too', async () => { - const primary = await runGcpDeploySetup('oauth-token', 'sam-staging-infra', envFor(PRIMARY)); - const staging2 = await runGcpDeploySetup('oauth-token', 'sam-staging-infra', envFor(STAGING2)); + const primary = await runGcpDeploySetup( + 'oauth-token', + 'sam-staging-infra', + envFor(PRIMARY), + 'sam-project-1' + ); + const staging2 = await runGcpDeploySetup( + 'oauth-token', + 'sam-staging-infra', + envFor(STAGING2), + 'sam-project-1' + ); expect(primary.wifPoolId).toBe('sam-deploy-pool'); expect(primary.wifProviderId).not.toBe(staging2.wifProviderId); diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index bfd8642a56..f97fdb3662 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -296,6 +296,18 @@ The complete source credential is encrypted at rest with AES-256-GCM. SAM signs Save and rotation verify the selected Compute zone before one D1 transaction updates the user's stored credential in place and replaces its composable copy. The stored credential keeps its id, which the compute pool's account and every node placed from it are keyed on, so a re-save does not reset pool choices or orphan running machines (`replaceUserGcpCredential()`). A failed verification or transaction leaves the previous credential intact. Disconnect removes SAM's encrypted copies and cached derivatives but does not revoke a Google-managed service-account key. +#### One owner per workload identity pool + +SAM signs an identity token for whatever pool a stored WIF credential names, so the pool's own trust must not be the only control. A WIF credential may name a pool (`gcpProjectNumber` + `wifPoolId`) only when no credential of a different owner names it (`assertGcpWifPoolOwnership()` in `apps/api/src/services/gcp-wif-pool-ownership.ts`). An owner is one SAM user, whose user-level and project-scoped credentials may share a pool, or the installation, which owns platform credentials. Deployment credentials count for the user who connected them. + +- **At save**, `POST /api/credentials`, the Google setup routes, project cloud credentials, composable credentials and admin platform credentials return `409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`. Guided setup checks the pool after reading the project number and before it changes anything in Google. +- **At token exchange**, the same check runs before SAM signs the identity token (`exchangeGcpWifAccessToken()` in `gcp-sts.ts`), so credentials saved before the check existed are refused too. The owner is the stored credential's owner, so a project member using another member's project credential still works. Refusals log `gcp_wif_pool.cross_owner_refused`. +- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the owner lookup, so a writer that skips the index, a rotation or a deletion cannot leave it stale. A normal check is one D1 round trip with no decryption. A row that cannot be decrypted or parsed is recorded with no pool and logged, and does not affect other credentials. If newly saved rows cannot be indexed within `gcpWif.poolIndexBudgetMs`, the check refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index. + +The Google side is scoped as well. User-level guided setup creates a provider whose condition is `assertion.iss == '' && assertion.user_id == ''` and grants the service account only to `principalSet://.../workloadIdentityPools//attribute.sam_user/`. Deployment setup uses `assertion.project_id` and `principal://.../subject/project:` (`wifAttributeCondition()`, `wifServiceAccountMember()` in `gcp-wif-setup.ts`). Setups before this change used an issuer-only condition and a `pool/*` binding. Re-running setup rewrites the provider's condition and removes the `pool/*` member from the service account. + +Residual risk: whoever saves a pool first owns it in SAM. A user who knows another person's Google Cloud project number can save a credential naming that pool before its owner connects, which blocks the owner's setup (a denial of service, not impersonation). An administrator resolves it by deleting the squatting credential. + ## Terminal Authentication Terminal WebSocket connections use short-lived JWTs: diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index 5c5808ad78..e2f32e8643 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -1104,6 +1104,8 @@ These control the live Google Cloud catalog described in [Google Cloud](/docs/gu | `gcpCatalog.apiIssueTtlMinutes` | 10080 | 60–43200 | How long a Google API problem Google reported stays shown on a credential; a successful check clears it. | | `gcpCatalog.bootDiskGbPerVcpu` | 20 | 1–256 | GB of boot disk a new Google Cloud node gets per vCPU, used by the catalog, prices and new nodes from the next catalog refresh; running nodes keep their disk. | | `gcpCatalog.bootDiskMinGb` | 50 | 10–4096 | Smallest boot disk, in GB, a new Google Cloud node gets whatever its vCPU count; same refresh rule. | +| `gcpWif.poolIndexPageSize` | 100 | 10–100 | Stored cloud credentials decrypted per step when indexing which workload identity pool each one names (only new or re-saved credentials are indexed). | +| `gcpWif.poolIndexBudgetMs` | 10000 | 1000–25000 | Most time one token exchange or credential save may spend indexing new credentials before it refuses and asks to retry, rather than trust a partial index. | ### Infomaniak boot volume diff --git a/apps/www/src/content/docs/docs/guides/google-cloud.md b/apps/www/src/content/docs/docs/guides/google-cloud.md index 92ae43738b..ed6b61634c 100644 --- a/apps/www/src/content/docs/docs/guides/google-cloud.md +++ b/apps/www/src/content/docs/docs/guides/google-cloud.md @@ -26,6 +26,8 @@ Being a Google Workspace administrator does not make a disabled API available. C 2. Select the GCP project and a **Default Zone**, then click **Connect with WIF**. 3. SAM enables the target project's APIs, creates or reuses its WIF pool/provider and service account, grants the required bindings, saves the connection, and attempts to verify token exchange. Newly created Google resources can take time to propagate; a saved connection can therefore report that verification is not yet complete. +The provider and the service-account binding accept only tokens SAM signs for you, so other users of the same SAM installation cannot use your service account. If another SAM user, or the installation's own platform credential, already uses the pool in that project, setup stops before changing anything and reports that the pool belongs to a different owner. Use a different Google Cloud project, or ask your administrator. + The setup identity needs permission to enable services, manage WIF pools/providers and service accounts, and update the project's IAM policy. Google documents the WIF administration prerequisites in its [Workload Identity Federation guide](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-providers). Organization policies can still restrict setup; investigate the specific Google error before adding broad IAM roles. SAM's VM setup requests these APIs in the **selected VM project**: Cloud Resource Manager, IAM, IAM Service Account Credentials (`iamcredentials.googleapis.com`), Security Token Service (`sts.googleapis.com`), Compute Engine (`compute.googleapis.com`), Vertex AI (`aiplatform.googleapis.com`), and Cloud Billing (`cloudbilling.googleapis.com`, read-only, for list prices). It calls Service Usage (`serviceusage.googleapis.com`) to enable them. This target-project setup does not replace the OAuth-client project prerequisites above. @@ -39,7 +41,7 @@ SAM tells you when this happens (`listGcpApiIssues()` in `apps/api/src/services/ - **Settings → Infrastructure** shows a warning naming your Google Cloud project and the API. **Review** opens the Google Cloud connection. - The connection card lists each API with the reason and an **Enable in Google Cloud** link that opens that API's enable page for your project. -- **Re-run Google setup** (Workload Identity) signs in to Google again and re-runs setup for the same project and zone. Setup reuses the existing pool, provider and service account, and enables the full current API list. +- **Re-run Google setup** (Workload Identity) signs in to Google again and re-runs setup for the same project and zone. Setup reuses the existing pool, provider and service account, enables the full current API list, and narrows a provider or binding created by an older SAM version to your user. - A service-account key connection shows the `gcloud services enable` command to run instead. - **Check again** re-tests the connection and asks Google whether the API is usable now. The warning clears as soon as a call succeeds. diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index 149e9b4e03..1bb5f5b8b1 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -454,6 +454,10 @@ The flow requests the Google `cloud-platform` scope. Runtime values saved by a s Several SAM installations can connect the same Google Cloud project. A workload identity provider trusts exactly one issuer URL, so each installation creates its own provider, named from its base domain (`installationWifProviderId()` in `apps/api/src/services/gcp-wif-setup.ts`; for example `sam-sammy2-party-` for `sammy2.party`). The installations share the pool (`sam-pool`, or `sam-deploy-pool` for deployments) and the service account, so every installation connected to a project can act as that project's service account; use separate Google Cloud projects when installations must not share cloud access. `GCP_WIF_PROVIDER_ID` and `GCP_DEPLOY_WIF_PROVIDER_ID` override the derived name. SAM still refuses to update an existing provider whose issuer differs from its own (`updateOidcProvider()`). Existing connections keep the pool and provider recorded when they were created; reconnecting creates the installation's own provider. +Each user-level connection is scoped to the SAM user who made it. The provider's condition requires `assertion.user_id == ''`, and the service account is granted to `principalSet://iam.googleapis.com/projects//locations/global/workloadIdentityPools//attribute.sam_user/` (`wifAttributeCondition()` and `wifServiceAccountMember()` in `apps/api/src/services/gcp-wif-setup.ts`). Connections made before this scoping used an issuer-only condition and a `pool/*` binding, which let any user of the installation who named the pool act as its service account. **Re-run Google setup** on each such connection: it rewrites the provider's condition and removes the `pool/*` member. If another installation shared that service account through `pool/*`, re-run that installation's setup too, so it gets its own scoped binding. + +Within one installation a pool has one owner: one user, or the installation for platform credentials. SAM refuses to save, or to exchange tokens for, a credential naming a pool that a different owner's credential already names (`409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`; see [Security](/docs/architecture/security/#one-owner-per-workload-identity-pool)). Give every user and the platform credential its own Google Cloud project or pool. + If STS reports an issuer mismatch, another installation's setup replaced the shared provider this connection was recorded against (setups before per-installation providers all used `sam-oidc`). Reconnect the affected installation through its Connect GCP flow, which creates its own provider. Do not switch a shared provider back and forth or accept both issuers. A failed token exchange does not prove a failed node has no cloud server. After independently checking the provider account and in-flight allocation, the existing owner-confirmed removal action can remove a failed node on user-owned cloud capacity. Its audit reason stays `owner_attested_manual_deletion`, separate from strict provider-confirmed termination. Fresh terminal provisioning failures positively proven to precede the provider create request retain an exact incarnation and placement absence proof, allowing normal teardown without minting another token. Intermediate durable retries keep their allocation state. ### Service account JSON (OAuth-free alternative) diff --git a/packages/worker-core/src/schema.ts b/packages/worker-core/src/schema.ts index 1c3bebf4cf..06bddf94c8 100644 --- a/packages/worker-core/src/schema.ts +++ b/packages/worker-core/src/schema.ts @@ -1121,6 +1121,35 @@ export const projectDeploymentCredentials = sqliteTable( table.provider ), userIdx: index('idx_project_deployment_creds_user').on(table.userId), + gcpProjectNumberIdx: index('idx_project_deployment_creds_gcp_project_number').on( + table.gcpProjectNumber + ), + }) +); + +// ============================================================================= +// GCP Workload Identity Pool Index (migration 0262) +// Which pool each stored cloud credential names, filled by the Worker on every ownership check +// (`apps/api/src/services/gcp-wif-pool-ownership.ts`). No secret material: `iv` identifies the +// indexed ciphertext generation, `pool_key` is `/` or NULL when the row +// names no workload identity pool. +// ============================================================================= +export const gcpWifPoolIndex = sqliteTable( + 'gcp_wif_pool_index', + { + sourceTable: text('source_table').notNull(), // 'credentials' | 'platform_credentials' | 'cc_credentials' + sourceId: text('source_id').notNull(), + iv: text('iv').notNull(), + ownerKind: text('owner_kind').notNull(), // 'user' | 'platform' + ownerUserId: text('owner_user_id'), + poolKey: text('pool_key'), + indexedAt: text('indexed_at').notNull(), + }, + (table) => ({ + pk: primaryKey({ columns: [table.sourceTable, table.sourceId] }), + poolIdx: index('idx_gcp_wif_pool_index_pool') + .on(table.poolKey) + .where(sql`pool_key IS NOT NULL`), }) ); diff --git a/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md b/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md new file mode 100644 index 0000000000..d763851c70 --- /dev/null +++ b/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md @@ -0,0 +1,46 @@ +# Block cross-owner GCP workload identity pool impersonation + +SAM task: 01M7SB8FRZ08M5NEX9WGM74X61 (dispatched by coordinator task 01M7JMXS2JRW6QQMB1356ENPM3). Severity HIGH, in production. + +## Problem + +User-level guided GCP setup created a pool provider whose attribute condition checked only SAM's issuer (`assertion.iss == ''`) and granted the service account to `principalSet://.../workloadIdentityPools//*`. `exchangeGcpWifAccessToken` signed an identity token for whatever pool a stored credential named, and `POST /api/credentials` only checked field formats. User B could save a credential naming user A's (or the installation's) pool, SAM signed a token, A's provider accepted the issuer, and `pool/*` let B impersonate A's service account. + +## Research findings + +- Pool identities are inside encrypted payloads in `credentials`, `platform_credentials` and `cc_credentials`; only `project_deployment_credentials` stores them in plaintext. An indexed lookup therefore needs a Worker-maintained index. +- Credential writers are numerous (routes, mirrors, make-default, lazy backfill). An index maintained by writers would desync (rule 44), so the index is self-reconciling: each check indexes rows whose IV the index has not seen, in the same D1 batch as the owner read. +- `getGcpAccessToken` callers: `routes/gcp.ts` (user), `provider-credentials.ts` (composable, legacy project/user/platform), `gcp-token-provider.ts` (exact path, catalogs, price table, API health, orphan reconciliation). Project-scoped credentials can be used by a member other than the one who saved them, so the exchange owner is the stored row's owner, plumbed through `ProviderFactory`. +- The token's `user_id` claim is the cache identity (``, `project::`, `platform:`); unchanged. +- `runGcpSetup` had no caller passing `samProjectId` (dead branch); `runGcpDeploySetup` always passes one. +- Re-running setup must also remove the legacy `pool/*` member, or an older issuer-only provider in the same pool keeps the hole open. +- Production audit (counts only, no decryption, 2026-11-19): 1 user-level GCP cloud row, 1 composable GCP row, 1 deployment row, 0 platform GCP rows, all belonging to ONE owner. No cross-owner sharing exists, so fix 1 cannot break production. + +## Implementation checklist + +- [x] `gcp-wif-pool-ownership.ts`: pool identity normalization, self-reconciling index, owner check, fail-closed budget, per-row isolation +- [x] Migration `0262_gcp_wif_pool_index.sql` + drizzle schema + deployment pool index +- [x] Admin settings `gcpWif.poolIndexPageSize` / `gcpWif.poolIndexBudgetMs` +- [x] Exchange-time refusal before signing (`gcp-sts.ts`), explicit `GcpTokenRequester` at every call site, row owner for project-scoped credentials +- [x] Save-time refusal: user GCP store (POST /api/credentials, /api/gcp/setup), project credentials, composable credentials, admin platform credentials +- [x] Guided setup checks the pool after reading the project number, before any Google mutation +- [x] User-scoped provider condition and `attribute.sam_user/` binding; update path rewrites the condition; re-run removes `pool/*` +- [x] Real-SQL attack/owner-control tests; each guard deleted once (results in PR) +- [x] Unit tests for condition/binding strings and the update path +- [ ] Docs: security.md, self-hosting.mdx, admin-settings.md, google-cloud.md +- [ ] Full quality suite +- [ ] Reviews: security-auditor, task-completion-validator, cloudflare-specialist +- [ ] Staging: live save-time and exchange-time refusals + +## Acceptance criteria + +- [ ] User B cannot save, or exchange with, a credential naming user A's pool (409 / refusal before signing) +- [ ] A user credential cannot name the platform credential's pool, and vice versa +- [ ] The owner, the same user's project-scoped credential, and a project member using it still work +- [ ] New guided user-level setups use `assertion.user_id == ''` and `attribute.sam_user/`; re-runs fix existing providers and bindings +- [ ] Production has no cross-owner sharing (verified: counts above) +- [ ] Refusals shown live on staging + +## References + +- `.claude/rules/19-external-service-integration.md`, `.claude/rules/28-credential-resolution-fallback-tests.md`, `.claude/rules/41-credential-snapshot-resilience.md`, `.claude/rules/62-tests-must-observe-the-real-trigger.md` From 1f8cceb7f552a7d2e7655f44bee0c990820f8ff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 08:51:40 +0000 Subject: [PATCH 02/13] fix(security): sticky GCP WIF pool claims and owner user_id claim Review round 1 on the pool-ownership guard: - Claims (gcp_wif_pool_claims) outlive the credential that made them: a disconnect or re-point leaves Google's pool/* trust in place, so it must not free the pool for another owner. First claim wins atomically; an operator releases a claim (documented in self-hosting). - Sign user_id as the credential owner for user and project-scoped credentials, so project-attached credentials match the user-scoped provider; the cache key keeps its old shape. - Partial indexes keep the probe proportional to cloud credentials (query-plan test), settings are read only when indexing, unparseable probe rows fail closed, unreadable rows retry after a window. - Exchange refuses leading-zero project numbers and provider IDs or service-account emails that could alter the audience or IAM URL. - Refusals log at warn; IAM conditions and policy version are kept. - Vertical tests through the real resolver for project members. Co-Authored-By: Claude Opus 5.5 --- .../db/migrations/0262_gcp_wif_pool_index.sql | 39 ++- apps/api/src/routes/gcp.ts | 2 +- apps/api/src/routes/mcp/human-input-tool.ts | 2 +- apps/api/src/routes/mcp/inbox-tools.ts | 2 +- apps/api/src/routes/project-deployment.ts | 319 +++++++++-------- .../admin-settings-gcp-catalog-definitions.ts | 21 +- apps/api/src/services/gcp-sts.ts | 29 +- apps/api/src/services/gcp-token-provider.ts | 4 +- .../services/gcp-wif-pool-ownership-sql.ts | 102 ++++++ .../src/services/gcp-wif-pool-ownership.ts | 325 ++++++++++-------- apps/api/src/services/gcp-wif-setup.ts | 21 +- apps/api/src/services/mcp-token-lifecycle.ts | 2 +- apps/api/src/services/provider-credentials.ts | 10 +- .../src/services/runtime-secret-requests.ts | 2 +- apps/api/tests/unit/routes/gcp.test.ts | 4 +- .../provider-orphan-platform-gcp.test.ts | 14 + .../services/default-capacity-pools.test.ts | 16 +- .../services/gcp-live-catalog-build.test.ts | 4 +- .../unit/services/gcp-price-table.test.ts | 4 +- .../gcp-provider-cancellation-slice.test.ts | 6 +- .../unit/services/gcp-service-account.test.ts | 4 +- .../services/gcp-wif-pool-ownership.test.ts | 263 +++++++++++++- .../services/node-teardown-gcp-resave.test.ts | 67 ++-- .../docs/docs/architecture/security.md | 20 +- .../docs/docs/guides/admin-settings.md | 3 +- .../content/docs/docs/guides/self-hosting.mdx | 11 +- packages/worker-core/src/schema.ts | 28 +- ...-gcp-wif-cross-owner-pool-impersonation.md | 18 +- 28 files changed, 942 insertions(+), 400 deletions(-) create mode 100644 apps/api/src/services/gcp-wif-pool-ownership-sql.ts diff --git a/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql b/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql index 741c66769b..2ee81d3a23 100644 --- a/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql +++ b/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql @@ -1,11 +1,14 @@ --- Which Google Cloud workload identity pool each stored cloud credential names, so a pool can be --- held by one owner (one SAM user, or the installation). See services/gcp-wif-pool-ownership.ts. --- Pool identities live inside encrypted payloads, so the Worker fills this table itself: every --- ownership check indexes rows whose IV it has not seen, and reads owners only through rows whose --- source credential still has the indexed IV. Existing credentials are indexed on the first check --- after deploy; nothing here can decrypt them. No secret material is stored: the IV identifies a --- ciphertext generation, the pool key is `/`. --- No foreign keys: a row references one of three tables, and deletions drop out of the owner read. +-- One owner per Google Cloud workload identity pool. See services/gcp-wif-pool-ownership.ts. +-- No secret material is stored: an IV identifies a ciphertext generation, and a pool key is +-- `/`. No foreign keys: an index row references one of three tables, and +-- a claim deliberately outlives the credential that made it. +-- +-- Existing credentials: pool identities are inside encrypted payloads, which SQL cannot read. +-- The Worker indexes every existing cloud credential, and claims the pools they name, on the first +-- ownership check after deploy (a token exchange or a GCP credential save). Until then the tables +-- are empty and no check trusts them: each check indexes unseen rows before it reads. + +-- The pool each stored cloud credential names, keyed by source row and indexed IV. CREATE TABLE IF NOT EXISTS gcp_wif_pool_index ( source_table TEXT NOT NULL CHECK (source_table IN ('credentials', 'platform_credentials', 'cc_credentials')), source_id TEXT NOT NULL, @@ -13,12 +16,32 @@ CREATE TABLE IF NOT EXISTS gcp_wif_pool_index ( owner_kind TEXT NOT NULL CHECK (owner_kind IN ('user', 'platform')), owner_user_id TEXT, pool_key TEXT, + -- 1 when the row could not be decrypted; retried after gcpWif.poolIndexUnreadableRetryMinutes. + unreadable INTEGER NOT NULL DEFAULT 0 CHECK (unreadable IN (0, 1)), indexed_at TEXT NOT NULL, PRIMARY KEY (source_table, source_id), CHECK ((owner_kind = 'user' AND owner_user_id IS NOT NULL) OR (owner_kind = 'platform' AND owner_user_id IS NULL)) ) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS idx_gcp_wif_pool_index_pool ON gcp_wif_pool_index (pool_key) WHERE pool_key IS NOT NULL; + +-- The first owner whose credential named a pool. Never released by deleting or re-pointing a +-- credential: the trust an earlier setup granted in Google outlives the SAM row. An operator +-- releases a claim by deleting its row once that Google-side trust is gone. +CREATE TABLE IF NOT EXISTS gcp_wif_pool_claims ( + pool_key TEXT PRIMARY KEY NOT NULL, + owner_kind TEXT NOT NULL CHECK (owner_kind IN ('user', 'platform')), + owner_user_id TEXT, + claimed_at TEXT NOT NULL, + CHECK ((owner_kind = 'user' AND owner_user_id IS NOT NULL) OR (owner_kind = 'platform' AND owner_user_id IS NULL)) +) WITHOUT ROWID; + +-- Keep the unindexed-row probe proportional to cloud credentials, not to every stored +-- credential (agent keys share these tables). +CREATE INDEX IF NOT EXISTS idx_credentials_gcp_cloud + ON credentials (id) WHERE provider = 'gcp' AND credential_type = 'cloud-provider'; +CREATE INDEX IF NOT EXISTS idx_cc_credentials_cloud + ON cc_credentials (id) WHERE kind = 'cloud-provider'; -- Deployment credentials store their pool in plaintext; the ownership check reads them directly. CREATE INDEX IF NOT EXISTS idx_project_deployment_creds_gcp_project_number ON project_deployment_credentials (gcp_project_number); diff --git a/apps/api/src/routes/gcp.ts b/apps/api/src/routes/gcp.ts index 14819b4393..10d2b0cd07 100644 --- a/apps/api/src/routes/gcp.ts +++ b/apps/api/src/routes/gcp.ts @@ -54,7 +54,7 @@ const gcpRoutes = new Hono<{ Bindings: Env }>(); /** A user acting on their own user-level GCP credential. */ function userTokenRequester(userId: string): GcpTokenRequester { - return { tokenUserId: userId, poolOwner: { kind: 'user', userId } }; + return { cacheUserId: userId, poolOwner: { kind: 'user', userId } }; } gcpRoutes.use('*', requireAuth(), requireApproved()); diff --git a/apps/api/src/routes/mcp/human-input-tool.ts b/apps/api/src/routes/mcp/human-input-tool.ts index 232ed37c14..7c1eee406a 100644 --- a/apps/api/src/routes/mcp/human-input-tool.ts +++ b/apps/api/src/routes/mcp/human-input-tool.ts @@ -109,7 +109,7 @@ export async function handleRequestHumanInput( // Verify task ownership matches token — use tokenData.userId as authoritative target if (taskRow.user_id !== tokenData.userId) { log.error('mcp.request_human_input.user_id_mismatch', { - tokenUserId: tokenData.userId, + cacheUserId: tokenData.userId, taskUserId: taskRow.user_id, taskId: tokenData.taskId, }); diff --git a/apps/api/src/routes/mcp/inbox-tools.ts b/apps/api/src/routes/mcp/inbox-tools.ts index 30eb082bfa..aac76a9e06 100644 --- a/apps/api/src/routes/mcp/inbox-tools.ts +++ b/apps/api/src/routes/mcp/inbox-tools.ts @@ -54,7 +54,7 @@ async function resolveSource(tokenData: McpTokenData, env: Env): Promise log.error('mcp.inbox.task_mismatch', { taskId: tokenData.taskId, projectId: tokenData.projectId, - tokenUserId: tokenData.userId, + cacheUserId: tokenData.userId, taskUserId: task?.user_id ?? null, action: 'rejected', }); diff --git a/apps/api/src/routes/project-deployment.ts b/apps/api/src/routes/project-deployment.ts index 3cf318699c..049ac60f83 100644 --- a/apps/api/src/routes/project-deployment.ts +++ b/apps/api/src/routes/project-deployment.ts @@ -73,9 +73,11 @@ projectDeploymentRoutes.get( const stateTtl = c.env.GCP_DEPLOY_OAUTH_STATE_TTL_SECONDS ? parseInt(c.env.GCP_DEPLOY_OAUTH_STATE_TTL_SECONDS, 10) : DEFAULT_GCP_DEPLOY_OAUTH_STATE_TTL_SECONDS; - await c.env.KV.put(`gcp-deploy-oauth-state:${state}`, JSON.stringify({ projectId, userId }), { - expirationTtl: stateTtl, - }); + await c.env.KV.put( + `gcp-deploy-oauth-state:${state}`, + JSON.stringify({ projectId, userId }), + { expirationTtl: stateTtl }, + ); const redirectUri = `https://api.${c.env.BASE_DOMAIN}/api/deployment/gcp/callback`; const params = new URLSearchParams({ @@ -90,7 +92,7 @@ projectDeploymentRoutes.get( }); return c.redirect(`${GOOGLE_AUTH_URL}?${params.toString()}`); - } + }, ); // OAuth callback moved to gcpDeployCallbackRoute — see below @@ -114,9 +116,7 @@ projectDeploymentRoutes.get( const kvKey = `gcp-deploy-oauth-result:${userId}:${projectId}`; const handle = await c.env.KV.get(kvKey); if (!handle) { - throw errors.notFound( - 'No pending OAuth result — it may have expired or already been retrieved' - ); + throw errors.notFound('No pending OAuth result — it may have expired or already been retrieved'); } // One-time use: delete after retrieval. @@ -125,7 +125,7 @@ projectDeploymentRoutes.get( await c.env.KV.delete(kvKey); return c.json({ handle }); - } + }, ); // ─── Setup + management (user session auth) ───────────────────────────── @@ -159,7 +159,7 @@ projectDeploymentRoutes.post( } catch (err) { throw toSanitizedAppError(err, 'deploy-list-projects'); } - } + }, ); /** @@ -203,8 +203,8 @@ projectDeploymentRoutes.post( .where( and( eq(schema.projectDeploymentCredentials.projectId, projectId), - eq(schema.projectDeploymentCredentials.provider, 'gcp') - ) + eq(schema.projectDeploymentCredentials.provider, 'gcp'), + ), ) .limit(1); @@ -246,43 +246,48 @@ projectDeploymentRoutes.post( createdAt: now, }, }); - } + }, ); /** * GET /api/projects/:id/deployment/gcp * Get deployment credential config for a project. */ -projectDeploymentRoutes.get('/:id/deployment/gcp', requireAuth(), requireApproved(), async (c) => { - const projectId = c.req.param('id'); - const userId = getUserId(c); - const db = drizzle(c.env.DATABASE, { schema }); - await requireProjectCapability(db, projectId, userId, 'infra:manage'); +projectDeploymentRoutes.get( + '/:id/deployment/gcp', + requireAuth(), + requireApproved(), + async (c) => { + const projectId = c.req.param('id'); + const userId = getUserId(c); + const db = drizzle(c.env.DATABASE, { schema }); + await requireProjectCapability(db, projectId, userId, 'infra:manage'); - const rows = await db - .select() - .from(schema.projectDeploymentCredentials) - .where( - and( - eq(schema.projectDeploymentCredentials.projectId, projectId), - eq(schema.projectDeploymentCredentials.provider, 'gcp') + const rows = await db + .select() + .from(schema.projectDeploymentCredentials) + .where( + and( + eq(schema.projectDeploymentCredentials.projectId, projectId), + eq(schema.projectDeploymentCredentials.provider, 'gcp'), + ), ) - ) - .limit(1); + .limit(1); - const cred = rows[0]; - if (!cred) { - return c.json({ connected: false }); - } + const cred = rows[0]; + if (!cred) { + return c.json({ connected: false }); + } - return c.json({ - connected: true, - provider: 'gcp' as const, - gcpProjectId: cred.gcpProjectId, - serviceAccountEmail: cred.serviceAccountEmail, - createdAt: cred.createdAt, - }); -}); + return c.json({ + connected: true, + provider: 'gcp' as const, + gcpProjectId: cred.gcpProjectId, + serviceAccountEmail: cred.serviceAccountEmail, + createdAt: cred.createdAt, + }); + }, +); /** * DELETE /api/projects/:id/deployment/gcp @@ -303,12 +308,12 @@ projectDeploymentRoutes.delete( .where( and( eq(schema.projectDeploymentCredentials.projectId, projectId), - eq(schema.projectDeploymentCredentials.provider, 'gcp') - ) + eq(schema.projectDeploymentCredentials.provider, 'gcp'), + ), ); return c.json({ success: true }); - } + }, ); // ─── Identity token endpoint (MCP token auth only) ────────────────────── @@ -360,8 +365,8 @@ deploymentIdentityTokenRoute.get('/:id/deployment-identity-token', async (c) => .where( and( eq(schema.projectDeploymentCredentials.projectId, projectId), - eq(schema.projectDeploymentCredentials.provider, 'gcp') - ) + eq(schema.projectDeploymentCredentials.provider, 'gcp'), + ), ) .limit(1); @@ -375,8 +380,7 @@ deploymentIdentityTokenRoute.get('/:id/deployment-identity-token', async (c) => // for identity tokens. The STS `audience` field in the credential config (deployment-tools.ts) // uses the protocol-relative `//` format. Both forms are intentionally different per GCP WIF spec. const poolId = cred.wifPoolId || c.env.GCP_DEPLOY_WIF_POOL_ID || DEFAULT_GCP_DEPLOY_WIF_POOL_ID; - const providerId = - cred.wifProviderId || c.env.GCP_DEPLOY_WIF_PROVIDER_ID || DEFAULT_GCP_DEPLOY_WIF_PROVIDER_ID; + const providerId = cred.wifProviderId || c.env.GCP_DEPLOY_WIF_PROVIDER_ID || DEFAULT_GCP_DEPLOY_WIF_PROVIDER_ID; const audience = `https://iam.googleapis.com/projects/${cred.gcpProjectNumber}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`; const expirySeconds = c.env.GCP_DEPLOY_IDENTITY_TOKEN_EXPIRY_SECONDS @@ -403,7 +407,7 @@ deploymentIdentityTokenRoute.get('/:id/deployment-identity-token', async (c) => c.env.KV, rlKey, rateLimitMax, - rateLimitWindowSeconds + rateLimitWindowSeconds, ); c.header('X-RateLimit-Limit', rateLimitMax.toString()); @@ -424,7 +428,7 @@ deploymentIdentityTokenRoute.get('/:id/deployment-identity-token', async (c) => audience, }, c.env, - expirySeconds + expirySeconds, ); // Cache the signed token with TTL = expiry - buffer (min floor) @@ -460,136 +464,131 @@ const gcpDeployCallbackRoute = new Hono<{ Bindings: Env }>(); * Project context comes from the KV state token, NOT the URL. * This allows a single static redirect URI in Google Cloud Console. */ -gcpDeployCallbackRoute.get('/gcp/callback', requireAuth(), requireApproved(), async (c) => { - const sessionUserId = getUserId(c); - const appBaseUrl = `https://app.${c.env.BASE_DOMAIN}`; +gcpDeployCallbackRoute.get( + '/gcp/callback', + requireAuth(), + requireApproved(), + async (c) => { + const sessionUserId = getUserId(c); + const appBaseUrl = `https://app.${c.env.BASE_DOMAIN}`; - const googleOAuth = await getGoogleInfraOAuthConfig(c.env); - if (!googleOAuth) { - throw errors.badRequest('Google OAuth is not configured'); - } + const googleOAuth = await getGoogleInfraOAuthConfig(c.env); + if (!googleOAuth) { + throw errors.badRequest('Google OAuth is not configured'); + } - const code = c.req.query('code'); - const state = c.req.query('state'); - const error = c.req.query('error'); + const code = c.req.query('code'); + const state = c.req.query('state'); + const error = c.req.query('error'); - if (error) { - // No project context yet — redirect to dashboard with error - return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent(error)}`); - } + if (error) { + // No project context yet — redirect to dashboard with error + return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent(error)}`); + } - if (!code || !state) { - return c.redirect( - `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Missing authorization code or state')}` - ); - } + if (!code || !state) { + return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Missing authorization code or state')}`); + } - // Validate state format before KV lookup (state is always a UUID) - const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (!UUID_RE.test(state)) { - return c.redirect( - `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid OAuth state')}` - ); - } + // Validate state format before KV lookup (state is always a UUID) + const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + if (!UUID_RE.test(state)) { + return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid OAuth state')}`); + } - // Validate CSRF state and extract project context - const storedStateRaw = await c.env.KV.get(`gcp-deploy-oauth-state:${state}`); - if (!storedStateRaw) { - return c.redirect( - `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid or expired OAuth state')}` - ); - } + // Validate CSRF state and extract project context + const storedStateRaw = await c.env.KV.get(`gcp-deploy-oauth-state:${state}`); + if (!storedStateRaw) { + return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid or expired OAuth state')}`); + } + + let storedState: { projectId: string; userId: string }; + try { + const parsed = expectJsonRecord(JSON.parse(storedStateRaw), 'gcp_deploy_oauth.state'); + if (typeof parsed.projectId !== 'string' || typeof parsed.userId !== 'string') { + throw new Error('Invalid state structure'); + } + storedState = { projectId: parsed.projectId, userId: parsed.userId }; + } catch { + await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); + return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid OAuth state format')}`); + } - let storedState: { projectId: string; userId: string }; - try { - const parsed = expectJsonRecord(JSON.parse(storedStateRaw), 'gcp_deploy_oauth.state'); - if (typeof parsed.projectId !== 'string' || typeof parsed.userId !== 'string') { - throw new Error('Invalid state structure'); + if (!storedState.projectId || !storedState.userId) { + await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); + return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Incomplete OAuth state')}`); } - storedState = { projectId: parsed.projectId, userId: parsed.userId }; - } catch { - await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); - return c.redirect( - `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Invalid OAuth state format')}` - ); - } - if (!storedState.projectId || !storedState.userId) { + // Validate user identity BEFORE consuming the state token — if the user doesn't + // match, the state remains valid for the legitimate user to retry + if (storedState.userId !== sessionUserId) { + return c.redirect(`${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('OAuth state user mismatch')}`); + } + + // All validation passed — consume the state token (one-time use) await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); - return c.redirect( - `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('Incomplete OAuth state')}` - ); - } - // Validate user identity BEFORE consuming the state token — if the user doesn't - // match, the state remains valid for the legitimate user to retry - if (storedState.userId !== sessionUserId) { - return c.redirect( - `${appBaseUrl}?gcp_deploy_error=${encodeURIComponent('OAuth state user mismatch')}` - ); - } + const projectId = storedState.projectId; - // All validation passed — consume the state token (one-time use) - await c.env.KV.delete(`gcp-deploy-oauth-state:${state}`); + // Defense-in-depth: verify the session user can still manage project + // infrastructure, even though the KV state was created by an authenticated + // actor at authorize time. + const db = drizzle(c.env.DATABASE, { schema }); + await requireProjectCapability(db, projectId, sessionUserId, 'infra:manage'); - const projectId = storedState.projectId; + const appUrl = `https://app.${c.env.BASE_DOMAIN}/projects/${projectId}/settings/deploy`; - // Defense-in-depth: verify the session user can still manage project - // infrastructure, even though the KV state was created by an authenticated - // actor at authorize time. - const db = drizzle(c.env.DATABASE, { schema }); - await requireProjectCapability(db, projectId, sessionUserId, 'infra:manage'); + // Exchange auth code for access token + const redirectUri = `https://api.${c.env.BASE_DOMAIN}/api/deployment/gcp/callback`; + const tokenResponse = await fetch(GOOGLE_TOKEN_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + code, + client_id: googleOAuth.clientId, + client_secret: googleOAuth.clientSecret, + redirect_uri: redirectUri, + grant_type: 'authorization_code', + }), + }); - const appUrl = `https://app.${c.env.BASE_DOMAIN}/projects/${projectId}/settings/deploy`; + if (!tokenResponse.ok) { + const errPayload: unknown = await tokenResponse.json().catch(() => ({})); + const errBody = maybeJsonRecord(errPayload) ?? {}; + log.error('project_deployment.google_token_exchange_failed', { + status: tokenResponse.status, + error: typeof errBody.error === 'string' ? errBody.error : 'unknown', + }); + return c.redirect(`${appUrl}?gcp_deploy_error=token_exchange_failed`); + } - // Exchange auth code for access token - const redirectUri = `https://api.${c.env.BASE_DOMAIN}/api/deployment/gcp/callback`; - const tokenResponse = await fetch(GOOGLE_TOKEN_URL, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ - code, - client_id: googleOAuth.clientId, - client_secret: googleOAuth.clientSecret, - redirect_uri: redirectUri, - grant_type: 'authorization_code', - }), - }); - - if (!tokenResponse.ok) { - const errPayload: unknown = await tokenResponse.json().catch(() => ({})); - const errBody = maybeJsonRecord(errPayload) ?? {}; - log.error('project_deployment.google_token_exchange_failed', { - status: tokenResponse.status, - error: typeof errBody.error === 'string' ? errBody.error : 'unknown', + const tokenData = await readResponseJson( + tokenResponse, + googleDeployTokenResponseSchema, + 'project_deployment.google_token_response', + ); + + // Store token in KV with opaque handle (for subsequent API calls) + const handle = crypto.randomUUID(); + const tokenHandleTtl = c.env.GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS + ? parseInt(c.env.GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS, 10) + : DEFAULT_GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS; + await c.env.KV.put(`gcp-deploy-oauth-token:${handle}`, tokenData.access_token, { + expirationTtl: tokenHandleTtl, }); - return c.redirect(`${appUrl}?gcp_deploy_error=token_exchange_failed`); - } - const tokenData = await readResponseJson( - tokenResponse, - googleDeployTokenResponseSchema, - 'project_deployment.google_token_response' - ); + // Store the handle reference in a user+project-scoped KV key so the frontend + // can retrieve it via an authenticated API call instead of from the URL. + // This prevents the handle from leaking in browser history, Referer headers, and logs. + await c.env.KV.put( + `gcp-deploy-oauth-result:${sessionUserId}:${projectId}`, + handle, + { expirationTtl: tokenHandleTtl }, + ); - // Store token in KV with opaque handle (for subsequent API calls) - const handle = crypto.randomUUID(); - const tokenHandleTtl = c.env.GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS - ? parseInt(c.env.GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS, 10) - : DEFAULT_GCP_DEPLOY_OAUTH_TOKEN_HANDLE_TTL_SECONDS; - await c.env.KV.put(`gcp-deploy-oauth-token:${handle}`, tokenData.access_token, { - expirationTtl: tokenHandleTtl, - }); - - // Store the handle reference in a user+project-scoped KV key so the frontend - // can retrieve it via an authenticated API call instead of from the URL. - // This prevents the handle from leaking in browser history, Referer headers, and logs. - await c.env.KV.put(`gcp-deploy-oauth-result:${sessionUserId}:${projectId}`, handle, { - expirationTtl: tokenHandleTtl, - }); - - // Redirect with only a flag — no sensitive token in the URL - return c.redirect(`${appUrl}?gcp_deploy_setup=ready`); -}); + // Redirect with only a flag — no sensitive token in the URL + return c.redirect(`${appUrl}?gcp_deploy_setup=ready`); + }, +); -export { deploymentIdentityTokenRoute, gcpDeployCallbackRoute, projectDeploymentRoutes }; +export { deploymentIdentityTokenRoute,gcpDeployCallbackRoute, projectDeploymentRoutes }; diff --git a/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts index 61deb0a1d6..20f4361a7a 100644 --- a/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts +++ b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts @@ -8,6 +8,10 @@ import { import { type AdminSettingDefinition, integerDefinition } from './admin-setting-definitions'; +/** Defaults for the workload identity pool index, also used before the settings are read. */ +export const DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE = 25; +export const DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES = 60; + export type GcpCatalogSettingName = | 'gcpCatalog.machineTypes' | 'gcpCatalog.priceTableTtlMinutes' @@ -20,7 +24,8 @@ export type GcpCatalogSettingName = | 'gcpCatalog.bootDiskGbPerVcpu' | 'gcpCatalog.bootDiskMinGb' | 'gcpWif.poolIndexPageSize' - | 'gcpWif.poolIndexBudgetMs'; + | 'gcpWif.poolIndexBudgetMs' + | 'gcpWif.poolIndexUnreadableRetryMinutes'; /** * General-purpose shapes SAM offers from Google Cloud by default: shared-core e2-medium, and the @@ -127,13 +132,14 @@ export const GCP_CATALOG_SETTINGS: readonly AdminSettingDefinition[] = [ ), // Workload identity pool ownership (`gcp-wif-pool-ownership.ts`). Indexing runs only for // credentials added or re-encrypted since the last check; a check that cannot finish inside the - // budget refuses rather than trusting a partial index. + // budget refuses rather than trusting a partial index. A page is one D1 batch of up to two + // statements per row, so the maximum stays well inside D1's per-invocation query limits. integerDefinition( 'gcpWif.poolIndexPageSize', - 100, + DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE, 'Operations', 'Stored cloud credentials SAM decrypts per step when indexing which Google Cloud workload identity pool each one names.', - { min: 10, max: 100 } + { min: 5, max: 50 } ), integerDefinition( 'gcpWif.poolIndexBudgetMs', @@ -142,4 +148,11 @@ export const GCP_CATALOG_SETTINGS: readonly AdminSettingDefinition[] = [ 'Most milliseconds one Google Cloud token exchange or credential save may spend indexing newly saved credentials before it refuses and asks to retry.', { min: 1_000, max: 25_000 } ), + integerDefinition( + 'gcpWif.poolIndexUnreadableRetryMinutes', + DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES, + 'Operations', + 'Minutes before SAM tries again to read a stored cloud credential it could not decrypt while indexing workload identity pools.', + { min: 1, max: 24 * 60 } + ), ]; diff --git a/apps/api/src/services/gcp-sts.ts b/apps/api/src/services/gcp-sts.ts index a06add8d01..567c21f338 100644 --- a/apps/api/src/services/gcp-sts.ts +++ b/apps/api/src/services/gcp-sts.ts @@ -23,20 +23,36 @@ import { exchangeGcpServiceAccountAccessToken, type GcpAccessTokenResult, } from './gcp-service-account'; -import { assertGcpWifPoolOwnership, type GcpWifPoolOwner } from './gcp-wif-pool-ownership'; +import { + assertGcpWifCredentialShape, + assertGcpWifPoolOwnership, + type GcpWifPoolOwner, +} from './gcp-wif-pool-ownership'; import { signIdentityToken } from './jwt'; /** Who a GCP access token is minted for. */ export interface GcpTokenRequester { /** - * The identity SAM asserts as the token's `user_id` claim and keys the token cache on: the - * user id, `project::` or `platform:`. + * The identity the token cache is keyed on: the user id, `project::` or + * `platform:`. For platform credentials it is also the token's `user_id` claim. */ - tokenUserId: string; + cacheUserId: string; /** The owner of the stored credential, which must own the workload identity pool it names. */ poolOwner: GcpWifPoolOwner; } +/** + * The `user_id` claim SAM signs. For a user's own credential, user-level or project-scoped, it is + * the credential owner's id: user-level guided setup scopes the provider to + * `assertion.user_id == ''` and binds `attribute.sam_user/`, and the pool-ownership + * check has already proved this owner holds the pool. A project member using another member's + * project credential therefore acts as the credential's owner, which is what sharing it means. + * Platform credentials keep `platform:`; the installation configures their trust itself. + */ +export function gcpIdentityTokenUserId(requester: GcpTokenRequester): string { + return requester.poolOwner.kind === 'user' ? requester.poolOwner.userId : requester.cacheUserId; +} + interface StsTokenResponse { access_token: string; token_type: string; @@ -149,7 +165,7 @@ export async function getGcpAccessToken( options: GcpAccessTokenOptions = {} ): Promise { throwIfProviderRequestAborted(context); - const userId = requester.tokenUserId; + const userId = requester.cacheUserId; // A token minted for different scopes is a different token; the suffix keeps the shared // prefix, so clearGcpAccessTokenCache still removes it. const cacheKey = options.scopes @@ -203,10 +219,11 @@ async function exchangeGcpWifAccessToken( const stsAudience = `//iam.googleapis.com/${wifResourcePath}`; // Refuse before signing: a provider that trusts only SAM's issuer would accept any token SAM // signs, so naming another owner's pool must never produce one. + assertGcpWifCredentialShape(credential); await assertGcpWifPoolOwnership(env, credential, requester.poolOwner, 'token_exchange'); throwIfProviderRequestAborted(context); const identityToken = await signIdentityToken( - { userId: requester.tokenUserId, projectId, audience: jwtAudience }, + { userId: gcpIdentityTokenUserId(requester), projectId, audience: jwtAudience }, env ); diff --git a/apps/api/src/services/gcp-token-provider.ts b/apps/api/src/services/gcp-token-provider.ts index bc58da2c9d..e047cb2c82 100644 --- a/apps/api/src/services/gcp-token-provider.ts +++ b/apps/api/src/services/gcp-token-provider.ts @@ -20,14 +20,14 @@ export interface GcpTokenOwner { /** The token identity and pool owner for a credential resolved for `owner`. */ export function gcpTokenRequester(owner: GcpTokenOwner): GcpTokenRequester { - const tokenUserId = + const cacheUserId = owner.credentialSource === 'platform' ? `platform:${owner.userId}` : owner.credentialSource === 'project' && owner.projectId ? `project:${owner.projectId}:${owner.userId}` : owner.userId; return { - tokenUserId, + cacheUserId, poolOwner: owner.credentialSource === 'platform' ? { kind: 'platform' } diff --git a/apps/api/src/services/gcp-wif-pool-ownership-sql.ts b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts new file mode 100644 index 0000000000..ad1b334211 --- /dev/null +++ b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts @@ -0,0 +1,102 @@ +/** + * SQL for `gcp-wif-pool-ownership.ts`. Kept apart so the queries and their index assumptions + * can be read (and plan-tested) on their own. + * + * Tables (migration 0262): + * - `gcp_wif_pool_index`: one row per stored cloud credential, keyed by source table + id, + * recording the IV it was indexed at and the pool it names (NULL when none). + * - `gcp_wif_pool_claims`: one row per pool, the first owner whose credential named it. Claims + * are never released by deleting or re-pointing a credential, because the Google-side trust an + * earlier setup granted outlives the SAM row. An operator releases one by deleting its row. + */ + +// Rows SAM has not indexed at their current IV and owner, plus rows that could not be decrypted +// and are due for another attempt. Every stored row that can be exchanged as a GCP credential is +// covered. Composable credentials do not record their provider in plaintext, so every +// cloud-provider row is indexed once; a non-GCP row is stored with a NULL pool. +// +// Every writer of `encrypted_token` encrypts with a fresh random IV (AES-GCM requires it), so an +// unchanged IV means unchanged ciphertext. The partial indexes from migration 0262 +// (`idx_credentials_gcp_cloud`, `idx_cc_credentials_cloud`) keep the scan proportional to cloud +// credentials rather than to every stored credential. +// +// Binds: retry cutoff x3, page size. +export const UNINDEXED_ROWS_SQL = ` +SELECT 'credentials' AS sourceTable, c.id AS sourceId, 'user' AS ownerKind, c.user_id AS ownerUserId, + c.encrypted_token AS encryptedToken, c.iv AS iv + FROM credentials c + WHERE c.provider = 'gcp' AND c.credential_type = 'cloud-provider' + AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i + WHERE i.source_table = 'credentials' AND i.source_id = c.id + AND i.iv = c.iv AND i.owner_kind = 'user' AND i.owner_user_id = c.user_id + AND (i.unreadable = 0 OR i.indexed_at >= ?)) +UNION ALL +SELECT 'platform_credentials', p.id, 'platform', NULL, p.encrypted_token, p.iv + FROM platform_credentials p + WHERE p.provider = 'gcp' AND p.credential_type = 'cloud-provider' + AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i + WHERE i.source_table = 'platform_credentials' AND i.source_id = p.id + AND i.iv = p.iv AND i.owner_kind = 'platform' + AND (i.unreadable = 0 OR i.indexed_at >= ?)) +UNION ALL +SELECT 'cc_credentials', cc.id, 'user', cc.owner_id, cc.encrypted_token, cc.iv + FROM cc_credentials cc + WHERE cc.kind = 'cloud-provider' + AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i + WHERE i.source_table = 'cc_credentials' AND i.source_id = cc.id + AND i.iv = cc.iv AND i.owner_kind = 'user' AND i.owner_user_id = cc.owner_id + AND (i.unreadable = 0 OR i.indexed_at >= ?)) +LIMIT ?`; + +// Everything that holds one pool: its claim, every live credential naming it (index rows whose +// source row still exists), and every deployment credential naming it (plaintext, read directly). +// Used only when the unindexed-row probe in the same D1 batch (one transaction) returned nothing, +// so every live row is indexed at its current IV and owner. Inactive and disabled credentials +// count: they can be re-enabled, and Google still trusts them. +// +// Binds: pool key x2, project number, pool id. +export const POOL_HOLDERS_SQL = ` +SELECT 'gcp_wif_pool_claims' AS sourceTable, k.pool_key AS sourceId, k.owner_kind AS ownerKind, + k.owner_user_id AS ownerUserId + FROM gcp_wif_pool_claims k + WHERE k.pool_key = ? +UNION ALL +SELECT i.source_table, i.source_id, i.owner_kind, i.owner_user_id + FROM gcp_wif_pool_index i + WHERE i.pool_key = ? + AND ( + (i.source_table = 'credentials' AND EXISTS ( + SELECT 1 FROM credentials c WHERE c.id = i.source_id AND c.provider = 'gcp' + AND c.credential_type = 'cloud-provider')) + OR (i.source_table = 'platform_credentials' AND EXISTS ( + SELECT 1 FROM platform_credentials p WHERE p.id = i.source_id AND p.provider = 'gcp' + AND p.credential_type = 'cloud-provider')) + OR (i.source_table = 'cc_credentials' AND EXISTS ( + SELECT 1 FROM cc_credentials cc WHERE cc.id = i.source_id AND cc.kind = 'cloud-provider')) + ) +UNION ALL +SELECT 'project_deployment_credentials', d.id, 'user', d.user_id + FROM project_deployment_credentials d + WHERE d.provider = 'gcp' AND d.gcp_project_number = ? AND lower(trim(d.wif_pool_id)) = ?`; + +// Binds: source table, source id, iv, owner kind, owner user id, pool key, unreadable, indexed at. +export const UPSERT_INDEX_SQL = ` +INSERT INTO gcp_wif_pool_index + (source_table, source_id, iv, owner_kind, owner_user_id, pool_key, unreadable, indexed_at) +VALUES (?, ?, ?, ?, ?, ?, ?, ?) +ON CONFLICT (source_table, source_id) DO UPDATE SET + iv = excluded.iv, owner_kind = excluded.owner_kind, owner_user_id = excluded.owner_user_id, + pool_key = excluded.pool_key, unreadable = excluded.unreadable, indexed_at = excluded.indexed_at`; + +// First owner wins: the primary key makes concurrent claims race-free. +// Binds: pool key, owner kind, owner user id, claimed at. +export const CLAIM_POOL_SQL = ` +INSERT INTO gcp_wif_pool_claims (pool_key, owner_kind, owner_user_id, claimed_at) +VALUES (?, ?, ?, ?) +ON CONFLICT (pool_key) DO NOTHING`; + +// Binds: pool key. +export const READ_CLAIM_SQL = ` +SELECT 'gcp_wif_pool_claims' AS sourceTable, pool_key AS sourceId, owner_kind AS ownerKind, + owner_user_id AS ownerUserId + FROM gcp_wif_pool_claims WHERE pool_key = ?`; diff --git a/apps/api/src/services/gcp-wif-pool-ownership.ts b/apps/api/src/services/gcp-wif-pool-ownership.ts index 008d093577..d598560e7b 100644 --- a/apps/api/src/services/gcp-wif-pool-ownership.ts +++ b/apps/api/src/services/gcp-wif-pool-ownership.ts @@ -4,29 +4,44 @@ * SAM signs an identity token for whatever pool a stored GCP credential names. A pool whose * provider checks only SAM's issuer, with a `pool/*` binding (the user-level guided setup before * this module existed), accepts any token SAM signs. So user B could save a credential naming - * user A's pool and impersonate A's service account. This module refuses that on the Worker side: - * a credential may name a `(gcpProjectNumber, wifPoolId)` only when no credential belonging to a - * different owner names it. Owners are one SAM user (user-level and project-scoped credentials of - * the same user may share a pool) or the installation (platform credentials). + * user A's pool and impersonate A's service account. This module refuses that on the Worker side. + * Owners are one SAM user (their user-level and project-scoped credentials may share a pool) or + * the installation (platform credentials). A credential may name a `(gcpProjectNumber, wifPoolId)` + * only when + * - no credential of a different owner names it, and + * - the pool is unclaimed or claimed by the same owner. The first owner whose credential names a + * pool claims it, and the claim outlives that credential: deleting or re-pointing a credential + * in SAM leaves the trust an earlier setup granted in Google, so it must not free the pool for + * someone else. An operator releases a claim by deleting its row (see the self-hosting guide). * * Pool identities live inside encrypted credential payloads, so they are indexed in * `gcp_wif_pool_index`, one row per stored credential, keyed by the row's IV. Writers do not - * maintain the index: every check first indexes rows whose IV the index has not seen (a new or - * re-encrypted row), then reads owners only through index rows whose source row still exists with - * the same IV. A writer that forgets the index, a deleted credential, or a rotation therefore - * cannot leave the check reading stale data. Deployment credentials store their pool in plaintext - * and are read directly. + * maintain the index: every check first indexes rows whose IV the index has not seen, in the same + * D1 batch (one transaction) as the read of the pool's holders. A writer that skips the index, a + * deleted credential, or a rotation therefore cannot leave the check reading stale data. * - * Per check: one D1 round trip (the unindexed-row probe and the owner lookup run as one batch). - * Only when a credential was added or re-encrypted since the last check does it decrypt those - * rows, page by page, inside a time budget, and run the owner lookup again. + * I/O per check when nothing changed: one D1 round trip, no decryption, no admin-settings read. + * A first-time claim adds one round trip for that pool. A new or re-encrypted credential adds + * one page of decrypts plus two round trips per `gcpWif.poolIndexPageSize` rows, within + * `gcpWif.poolIndexBudgetMs`; past the budget the check refuses rather than trust a partial index. */ import type { Env } from '../env'; import { log } from '../lib/logger'; import { getCredentialEncryptionKey } from '../lib/secrets'; import { AppError } from '../middleware/error'; +import { + DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE, + DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES, +} from './admin-settings-gcp-catalog-definitions'; import { resolveAdminSetting } from './admin-settings-resolution'; import { decrypt } from './encryption'; +import { + CLAIM_POOL_SQL, + POOL_HOLDERS_SQL, + READ_CLAIM_SQL, + UNINDEXED_ROWS_SQL, + UPSERT_INDEX_SQL, +} from './gcp-wif-pool-ownership-sql'; import { extractCloudProviderToken, parseGcpCredential } from './provider-credential-codecs'; /** Who a stored GCP credential belongs to, for pool ownership. */ @@ -36,28 +51,52 @@ export type GcpWifPoolOwner = { kind: 'platform' } | { kind: 'user'; userId: str export interface GcpWifPoolIdentity { gcpProjectNumber: string; wifPoolId: string; - /** `/`, the index key. */ + /** `/`, the index and claim key. */ key: string; } -const PROJECT_NUMBER_PATTERN = /^\d{1,20}$/; +// Google project numbers never start with 0, so `0123` cannot alias `123`. +const PROJECT_NUMBER_PATTERN = /^[1-9]\d{0,19}$/; const POOL_ID_PATTERN = /^[a-z0-9-]{1,63}$/; /** * Normalize a pool identity, or return null when the values cannot name a real pool. Google * resource IDs are lowercase and STS audiences use the project number, so a value that differs - * only in case or whitespace is the same pool. + * only in case or surrounding whitespace is the same pool. */ export function gcpWifPoolIdentity( gcpProjectNumber: string, wifPoolId: string ): GcpWifPoolIdentity | null { + if (typeof gcpProjectNumber !== 'string' || typeof wifPoolId !== 'string') return null; const projectNumber = gcpProjectNumber.trim(); const poolId = wifPoolId.trim().toLowerCase(); if (!PROJECT_NUMBER_PATTERN.test(projectNumber) || !POOL_ID_PATTERN.test(poolId)) return null; return { gcpProjectNumber: projectNumber, wifPoolId: poolId, key: `${projectNumber}/${poolId}` }; } +const PROVIDER_ID_PATTERN = /^[a-z0-9-]{1,63}$/; +const SERVICE_ACCOUNT_EMAIL_PATTERN = /^[a-z0-9][a-z0-9._-]{0,62}@[a-z0-9][a-z0-9.-]{0,252}$/i; + +/** + * Refuse a credential whose provider ID or service account could change the STS audience or the + * impersonation URL they are interpolated into (path segments, query strings). + */ +export function assertGcpWifCredentialShape(credential: { + wifProviderId: string; + serviceAccountEmail: string; +}): void { + if ( + typeof credential.wifProviderId !== 'string' || + typeof credential.serviceAccountEmail !== 'string' || + !PROVIDER_ID_PATTERN.test(credential.wifProviderId) || + !SERVICE_ACCOUNT_EMAIL_PATTERN.test(credential.serviceAccountEmail) + ) { + log.warn('gcp_wif_pool.invalid_credential_shape', { action: 'refused' }); + throw new GcpWifPoolInvalidError(); + } +} + /** * The pool a decrypted cloud-provider payload names, or null when it is not a GCP * workload-identity credential. Never throws: stored payloads come in several encodings @@ -79,7 +118,7 @@ export class GcpWifPoolOwnedByAnotherOwnerError extends AppError { super( 409, 'GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER', - 'This Google Cloud workload identity pool is already used by a credential that belongs to a different SAM owner. Each SAM user, and the installation itself, must use its own pool.' + 'This Google Cloud workload identity pool already belongs to a different SAM owner. Each SAM user, and the installation itself, must use its own pool.' ); this.name = 'GcpWifPoolOwnedByAnotherOwnerError'; } @@ -90,7 +129,7 @@ export class GcpWifPoolInvalidError extends AppError { super( 400, 'GCP_WIF_POOL_INVALID', - 'The Google Cloud project number must be digits and the workload identity pool ID may contain only lowercase letters, digits and hyphens.' + 'The Google Cloud project number must be digits, the workload identity pool and provider IDs may contain only lowercase letters, digits and hyphens, and the service account must be an email address.' ); this.name = 'GcpWifPoolInvalidError'; } @@ -127,73 +166,13 @@ interface UnindexedRow { iv: string; } -interface PoolOwnerRow { +interface PoolHolderRow { sourceTable: string; sourceId: string; ownerKind: 'user' | 'platform'; ownerUserId: string | null; } -// Every stored row that can be exchanged as a GCP credential. Composable credentials do not -// record their provider in plaintext, so every cloud-provider row is indexed once (a non-GCP row -// is stored with a NULL pool and is not decrypted again until it is re-encrypted). -const UNINDEXED_ROWS_SQL = ` -SELECT 'credentials' AS sourceTable, c.id AS sourceId, 'user' AS ownerKind, c.user_id AS ownerUserId, - c.encrypted_token AS encryptedToken, c.iv AS iv - FROM credentials c - WHERE c.provider = 'gcp' AND c.credential_type = 'cloud-provider' - AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i - WHERE i.source_table = 'credentials' AND i.source_id = c.id - AND i.iv = c.iv AND i.owner_kind = 'user' AND i.owner_user_id = c.user_id) -UNION ALL -SELECT 'platform_credentials', p.id, 'platform', NULL, p.encrypted_token, p.iv - FROM platform_credentials p - WHERE p.provider = 'gcp' AND p.credential_type = 'cloud-provider' - AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i - WHERE i.source_table = 'platform_credentials' AND i.source_id = p.id - AND i.iv = p.iv AND i.owner_kind = 'platform') -UNION ALL -SELECT 'cc_credentials', cc.id, 'user', cc.owner_id, cc.encrypted_token, cc.iv - FROM cc_credentials cc - WHERE cc.kind = 'cloud-provider' - AND NOT EXISTS (SELECT 1 FROM gcp_wif_pool_index i - WHERE i.source_table = 'cc_credentials' AND i.source_id = cc.id - AND i.iv = cc.iv AND i.owner_kind = 'user' AND i.owner_user_id = cc.owner_id) -LIMIT ?`; - -// Owners of one pool. Index rows of deleted credentials drop out through the existence checks. -// The read is used only when the unindexed-row probe in the same D1 batch (one transaction) -// returned nothing, so every remaining index row already matches its credential's current IV and -// owner. Inactive and disabled rows still count: they can be re-enabled, and the pool's binding -// in Google still trusts them. -const POOL_OWNERS_SQL = ` -SELECT i.source_table AS sourceTable, i.source_id AS sourceId, i.owner_kind AS ownerKind, - i.owner_user_id AS ownerUserId - FROM gcp_wif_pool_index i - WHERE i.pool_key = ? - AND ( - (i.source_table = 'credentials' AND EXISTS ( - SELECT 1 FROM credentials c WHERE c.id = i.source_id AND c.provider = 'gcp' - AND c.credential_type = 'cloud-provider')) - OR (i.source_table = 'platform_credentials' AND EXISTS ( - SELECT 1 FROM platform_credentials p WHERE p.id = i.source_id AND p.provider = 'gcp' - AND p.credential_type = 'cloud-provider')) - OR (i.source_table = 'cc_credentials' AND EXISTS ( - SELECT 1 FROM cc_credentials cc WHERE cc.id = i.source_id AND cc.kind = 'cloud-provider')) - ) -UNION ALL -SELECT 'project_deployment_credentials', d.id, 'user', d.user_id - FROM project_deployment_credentials d - WHERE d.provider = 'gcp' AND d.gcp_project_number = ? AND lower(trim(d.wif_pool_id)) = ?`; - -const UPSERT_INDEX_SQL = ` -INSERT INTO gcp_wif_pool_index - (source_table, source_id, iv, owner_kind, owner_user_id, pool_key, indexed_at) -VALUES (?, ?, ?, ?, ?, ?, ?) -ON CONFLICT (source_table, source_id) DO UPDATE SET - iv = excluded.iv, owner_kind = excluded.owner_kind, owner_user_id = excluded.owner_user_id, - pool_key = excluded.pool_key, indexed_at = excluded.indexed_at`; - function isSourceTable(value: unknown): value is SourceTable { return value === 'credentials' || value === 'platform_credentials' || value === 'cc_credentials'; } @@ -203,17 +182,21 @@ function toUnindexedRow(row: Record): UnindexedRow | null { if ( !isSourceTable(sourceTable) || typeof sourceId !== 'string' || - (ownerKind !== 'user' && ownerKind !== 'platform') || - (ownerUserId !== null && typeof ownerUserId !== 'string') || typeof encryptedToken !== 'string' || typeof iv !== 'string' ) { return null; } - return { sourceTable, sourceId, ownerKind, ownerUserId, encryptedToken, iv }; + if (ownerKind === 'platform') { + return { sourceTable, sourceId, ownerKind, ownerUserId: null, encryptedToken, iv }; + } + if (ownerKind === 'user' && typeof ownerUserId === 'string') { + return { sourceTable, sourceId, ownerKind, ownerUserId, encryptedToken, iv }; + } + return null; } -function toPoolOwnerRow(row: Record): PoolOwnerRow | null { +function toPoolHolderRow(row: Record): PoolHolderRow | null { const { sourceTable, sourceId, ownerKind, ownerUserId } = row; if ( typeof sourceTable !== 'string' || @@ -226,41 +209,66 @@ function toPoolOwnerRow(row: Record): PoolOwnerRow | null { return { sourceTable, sourceId, ownerKind, ownerUserId }; } +/** + * Parse every row or fail closed. A row these queries return always has these shapes (the + * columns are NOT NULL), so an unparseable row means the check cannot be trusted: treating it + * as absent could hide an unindexed credential or a foreign holder. + */ +function parseAll( + results: Record[] | undefined, + parse: (row: Record) => T | null, + context: string +): T[] { + const parsed: T[] = []; + for (const row of results ?? []) { + const value = parse(row); + if (!value) { + log.error('gcp_wif_pool_index.row_unparseable', { context, action: 'refused' }); + throw new GcpWifPoolIndexUnavailableError(); + } + parsed.push(value); + } + return parsed; +} + function ownerLabel(owner: GcpWifPoolOwner): string { return owner.kind === 'platform' ? 'platform' : `user:${owner.userId}`; } -function belongsToOwner(row: PoolOwnerRow, owner: GcpWifPoolOwner): boolean { +function heldBy(row: PoolHolderRow, owner: GcpWifPoolOwner): boolean { if (owner.kind === 'platform') return row.ownerKind === 'platform'; return row.ownerKind === 'user' && row.ownerUserId === owner.userId; } -async function readIndexSettings(env: Env): Promise<{ pageSize: number; budgetMs: number }> { - const [pageSize, budgetMs] = await Promise.all([ - resolveAdminSetting(env, 'gcpWif.poolIndexPageSize'), - resolveAdminSetting(env, 'gcpWif.poolIndexBudgetMs'), - ]); - return { pageSize: Number(pageSize), budgetMs: Number(budgetMs) }; +function ownerColumns(owner: GcpWifPoolOwner): ['user' | 'platform', string | null] { + return owner.kind === 'platform' ? ['platform', null] : ['user', owner.userId]; } -/** Decrypt and index one page of unindexed rows. A row that fails is indexed with no pool. */ +function retryCutoff(retryMinutes: number): string { + return new Date(Date.now() - retryMinutes * 60_000).toISOString(); +} + +/** Decrypt and index one page; claim each named pool for the row's owner if it is unclaimed. */ async function indexRows(env: Env, rows: UnindexedRow[]): Promise { const key = getCredentialEncryptionKey(env); const now = new Date().toISOString(); const statements: D1PreparedStatement[] = []; for (const row of rows) { let poolKey: string | null = null; + let unreadable = 0; try { const decrypted = await decrypt(row.encryptedToken, row.iv, key); poolKey = gcpWifPoolFromDecryptedPayload(decrypted)?.key ?? null; } catch (err) { - // An unreadable row cannot be exchanged either, so it owns no pool. Recording it stops - // it being decrypted again on every check until it is re-encrypted (rule 41, rule 47). + // An unreadable row cannot be exchanged either. It is retried after + // `gcpWif.poolIndexUnreadableRetryMinutes` (a key fix makes it readable without a new IV), + // not on every check, so one bad row cannot stall every check (rule 41, rule 47). + unreadable = 1; log.error('gcp_wif_pool_index.row_unreadable', { sourceTable: row.sourceTable, sourceId: row.sourceId, error: err instanceof Error ? err.message : String(err), - action: 'indexed_without_pool', + action: 'indexed_unreadable', }); } statements.push( @@ -269,60 +277,76 @@ async function indexRows(env: Env, rows: UnindexedRow[]): Promise { row.sourceId, row.iv, row.ownerKind, - row.ownerKind === 'platform' ? null : row.ownerUserId, + row.ownerUserId, poolKey, + unreadable, now ) ); + if (poolKey) { + statements.push( + env.DATABASE.prepare(CLAIM_POOL_SQL).bind(poolKey, row.ownerKind, row.ownerUserId, now) + ); + } } if (statements.length > 0) await env.DATABASE.batch(statements); } -function parseRows( - results: Record[] | undefined, - parse: (row: Record) => T | null, - context: string -): T[] { - const parsed: T[] = []; - for (const row of results ?? []) { - const value = parse(row); - if (value) parsed.push(value); - else log.error('gcp_wif_pool_index.row_skipped', { context, action: 'skipped' }); - } - return parsed; +async function readIndexSettings( + env: Env +): Promise<{ pageSize: number; budgetMs: number; retryMinutes: number }> { + const [pageSize, budgetMs, retryMinutes] = await Promise.all([ + resolveAdminSetting(env, 'gcpWif.poolIndexPageSize'), + resolveAdminSetting(env, 'gcpWif.poolIndexBudgetMs'), + resolveAdminSetting(env, 'gcpWif.poolIndexUnreadableRetryMinutes'), + ]); + return { + pageSize: Number(pageSize), + budgetMs: Number(budgetMs), + retryMinutes: Number(retryMinutes), + }; } /** - * Bring the index up to date, then return every live credential that names `pool`. - * Throws GcpWifPoolIndexUnavailableError when unindexed rows remain after the time budget, - * because an incomplete index cannot prove that no other owner names the pool. + * Bring the index up to date, then return everything that holds `pool`: its claim, live + * credentials naming it, and deployment credentials naming it. Throws + * GcpWifPoolIndexUnavailableError when unindexed rows remain after the time budget. */ -async function listPoolOwners(env: Env, pool: GcpWifPoolIdentity): Promise { - const { pageSize, budgetMs } = await readIndexSettings(env); - const deadline = Date.now() + budgetMs; - const ownersStatement = env.DATABASE.prepare(POOL_OWNERS_SQL).bind( +async function listPoolHolders(env: Env, pool: GcpWifPoolIdentity): Promise { + const holders = env.DATABASE.prepare(POOL_HOLDERS_SQL).bind( + pool.key, pool.key, pool.gcpProjectNumber, pool.wifPoolId ); + // Settings are read only when something needs indexing, so the steady state costs one batch. + let settings: Awaited> | null = null; + let deadline = Infinity; let indexedAny = false; for (;;) { - const [unindexedResult, ownersResult] = await env.DATABASE.batch>([ - env.DATABASE.prepare(UNINDEXED_ROWS_SQL).bind(pageSize), - ownersStatement, + const pageSize = settings?.pageSize ?? DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE; + const cutoff = retryCutoff( + settings?.retryMinutes ?? DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES + ); + const [unindexedResult, holdersResult] = await env.DATABASE.batch>([ + env.DATABASE.prepare(UNINDEXED_ROWS_SQL).bind(cutoff, cutoff, cutoff, pageSize), + holders, ]); - const unindexed = parseRows(unindexedResult?.results, toUnindexedRow, 'unindexed'); + const unindexed = parseAll(unindexedResult?.results, toUnindexedRow, 'unindexed'); if (unindexed.length === 0) { - const owners = parseRows(ownersResult?.results, toPoolOwnerRow, 'owners'); + const found = parseAll(holdersResult?.results, toPoolHolderRow, 'holders'); if (indexedAny) { - log.info('gcp_wif_pool_index.reconciled', { poolKey: pool.key, owners: owners.length }); + log.info('gcp_wif_pool_index.reconciled', { poolKey: pool.key, holders: found.length }); } - return owners; + return found; } - if (Date.now() >= deadline) { + if (!settings) { + settings = await readIndexSettings(env); + deadline = Date.now() + settings.budgetMs; + } else if (Date.now() >= deadline) { log.error('gcp_wif_pool_index.budget_exhausted', { poolKey: pool.key, - budgetMs, + budgetMs: settings.budgetMs, remainingPage: unindexed.length, action: 'refused', }); @@ -333,9 +357,28 @@ async function listPoolOwners(env: Env, pool: GcpWifPoolIdentity): Promise `${row.sourceTable}:${row.sourceId}`), + conflictingOwnerKinds: [...new Set(foreign.map((row) => row.ownerKind))], + action: 'refused', + }); + throw new GcpWifPoolOwnedByAnotherOwnerError(); +} + /** - * Refuse when a credential belonging to a different owner names `pool`. - * `context` names the caller (save route or token exchange) for the structured log line. + * Refuse when the pool is claimed by, or named by a credential of, a different owner; otherwise + * claim it for `owner` if nobody has. `context` names the caller (a save route or the token + * exchange) for the structured log line. */ export async function assertGcpWifPoolOwnership( env: Env, @@ -345,25 +388,33 @@ export async function assertGcpWifPoolOwnership( ): Promise { const identity = gcpWifPoolIdentity(pool.gcpProjectNumber, pool.wifPoolId); if (!identity) { - log.error('gcp_wif_pool.invalid_identity', { + log.warn('gcp_wif_pool.invalid_identity', { context, owner: ownerLabel(owner), action: 'refused', }); throw new GcpWifPoolInvalidError(); } - const owners = await listPoolOwners(env, identity); - const foreign = owners.filter((row) => !belongsToOwner(row, owner)); - if (foreign.length === 0) return; - log.error('gcp_wif_pool.cross_owner_refused', { - context, - poolKey: identity.key, - owner: ownerLabel(owner), - conflictingCredentials: foreign.map((row) => `${row.sourceTable}:${row.sourceId}`), - conflictingOwnerKinds: [...new Set(foreign.map((row) => row.ownerKind))], - action: 'refused', - }); - throw new GcpWifPoolOwnedByAnotherOwnerError(); + const holders = await listPoolHolders(env, identity); + const foreign = holders.filter((row) => !heldBy(row, owner)); + if (foreign.length > 0) refuse(context, identity, owner, foreign); + if (holders.some((row) => row.sourceTable === 'gcp_wif_pool_claims')) return; + + // Unclaimed: claim it. The primary key decides a concurrent claim, so re-read the winner. + const [ownerKind, ownerUserId] = ownerColumns(owner); + const [, claimResult] = await env.DATABASE.batch>([ + env.DATABASE.prepare(CLAIM_POOL_SQL).bind( + identity.key, + ownerKind, + ownerUserId, + new Date().toISOString() + ), + env.DATABASE.prepare(READ_CLAIM_SQL).bind(identity.key), + ]); + const claim = parseAll(claimResult?.results, toPoolHolderRow, 'claim'); + const [winner] = claim; + if (!winner || claim.length !== 1) throw new GcpWifPoolIndexUnavailableError(); + if (!heldBy(winner, owner)) refuse(context, identity, owner, claim); } /** diff --git a/apps/api/src/services/gcp-wif-setup.ts b/apps/api/src/services/gcp-wif-setup.ts index a5266dbdad..035d39d8b0 100644 --- a/apps/api/src/services/gcp-wif-setup.ts +++ b/apps/api/src/services/gcp-wif-setup.ts @@ -11,9 +11,15 @@ import { requireOperationName, } from './gcp-setup-transport'; -const serviceAccountPolicySchema = v.object({ - bindings: v.optional(v.array(iamBindingSchema)), +// Loose, so a binding's IAM `condition` and the policy `version` survive the read-modify-write. +const serviceAccountBindingSchema = v.looseObject({ + ...iamBindingSchema.entries, + condition: v.optional(v.unknown()), +}); +const serviceAccountPolicySchema = v.looseObject({ + bindings: v.optional(v.array(serviceAccountBindingSchema)), etag: v.string(), + version: v.optional(v.number()), }); /** @@ -397,7 +403,8 @@ export async function grantWifUserOnSa( b.role === role ? { ...b, members: b.members.filter((m) => m !== legacyMember) } : b ); if (!granted) { - const target = bindings.find((b) => b.role === role); + // Never add the member under another binding's IAM condition. + const target = bindings.find((b) => b.role === role && b.condition === undefined); if (target) target.members.push(member); else bindings.push({ role, members: [member] }); } @@ -414,7 +421,13 @@ export async function grantWifUserOnSa( Authorization: `Bearer ${oauthToken}`, 'Content-Type': 'application/json', }, - body: JSON.stringify({ policy: { bindings: nonEmptyBindings, etag: policy.etag } }), + body: JSON.stringify({ + policy: { + bindings: nonEmptyBindings, + etag: policy.etag, + ...(policy.version !== undefined ? { version: policy.version } : {}), + }, + }), }, timeoutMs ); diff --git a/apps/api/src/services/mcp-token-lifecycle.ts b/apps/api/src/services/mcp-token-lifecycle.ts index a992cd1301..5e6194cbfc 100644 --- a/apps/api/src/services/mcp-token-lifecycle.ts +++ b/apps/api/src/services/mcp-token-lifecycle.ts @@ -200,7 +200,7 @@ export async function validateActiveWorkspaceMcpToken( workspaceId: data.workspaceId || null, projectId: data.projectId, taskId: data.taskId || null, - tokenUserId: data.userId, + cacheUserId: data.userId, workspaceUserId: row?.userId ?? null, workspaceProjectId: row?.projectId ?? null, userStatus: joinedStatus(row?.joinedUserId, row?.userStatus), diff --git a/apps/api/src/services/provider-credentials.ts b/apps/api/src/services/provider-credentials.ts index b9767d4d1e..e30f95bc2a 100644 --- a/apps/api/src/services/provider-credentials.ts +++ b/apps/api/src/services/provider-credentials.ts @@ -269,8 +269,8 @@ async function createProviderFromComposableConfig( const gcpCred = parseGcpCredential(token); const { getGcpAccessToken } = await import('./gcp-sts'); const requester: GcpTokenRequester = isPlatform - ? { tokenUserId: `platform:${userId}`, poolOwner: { kind: 'platform' } } - : { tokenUserId: userId, poolOwner: { kind: 'user', userId } }; + ? { cacheUserId: `platform:${userId}`, poolOwner: { kind: 'platform' } } + : { cacheUserId: userId, poolOwner: { kind: 'user', userId } }; const cacheProjectId = projectId ?? gcpCred.gcpProjectId; const tokenProvider = (context?: ProviderRequestContext) => getGcpAccessToken(requester, cacheProjectId, gcpCred, env, context); @@ -417,7 +417,7 @@ async function createProviderForUserLegacy( const tokenProvider = (context?: ProviderRequestContext) => getGcpAccessToken( { - tokenUserId: `project:${projectId}:${userId}`, + cacheUserId: `project:${projectId}:${userId}`, // The project credential may have been saved by another member of the project. poolOwner: { kind: 'user', userId: projectCred.userId }, }, @@ -490,7 +490,7 @@ async function createProviderForUserLegacy( const cacheProjectId = projectId ?? gcpCred.gcpProjectId; const tokenProvider = (context?: ProviderRequestContext) => getGcpAccessToken( - { tokenUserId: userId, poolOwner: { kind: 'user', userId } }, + { cacheUserId: userId, poolOwner: { kind: 'user', userId } }, cacheProjectId, gcpCred, env, @@ -545,7 +545,7 @@ async function createProviderForUserLegacy( const cacheProjectId = projectId ?? gcpCred.gcpProjectId; const tokenProvider = (context?: ProviderRequestContext) => getGcpAccessToken( - { tokenUserId: `platform:${userId}`, poolOwner: { kind: 'platform' } }, + { cacheUserId: `platform:${userId}`, poolOwner: { kind: 'platform' } }, cacheProjectId, gcpCred, env, diff --git a/apps/api/src/services/runtime-secret-requests.ts b/apps/api/src/services/runtime-secret-requests.ts index 34e92a062e..67186c431c 100644 --- a/apps/api/src/services/runtime-secret-requests.ts +++ b/apps/api/src/services/runtime-secret-requests.ts @@ -163,7 +163,7 @@ async function loadRequestingTask(env: Env, identity: SecretRequesterIdentity) { log.error('runtime_secret_request.task_mismatch', { taskId: identity.taskId, projectId: identity.projectId, - tokenUserId: identity.userId, + cacheUserId: identity.userId, taskUserId: row?.user_id ?? null, action: 'rejected', }); diff --git a/apps/api/tests/unit/routes/gcp.test.ts b/apps/api/tests/unit/routes/gcp.test.ts index b31486a47a..4a6b1c811d 100644 --- a/apps/api/tests/unit/routes/gcp.test.ts +++ b/apps/api/tests/unit/routes/gcp.test.ts @@ -159,7 +159,7 @@ describe('GCP routes', () => { expect(res.status).toBe(200); expect(mocks.replaceUserGcpCredential).toHaveBeenCalledWith(env, 'test-user-id', wifCredential); expect(mocks.verifyGcpOidcSetup).toHaveBeenCalledWith( - { tokenUserId: 'test-user-id', poolOwner: { kind: 'user', userId: 'test-user-id' } }, + { cacheUserId: 'test-user-id', poolOwner: { kind: 'user', userId: 'test-user-id' } }, 'setup-verification', wifCredential, env @@ -197,7 +197,7 @@ describe('GCP routes', () => { ); expect(mocks.parseServiceAccountJson).toHaveBeenCalledWith(uploadedJson, 'us-central1-a'); expect(mocks.getGcpAccessToken).toHaveBeenCalledWith( - { tokenUserId: 'test-user-id', poolOwner: { kind: 'user', userId: 'test-user-id' } }, + { cacheUserId: 'test-user-id', poolOwner: { kind: 'user', userId: 'test-user-id' } }, 'service-account-setup', serviceAccountCredential, env diff --git a/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts b/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts index be19e279b1..164b8af17a 100644 --- a/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts +++ b/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts @@ -20,6 +20,12 @@ vi.mock('../../../src/scheduled/provider-orphan-credentials', () => ({ resolveInventoryProvider: vi.fn(), })); vi.mock('../../../src/services/observability', () => ({ persistError: vi.fn() })); +// This suite has no database; pool ownership has its own real-SQL suite. Spy on the check to +// prove the sweep's exchange runs it as the installation. +vi.mock('../../../src/services/gcp-wif-pool-ownership', async (importOriginal) => ({ + ...(await importOriginal()), + assertGcpWifPoolOwnership: vi.fn(async () => undefined), +})); vi.mock('../../../src/lib/logger', async (importOriginal) => ({ ...(await importOriginal()), log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, @@ -163,6 +169,14 @@ describe('platform GCP orphan sweep configuration and authentication', () => { expect(result.errors).toBe(0); expect(result.deletionRequested).toBe(1); expect(result.destroyed).toBe(0); + const { assertGcpWifPoolOwnership } = + await import('../../../src/services/gcp-wif-pool-ownership'); + expect(assertGcpWifPoolOwnership).toHaveBeenCalledWith( + env, + expect.objectContaining({ authType: 'workload-identity' }), + { kind: 'platform' }, + 'token_exchange' + ); const sts = fetchMock.mock.calls.find(([url]) => String(url).includes('sts.googleapis.com')); expect(sts).toBeDefined(); const body = JSON.parse(sts![1]!.body as string); diff --git a/apps/api/tests/unit/services/default-capacity-pools.test.ts b/apps/api/tests/unit/services/default-capacity-pools.test.ts index a88814219b..449f8f7cf3 100644 --- a/apps/api/tests/unit/services/default-capacity-pools.test.ts +++ b/apps/api/tests/unit/services/default-capacity-pools.test.ts @@ -59,7 +59,7 @@ import { catalogPublicationMigrationSql, } from '../../helpers/capacity-pool-migrations'; import { pickStarterMachines } from '../../helpers/capacity-pool-picks'; -import { createSqliteD1WithBindLimit } from '../../helpers/sqlite-d1'; +import { applySqliteMigration, createSqliteD1WithBindLimit } from '../../helpers/sqlite-d1'; let sqlite: Database.Database | null = null; const TEST_ENCRYPTION_KEY = Buffer.from('0123456789abcdef0123456789abcdef').toString('base64'); @@ -214,7 +214,21 @@ function createDb(options: { includeCatalogPublication?: boolean } = {}) { created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP ); + + CREATE TABLE project_deployment_credentials ( + id TEXT PRIMARY KEY, + project_id TEXT NOT NULL, + user_id TEXT NOT NULL, + provider TEXT NOT NULL DEFAULT 'gcp', + gcp_project_number TEXT NOT NULL, + wif_pool_id TEXT NOT NULL + ); `); + // GCP credential saves check workload identity pool ownership (migration 0262). + applySqliteMigration( + sqlite, + new URL('../../../src/db/migrations/0262_gcp_wif_pool_index.sql', import.meta.url) + ); seedIdentity(); applyCapacityPoolSchemaMigrations(sqlite, options); return poolDb(); diff --git a/apps/api/tests/unit/services/gcp-live-catalog-build.test.ts b/apps/api/tests/unit/services/gcp-live-catalog-build.test.ts index 815df44d74..3ddb6bf2c5 100644 --- a/apps/api/tests/unit/services/gcp-live-catalog-build.test.ts +++ b/apps/api/tests/unit/services/gcp-live-catalog-build.test.ts @@ -21,10 +21,10 @@ import { createAllSchemaTables, createMemoryKv, createSqliteD1 } from '../../hel const tokenCalls: Array<{ userId: string; poolOwner: unknown; projectId: string }> = []; vi.mock('../../../src/services/gcp-sts', () => ({ getGcpAccessToken: async ( - requester: { tokenUserId: string; poolOwner: unknown }, + requester: { cacheUserId: string; poolOwner: unknown }, projectId: string ) => { - tokenCalls.push({ userId: requester.tokenUserId, poolOwner: requester.poolOwner, projectId }); + tokenCalls.push({ userId: requester.cacheUserId, poolOwner: requester.poolOwner, projectId }); return 'gcp-token'; }, })); diff --git a/apps/api/tests/unit/services/gcp-price-table.test.ts b/apps/api/tests/unit/services/gcp-price-table.test.ts index 689b6ef48c..5701adb1e8 100644 --- a/apps/api/tests/unit/services/gcp-price-table.test.ts +++ b/apps/api/tests/unit/services/gcp-price-table.test.ts @@ -40,7 +40,7 @@ const tokenCalls: Array<{ const tokenScopes: Array = []; vi.mock('../../../src/services/gcp-sts', () => ({ getGcpAccessToken: async ( - requester: { tokenUserId: string; poolOwner: unknown }, + requester: { cacheUserId: string; poolOwner: unknown }, projectId: string, credential: { gcpProjectId: string }, _env: unknown, @@ -48,7 +48,7 @@ vi.mock('../../../src/services/gcp-sts', () => ({ options?: { scopes?: readonly string[] } ) => { tokenCalls.push({ - userId: requester.tokenUserId, + userId: requester.cacheUserId, poolOwner: requester.poolOwner, projectId, gcpProjectId: credential.gcpProjectId, diff --git a/apps/api/tests/unit/services/gcp-provider-cancellation-slice.test.ts b/apps/api/tests/unit/services/gcp-provider-cancellation-slice.test.ts index c3a09cb1d8..fac068d689 100644 --- a/apps/api/tests/unit/services/gcp-provider-cancellation-slice.test.ts +++ b/apps/api/tests/unit/services/gcp-provider-cancellation-slice.test.ts @@ -139,13 +139,13 @@ describe('GCP provider credential cancellation wiring', () => { mocks.resolveForConsumer.mockResolvedValue(composableGcpResolution()); return makeCredentialDbMock(); }, - expectedRequester: { tokenUserId: USER_ID, poolOwner: { kind: 'user', userId: USER_ID } }, + expectedRequester: { cacheUserId: USER_ID, poolOwner: { kind: 'user', userId: USER_ID } }, expectedSource: 'user', }, { name: 'legacy user credential', setup: () => makeCredentialDbMock(legacyGcpCredential()), - expectedRequester: { tokenUserId: USER_ID, poolOwner: { kind: 'user', userId: USER_ID } }, + expectedRequester: { cacheUserId: USER_ID, poolOwner: { kind: 'user', userId: USER_ID } }, expectedSource: 'user', }, { @@ -157,7 +157,7 @@ describe('GCP provider credential cancellation wiring', () => { }); return makeCredentialDbMock(); }, - expectedRequester: { tokenUserId: `platform:${USER_ID}`, poolOwner: { kind: 'platform' } }, + expectedRequester: { cacheUserId: `platform:${USER_ID}`, poolOwner: { kind: 'platform' } }, expectedSource: 'platform', }, ])( diff --git a/apps/api/tests/unit/services/gcp-service-account.test.ts b/apps/api/tests/unit/services/gcp-service-account.test.ts index 14e29e00a6..d191a44662 100644 --- a/apps/api/tests/unit/services/gcp-service-account.test.ts +++ b/apps/api/tests/unit/services/gcp-service-account.test.ts @@ -33,7 +33,7 @@ vi.mock('../../../src/services/gcp-wif-pool-ownership', () => ({ assertGcpWifPoolOwnership: vi.fn().mockResolvedValue(undefined), })); -const USER_1 = { tokenUserId: 'user-1', poolOwner: { kind: 'user', userId: 'user-1' } } as const; +const USER_1 = { cacheUserId: 'user-1', poolOwner: { kind: 'user', userId: 'user-1' } } as const; let privateKey: string; @@ -294,7 +294,7 @@ describe('service-account verification and caching', () => { await expect( getGcpAccessToken( - { tokenUserId: 'project:p-1:user-2', poolOwner: { kind: 'user', userId: 'user-9' } }, + { cacheUserId: 'project:p-1:user-2', poolOwner: { kind: 'user', userId: 'user-9' } }, 'p-1', credential, env diff --git a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts index 759e5cfa9a..2f0a9c9a62 100644 --- a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -10,6 +10,7 @@ import { readFileSync } from 'node:fs'; import { GCP_CREDENTIAL_VERSION, type GcpOidcCredential } from '@simple-agent-manager/shared'; import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/d1'; import { Hono } from 'hono'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -41,7 +42,9 @@ const { GcpWifPoolInvalidError, GcpWifPoolOwnedByAnotherOwnerError, } = await import('../../../src/services/gcp-wif-pool-ownership'); -const { serializeCredentialToken } = await import('../../../src/services/provider-credentials'); +const { serializeCredentialToken, createProviderForUser } = + await import('../../../src/services/provider-credentials'); +const { UNINDEXED_ROWS_SQL } = await import('../../../src/services/gcp-wif-pool-ownership-sql'); const KEY = Buffer.from('0123456789abcdef0123456789abcdef').toString('base64'); const NOW = '2026-11-19T00:00:00.000Z'; @@ -115,7 +118,7 @@ async function storeCcRow(id: string, ownerId: string, plaintext: string) { } function user(userId: string) { - return { tokenUserId: userId, poolOwner: { kind: 'user' as const, userId } }; + return { cacheUserId: userId, poolOwner: { kind: 'user' as const, userId } }; } function exchange( @@ -255,12 +258,40 @@ describe('token exchange refuses a pool another owner uses (rows that predate th await expect( exchange( user('user-b'), - wif({ gcpProjectNumber: ` ${POOL_A.gcpProjectNumber} `, wifPoolId: 'SAM-Pool' }) + wif( + { gcpProjectNumber: ` ${POOL_A.gcpProjectNumber} `, wifPoolId: 'SAM-Pool' }, + { gcpProjectId: 'gcp-b', serviceAccountEmail: 'sam@gcp-b.iam.gserviceaccount.com' } + ) ) ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); expect(signIdentityToken).not.toHaveBeenCalled(); }); + it('attack: a leading zero cannot alias A’s project number', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await expect( + exchange( + user('user-b'), + wif({ gcpProjectNumber: `0${POOL_A.gcpProjectNumber}`, wifPoolId: 'sam-pool' }) + ) + ).rejects.toBeInstanceOf(GcpWifPoolInvalidError); + expect(signIdentityToken).not.toHaveBeenCalled(); + }); + + it.each([ + ['provider id with a path', { wifProviderId: 'p/../../other-pool/providers/x' }], + ['service account with a query', { serviceAccountEmail: 'sa@x.iam.gserviceaccount.com?a=b' }], + ])('refuses a %s before signing', async (_name, overrides) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + await expect(exchange(user('user-a'), wif(POOL_A, overrides))).rejects.toBeInstanceOf( + GcpWifPoolInvalidError + ); + expect(signIdentityToken).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it('attack: a user credential cannot name the platform credential’s pool', async () => { await storePlatformRow('plat-1', wif(POOL_PLATFORM)); @@ -272,7 +303,7 @@ describe('token exchange refuses a pool another owner uses (rows that predate th // Owner control: the installation still exchanges with its own pool. await expect( exchange( - { tokenUserId: 'platform:user-b', poolOwner: { kind: 'platform' } }, + { cacheUserId: 'platform:user-b', poolOwner: { kind: 'platform' } }, wif(POOL_PLATFORM) ) ).resolves.toBe('sa-token'); @@ -282,7 +313,7 @@ describe('token exchange refuses a pool another owner uses (rows that predate th await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); await expect( - exchange({ tokenUserId: 'platform:user-b', poolOwner: { kind: 'platform' } }, wif(POOL_A)) + exchange({ cacheUserId: 'platform:user-b', poolOwner: { kind: 'platform' } }, wif(POOL_A)) ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); expect(fetchMock).not.toHaveBeenCalled(); }); @@ -310,7 +341,7 @@ describe('token exchange refuses a pool another owner uses (rows that predate th await expect( exchange( - { tokenUserId: 'project:proj-a:user-a', poolOwner: { kind: 'user', userId: 'user-a' } }, + { cacheUserId: 'project:proj-a:user-a', poolOwner: { kind: 'user', userId: 'user-a' } }, wif(POOL_A), 'proj-a' ) @@ -318,34 +349,70 @@ describe('token exchange refuses a pool another owner uses (rows that predate th // Another project member's run uses A's project credential, so A owns the pool. await expect( exchange( - { tokenUserId: 'project:proj-a:user-m', poolOwner: { kind: 'user', userId: 'user-a' } }, + { cacheUserId: 'project:proj-a:user-m', poolOwner: { kind: 'user', userId: 'user-a' } }, wif(POOL_A), 'proj-a' ) ).resolves.toBe('sa-token'); }); - it('a deleted or re-pointed credential stops owning its old pool', async () => { + it('a pool stays claimed after its credential is deleted or re-pointed (Google still trusts it)', async () => { await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( GcpWifPoolOwnedByAnotherOwnerError ); - // A re-saves their credential for a different pool (new IV), then B may use the old one. + // A re-saves their credential for a different pool (new IV): A now holds both pools. const repointed = await sealed(JSON.stringify(wif(POOL_B))); sqlite .prepare('UPDATE credentials SET encrypted_token = ?, iv = ? WHERE id = ?') .run(repointed.ciphertext, repointed.iv, 'cred-a'); - await expect(exchange(user('user-b'), wif(POOL_A))).resolves.toBe('sa-token'); + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); await expect(exchange(user('user-b'), wif(POOL_B))).rejects.toBeInstanceOf( GcpWifPoolOwnedByAnotherOwnerError ); + // A disconnects entirely: the claims remain, because A's `pool/*` binding may remain too. sqlite.prepare('DELETE FROM credentials WHERE id = ?').run('cred-a'); - await expect(exchange(user('user-b'), wif(POOL_B))).resolves.toBe('sa-token'); + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + // Owner control: A reconnects to the same pool. + await expect(exchange(user('user-a'), wif(POOL_A))).resolves.toBe('sa-token'); + + // An operator releases the claim once Google-side trust is gone; then B may use the pool. + sqlite + .prepare('DELETE FROM gcp_wif_pool_claims WHERE pool_key = ?') + .run('111111111111/sam-pool'); + await expect(exchange(user('user-b'), wif(POOL_A))).resolves.toBe('sa-token'); + // B now holds the released pool. + expect( + sqlite + .prepare('SELECT owner_user_id FROM gcp_wif_pool_claims WHERE pool_key = ?') + .get('111111111111/sam-pool') + ).toEqual({ owner_user_id: 'user-b' }); + }); + + it('a live credential of another owner still blocks after a claim is released (symmetric check)', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + await storeLegacyRow('cred-b', 'user-b', wif(POOL_A)); + await expect(exchange(user('user-a'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + sqlite.prepare('DELETE FROM gcp_wif_pool_claims').run(); + // Both rows still exist and name the pool: neither owner may use it. + await expect(exchange(user('user-a'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + expect(fetchMock).not.toHaveBeenCalled(); }); - it('deleted platform and composable credentials stop owning their pools', async () => { + it('platform and composable credentials claim their pools', async () => { await storePlatformRow('plat-1', wif(POOL_PLATFORM)); await storeCcRow('cc-a', 'user-a', JSON.stringify(wif(POOL_A))); await expect(exchange(user('user-b'), wif(POOL_PLATFORM))).rejects.toBeInstanceOf( @@ -354,11 +421,36 @@ describe('token exchange refuses a pool another owner uses (rows that predate th await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( GcpWifPoolOwnedByAnotherOwnerError ); + expect( + sqlite + .prepare( + 'SELECT pool_key, owner_kind, owner_user_id FROM gcp_wif_pool_claims ORDER BY pool_key' + ) + .all() + ).toEqual([ + { pool_key: '111111111111/sam-pool', owner_kind: 'user', owner_user_id: 'user-a' }, + { pool_key: '222222222222/sam-pool', owner_kind: 'platform', owner_user_id: null }, + ]); + }); - sqlite.prepare('DELETE FROM platform_credentials WHERE id = ?').run('plat-1'); - sqlite.prepare('DELETE FROM cc_credentials WHERE id = ?').run('cc-a'); - await expect(exchange(user('user-b'), wif(POOL_PLATFORM))).resolves.toBe('sa-token'); - await expect(exchange(user('user-b'), wif(POOL_A))).resolves.toBe('sa-token'); + it('concurrent first claims of an unclaimed pool: exactly one owner wins', async () => { + const results = await Promise.allSettled([ + assertGcpWifPayloadOwnership( + env, + JSON.stringify(wif(POOL_B)), + { kind: 'user', userId: 'user-a' }, + 't' + ), + assertGcpWifPayloadOwnership( + env, + JSON.stringify(wif(POOL_B)), + { kind: 'user', userId: 'user-b' }, + 't' + ), + ]); + expect(results.map((r) => r.status).sort()).toEqual(['fulfilled', 'rejected']); + const rejected = results.find((r) => r.status === 'rejected') as PromiseRejectedResult; + expect(rejected.reason).toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); }); it('a bad row does not break the check for others (rule 41)', async () => { @@ -411,6 +503,10 @@ describe('token exchange refuses a pool another owner uses (rows that predate th it('fails closed when unindexed rows remain after the time budget', async () => { await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + // More rows than one page (default 25), so a second page is needed after the deadline. + for (let i = 0; i < 30; i++) { + await storeCcRow(`cc-other-${String(i).padStart(2, '0')}`, 'user-b', `token-${i}`); + } // Every clock reading is 20 s after the previous one, so whichever reading sets the // deadline (default budget 10 s), the next reading is already past it. let clock = Date.now(); @@ -549,3 +645,138 @@ describe('save time refuses a pool another owner uses', () => { expect(google).toHaveBeenCalledTimes(1); }); }); + +describe('index maintenance and cost', () => { + it('retries an undecryptable row only after the retry window, then indexes it', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + // Encrypted under another key, as if the Worker's key were misconfigured when it was read. + const otherKey = Buffer.from('fedcba9876543210fedcba9876543210').toString('base64'); + const foreign = await encrypt(JSON.stringify(wif(POOL_B)), otherKey); + sqlite + .prepare( + `INSERT INTO cc_credentials (id, owner_id, name, kind, encrypted_token, iv, is_active, created_at, updated_at) + VALUES ('cc-other-key', 'user-a', 'x', 'cloud-provider', ?, ?, 1, ?, ?)` + ) + .run(foreign.ciphertext, foreign.iv, NOW, NOW); + vi.spyOn(console, 'error').mockImplementation(() => {}); + const row = () => + sqlite + .prepare( + `SELECT pool_key, unreadable FROM gcp_wif_pool_index WHERE source_id = 'cc-other-key'` + ) + .get(); + + await expect(exchange(user('user-a'), wif(POOL_A))).resolves.toBe('sa-token'); + expect(row()).toEqual({ pool_key: null, unreadable: 1 }); + + // The key is fixed. Inside the retry window the row is not decrypted again. + (env as { ENCRYPTION_KEY: string }).ENCRYPTION_KEY = otherKey; + const encryption = await import('../../../src/services/encryption'); + const decryptSpy = vi.spyOn(encryption, 'decrypt'); + await expect( + assertGcpWifPayloadOwnership( + env, + JSON.stringify(wif(POOL_A)), + { kind: 'user', userId: 'user-a' }, + 't' + ) + ).resolves.toBeUndefined(); + expect(decryptSpy).not.toHaveBeenCalled(); + expect(row()).toEqual({ pool_key: null, unreadable: 1 }); + + // After the default 60-minute window it is read and its pool claimed for its owner. + const later = Date.now() + 61 * 60_000; + vi.spyOn(Date, 'now').mockReturnValue(later); + await expect( + assertGcpWifPayloadOwnership( + env, + JSON.stringify(wif(POOL_A)), + { kind: 'user', userId: 'user-a' }, + 't' + ) + ).resolves.toBeUndefined(); + expect(row()).toEqual({ pool_key: '333333333333/sam-pool', unreadable: 0 }); + await expect( + assertGcpWifPayloadOwnership( + env, + JSON.stringify(wif(POOL_B)), + { kind: 'user', userId: 'user-b' }, + 't' + ) + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + }); + + it('the probe reads only cloud credentials through the partial indexes', () => { + const plan = sqlite + .prepare(`EXPLAIN QUERY PLAN ${UNINDEXED_ROWS_SQL}`) + .all(NOW, NOW, NOW, 25) as Array<{ detail: string }>; + const details = plan.map((step) => step.detail); + // No full scan of `credentials` (agent keys live there) or `cc_credentials`. + expect(details.filter((d) => /^SCAN (c|cc)$/.test(d))).toEqual([]); + expect(details.some((d) => d.includes('idx_credentials_gcp_cloud'))).toBe(true); + expect(details.some((d) => d.includes('idx_cc_credentials_cloud'))).toBe(true); + }); +}); + +describe('the credential owner reaches the exchange through the real resolver', () => { + it('a project member using another member’s project credential signs as, and is checked as, its owner', async () => { + await storeLegacyRow('cred-a-proj', 'user-a', wif(POOL_A), 'proj-a'); + // A's pool is claimed by A (e.g. A also has a user-level credential for it). + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + + const resolved = await createProviderForUser( + drizzle(env.DATABASE, { schema }), + 'user-m', + KEY, + env, + 'gcp', + 'proj-a' + ); + expect(resolved?.credentialSource).toBe('project'); + await expect(resolved!.provider.validateToken()).resolves.toBe(true); + expect(signIdentityToken).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-a', projectId: 'proj-a' }), + env + ); + }); + + it('the exact-credential path uses the stored row’s owner too', async () => { + await storeLegacyRow('cred-a-proj', 'user-a', wif(POOL_A), 'proj-a'); + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + + const resolved = await createProviderForUser( + drizzle(env.DATABASE, { schema }), + 'user-m', + KEY, + env, + 'gcp', + 'proj-a', + { + credentialSource: 'project', + credentialReference: 'credentials:cred-a-proj', + credentialVersion: Date.parse(NOW), + } + ); + await expect(resolved!.provider.validateToken()).resolves.toBe(true); + expect(signIdentityToken).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-a', projectId: 'proj-a' }), + env + ); + }); + + it('a user-level credential signs its owner’s id, which the user-scoped condition requires', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + const resolved = await createProviderForUser( + drizzle(env.DATABASE, { schema }), + 'user-a', + KEY, + env, + 'gcp' + ); + await expect(resolved!.provider.validateToken()).resolves.toBe(true); + expect(signIdentityToken).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-a' }), + env + ); + }); +}); diff --git a/apps/api/tests/unit/services/node-teardown-gcp-resave.test.ts b/apps/api/tests/unit/services/node-teardown-gcp-resave.test.ts index 307d26a82f..bf944c6ada 100644 --- a/apps/api/tests/unit/services/node-teardown-gcp-resave.test.ts +++ b/apps/api/tests/unit/services/node-teardown-gcp-resave.test.ts @@ -324,7 +324,12 @@ describe('node teardown after the GCP connection is saved again (incident 2026-1 // A stale caller that observed an older incarnation or another episode claims nothing. await alertNodeCleanupBlocked(env, { ...input, runtimeIncarnationId: 'older' }, now, 60_000); - await alertNodeCleanupBlocked(env, { ...input, blockedSince: '2026-11-13T22:00:00.000Z' }, now, 60_000); + await alertNodeCleanupBlocked( + env, + { ...input, blockedSince: '2026-11-13T22:00:00.000Z' }, + now, + 60_000 + ); expect(nodeRow()).toMatchObject({ alertedAt: null }); // Control: the matching runtime and episode is claimed and alerted. @@ -334,17 +339,17 @@ describe('node teardown after the GCP connection is saved again (incident 2026-1 it('records a blocked verdict only on the runtime incarnation that was refused', async () => { await placeNode(); - const { recordNodeTeardownBlocked } = await import( - '../../../src/services/node-teardown-blocked' - ); - const { NodeTeardownBlockedError } = await import( - '../../../src/services/node-teardown-authority' - ); + const { recordNodeTeardownBlocked } = + await import('../../../src/services/node-teardown-blocked'); + const { NodeTeardownBlockedError } = + await import('../../../src/services/node-teardown-authority'); sqlite.prepare("UPDATE nodes SET status = 'destroying' WHERE id = ?").run(NODE_ID); const db = drizzle(env.DATABASE, { schema }); const [stale] = await db.select().from(schema.nodes); // The node was re-provisioned after the refused attempt read it. - sqlite.prepare("UPDATE nodes SET runtime_incarnation_id = 'replacement' WHERE id = ?").run(NODE_ID); + sqlite + .prepare("UPDATE nodes SET runtime_incarnation_id = 'replacement' WHERE id = ?") + .run(NODE_ID); await recordNodeTeardownBlocked( env, @@ -393,17 +398,25 @@ describe('node teardown after the GCP connection is saved again (incident 2026-1 ]); }); - it('never uses another user\'s credential, even one that can see the instance', async () => { + it("never uses another user's credential, even one that can see the instance", async () => { await placeNode(); putInstance('sam-staging-infra', { id: INSTANCE_ID, labels: samLabels() }); - // The owner disconnects GCP; a different user connects the SAME GCP project. + // The owner disconnects GCP; a different user connects the SAME GCP project. The owner's + // workload identity pool stays claimed by the owner after the disconnect (pool ownership, + // gcp-wif-pool-ownership.ts), so the other user connects through a pool of their own. await env.DATABASE.batch([ - env.DATABASE.prepare( - "DELETE FROM credentials WHERE user_id = ? AND provider = 'gcp'" - ).bind(OWNER), + env.DATABASE.prepare("DELETE FROM credentials WHERE user_id = ? AND provider = 'gcp'").bind( + OWNER + ), env.DATABASE.prepare('DELETE FROM cc_attachments WHERE user_id = ?').bind(OWNER), ]); - await replaceUserGcpCredential(env, 'other-user', gcpCredential('sam-staging-infra')); + await expect( + replaceUserGcpCredential(env, 'other-user', gcpCredential('sam-staging-infra')) + ).rejects.toMatchObject({ error: 'GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER' }); + await replaceUserGcpCredential(env, 'other-user', { + ...gcpCredential('sam-staging-infra'), + wifPoolId: 'other-user-pool', + } as Parameters[2]); const response = await ownerDelete(); @@ -416,9 +429,8 @@ describe('node teardown after the GCP connection is saved again (incident 2026-1 describe('proveNodeInstanceOwnership: provider refusals', () => { async function prove(error: Error) { - const { proveNodeInstanceOwnership } = await import( - '../../../src/services/node-teardown-authority' - ); + const { proveNodeInstanceOwnership } = + await import('../../../src/services/node-teardown-authority'); const node = { id: NODE_ID, nodeRole: 'workspace', @@ -456,7 +468,8 @@ describe('proveNodeInstanceOwnership: provider refusals', () => { step: 'sa_impersonation', message: 'Permission denied on projects/corporate-prod', statusCode: 403, - rawBody: '{"error":{"status":"PERMISSION_DENIED","message":"generate access token denied"}}', + rawBody: + '{"error":{"status":"PERMISSION_DENIED","message":"generate access token denied"}}', }) ); expect(result.message).toMatch(/^teardown_instance_not_visible/); @@ -478,11 +491,17 @@ describe('proveNodeInstanceOwnership: provider refusals', () => { step: 'sts_exchange', message: 'The caller does not have access to rate-limit-tests', statusCode: 401, - rawBody: '{"error":"invalid_grant","error_description":"token for project quota-prod is revoked"}', - }), - new ProviderError('hetzner', 403, 'hetzner API error (403): forbidden on project quota-prod', { - providerCode: 'forbidden', + rawBody: + '{"error":"invalid_grant","error_description":"token for project quota-prod is revoked"}', }), + new ProviderError( + 'hetzner', + 403, + 'hetzner API error (403): forbidden on project quota-prod', + { + providerCode: 'forbidden', + } + ), ]; for (const error of cases) { expect((await prove(error)).message).toMatch(/^teardown_instance_not_visible/); @@ -498,7 +517,8 @@ describe('proveNodeInstanceOwnership: provider refusals', () => { step: 'sa_impersonation', message: 'Forbidden', statusCode: 403, - rawBody: '{"error":{"status":"PERMISSION_DENIED","details":[{"reason":"RATE_LIMIT_EXCEEDED"}]}}', + rawBody: + '{"error":{"status":"PERMISSION_DENIED","details":[{"reason":"RATE_LIMIT_EXCEEDED"}]}}', }), new GcpApiError({ step: 'sa_impersonation', @@ -534,4 +554,3 @@ describe('proveNodeInstanceOwnership: provider refusals', () => { } }); }); - diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index f97fdb3662..dfd7dbf312 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -298,15 +298,23 @@ Save and rotation verify the selected Compute zone before one D1 transaction upd #### One owner per workload identity pool -SAM signs an identity token for whatever pool a stored WIF credential names, so the pool's own trust must not be the only control. A WIF credential may name a pool (`gcpProjectNumber` + `wifPoolId`) only when no credential of a different owner names it (`assertGcpWifPoolOwnership()` in `apps/api/src/services/gcp-wif-pool-ownership.ts`). An owner is one SAM user, whose user-level and project-scoped credentials may share a pool, or the installation, which owns platform credentials. Deployment credentials count for the user who connected them. +SAM signs an identity token for whatever pool a stored WIF credential names, so the pool's own trust must not be the only control (`assertGcpWifPoolOwnership()` in `apps/api/src/services/gcp-wif-pool-ownership.ts`). An owner is one SAM user, whose user-level and project-scoped credentials may share a pool, or the installation, which owns platform credentials. A WIF credential may name a pool (`gcpProjectNumber` + `wifPoolId`) only when: -- **At save**, `POST /api/credentials`, the Google setup routes, project cloud credentials, composable credentials and admin platform credentials return `409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`. Guided setup checks the pool after reading the project number and before it changes anything in Google. -- **At token exchange**, the same check runs before SAM signs the identity token (`exchangeGcpWifAccessToken()` in `gcp-sts.ts`), so credentials saved before the check existed are refused too. The owner is the stored credential's owner, so a project member using another member's project credential still works. Refusals log `gcp_wif_pool.cross_owner_refused`. -- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the owner lookup, so a writer that skips the index, a rotation or a deletion cannot leave it stale. A normal check is one D1 round trip with no decryption. A row that cannot be decrypted or parsed is recorded with no pool and logged, and does not affect other credentials. If newly saved rows cannot be indexed within `gcpWif.poolIndexBudgetMs`, the check refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index. +- no credential of a different owner names it (deployment credentials count for the user who connected them), and +- the pool is unclaimed or claimed by the same owner. The first owner whose credential names a pool claims it (`gcp_wif_pool_claims`; the primary key decides concurrent claims). **A claim outlives the credential.** Deleting or re-pointing a credential in SAM leaves the trust an earlier setup granted in Google, so it does not free the pool for someone else. An operator releases a claim once that Google-side trust is gone (see the self-hosting guide). -The Google side is scoped as well. User-level guided setup creates a provider whose condition is `assertion.iss == '' && assertion.user_id == ''` and grants the service account only to `principalSet://.../workloadIdentityPools//attribute.sam_user/`. Deployment setup uses `assertion.project_id` and `principal://.../subject/project:` (`wifAttributeCondition()`, `wifServiceAccountMember()` in `gcp-wif-setup.ts`). Setups before this change used an issuer-only condition and a `pool/*` binding. Re-running setup rewrites the provider's condition and removes the `pool/*` member from the service account. +Where it is enforced: -Residual risk: whoever saves a pool first owns it in SAM. A user who knows another person's Google Cloud project number can save a credential naming that pool before its owner connects, which blocks the owner's setup (a denial of service, not impersonation). An administrator resolves it by deleting the squatting credential. +- **At save**: `POST /api/credentials`, the Google setup routes, project cloud credentials, composable credentials and admin platform credentials return `409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`. Guided setup checks the pool after reading the project number and before it changes anything in Google. +- **At token exchange**: the same check runs before SAM signs the identity token (`exchangeGcpWifAccessToken()` in `gcp-sts.ts`), so credentials saved before the check existed are refused too. The owner is the stored credential's owner, so a project member using another member's project credential still works. Refusals log `gcp_wif_pool.cross_owner_refused` at warn level. The exchange also refuses a project number with a leading zero, and a provider ID or service-account email that could alter the STS audience or the impersonation URL. +- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the read of the pool's holders, so a writer that skips the index, a rotation or a deletion cannot leave it stale. With nothing new to index a check is one D1 round trip with no decryption. A row that cannot be decrypted is recorded as unreadable, logged, and tried again after `gcpWif.poolIndexUnreadableRetryMinutes`; it does not affect other credentials. If newly saved rows cannot be indexed within `gcpWif.poolIndexBudgetMs`, the check refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index. + +The Google side is scoped as well. User-level guided setup creates a provider whose condition is `assertion.iss == '' && assertion.user_id == ''` and grants the service account only to `principalSet://.../workloadIdentityPools//attribute.sam_user/`. Deployment setup uses `assertion.project_id` and `principal://.../subject/project:` (`wifAttributeCondition()`, `wifServiceAccountMember()` in `gcp-wif-setup.ts`). For a user's own credential, user-level or project-scoped, SAM signs `user_id` as the credential owner's id (`gcpIdentityTokenUserId()`), so both match the user-scoped provider. Platform credentials sign `platform:` and need a pool their installation configured; guided setup does not create one. Setups before this change used an issuer-only condition and a `pool/*` binding. Re-running setup rewrites the provider's condition and removes the `pool/*` member from the service account, keeping other members and IAM conditions. + +Residual risks: + +- **First claim wins.** A user who knows another person's Google Cloud project number can save a credential naming that pool before its owner connects, which blocks the owner's setup (a denial of service, not impersonation). The `409` also tells the caller that another SAM owner uses that project. An operator resolves a squat by deleting the squatting credential and the claim. +- **Cached tokens.** The check runs when SAM mints a token, not on a token-cache hit, so a token minted before a conflict appeared stays usable until `GCP_TOKEN_CACHE_TTL_SECONDS` ends. ## Terminal Authentication diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index e2f32e8643..6f98361ee5 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -1104,8 +1104,9 @@ These control the live Google Cloud catalog described in [Google Cloud](/docs/gu | `gcpCatalog.apiIssueTtlMinutes` | 10080 | 60–43200 | How long a Google API problem Google reported stays shown on a credential; a successful check clears it. | | `gcpCatalog.bootDiskGbPerVcpu` | 20 | 1–256 | GB of boot disk a new Google Cloud node gets per vCPU, used by the catalog, prices and new nodes from the next catalog refresh; running nodes keep their disk. | | `gcpCatalog.bootDiskMinGb` | 50 | 10–4096 | Smallest boot disk, in GB, a new Google Cloud node gets whatever its vCPU count; same refresh rule. | -| `gcpWif.poolIndexPageSize` | 100 | 10–100 | Stored cloud credentials decrypted per step when indexing which workload identity pool each one names (only new or re-saved credentials are indexed). | +| `gcpWif.poolIndexPageSize` | 25 | 5–50 | Stored cloud credentials decrypted per step when indexing which workload identity pool each one names (only new or re-saved credentials are indexed). | | `gcpWif.poolIndexBudgetMs` | 10000 | 1000–25000 | Most time one token exchange or credential save may spend indexing new credentials before it refuses and asks to retry, rather than trust a partial index. | +| `gcpWif.poolIndexUnreadableRetryMinutes` | 60 | 1–1440 | Wait before SAM tries again to read a stored cloud credential it could not decrypt while indexing workload identity pools. | ### Infomaniak boot volume diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index 1bb5f5b8b1..6b02401059 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -454,9 +454,16 @@ The flow requests the Google `cloud-platform` scope. Runtime values saved by a s Several SAM installations can connect the same Google Cloud project. A workload identity provider trusts exactly one issuer URL, so each installation creates its own provider, named from its base domain (`installationWifProviderId()` in `apps/api/src/services/gcp-wif-setup.ts`; for example `sam-sammy2-party-` for `sammy2.party`). The installations share the pool (`sam-pool`, or `sam-deploy-pool` for deployments) and the service account, so every installation connected to a project can act as that project's service account; use separate Google Cloud projects when installations must not share cloud access. `GCP_WIF_PROVIDER_ID` and `GCP_DEPLOY_WIF_PROVIDER_ID` override the derived name. SAM still refuses to update an existing provider whose issuer differs from its own (`updateOidcProvider()`). Existing connections keep the pool and provider recorded when they were created; reconnecting creates the installation's own provider. -Each user-level connection is scoped to the SAM user who made it. The provider's condition requires `assertion.user_id == ''`, and the service account is granted to `principalSet://iam.googleapis.com/projects//locations/global/workloadIdentityPools//attribute.sam_user/` (`wifAttributeCondition()` and `wifServiceAccountMember()` in `apps/api/src/services/gcp-wif-setup.ts`). Connections made before this scoping used an issuer-only condition and a `pool/*` binding, which let any user of the installation who named the pool act as its service account. **Re-run Google setup** on each such connection: it rewrites the provider's condition and removes the `pool/*` member. If another installation shared that service account through `pool/*`, re-run that installation's setup too, so it gets its own scoped binding. +Each user-level connection is scoped to the SAM user who made it. The provider's condition requires `assertion.user_id == ''`, and the service account is granted to `principalSet://iam.googleapis.com/projects//locations/global/workloadIdentityPools//attribute.sam_user/` (`wifAttributeCondition()` and `wifServiceAccountMember()` in `apps/api/src/services/gcp-wif-setup.ts`). Connections made before this scoping used an issuer-only condition and a `pool/*` binding, which let any user of the installation who named the pool act as its service account. **Re-run Google setup** on each such connection: it rewrites the provider's condition and removes the `pool/*` member. If another installation shared that service account through `pool/*`, re-run that installation's setup too, so it gets its own scoped binding. A platform GCP workload identity credential needs a pool the installation configures for it; the guided setup only creates user-scoped pools. -Within one installation a pool has one owner: one user, or the installation for platform credentials. SAM refuses to save, or to exchange tokens for, a credential naming a pool that a different owner's credential already names (`409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`; see [Security](/docs/architecture/security/#one-owner-per-workload-identity-pool)). Give every user and the platform credential its own Google Cloud project or pool. +Within one installation a pool has one owner: one user, or the installation for platform credentials. SAM refuses to save, or to exchange tokens for, a credential naming a pool that another owner claimed or that a different owner's credential names (`409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`; see [Security](/docs/architecture/security/#one-owner-per-workload-identity-pool)). Give every user and the platform credential its own Google Cloud project or pool. + +A claim stays after its credential is deleted, because the Google-side trust may stay too. To hand a pool to a different owner (for example after a Google Cloud project changes hands), first remove the old owner's trust in Google: delete the old workload identity provider, or remove its members from the service account's `roles/iam.workloadIdentityUser` binding. Then release the claim (`/`, lowercase pool ID): + +```bash +npx wrangler d1 execute --remote \ + --command "DELETE FROM gcp_wif_pool_claims WHERE pool_key = '123456789012/sam-pool'" +``` If STS reports an issuer mismatch, another installation's setup replaced the shared provider this connection was recorded against (setups before per-installation providers all used `sam-oidc`). Reconnect the affected installation through its Connect GCP flow, which creates its own provider. Do not switch a shared provider back and forth or accept both issuers. A failed token exchange does not prove a failed node has no cloud server. After independently checking the provider account and in-flight allocation, the existing owner-confirmed removal action can remove a failed node on user-owned cloud capacity. Its audit reason stays `owner_attested_manual_deletion`, separate from strict provider-confirmed termination. Fresh terminal provisioning failures positively proven to precede the provider create request retain an exact incarnation and placement absence proof, allowing normal teardown without minting another token. Intermediate durable retries keep their allocation state. diff --git a/packages/worker-core/src/schema.ts b/packages/worker-core/src/schema.ts index 06bddf94c8..70f58e7bd1 100644 --- a/packages/worker-core/src/schema.ts +++ b/packages/worker-core/src/schema.ts @@ -341,6 +341,10 @@ export const credentials = sqliteTable( activeCredential: index('idx_credentials_active') .on(table.userId, table.projectId, table.agentType, table.isActive) .where(sql`credential_type = 'agent-api-key' AND is_active = 1`), + // GCP workload identity pool ownership probe (migration 0262). + gcpCloudCredential: index('idx_credentials_gcp_cloud') + .on(table.id) + .where(sql`provider = 'gcp' AND credential_type = 'cloud-provider'`), }) ); @@ -1128,11 +1132,13 @@ export const projectDeploymentCredentials = sqliteTable( ); // ============================================================================= -// GCP Workload Identity Pool Index (migration 0262) -// Which pool each stored cloud credential names, filled by the Worker on every ownership check -// (`apps/api/src/services/gcp-wif-pool-ownership.ts`). No secret material: `iv` identifies the -// indexed ciphertext generation, `pool_key` is `/` or NULL when the row -// names no workload identity pool. +// GCP Workload Identity Pool Index and Claims (migration 0262) +// `gcp_wif_pool_index`: which pool each stored cloud credential names, filled by the Worker on +// every ownership check (`apps/api/src/services/gcp-wif-pool-ownership.ts`). No secret material: +// `iv` identifies the indexed ciphertext generation, `pool_key` is `/` or +// NULL when the row names no workload identity pool. `gcp_wif_pool_claims`: the first owner of +// each pool, never released by credential deletion (an operator deletes the row to release it). +// The CHECK constraints live in the migration only. // ============================================================================= export const gcpWifPoolIndex = sqliteTable( 'gcp_wif_pool_index', @@ -1143,6 +1149,7 @@ export const gcpWifPoolIndex = sqliteTable( ownerKind: text('owner_kind').notNull(), // 'user' | 'platform' ownerUserId: text('owner_user_id'), poolKey: text('pool_key'), + unreadable: integer('unreadable').notNull().default(0), indexedAt: text('indexed_at').notNull(), }, (table) => ({ @@ -1153,6 +1160,13 @@ export const gcpWifPoolIndex = sqliteTable( }) ); +export const gcpWifPoolClaims = sqliteTable('gcp_wif_pool_claims', { + poolKey: text('pool_key').primaryKey(), + ownerKind: text('owner_kind').notNull(), // 'user' | 'platform' + ownerUserId: text('owner_user_id'), + claimedAt: text('claimed_at').notNull(), +}); + // ============================================================================= // Missions (Phase 2: Orchestration Primitives) // ============================================================================= @@ -5900,6 +5914,10 @@ export const ccCredentials = sqliteTable( (table) => ({ ownerIdx: index('idx_cc_credentials_owner').on(table.ownerId), ownerKindIdx: index('idx_cc_credentials_owner_kind').on(table.ownerId, table.kind), + // GCP workload identity pool ownership probe (migration 0262). + cloudCredential: index('idx_cc_credentials_cloud') + .on(table.id) + .where(sql`kind = 'cloud-provider'`), }) ); diff --git a/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md b/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md index d763851c70..b3c63a2912 100644 --- a/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md +++ b/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md @@ -27,18 +27,30 @@ User-level guided GCP setup created a pool provider whose attribute condition ch - [x] User-scoped provider condition and `attribute.sam_user/` binding; update path rewrites the condition; re-run removes `pool/*` - [x] Real-SQL attack/owner-control tests; each guard deleted once (results in PR) - [x] Unit tests for condition/binding strings and the update path -- [ ] Docs: security.md, self-hosting.mdx, admin-settings.md, google-cloud.md +- [x] Docs: security.md, self-hosting.mdx, admin-settings.md, google-cloud.md +- [x] Production audit (counts only): one owner for every GCP credential, no conflicts +- [x] Review round 1 fixes: sticky claims (`gcp_wif_pool_claims`, first claim wins atomically, operator release), signed `user_id` = credential owner for user/project credentials, partial indexes + query-plan test, lazy settings read, fail closed on unparseable probe rows, unreadable-row retry window, leading-zero / provider-id / SA-email validation, warn-level refusal log, IAM conditions and policy version preserved +- [x] Vertical tests through the real resolver (legacy and exact paths) for project-member owner plumbing and the signed claim +- [x] Fixtures updated: capacity-pool suite applies migration 0262; teardown test uses a pool of the other user's own; orphan sweep asserts the platform owner check - [ ] Full quality suite -- [ ] Reviews: security-auditor, task-completion-validator, cloudflare-specialist +- [ ] Reviews: security-auditor (re-verify), task-completion-validator, cloudflare-specialist - [ ] Staging: live save-time and exchange-time refusals +## Review round 1 (2026-11-19) + +- security-auditor H1: ownership disappeared with the credential row while Google's `pool/*` binding survived; a disconnect re-opened the hole. Fixed with sticky claims. +- security-auditor M2: save race. Fixed: the claim insert is atomic on the pool key and re-read. +- validator HIGH / security M4: project-attached credentials signed `user_id = project::`, which the user-scoped provider rejects. Fixed: `gcpIdentityTokenUserId()` signs the credential owner's id. +- cloudflare 1/3/6: full scans, settings read on the hot path, fail-open on unparseable rows. Fixed. +- security M3 (409 reveals another owner uses a project number), L1 (parser divergence; not exploitable because the exchange check keys on the credential actually exchanged), L3 (cached tokens): documented as residual. + ## Acceptance criteria - [ ] User B cannot save, or exchange with, a credential naming user A's pool (409 / refusal before signing) - [ ] A user credential cannot name the platform credential's pool, and vice versa - [ ] The owner, the same user's project-scoped credential, and a project member using it still work - [ ] New guided user-level setups use `assertion.user_id == ''` and `attribute.sam_user/`; re-runs fix existing providers and bindings -- [ ] Production has no cross-owner sharing (verified: counts above) +- [x] Production has no cross-owner sharing (verified: counts above) - [ ] Refusals shown live on staging ## References From d7a652908e8dc5b3b08499f8cdcb77522b733cf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 09:04:25 +0000 Subject: [PATCH 03/13] fix(security): namespace fallback project_id; fail closed on WIF index limits Review round 2 on the pool-ownership guard: - When a token acts for no SAM project, sign the credential's own GCP project as gcp-project:, so a typed gcpProjectId can never pass for another user's SAM project at a project-scoped provider. - Cap D1 queries per check (gcpWif.poolIndexMaxQueriesPerCheck, exact statement count) and map indexing faults and malformed batch results to the designed 503; progress stays durable. - Docs: corrected residual risk (pools SAM never recorded), release steps, new setting. Backlog task for probing open providers. Co-Authored-By: Claude Opus 5.5 --- .../admin-settings-gcp-catalog-definitions.ts | 19 ++- apps/api/src/services/gcp-sts.ts | 20 +++- .../src/services/gcp-wif-pool-ownership.ts | 113 ++++++++++++++---- .../provider-orphan-platform-gcp.test.ts | 7 +- .../unit/services/gcp-service-account.test.ts | 3 +- .../services/gcp-wif-pool-ownership.test.ts | 101 +++++++++++++++- .../docs/docs/architecture/security.md | 7 +- .../docs/docs/guides/admin-settings.md | 1 + .../content/docs/docs/guides/self-hosting.mdx | 6 +- ...p-wif-probe-open-providers-before-claim.md | 29 +++++ 10 files changed, 268 insertions(+), 38 deletions(-) create mode 100644 tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md diff --git a/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts index 20f4361a7a..d1172afe3e 100644 --- a/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts +++ b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts @@ -11,6 +11,9 @@ import { type AdminSettingDefinition, integerDefinition } from './admin-setting- /** Defaults for the workload identity pool index, also used before the settings are read. */ export const DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE = 25; export const DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES = 60; +export const DEFAULT_GCP_WIF_POOL_INDEX_BUDGET_MS = 10_000; +/** Under the 1,000 D1 queries a paid Workers invocation allows, leaving room for the request. */ +export const DEFAULT_GCP_WIF_POOL_INDEX_MAX_QUERIES_PER_CHECK = 500; export type GcpCatalogSettingName = | 'gcpCatalog.machineTypes' @@ -25,7 +28,8 @@ export type GcpCatalogSettingName = | 'gcpCatalog.bootDiskMinGb' | 'gcpWif.poolIndexPageSize' | 'gcpWif.poolIndexBudgetMs' - | 'gcpWif.poolIndexUnreadableRetryMinutes'; + | 'gcpWif.poolIndexUnreadableRetryMinutes' + | 'gcpWif.poolIndexMaxQueriesPerCheck'; /** * General-purpose shapes SAM offers from Google Cloud by default: shared-core e2-medium, and the @@ -132,8 +136,8 @@ export const GCP_CATALOG_SETTINGS: readonly AdminSettingDefinition[] = [ ), // Workload identity pool ownership (`gcp-wif-pool-ownership.ts`). Indexing runs only for // credentials added or re-encrypted since the last check; a check that cannot finish inside the - // budget refuses rather than trusting a partial index. A page is one D1 batch of up to two - // statements per row, so the maximum stays well inside D1's per-invocation query limits. + // budget refuses rather than trusting a partial index. A page costs 2 + 2 x page size D1 + // statements; `gcpWif.poolIndexMaxQueriesPerCheck` caps their sum per check. integerDefinition( 'gcpWif.poolIndexPageSize', DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE, @@ -143,7 +147,7 @@ export const GCP_CATALOG_SETTINGS: readonly AdminSettingDefinition[] = [ ), integerDefinition( 'gcpWif.poolIndexBudgetMs', - 10_000, + DEFAULT_GCP_WIF_POOL_INDEX_BUDGET_MS, 'Operations', 'Most milliseconds one Google Cloud token exchange or credential save may spend indexing newly saved credentials before it refuses and asks to retry.', { min: 1_000, max: 25_000 } @@ -155,4 +159,11 @@ export const GCP_CATALOG_SETTINGS: readonly AdminSettingDefinition[] = [ 'Minutes before SAM tries again to read a stored cloud credential it could not decrypt while indexing workload identity pools.', { min: 1, max: 24 * 60 } ), + integerDefinition( + 'gcpWif.poolIndexMaxQueriesPerCheck', + DEFAULT_GCP_WIF_POOL_INDEX_MAX_QUERIES_PER_CHECK, + 'Operations', + 'Most D1 queries one token exchange or credential save may spend indexing new credentials. Keep it under your Workers plan’s per-request D1 query limit (1,000 on paid; on the free plan use 40 with a page size of 5).', + { min: 12, max: 900 } + ), ]; diff --git a/apps/api/src/services/gcp-sts.ts b/apps/api/src/services/gcp-sts.ts index 567c21f338..8f677b28d9 100644 --- a/apps/api/src/services/gcp-sts.ts +++ b/apps/api/src/services/gcp-sts.ts @@ -53,6 +53,20 @@ export function gcpIdentityTokenUserId(requester: GcpTokenRequester): string { return requester.poolOwner.kind === 'user' ? requester.poolOwner.userId : requester.cacheUserId; } +/** + * The `project_id` claim (and `sub = project:`) SAM signs. Callers pass a SAM project the + * caller is authorized for, or, when the token acts for no SAM project, the credential's own + * `gcpProjectId`. That second value is whatever the credential's owner typed, so it is + * namespaced: signed bare it could equal another user's SAM project ID, which a deployment + * provider trusts (`assertion.project_id == ''`, `subject/project:`). + */ +export function gcpIdentityTokenProjectId( + projectId: string, + credential: GcpOidcCredential +): string { + return projectId === credential.gcpProjectId ? `gcp-project:${projectId}` : projectId; +} + interface StsTokenResponse { access_token: string; token_type: string; @@ -223,7 +237,11 @@ async function exchangeGcpWifAccessToken( await assertGcpWifPoolOwnership(env, credential, requester.poolOwner, 'token_exchange'); throwIfProviderRequestAborted(context); const identityToken = await signIdentityToken( - { userId: gcpIdentityTokenUserId(requester), projectId, audience: jwtAudience }, + { + userId: gcpIdentityTokenUserId(requester), + projectId: gcpIdentityTokenProjectId(projectId, credential), + audience: jwtAudience, + }, env ); diff --git a/apps/api/src/services/gcp-wif-pool-ownership.ts b/apps/api/src/services/gcp-wif-pool-ownership.ts index d598560e7b..ca1125cd21 100644 --- a/apps/api/src/services/gcp-wif-pool-ownership.ts +++ b/apps/api/src/services/gcp-wif-pool-ownership.ts @@ -20,6 +20,10 @@ * D1 batch (one transaction) as the read of the pool's holders. A writer that skips the index, a * deleted credential, or a rotation therefore cannot leave the check reading stale data. * + * The holders read may be served by a read replica at or after the request's bookmark; the + * claim insert and its re-read are one write batch on the primary, which is what decides who + * holds an unclaimed pool. + * * I/O per check when nothing changed: one D1 round trip, no decryption, no admin-settings read. * A first-time claim adds one round trip for that pool. A new or re-encrypted credential adds * one page of decrypts plus two round trips per `gcpWif.poolIndexPageSize` rows, within @@ -215,12 +219,12 @@ function toPoolHolderRow(row: Record): PoolHolderRow | null { * as absent could hide an unindexed credential or a foreign holder. */ function parseAll( - results: Record[] | undefined, + results: Record[], parse: (row: Record) => T | null, context: string ): T[] { const parsed: T[] = []; - for (const row of results ?? []) { + for (const row of results) { const value = parse(row); if (!value) { log.error('gcp_wif_pool_index.row_unparseable', { context, action: 'refused' }); @@ -248,8 +252,11 @@ function retryCutoff(retryMinutes: number): string { return new Date(Date.now() - retryMinutes * 60_000).toISOString(); } -/** Decrypt and index one page; claim each named pool for the row's owner if it is unclaimed. */ -async function indexRows(env: Env, rows: UnindexedRow[]): Promise { +/** + * Decrypt and index one page; claim each named pool for the row's owner if it is unclaimed. + * Returns the number of D1 statements issued. + */ +async function indexRows(env: Env, rows: UnindexedRow[]): Promise { const key = getCredentialEncryptionKey(env); const now = new Date().toISOString(); const statements: D1PreparedStatement[] = []; @@ -290,20 +297,26 @@ async function indexRows(env: Env, rows: UnindexedRow[]): Promise { } } if (statements.length > 0) await env.DATABASE.batch(statements); + return statements.length; } -async function readIndexSettings( - env: Env -): Promise<{ pageSize: number; budgetMs: number; retryMinutes: number }> { - const [pageSize, budgetMs, retryMinutes] = await Promise.all([ +async function readIndexSettings(env: Env): Promise<{ + pageSize: number; + budgetMs: number; + retryMinutes: number; + maxQueries: number; +}> { + const [pageSize, budgetMs, retryMinutes, maxQueries] = await Promise.all([ resolveAdminSetting(env, 'gcpWif.poolIndexPageSize'), resolveAdminSetting(env, 'gcpWif.poolIndexBudgetMs'), resolveAdminSetting(env, 'gcpWif.poolIndexUnreadableRetryMinutes'), + resolveAdminSetting(env, 'gcpWif.poolIndexMaxQueriesPerCheck'), ]); return { pageSize: Number(pageSize), budgetMs: Number(budgetMs), retryMinutes: Number(retryMinutes), + maxQueries: Number(maxQueries), }; } @@ -312,6 +325,32 @@ async function readIndexSettings( * credentials naming it, and deployment credentials naming it. Throws * GcpWifPoolIndexUnavailableError when unindexed rows remain after the time budget. */ +/** Both statements of a two-statement batch returned a row array, or the check cannot be trusted. */ +function batchRows( + results: D1Result>[] | undefined, + context: string +): [Record[], Record[]] { + const first = Array.isArray(results) && results.length === 2 ? results[0]?.results : undefined; + const second = Array.isArray(results) && results.length === 2 ? results[1]?.results : undefined; + if (!Array.isArray(first) || !Array.isArray(second)) { + log.error('gcp_wif_pool_index.batch_malformed', { context, action: 'refused' }); + throw new GcpWifPoolIndexUnavailableError(); + } + return [first, second]; +} + +/** D1 statements one page of indexing can issue: the probe batch plus up to two per row. */ +function queriesPerPage(pageSize: number): number { + return 2 + 2 * pageSize; +} + +/** + * Bring the index up to date, then return everything that holds `pool`: its claim, live + * credentials naming it, and deployment credentials naming it. Throws + * GcpWifPoolIndexUnavailableError when unindexed rows remain after the time budget or the query + * budget (`gcpWif.poolIndexMaxQueriesPerCheck`, kept under D1's per-invocation query limit), or + * when D1 fails while indexing. Progress is durable, so the next check continues. + */ async function listPoolHolders(env: Env, pool: GcpWifPoolIdentity): Promise { const holders = env.DATABASE.prepare(POOL_HOLDERS_SQL).bind( pool.key, @@ -322,19 +361,24 @@ async function listPoolHolders(env: Env, pool: GcpWifPoolIdentity): Promise> | null = null; let deadline = Infinity; + let queries = 0; let indexedAny = false; for (;;) { const pageSize = settings?.pageSize ?? DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE; const cutoff = retryCutoff( settings?.retryMinutes ?? DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES ); - const [unindexedResult, holdersResult] = await env.DATABASE.batch>([ - env.DATABASE.prepare(UNINDEXED_ROWS_SQL).bind(cutoff, cutoff, cutoff, pageSize), - holders, - ]); - const unindexed = parseAll(unindexedResult?.results, toUnindexedRow, 'unindexed'); + const [unindexedRows, holderRows] = batchRows( + await env.DATABASE.batch>([ + env.DATABASE.prepare(UNINDEXED_ROWS_SQL).bind(cutoff, cutoff, cutoff, pageSize), + holders, + ]), + 'probe' + ); + queries += 2; + const unindexed = parseAll(unindexedRows, toUnindexedRow, 'unindexed'); if (unindexed.length === 0) { - const found = parseAll(holdersResult?.results, toPoolHolderRow, 'holders'); + const found = parseAll(holderRows, toPoolHolderRow, 'holders'); if (indexedAny) { log.info('gcp_wif_pool_index.reconciled', { poolKey: pool.key, holders: found.length }); } @@ -343,16 +387,30 @@ async function listPoolHolders(env: Env, pool: GcpWifPoolIdentity): Promise= deadline) { + } else if ( + Date.now() >= deadline || + queries + queriesPerPage(settings.pageSize) > settings.maxQueries + ) { log.error('gcp_wif_pool_index.budget_exhausted', { poolKey: pool.key, budgetMs: settings.budgetMs, + queries, + maxQueries: settings.maxQueries, remainingPage: unindexed.length, action: 'refused', }); throw new GcpWifPoolIndexUnavailableError(); } - await indexRows(env, unindexed); + try { + queries += await indexRows(env, unindexed); + } catch (err) { + log.error('gcp_wif_pool_index.index_write_failed', { + poolKey: pool.key, + error: err instanceof Error ? err.message : String(err), + action: 'refused', + }); + throw new GcpWifPoolIndexUnavailableError(); + } indexedAny = true; } } @@ -402,16 +460,19 @@ export async function assertGcpWifPoolOwnership( // Unclaimed: claim it. The primary key decides a concurrent claim, so re-read the winner. const [ownerKind, ownerUserId] = ownerColumns(owner); - const [, claimResult] = await env.DATABASE.batch>([ - env.DATABASE.prepare(CLAIM_POOL_SQL).bind( - identity.key, - ownerKind, - ownerUserId, - new Date().toISOString() - ), - env.DATABASE.prepare(READ_CLAIM_SQL).bind(identity.key), - ]); - const claim = parseAll(claimResult?.results, toPoolHolderRow, 'claim'); + const [, claimRows] = batchRows( + await env.DATABASE.batch>([ + env.DATABASE.prepare(CLAIM_POOL_SQL).bind( + identity.key, + ownerKind, + ownerUserId, + new Date().toISOString() + ), + env.DATABASE.prepare(READ_CLAIM_SQL).bind(identity.key), + ]), + 'claim' + ); + const claim = parseAll(claimRows, toPoolHolderRow, 'claim'); const [winner] = claim; if (!winner || claim.length !== 1) throw new GcpWifPoolIndexUnavailableError(); if (!heldBy(winner, owner)) refuse(context, identity, owner, claim); diff --git a/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts b/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts index 164b8af17a..cc11b28ed6 100644 --- a/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts +++ b/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts @@ -183,7 +183,12 @@ describe('platform GCP orphan sweep configuration and authentication', () => { const claims = JSON.parse( atob(body.subjectToken.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')) ); - expect(claims).toMatchObject({ user_id: 'platform:admin-owner', project_id: 'test-project' }); + // No SAM project: the credential's own GCP project is signed namespaced, never as a SAM project id. + expect(claims).toMatchObject({ + user_id: 'platform:admin-owner', + project_id: 'gcp-project:test-project', + sub: 'project:gcp-project:test-project', + }); const deletes = fetchMock.mock.calls.filter(([, init]) => init?.method === 'DELETE'); expect(deletes.map(([url]) => String(url))).toEqual([ 'https://compute.googleapis.com/compute/v1/projects/test-project/zones/us-central1-a/instances/vm-123', diff --git a/apps/api/tests/unit/services/gcp-service-account.test.ts b/apps/api/tests/unit/services/gcp-service-account.test.ts index d191a44662..19881fec7a 100644 --- a/apps/api/tests/unit/services/gcp-service-account.test.ts +++ b/apps/api/tests/unit/services/gcp-service-account.test.ts @@ -29,7 +29,8 @@ vi.mock('../../../src/services/jwt', () => ({ })); // Pool ownership has its own real-SQL suite (gcp-wif-pool-ownership.test.ts); here it is a // pass-through so these tests stay about cancellation and caching. -vi.mock('../../../src/services/gcp-wif-pool-ownership', () => ({ +vi.mock('../../../src/services/gcp-wif-pool-ownership', async (importOriginal) => ({ + ...(await importOriginal()), assertGcpWifPoolOwnership: vi.fn().mockResolvedValue(undefined), })); diff --git a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts index 2f0a9c9a62..7f3e0a2e9f 100644 --- a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -484,7 +484,7 @@ describe('token exchange refuses a pool another owner uses (rows that predate th }); it('indexes more rows than one page in a single check, then reads the index without decrypting', async () => { - // 230 non-GCP rows (more than two pages at the default page size of 100) ahead of A's row. + // 230 non-GCP rows (more than nine pages at the default page size of 25) ahead of A's row. for (let i = 0; i < 230; i++) { await storeCcRow(`cc-other-${String(i).padStart(3, '0')}`, 'user-b', `token-${i}`); } @@ -780,3 +780,102 @@ describe('the credential owner reaches the exchange through the real resolver', ); }); }); + +describe('the signed project_id cannot be chosen by the credential owner', () => { + it('a user-level credential naming a SAM project id as its GCP project signs it namespaced', async () => { + // B's own pool; B sets gcpProjectId to A's SAM project id, hoping a deployment provider + // that trusts `project_id == 'proj-a'` accepts the token. + const credential = wif(POOL_B, { gcpProjectId: 'proj-a' }); + await expect(exchange(user('user-b'), credential)).resolves.toBe('sa-token'); + expect(signIdentityToken).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-b', projectId: 'gcp-project:proj-a' }), + env + ); + }); + + it('control: a token for a SAM project the caller acts for keeps that project id', async () => { + await expect( + exchange( + { cacheUserId: 'project:proj-a:user-a', poolOwner: { kind: 'user', userId: 'user-a' } }, + wif(POOL_A), + 'proj-a' + ) + ).resolves.toBe('sa-token'); + expect(signIdentityToken).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-a', projectId: 'proj-a' }), + env + ); + }); +}); + +describe('the check fails closed on its own limits', () => { + afterEach(async () => { + const { __resetAdminSettingsCacheForTest } = + await import('../../../src/services/admin-settings-resolution'); + __resetAdminSettingsCacheForTest(); + }); + + it('refuses with 503 once indexing would pass the per-check D1 query budget, then resumes', async () => { + const { __resetAdminSettingsCacheForTest } = + await import('../../../src/services/admin-settings-resolution'); + __resetAdminSettingsCacheForTest(); + // Page size 5 costs at most 2 + 2 x 5 = 12 statements; a budget of 30 allows two pages. + for (const [key, value] of [ + ['gcpWif.poolIndexPageSize', '5'], + ['gcpWif.poolIndexMaxQueriesPerCheck', '30'], + ]) { + sqlite + .prepare('INSERT INTO platform_settings (key, value, updated_at) VALUES (?, ?, ?)') + .run(key, value, NOW); + } + for (let i = 0; i < 40; i++) { + await storeCcRow(`cc-other-${String(i).padStart(2, '0')}`, 'user-b', `token-${i}`); + } + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + vi.spyOn(console, 'error').mockImplementation(() => {}); + + await expect(exchange(user('user-a'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolIndexUnavailableError + ); + expect(signIdentityToken).not.toHaveBeenCalled(); + const indexed = () => + (sqlite.prepare('SELECT count(*) AS n FROM gcp_wif_pool_index').get() as { n: number }).n; + const afterFirst = indexed(); + expect(afterFirst).toBeGreaterThan(0); + expect(afterFirst).toBeLessThan(41); + + // Progress is durable: later checks continue where the first stopped, then succeed. + let attempts = 1; + for (;;) { + attempts += 1; + try { + await exchange(user('user-a'), wif(POOL_A)); + break; + } catch (err) { + expect(err).toBeInstanceOf(GcpWifPoolIndexUnavailableError); + expect(attempts).toBeLessThan(10); + } + } + expect(indexed()).toBe(41); + }); + + it.each([ + ['a short batch result', () => []], + ['statements without row arrays', () => [{}, {}]], + ])('refuses on %s instead of reading it as "no holders"', async (_name, shape) => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + const realBatch = env.DATABASE.batch.bind(env.DATABASE); + vi.spyOn(env.DATABASE, 'batch').mockImplementationOnce(async () => shape() as never); + vi.spyOn(console, 'error').mockImplementation(() => {}); + + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolIndexUnavailableError + ); + expect(signIdentityToken).not.toHaveBeenCalled(); + // Liveness control: the real batch still refuses B as another owner. + vi.mocked(env.DATABASE.batch).mockImplementation(realBatch); + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolOwnedByAnotherOwnerError + ); + }); +}); diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index dfd7dbf312..e3e9e5ae83 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -307,13 +307,14 @@ Where it is enforced: - **At save**: `POST /api/credentials`, the Google setup routes, project cloud credentials, composable credentials and admin platform credentials return `409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`. Guided setup checks the pool after reading the project number and before it changes anything in Google. - **At token exchange**: the same check runs before SAM signs the identity token (`exchangeGcpWifAccessToken()` in `gcp-sts.ts`), so credentials saved before the check existed are refused too. The owner is the stored credential's owner, so a project member using another member's project credential still works. Refusals log `gcp_wif_pool.cross_owner_refused` at warn level. The exchange also refuses a project number with a leading zero, and a provider ID or service-account email that could alter the STS audience or the impersonation URL. -- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the read of the pool's holders, so a writer that skips the index, a rotation or a deletion cannot leave it stale. With nothing new to index a check is one D1 round trip with no decryption. A row that cannot be decrypted is recorded as unreadable, logged, and tried again after `gcpWif.poolIndexUnreadableRetryMinutes`; it does not affect other credentials. If newly saved rows cannot be indexed within `gcpWif.poolIndexBudgetMs`, the check refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index. +- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the read of the pool's holders, so a writer that skips the index, a rotation or a deletion cannot leave it stale. With nothing new to index a check is one D1 round trip with no decryption. A row that cannot be decrypted is recorded as unreadable, logged, and tried again after `gcpWif.poolIndexUnreadableRetryMinutes`; it does not affect other credentials. If newly saved rows cannot be indexed within `gcpWif.poolIndexBudgetMs` and `gcpWif.poolIndexMaxQueriesPerCheck`, or D1 fails or returns an unexpected result while the check runs, it refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index; progress is kept, so the next check continues. -The Google side is scoped as well. User-level guided setup creates a provider whose condition is `assertion.iss == '' && assertion.user_id == ''` and grants the service account only to `principalSet://.../workloadIdentityPools//attribute.sam_user/`. Deployment setup uses `assertion.project_id` and `principal://.../subject/project:` (`wifAttributeCondition()`, `wifServiceAccountMember()` in `gcp-wif-setup.ts`). For a user's own credential, user-level or project-scoped, SAM signs `user_id` as the credential owner's id (`gcpIdentityTokenUserId()`), so both match the user-scoped provider. Platform credentials sign `platform:` and need a pool their installation configured; guided setup does not create one. Setups before this change used an issuer-only condition and a `pool/*` binding. Re-running setup rewrites the provider's condition and removes the `pool/*` member from the service account, keeping other members and IAM conditions. +The Google side is scoped as well. User-level guided setup creates a provider whose condition is `assertion.iss == '' && assertion.user_id == ''` and grants the service account only to `principalSet://.../workloadIdentityPools//attribute.sam_user/`. Deployment setup uses `assertion.project_id` and `principal://.../subject/project:` (`wifAttributeCondition()`, `wifServiceAccountMember()` in `gcp-wif-setup.ts`). For a user's own credential, user-level or project-scoped, SAM signs `user_id` as the credential owner's id (`gcpIdentityTokenUserId()`), so both match the user-scoped provider. `project_id` (and `sub = project:`) is a SAM project the caller acts for; when the token acts for no SAM project, SAM signs the credential's own Google project as `gcp-project:` (`gcpIdentityTokenProjectId()`), so a value the credential's owner typed can never pass for another user's SAM project at a deployment provider. Platform credentials sign `platform:` and need a pool their installation configured; guided setup does not create one. Setups before this change used an issuer-only condition and a `pool/*` binding. Re-running setup rewrites the provider's condition and removes the `pool/*` member from the service account, keeping other members and IAM conditions. Residual risks: -- **First claim wins.** A user who knows another person's Google Cloud project number can save a credential naming that pool before its owner connects, which blocks the owner's setup (a denial of service, not impersonation). The `409` also tells the caller that another SAM owner uses that project. An operator resolves a squat by deleting the squatting credential and the claim. +- **Pools SAM has never recorded.** The Worker check protects every pool a stored credential has ever named, including after a disconnect. It cannot protect a pool SAM has no record of whose Google trust is still issuer-only with `pool/*` (a guided setup from before this change whose credential was removed before this release, or a platform pool created in Google before the platform credential is saved). Whoever names such a pool first claims it, and that is impersonation, not only denial of service. Re-run setup for old connections, and save a platform credential as soon as its pool exists. Probing Google for issuer-only trust before a first claim is tracked in `tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md`. +- **First claim wins.** A user who knows another person's Google Cloud project number can save a credential naming that pool before its owner connects, which blocks the owner's setup or the platform credential. The `409` also tells the caller that another SAM owner uses that project. An operator resolves a squat by deleting the squatting credential and then the claim. - **Cached tokens.** The check runs when SAM mints a token, not on a token-cache hit, so a token minted before a conflict appeared stays usable until `GCP_TOKEN_CACHE_TTL_SECONDS` ends. ## Terminal Authentication diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index 6f98361ee5..d9fc7120b2 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -1107,6 +1107,7 @@ These control the live Google Cloud catalog described in [Google Cloud](/docs/gu | `gcpWif.poolIndexPageSize` | 25 | 5–50 | Stored cloud credentials decrypted per step when indexing which workload identity pool each one names (only new or re-saved credentials are indexed). | | `gcpWif.poolIndexBudgetMs` | 10000 | 1000–25000 | Most time one token exchange or credential save may spend indexing new credentials before it refuses and asks to retry, rather than trust a partial index. | | `gcpWif.poolIndexUnreadableRetryMinutes` | 60 | 1–1440 | Wait before SAM tries again to read a stored cloud credential it could not decrypt while indexing workload identity pools. | +| `gcpWif.poolIndexMaxQueriesPerCheck` | 500 | 12–900 | Most D1 queries one check may spend indexing. Keep it under your Workers plan's per-request D1 query limit; on the free plan use 40 with a page size of 5. | ### Infomaniak boot volume diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index 6b02401059..08143515a6 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -458,7 +458,11 @@ Each user-level connection is scoped to the SAM user who made it. The provider's Within one installation a pool has one owner: one user, or the installation for platform credentials. SAM refuses to save, or to exchange tokens for, a credential naming a pool that another owner claimed or that a different owner's credential names (`409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`; see [Security](/docs/architecture/security/#one-owner-per-workload-identity-pool)). Give every user and the platform credential its own Google Cloud project or pool. -A claim stays after its credential is deleted, because the Google-side trust may stay too. To hand a pool to a different owner (for example after a Google Cloud project changes hands), first remove the old owner's trust in Google: delete the old workload identity provider, or remove its members from the service account's `roles/iam.workloadIdentityUser` binding. Then release the claim (`/`, lowercase pool ID): +A claim stays after its credential is deleted, because the Google-side trust may stay too. Deleting a SAM account leaves its claims behind for the same reason. To hand a pool to a different owner (for example after a Google Cloud project changes hands): + +1. Remove the old owner's trust in Google: delete the old workload identity provider, or remove its members from the service account's `roles/iam.workloadIdentityUser` binding. +2. Delete or re-point every SAM credential of the old owner that still names the pool. A live credential keeps blocking other owners even without a claim. +3. Release the claim (`/`, lowercase pool ID): ```bash npx wrangler d1 execute --remote \ diff --git a/tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md b/tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md new file mode 100644 index 0000000000..ec887d7cdc --- /dev/null +++ b/tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md @@ -0,0 +1,29 @@ +# Probe Google for issuer-only WIF trust before a first pool claim + +## Problem + +PR #2905 (task 01M7SB8FRZ08M5NEX9WGM74X61) made SAM refuse to sign identity tokens for a GCP workload identity pool that another owner's credential names or has claimed. Claims are sticky, so every pool SAM has ever recorded stays protected after a disconnect. + +It cannot protect a pool SAM has **never** recorded whose Google-side trust is still issuer-only with a `pool/*` service-account binding: +- a pre-#2905 guided setup whose SAM credential was deleted before #2905 deployed; +- a platform pool an admin created in Google before saving the platform credential. + +Any approved user who knows the project number, pool, provider ID and service-account email can save a credential naming it, claim it first, and impersonate the service account (independent adversarial review of #2905, M1). + +Related: claim squatting with no proof of control (cloudflare-specialist M3, security L3): any approved user can claim unbounded pools from metadata alone. + +## Proposed fix + +Before the first claim of a pool (no claim, no holder), mint a probe identity token with a synthetic foreign `user_id`/`project_id` for the named provider and call Google STS. If STS accepts it, the provider trusts SAM's issuer alone: refuse the save/exchange and tell the owner to re-run guided setup. Treat any STS failure as "not open". + +Decide with Raphaël whether the probe should also run on exchanges of already-claimed pools (closes legacy issuer-only providers fleet-wide, but would refuse production's one legacy guided connection until its owner re-runs setup). + +Also consider: a per-owner cap on claims, and recording a claim when a deployment credential is saved. + +## Acceptance criteria + +- [ ] A first claim of a pool whose named provider accepts a foreign `user_id` is refused, with a message telling the owner to re-run setup +- [ ] A user-scoped (guided) provider passes the probe +- [ ] STS errors other than acceptance do not block the claim +- [ ] Decision recorded on probing already-claimed pools +- [ ] Tests: attack (open provider refused), owner control (scoped provider claimed), STS error control From cff61fc6cc632b4051fd49f9f505ed7717fe6c93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 09:09:11 +0000 Subject: [PATCH 04/13] test(security): composable exact-path owner test; revert unrelated log-key rename Co-Authored-By: Claude Opus 5.5 --- apps/api/src/routes/mcp/human-input-tool.ts | 2 +- apps/api/src/routes/mcp/inbox-tools.ts | 2 +- apps/api/src/services/mcp-token-lifecycle.ts | 2 +- .../src/services/runtime-secret-requests.ts | 2 +- .../services/gcp-wif-pool-ownership.test.ts | 37 +++++++++++++++++++ ...-gcp-wif-cross-owner-pool-impersonation.md | 16 ++++++-- 6 files changed, 53 insertions(+), 8 deletions(-) diff --git a/apps/api/src/routes/mcp/human-input-tool.ts b/apps/api/src/routes/mcp/human-input-tool.ts index 7c1eee406a..232ed37c14 100644 --- a/apps/api/src/routes/mcp/human-input-tool.ts +++ b/apps/api/src/routes/mcp/human-input-tool.ts @@ -109,7 +109,7 @@ export async function handleRequestHumanInput( // Verify task ownership matches token — use tokenData.userId as authoritative target if (taskRow.user_id !== tokenData.userId) { log.error('mcp.request_human_input.user_id_mismatch', { - cacheUserId: tokenData.userId, + tokenUserId: tokenData.userId, taskUserId: taskRow.user_id, taskId: tokenData.taskId, }); diff --git a/apps/api/src/routes/mcp/inbox-tools.ts b/apps/api/src/routes/mcp/inbox-tools.ts index aac76a9e06..30eb082bfa 100644 --- a/apps/api/src/routes/mcp/inbox-tools.ts +++ b/apps/api/src/routes/mcp/inbox-tools.ts @@ -54,7 +54,7 @@ async function resolveSource(tokenData: McpTokenData, env: Env): Promise log.error('mcp.inbox.task_mismatch', { taskId: tokenData.taskId, projectId: tokenData.projectId, - cacheUserId: tokenData.userId, + tokenUserId: tokenData.userId, taskUserId: task?.user_id ?? null, action: 'rejected', }); diff --git a/apps/api/src/services/mcp-token-lifecycle.ts b/apps/api/src/services/mcp-token-lifecycle.ts index 5e6194cbfc..a992cd1301 100644 --- a/apps/api/src/services/mcp-token-lifecycle.ts +++ b/apps/api/src/services/mcp-token-lifecycle.ts @@ -200,7 +200,7 @@ export async function validateActiveWorkspaceMcpToken( workspaceId: data.workspaceId || null, projectId: data.projectId, taskId: data.taskId || null, - cacheUserId: data.userId, + tokenUserId: data.userId, workspaceUserId: row?.userId ?? null, workspaceProjectId: row?.projectId ?? null, userStatus: joinedStatus(row?.joinedUserId, row?.userStatus), diff --git a/apps/api/src/services/runtime-secret-requests.ts b/apps/api/src/services/runtime-secret-requests.ts index 67186c431c..34e92a062e 100644 --- a/apps/api/src/services/runtime-secret-requests.ts +++ b/apps/api/src/services/runtime-secret-requests.ts @@ -163,7 +163,7 @@ async function loadRequestingTask(env: Env, identity: SecretRequesterIdentity) { log.error('runtime_secret_request.task_mismatch', { taskId: identity.taskId, projectId: identity.projectId, - cacheUserId: identity.userId, + tokenUserId: identity.userId, taskUserId: row?.user_id ?? null, action: 'rejected', }); diff --git a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts index 7f3e0a2e9f..a533884d3e 100644 --- a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -764,6 +764,43 @@ describe('the credential owner reaches the exchange through the real resolver', ); }); + it('the exact path through a composable project credential uses its owner too', async () => { + await storeCcRow('cc-a', 'user-a', JSON.stringify(wif(POOL_A))); + sqlite + .prepare( + `INSERT INTO cc_configurations (id, owner_id, name, consumer_kind, consumer_target, credential_id, + settings_json, is_active, created_at, updated_at) + VALUES ('cfg-a', 'user-a', 'GCP', 'compute', 'gcp', 'cc-a', NULL, 1, ?, ?)` + ) + .run(NOW, NOW); + sqlite + .prepare( + `INSERT INTO cc_attachments (id, configuration_id, consumer_kind, consumer_target, user_id, + project_id, is_active, created_at, updated_at) + VALUES ('att-a', 'cfg-a', 'compute', 'gcp', 'user-a', 'proj-a', 1, ?, ?)` + ) + .run(NOW, NOW); + + const resolved = await createProviderForUser( + drizzle(env.DATABASE, { schema }), + 'user-m', + KEY, + env, + 'gcp', + 'proj-a', + { + credentialSource: 'project', + credentialReference: 'cc_credentials:cc-a', + credentialVersion: Date.parse(NOW), + } + ); + await expect(resolved!.provider.validateToken()).resolves.toBe(true); + expect(signIdentityToken).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-a', projectId: 'proj-a' }), + env + ); + }); + it('a user-level credential signs its owner’s id, which the user-scoped condition requires', async () => { await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); const resolved = await createProviderForUser( diff --git a/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md b/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md index b3c63a2912..e7a5964769 100644 --- a/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md +++ b/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md @@ -32,6 +32,9 @@ User-level guided GCP setup created a pool provider whose attribute condition ch - [x] Review round 1 fixes: sticky claims (`gcp_wif_pool_claims`, first claim wins atomically, operator release), signed `user_id` = credential owner for user/project credentials, partial indexes + query-plan test, lazy settings read, fail closed on unparseable probe rows, unreadable-row retry window, leading-zero / provider-id / SA-email validation, warn-level refusal log, IAM conditions and policy version preserved - [x] Vertical tests through the real resolver (legacy and exact paths) for project-member owner plumbing and the signed claim - [x] Fixtures updated: capacity-pool suite applies migration 0262; teardown test uses a pool of the other user's own; orphan sweep asserts the platform owner check +- [x] Review round 2 fixes: namespaced fallback `project_id` (`gcpIdentityTokenProjectId`, `gcp-project:`); per-check D1 query cap (`gcpWif.poolIndexMaxQueriesPerCheck`, exact statement count); fail closed (503) on malformed batch results and D1 faults while indexing +- [x] Composable (`cc_credentials:`) exact-path owner test (G23); reverted an accidental `tokenUserId` log-key rename in four unrelated MCP files +- [x] Deferred (MEDIUM, with justification): open issuer-only providers on pools SAM never recorded, and claims without proof of Google control → `tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md` - [ ] Full quality suite - [ ] Reviews: security-auditor (re-verify), task-completion-validator, cloudflare-specialist - [ ] Staging: live save-time and exchange-time refusals @@ -44,12 +47,17 @@ User-level guided GCP setup created a pool provider whose attribute condition ch - cloudflare 1/3/6: full scans, settings read on the hot path, fail-open on unparseable rows. Fixed. - security M3 (409 reveals another owner uses a project number), L1 (parser divergence; not exploitable because the exchange check keys on the credential actually exchanged), L3 (cached tokens): documented as residual. +## Review round 2 (2026-11-19) + +- Independent security re-verification: no CRITICAL/HIGH; no impersonation path for any owner SAM has recorded. M2 (signed `project_id` fell back to the credential's typed `gcpProjectId`, spoofable against a deployment provider) fixed with `gcpIdentityTokenProjectId()`. M1 (a pool SAM has never recorded whose Google trust is still issuer-only can be claimed first by anyone: impersonation) **deferred** to `tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md`: the fix is a Google probe before first claim, and probing already-claimed pools would refuse production's one legacy connection until re-run, which needs Raphaël's decision. Round-2 confirmation: PASS. +- Cloudflare re-check: no HIGH. Batch-envelope fail-open and per-check query budget fixed; claims without proof of control deferred to the same backlog task. + ## Acceptance criteria -- [ ] User B cannot save, or exchange with, a credential naming user A's pool (409 / refusal before signing) -- [ ] A user credential cannot name the platform credential's pool, and vice versa -- [ ] The owner, the same user's project-scoped credential, and a project member using it still work -- [ ] New guided user-level setups use `assertion.user_id == ''` and `attribute.sam_user/`; re-runs fix existing providers and bindings +- [x] User B cannot save, or exchange with, a credential naming user A's pool (409 / refusal before signing): `gcp-wif-pool-ownership.test.ts` "attack: user B naming user A's pool…", "POST /api/credentials: B naming A's pool gets 409…" +- [x] A user credential cannot name the platform credential's pool, and vice versa: "attack: a user credential cannot name the platform credential's pool", "attack: the platform credential cannot name a user's pool", "POST /api/credentials: a user cannot save the platform credential's pool" +- [x] The owner, the same user's project-scoped credential, and a project member using it still work: "owner control…", "a project member using another member's project credential…", exact and composable exact-path resolver tests +- [x] New guided user-level setups use `assertion.user_id == ''` and `attribute.sam_user/`; re-runs fix existing providers and bindings: `gcp-wif-scoping.test.ts` (Google faked; strings, PATCH path and `pool/*` removal) - [x] Production has no cross-owner sharing (verified: counts above) - [ ] Refusals shown live on staging From 138116de23d36a6c1a7b68f442686c5429d2d3fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 09:14:39 +0000 Subject: [PATCH 05/13] task: archive gcp-wif-cross-owner-pool-impersonation Co-Authored-By: Claude Opus 5.5 --- .../2026-11-19-gcp-wif-cross-owner-pool-impersonation.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tasks/{active => archive}/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md (100%) diff --git a/tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md b/tasks/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md similarity index 100% rename from tasks/active/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md rename to tasks/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md From 2e5db6799f4257c3a449b6b3290a856c35ff04d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 09:38:00 +0000 Subject: [PATCH 06/13] test: give each resave Workers test its own GCP pool (claims are sticky) Co-Authored-By: Claude Opus 5.5 --- ...dential-resave-capacity-provenance.test.ts | 36 +++++++++++-------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts b/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts index 572b527fb3..56528086cf 100644 --- a/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts +++ b/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts @@ -121,15 +121,21 @@ async function request( ); } -const GCP_CONNECTION = { - provider: 'gcp', - gcpProjectId: 'sam-staging-infra', - gcpProjectNumber: '353771248703', - serviceAccountEmail: 'sam-vm-manager@sam-staging-infra.iam.gserviceaccount.com', - wifPoolId: 'sam-pool', - wifProviderId: 'sam-oidc', - defaultZone: 'europe-west1-b', -}; +/** + * Each test gets its own workload identity pool: the suite shares one D1, and a pool stays + * claimed by the first owner whose credential named it (gcp-wif-pool-ownership.ts). + */ +function gcpConnection() { + return { + provider: 'gcp', + gcpProjectId: 'sam-staging-infra', + gcpProjectNumber: '353771248703', + serviceAccountEmail: 'sam-vm-manager@sam-staging-infra.iam.gserviceaccount.com', + wifPoolId: prefix, + wifProviderId: 'sam-oidc', + defaultZone: 'europe-west1-b', + }; +} /** Reconcile the default pools the way the scheduled backfill does, with a complete catalog. */ async function reconcile(scope: { userId?: string; projectId?: string; installation?: boolean }) { @@ -329,7 +335,7 @@ function claim(nodeId: string, userId: string, status: string, allowRunning = fa describe('a GCP connection re-saved through the product', () => { it('keeps the connection, its pool choices and its order, so GCP stays placeable', async () => { - const saved = await request(ownerId, 'POST', '/api/credentials', GCP_CONNECTION); + const saved = await request(ownerId, 'POST', '/api/credentials', gcpConnection()); expect(saved.status).toBe(201); await reconcile({ userId: ownerId }); const credentialId = await userGcpCredentialId(ownerId); @@ -341,7 +347,7 @@ describe('a GCP connection re-saved through the product', () => { }); expect(picked.sourceId).toBe(`cap-source-default:user:${credentialId}`); - const resaved = await request(ownerId, 'POST', '/api/credentials', GCP_CONNECTION); + const resaved = await request(ownerId, 'POST', '/api/credentials', gcpConnection()); expect(resaved.status).toBe(200); expect(((await resaved.json()) as { id: string }).id).toBe(credentialId); await reconcile({ userId: ownerId }); @@ -358,7 +364,7 @@ describe('a GCP connection re-saved through the product', () => { }); it('leaves nodes placed before the save reapable by the cron and the warm handoff', async () => { - expect((await request(ownerId, 'POST', '/api/credentials', GCP_CONNECTION)).status).toBe(201); + expect((await request(ownerId, 'POST', '/api/credentials', gcpConnection())).status).toBe(201); await reconcile({ userId: ownerId }); await pickProvider({ scope: 'user', @@ -371,7 +377,7 @@ describe('a GCP connection re-saved through the product', () => { const placed = await placeNode(stoppedNode, ownerId, null, 'stopped'); await placeNode(runningNode, ownerId, null, 'running'); - expect((await request(ownerId, 'POST', '/api/credentials', GCP_CONNECTION)).status).toBe(200); + expect((await request(ownerId, 'POST', '/api/credentials', gcpConnection())).status).toBe(200); await reconcile({ userId: ownerId }); // The column the cleanup predicate reads survives the save. @@ -558,7 +564,7 @@ describe('a source deleted with its credential (disconnect, platform rotation)', provider: 'gcp', label: 'platform gcp', credential: JSON.stringify({ - ...GCP_CONNECTION, + ...gcpConnection(), version: 2, authType: 'workload-identity', }), @@ -821,7 +827,7 @@ describe('rows already damaged in the production shape', () => { }); it('a pool whose order names a deleted source still places on its active options', async () => { - expect((await request(ownerId, 'POST', '/api/credentials', GCP_CONNECTION)).status).toBe(201); + expect((await request(ownerId, 'POST', '/api/credentials', gcpConnection())).status).toBe(201); await reconcile({ userId: ownerId }); const picked = await pickProvider({ scope: 'user', From cc67c15eb74560c029dae4de7d33d15d18433bfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 09:48:36 +0000 Subject: [PATCH 07/13] fix(security): CodeRabbit round on GCP WIF pool ownership - Withhold first claims while another owner's credential is unreadable (it might name the pool); retry window default 10 minutes. - Claim deployment pools: migration 0262 backfills unambiguous owners, and deployment setup checks ownership before mutating Google. - Reconcile the index before any cloud credential delete, so a disconnect before the first post-deploy check keeps its claim. - Read service-account IAM policies as version 3 so a conditional pool/* grant is removed; write version 3 when conditions remain. - Fit each indexing page to the statement budget before any write, translate D1 rejections to the retryable 503, honour the configured retry interval, and read at most one foreign holder per source. - Tests use the production error handler and build both tables from the real migration. Co-Authored-By: Claude Opus 5.5 --- .../db/migrations/0262_gcp_wif_pool_index.sql | 15 ++ .../src/routes/admin-platform-credentials.ts | 3 + apps/api/src/routes/composable-credentials.ts | 4 + apps/api/src/routes/credentials.ts | 3 + apps/api/src/routes/project-deployment.ts | 27 ++- apps/api/src/routes/projects/credentials.ts | 5 + .../admin-settings-gcp-catalog-definitions.ts | 17 +- apps/api/src/services/gcp-deploy-setup.ts | 11 +- .../services/gcp-wif-pool-ownership-sql.ts | 73 ++++--- .../src/services/gcp-wif-pool-ownership.ts | 204 +++++++++++------- apps/api/src/services/gcp-wif-setup.ts | 12 +- apps/api/tests/unit/gcp-deploy-setup.test.ts | 2 +- .../services/gcp-wif-pool-ownership.test.ts | 176 ++++++++++++++- .../unit/services/gcp-wif-scoping.test.ts | 41 ++++ .../docs/docs/architecture/security.md | 7 +- .../docs/docs/guides/admin-settings.md | 6 +- ...-gcp-wif-cross-owner-pool-impersonation.md | 2 +- ...p-wif-probe-open-providers-before-claim.md | 9 +- 18 files changed, 476 insertions(+), 141 deletions(-) diff --git a/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql b/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql index 2ee81d3a23..1fd98b0f98 100644 --- a/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql +++ b/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql @@ -24,6 +24,9 @@ CREATE TABLE IF NOT EXISTS gcp_wif_pool_index ( ) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS idx_gcp_wif_pool_index_pool ON gcp_wif_pool_index (pool_key) WHERE pool_key IS NOT NULL; +-- Unreadable rows withhold first claims for other owners; keep that lookup off a table scan. +CREATE INDEX IF NOT EXISTS idx_gcp_wif_pool_index_unreadable + ON gcp_wif_pool_index (source_table, source_id) WHERE unreadable = 1; -- The first owner whose credential named a pool. Never released by deleting or re-pointing a -- credential: the trust an earlier setup granted in Google outlives the SAM row. An operator @@ -36,6 +39,18 @@ CREATE TABLE IF NOT EXISTS gcp_wif_pool_claims ( CHECK ((owner_kind = 'user' AND owner_user_id IS NOT NULL) OR (owner_kind = 'platform' AND owner_user_id IS NULL)) ) WITHOUT ROWID; +-- Deployment credentials store their pool in plaintext, so their claims are recorded here, before +-- any check runs: deleting a deployment credential must not free its pool. A pool named by more +-- than one owner gets no claim; the live rows keep refusing every owner until an operator decides. +INSERT INTO gcp_wif_pool_claims (pool_key, owner_kind, owner_user_id, claimed_at) +SELECT trim(gcp_project_number) || '/' || lower(trim(wif_pool_id)), 'user', min(user_id), + strftime('%Y-%m-%dT%H:%M:%fZ', 'now') + FROM project_deployment_credentials + WHERE provider = 'gcp' + GROUP BY trim(gcp_project_number) || '/' || lower(trim(wif_pool_id)) +HAVING count(DISTINCT user_id) = 1 +ON CONFLICT (pool_key) DO NOTHING; + -- Keep the unindexed-row probe proportional to cloud credentials, not to every stored -- credential (agent keys share these tables). CREATE INDEX IF NOT EXISTS idx_credentials_gcp_cloud diff --git a/apps/api/src/routes/admin-platform-credentials.ts b/apps/api/src/routes/admin-platform-credentials.ts index 6015a5a4a5..244cab4598 100644 --- a/apps/api/src/routes/admin-platform-credentials.ts +++ b/apps/api/src/routes/admin-platform-credentials.ts @@ -26,6 +26,7 @@ import { reconcileCapacityPoolsForCredentialMutation } from '../services/capacit import { decrypt, encrypt } from '../services/encryption'; import { deleteGcpApiHealthSafely } from '../services/gcp-api-health'; import { assertGcpWifPayloadOwnership } from '../services/gcp-wif-pool-ownership'; +import { reconcileGcpWifPoolIndex } from '../services/gcp-wif-pool-ownership'; import { buildProviderConfig } from '../services/provider-credentials'; import { CredentialValidator } from '../services/validation'; @@ -245,6 +246,8 @@ adminPlatformCredentialRoutes.patch( adminPlatformCredentialRoutes.delete('/:id', async (c) => { const credentialId = c.req.param('id'); const db = drizzle(c.env.DATABASE, { schema }); + // Record the pool a GCP platform credential names before it goes: Google may still trust it. + await reconcileGcpWifPoolIndex(c.env, 'delete_platform_credential'); const result = await db .delete(schema.platformCredentials) diff --git a/apps/api/src/routes/composable-credentials.ts b/apps/api/src/routes/composable-credentials.ts index cf7381ed50..41abda79dc 100644 --- a/apps/api/src/routes/composable-credentials.ts +++ b/apps/api/src/routes/composable-credentials.ts @@ -25,6 +25,7 @@ import { errors } from '../middleware/error'; import { reconcileCapacityPoolsForCredentialMutation } from '../services/capacity-pool-credential-lifecycle'; import { encrypt } from '../services/encryption'; import { assertGcpWifPayloadOwnership } from '../services/gcp-wif-pool-ownership'; +import { reconcileGcpWifPoolIndex } from '../services/gcp-wif-pool-ownership'; import { registerCCAttachmentRoutes, uniqueProjectIds } from './composable-credentials-attachments'; import { registerCCProfileAttachmentRoutes } from './composable-credentials-profile-attachments'; @@ -245,6 +246,9 @@ ccRoutes.delete('/credentials/:id', async (c) => { const { id } = c.req.param(); const affectedProjectIds = await listAffectedCredentialProjectIds(db, userId, id); + // A cloud credential may name a GCP pool; record it before the row goes (Google may still + // trust it). One D1 batch when nothing is unindexed. + await reconcileGcpWifPoolIndex(c.env, 'delete_composable_credential'); const result = await db .delete(schema.ccCredentials) diff --git a/apps/api/src/routes/credentials.ts b/apps/api/src/routes/credentials.ts index 0acd3760b0..55bb82f66e 100644 --- a/apps/api/src/routes/credentials.ts +++ b/apps/api/src/routes/credentials.ts @@ -53,6 +53,7 @@ import { replaceUserGcpCredential, } from '../services/gcp-credential-store'; import { clearGcpAccessTokenCache } from '../services/gcp-sts'; +import { reconcileGcpWifPoolIndex } from '../services/gcp-wif-pool-ownership'; import { parseGcpCredential, serializeCredentialToken } from '../services/provider-credentials'; import { CredentialValidator, @@ -448,6 +449,8 @@ credentialsRoutes.delete('/:provider', async (c) => { ) .limit(1); if (!stored) throw errors.notFound('Credential'); + // Record the pool this credential names before it goes: Google may still trust it. + await reconcileGcpWifPoolIndex(c.env, 'delete_user_gcp_credential'); let credential; try { diff --git a/apps/api/src/routes/project-deployment.ts b/apps/api/src/routes/project-deployment.ts index 049ac60f83..b9b993e148 100644 --- a/apps/api/src/routes/project-deployment.ts +++ b/apps/api/src/routes/project-deployment.ts @@ -32,6 +32,7 @@ import { GcpOAuthHandleSchema, jsonValidator, ProjectDeploymentSetupSchema } fro import { runGcpDeploySetup } from '../services/gcp-deploy-setup'; import { toSanitizedAppError } from '../services/gcp-errors'; import { listGcpProjects } from '../services/gcp-setup'; +import { assertGcpWifPoolOwnership, isGcpWifPoolOwnershipError } from '../services/gcp-wif-pool-ownership'; import { signIdentityToken } from '../services/jwt'; import { validateActiveWorkspaceMcpToken } from '../services/mcp-token-lifecycle'; import { getGoogleInfraOAuthConfig } from '../services/platform-config'; @@ -185,10 +186,34 @@ projectDeploymentRoutes.post( const oauthToken = await resolveDeployOAuthToken(body.oauthHandle, c.env.KV); + // The deployment credential belongs to whoever first connected it; a project member who + // re-runs setup keeps that owner (the row's user_id is never rewritten below). + const [currentCredential] = await db + .select({ userId: schema.projectDeploymentCredentials.userId }) + .from(schema.projectDeploymentCredentials) + .where( + and( + eq(schema.projectDeploymentCredentials.projectId, projectId), + eq(schema.projectDeploymentCredentials.provider, 'gcp'), + ), + ) + .limit(1); + const poolOwnerUserId = currentCredential?.userId ?? userId; + let result; try { - result = await runGcpDeploySetup(oauthToken, body.gcpProjectId, c.env, projectId); + result = await runGcpDeploySetup(oauthToken, body.gcpProjectId, c.env, projectId, { + // Before any Google change: a pool another owner holds must not be re-pointed here. + assertPoolAvailable: (pool) => + assertGcpWifPoolOwnership( + c.env, + pool, + { kind: 'user', userId: poolOwnerUserId }, + 'gcp_deploy_setup', + ), + }); } catch (err) { + if (isGcpWifPoolOwnershipError(err)) throw err; throw toSanitizedAppError(err, 'deploy-setup'); } diff --git a/apps/api/src/routes/projects/credentials.ts b/apps/api/src/routes/projects/credentials.ts index bd4655bce3..584a5d8952 100644 --- a/apps/api/src/routes/projects/credentials.ts +++ b/apps/api/src/routes/projects/credentials.ts @@ -54,6 +54,7 @@ import { decrypt, encrypt } from '../../services/encryption'; import { getTimeoutMs } from '../../services/fetch-timeout'; import { deleteGcpApiHealthSafely } from '../../services/gcp-api-health'; import { assertGcpWifPayloadOwnership } from '../../services/gcp-wif-pool-ownership'; +import { reconcileGcpWifPoolIndex } from '../../services/gcp-wif-pool-ownership'; import { serializeCredentialToken } from '../../services/provider-credentials'; import { CredentialValidator, @@ -412,6 +413,10 @@ projectCredentialsRoutes.delete('/:id/cloud-credentials/:provider', async (c) => } const providerName = provider as CredentialProvider; + if (providerName === 'gcp') { + // Record the pool this credential names before it goes: Google may still trust it. + await reconcileGcpWifPoolIndex(c.env, 'delete_project_gcp_credential'); + } const deleted = await db .delete(schema.credentials) .where( diff --git a/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts index d1172afe3e..2c301f995b 100644 --- a/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts +++ b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts @@ -8,11 +8,11 @@ import { import { type AdminSettingDefinition, integerDefinition } from './admin-setting-definitions'; -/** Defaults for the workload identity pool index, also used before the settings are read. */ +/** Defaults for the workload identity pool index (`gcp-wif-pool-ownership.ts`). */ export const DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE = 25; -export const DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES = 60; +/** Short, because an unreadable row withholds first claims for other owners until it is retried. */ +export const DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES = 10; export const DEFAULT_GCP_WIF_POOL_INDEX_BUDGET_MS = 10_000; -/** Under the 1,000 D1 queries a paid Workers invocation allows, leaving room for the request. */ export const DEFAULT_GCP_WIF_POOL_INDEX_MAX_QUERIES_PER_CHECK = 500; export type GcpCatalogSettingName = @@ -136,8 +136,9 @@ export const GCP_CATALOG_SETTINGS: readonly AdminSettingDefinition[] = [ ), // Workload identity pool ownership (`gcp-wif-pool-ownership.ts`). Indexing runs only for // credentials added or re-encrypted since the last check; a check that cannot finish inside the - // budget refuses rather than trusting a partial index. A page costs 2 + 2 x page size D1 - // statements; `gcpWif.poolIndexMaxQueriesPerCheck` caps their sum per check. + // budget refuses rather than trusting a partial index. A page costs a probe batch (2 SQL + // statements) plus up to 2 statements per row; `gcpWif.poolIndexMaxQueriesPerCheck` caps the + // statements one check issues, and a page shrinks to fit. integerDefinition( 'gcpWif.poolIndexPageSize', DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE, @@ -156,14 +157,14 @@ export const GCP_CATALOG_SETTINGS: readonly AdminSettingDefinition[] = [ 'gcpWif.poolIndexUnreadableRetryMinutes', DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES, 'Operations', - 'Minutes before SAM tries again to read a stored cloud credential it could not decrypt while indexing workload identity pools.', + 'Minutes before SAM tries again to read a stored cloud credential it could not decrypt while indexing workload identity pools. Until then the unreadable credential stops other owners from claiming new pools.', { min: 1, max: 24 * 60 } ), integerDefinition( 'gcpWif.poolIndexMaxQueriesPerCheck', DEFAULT_GCP_WIF_POOL_INDEX_MAX_QUERIES_PER_CHECK, 'Operations', - 'Most D1 queries one token exchange or credential save may spend indexing new credentials. Keep it under your Workers plan’s per-request D1 query limit (1,000 on paid; on the free plan use 40 with a page size of 5).', - { min: 12, max: 900 } + 'Most SQL statements one token exchange or credential save may issue while indexing new credentials (each page is a probe batch plus up to two statements per credential). Past it the check refuses with a retryable error and the next one continues.', + { min: 6, max: 900 } ), ]; diff --git a/apps/api/src/services/gcp-deploy-setup.ts b/apps/api/src/services/gcp-deploy-setup.ts index 44846f1364..ed75e73fbf 100644 --- a/apps/api/src/services/gcp-deploy-setup.ts +++ b/apps/api/src/services/gcp-deploy-setup.ts @@ -49,8 +49,16 @@ export async function runGcpDeploySetup( gcpProjectId: string, env: Env, samProjectId: string, - onProgress?: SetupProgressCallback + hooks: { + onProgress?: SetupProgressCallback; + /** + * Called with the pool once the project number is known, before SAM creates or changes any + * Google resource. Throws to stop a setup that would take over another owner's pool. + */ + assertPoolAvailable?: (pool: { gcpProjectNumber: string; wifPoolId: string }) => Promise; + } = {} ): Promise> { + const { onProgress } = hooks; const trustScope = { kind: 'project', samProjectId } as const; const timeoutMs = env.GCP_API_TIMEOUT_MS ? parseInt(env.GCP_API_TIMEOUT_MS, 10) @@ -66,6 +74,7 @@ export async function runGcpDeploySetup( onProgress?.('get_project_number', 'in_progress'); const projectNumber = await getProjectNumber(oauthToken, gcpProjectId, timeoutMs); onProgress?.('get_project_number', 'done'); + await hooks.assertPoolAvailable?.({ gcpProjectNumber: projectNumber, wifPoolId: poolId }); // Step 2: Enable deployment APIs onProgress?.('enable_apis', 'in_progress'); diff --git a/apps/api/src/services/gcp-wif-pool-ownership-sql.ts b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts index ad1b334211..cee639733e 100644 --- a/apps/api/src/services/gcp-wif-pool-ownership-sql.ts +++ b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts @@ -48,36 +48,44 @@ SELECT 'cc_credentials', cc.id, 'user', cc.owner_id, cc.encrypted_token, cc.iv AND (i.unreadable = 0 OR i.indexed_at >= ?)) LIMIT ?`; -// Everything that holds one pool: its claim, every live credential naming it (index rows whose -// source row still exists), and every deployment credential naming it (plaintext, read directly). -// Used only when the unindexed-row probe in the same D1 batch (one transaction) returned nothing, -// so every live row is indexed at its current IV and owner. Inactive and disabled credentials -// count: they can be re-enabled, and Google still trusts them. +// What decides one pool for one owner: its claim, plus at most one live credential and at most one +// deployment credential of a DIFFERENT owner naming it (one foreign holder is enough to refuse). +// Index rows of deleted credentials drop out through the existence checks. Used only when the +// unindexed-row probe in the same D1 batch (one transaction) returned nothing, so every live row +// is indexed at its current IV and owner. Inactive and disabled credentials count: they can be +// re-enabled, and Google still trusts them. // -// Binds: pool key x2, project number, pool id. +// Binds: pool key; pool key, owner kind, owner user id or ''; project number, pool id, +// owner kind, owner user id or ''. export const POOL_HOLDERS_SQL = ` SELECT 'gcp_wif_pool_claims' AS sourceTable, k.pool_key AS sourceId, k.owner_kind AS ownerKind, k.owner_user_id AS ownerUserId FROM gcp_wif_pool_claims k WHERE k.pool_key = ? UNION ALL -SELECT i.source_table, i.source_id, i.owner_kind, i.owner_user_id - FROM gcp_wif_pool_index i - WHERE i.pool_key = ? - AND ( - (i.source_table = 'credentials' AND EXISTS ( - SELECT 1 FROM credentials c WHERE c.id = i.source_id AND c.provider = 'gcp' - AND c.credential_type = 'cloud-provider')) - OR (i.source_table = 'platform_credentials' AND EXISTS ( - SELECT 1 FROM platform_credentials p WHERE p.id = i.source_id AND p.provider = 'gcp' - AND p.credential_type = 'cloud-provider')) - OR (i.source_table = 'cc_credentials' AND EXISTS ( - SELECT 1 FROM cc_credentials cc WHERE cc.id = i.source_id AND cc.kind = 'cloud-provider')) - ) +SELECT * FROM ( + SELECT i.source_table, i.source_id, i.owner_kind, i.owner_user_id + FROM gcp_wif_pool_index i + WHERE i.pool_key = ? + AND NOT (i.owner_kind = ? AND COALESCE(i.owner_user_id, '') = ?) + AND ( + (i.source_table = 'credentials' AND EXISTS ( + SELECT 1 FROM credentials c WHERE c.id = i.source_id AND c.provider = 'gcp' + AND c.credential_type = 'cloud-provider')) + OR (i.source_table = 'platform_credentials' AND EXISTS ( + SELECT 1 FROM platform_credentials p WHERE p.id = i.source_id AND p.provider = 'gcp' + AND p.credential_type = 'cloud-provider')) + OR (i.source_table = 'cc_credentials' AND EXISTS ( + SELECT 1 FROM cc_credentials cc WHERE cc.id = i.source_id AND cc.kind = 'cloud-provider')) + ) + LIMIT 1) UNION ALL -SELECT 'project_deployment_credentials', d.id, 'user', d.user_id - FROM project_deployment_credentials d - WHERE d.provider = 'gcp' AND d.gcp_project_number = ? AND lower(trim(d.wif_pool_id)) = ?`; +SELECT * FROM ( + SELECT 'project_deployment_credentials', d.id, 'user', d.user_id + FROM project_deployment_credentials d + WHERE d.provider = 'gcp' AND d.gcp_project_number = ? AND lower(trim(d.wif_pool_id)) = ? + AND NOT (? = 'user' AND d.user_id = ?) + LIMIT 1)`; // Binds: source table, source id, iv, owner kind, owner user id, pool key, unreadable, indexed at. export const UPSERT_INDEX_SQL = ` @@ -88,11 +96,26 @@ ON CONFLICT (source_table, source_id) DO UPDATE SET iv = excluded.iv, owner_kind = excluded.owner_kind, owner_user_id = excluded.owner_user_id, pool_key = excluded.pool_key, unreadable = excluded.unreadable, indexed_at = excluded.indexed_at`; -// First owner wins: the primary key makes concurrent claims race-free. -// Binds: pool key, owner kind, owner user id, claimed at. +// First owner wins: the primary key makes concurrent claims race-free. A claim is withheld while +// a live credential of a different owner could not be decrypted: it might name this pool, and a +// claim granted now would outlive the key fix. The unreadable row is retried after +// `gcpWif.poolIndexUnreadableRetryMinutes`; an operator removes a permanently corrupt row. +// Binds: pool key, owner kind, owner user id, claimed at, owner kind, owner user id or ''. export const CLAIM_POOL_SQL = ` INSERT INTO gcp_wif_pool_claims (pool_key, owner_kind, owner_user_id, claimed_at) -VALUES (?, ?, ?, ?) +SELECT ?, ?, ?, ? + WHERE NOT EXISTS ( + SELECT 1 FROM gcp_wif_pool_index u + WHERE u.unreadable = 1 + AND NOT (u.owner_kind = ? AND COALESCE(u.owner_user_id, '') = ?) + AND ( + (u.source_table = 'credentials' AND EXISTS ( + SELECT 1 FROM credentials c WHERE c.id = u.source_id AND c.iv = u.iv)) + OR (u.source_table = 'platform_credentials' AND EXISTS ( + SELECT 1 FROM platform_credentials p WHERE p.id = u.source_id AND p.iv = u.iv)) + OR (u.source_table = 'cc_credentials' AND EXISTS ( + SELECT 1 FROM cc_credentials cc WHERE cc.id = u.source_id AND cc.iv = u.iv)) + )) ON CONFLICT (pool_key) DO NOTHING`; // Binds: pool key. diff --git a/apps/api/src/services/gcp-wif-pool-ownership.ts b/apps/api/src/services/gcp-wif-pool-ownership.ts index ca1125cd21..c4a610c294 100644 --- a/apps/api/src/services/gcp-wif-pool-ownership.ts +++ b/apps/api/src/services/gcp-wif-pool-ownership.ts @@ -24,19 +24,16 @@ * claim insert and its re-read are one write batch on the primary, which is what decides who * holds an unclaimed pool. * - * I/O per check when nothing changed: one D1 round trip, no decryption, no admin-settings read. - * A first-time claim adds one round trip for that pool. A new or re-encrypted credential adds - * one page of decrypts plus two round trips per `gcpWif.poolIndexPageSize` rows, within - * `gcpWif.poolIndexBudgetMs`; past the budget the check refuses rather than trust a partial index. + * I/O per check when nothing changed: one D1 round trip and no decryption, plus the admin + * settings read (cached per isolate). A first-time claim adds one round trip for that pool. A new + * or re-encrypted credential adds decrypts plus two round trips per `gcpWif.poolIndexPageSize` + * rows, within `gcpWif.poolIndexBudgetMs` and `gcpWif.poolIndexMaxQueriesPerCheck`; past either + * the check refuses rather than trust a partial index. */ import type { Env } from '../env'; import { log } from '../lib/logger'; import { getCredentialEncryptionKey } from '../lib/secrets'; import { AppError } from '../middleware/error'; -import { - DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE, - DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES, -} from './admin-settings-gcp-catalog-definitions'; import { resolveAdminSetting } from './admin-settings-resolution'; import { decrypt } from './encryption'; import { @@ -252,8 +249,29 @@ function retryCutoff(retryMinutes: number): string { return new Date(Date.now() - retryMinutes * 60_000).toISOString(); } +/** Owner binds for SQL that compares owners: kind, and user id or '' for the installation. */ +function ownerBinds(kind: 'user' | 'platform', userId: string | null): [string, string] { + return [kind, userId ?? '']; +} + +function claimStatement( + env: Env, + poolKey: string, + kind: 'user' | 'platform', + userId: string | null, + now: string +): D1PreparedStatement { + return env.DATABASE.prepare(CLAIM_POOL_SQL).bind( + poolKey, + kind, + userId, + now, + ...ownerBinds(kind, userId) + ); +} + /** - * Decrypt and index one page; claim each named pool for the row's owner if it is unclaimed. + * Decrypt and index rows; claim each named pool for the row's owner if it is unclaimed. * Returns the number of D1 statements issued. */ async function indexRows(env: Env, rows: UnindexedRow[]): Promise { @@ -269,7 +287,8 @@ async function indexRows(env: Env, rows: UnindexedRow[]): Promise { } catch (err) { // An unreadable row cannot be exchanged either. It is retried after // `gcpWif.poolIndexUnreadableRetryMinutes` (a key fix makes it readable without a new IV), - // not on every check, so one bad row cannot stall every check (rule 41, rule 47). + // not on every check. Until then it withholds first claims for other owners + // (CLAIM_POOL_SQL), because it might name the pool being claimed (rule 41, rule 47). unreadable = 1; log.error('gcp_wif_pool_index.row_unreadable', { sourceTable: row.sourceTable, @@ -290,22 +309,20 @@ async function indexRows(env: Env, rows: UnindexedRow[]): Promise { now ) ); - if (poolKey) { - statements.push( - env.DATABASE.prepare(CLAIM_POOL_SQL).bind(poolKey, row.ownerKind, row.ownerUserId, now) - ); - } + if (poolKey) statements.push(claimStatement(env, poolKey, row.ownerKind, row.ownerUserId, now)); } if (statements.length > 0) await env.DATABASE.batch(statements); return statements.length; } -async function readIndexSettings(env: Env): Promise<{ +interface IndexSettings { pageSize: number; budgetMs: number; retryMinutes: number; maxQueries: number; -}> { +} + +async function readIndexSettings(env: Env): Promise { const [pageSize, budgetMs, retryMinutes, maxQueries] = await Promise.all([ resolveAdminSetting(env, 'gcpWif.poolIndexPageSize'), resolveAdminSetting(env, 'gcpWif.poolIndexBudgetMs'), @@ -320,16 +337,23 @@ async function readIndexSettings(env: Env): Promise<{ }; } -/** - * Bring the index up to date, then return everything that holds `pool`: its claim, live - * credentials naming it, and deployment credentials naming it. Throws - * GcpWifPoolIndexUnavailableError when unindexed rows remain after the time budget. - */ -/** Both statements of a two-statement batch returned a row array, or the check cannot be trusted. */ -function batchRows( - results: D1Result>[] | undefined, +/** A two-statement batch whose statements both returned row arrays; anything else fails closed. */ +async function runPair( + env: Env, + statements: [D1PreparedStatement, D1PreparedStatement], context: string -): [Record[], Record[]] { +): Promise<[Record[], Record[]]> { + let results: D1Result>[] | undefined; + try { + results = await env.DATABASE.batch>(statements); + } catch (err) { + log.error('gcp_wif_pool_index.batch_failed', { + context, + error: err instanceof Error ? err.message : String(err), + action: 'refused', + }); + throw new GcpWifPoolIndexUnavailableError(); + } const first = Array.isArray(results) && results.length === 2 ? results[0]?.results : undefined; const second = Array.isArray(results) && results.length === 2 ? results[1]?.results : undefined; if (!Array.isArray(first) || !Array.isArray(second)) { @@ -339,60 +363,47 @@ function batchRows( return [first, second]; } -/** D1 statements one page of indexing can issue: the probe batch plus up to two per row. */ -function queriesPerPage(pageSize: number): number { - return 2 + 2 * pageSize; -} +// A trivial second statement so a probe without a pool still runs as a checked pair. +const NO_HOLDERS_SQL = 'SELECT 1 AS none WHERE 0'; /** - * Bring the index up to date, then return everything that holds `pool`: its claim, live - * credentials naming it, and deployment credentials naming it. Throws - * GcpWifPoolIndexUnavailableError when unindexed rows remain after the time budget or the query - * budget (`gcpWif.poolIndexMaxQueriesPerCheck`, kept under D1's per-invocation query limit), or - * when D1 fails while indexing. Progress is durable, so the next check continues. + * Bring the index up to date, then return what `holders` reads in the same batch as the final, + * empty probe. Every probe and page counts against `gcpWif.poolIndexMaxQueriesPerCheck` (SQL + * statements, a budget kept well under D1's per-invocation limits); a page is shrunk to fit the + * statements left, keeping room for the final probe. `gcpWif.poolIndexBudgetMs` limits whether + * another page starts. Past either limit, or when D1 fails or answers oddly, the check refuses + * (503). Progress is durable, so the next check continues. */ -async function listPoolHolders(env: Env, pool: GcpWifPoolIdentity): Promise { - const holders = env.DATABASE.prepare(POOL_HOLDERS_SQL).bind( - pool.key, - pool.key, - pool.gcpProjectNumber, - pool.wifPoolId - ); - // Settings are read only when something needs indexing, so the steady state costs one batch. - let settings: Awaited> | null = null; - let deadline = Infinity; +async function reconcileIndex( + env: Env, + holders: D1PreparedStatement | null, + context: string +): Promise[]> { + const settings = await readIndexSettings(env); + const deadline = Date.now() + settings.budgetMs; + const cutoff = retryCutoff(settings.retryMinutes); let queries = 0; let indexedAny = false; for (;;) { - const pageSize = settings?.pageSize ?? DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE; - const cutoff = retryCutoff( - settings?.retryMinutes ?? DEFAULT_GCP_WIF_POOL_INDEX_UNREADABLE_RETRY_MINUTES - ); - const [unindexedRows, holderRows] = batchRows( - await env.DATABASE.batch>([ - env.DATABASE.prepare(UNINDEXED_ROWS_SQL).bind(cutoff, cutoff, cutoff, pageSize), - holders, - ]), - 'probe' + const [unindexedRows, holderRows] = await runPair( + env, + [ + env.DATABASE.prepare(UNINDEXED_ROWS_SQL).bind(cutoff, cutoff, cutoff, settings.pageSize), + holders ?? env.DATABASE.prepare(NO_HOLDERS_SQL), + ], + `${context}:probe` ); queries += 2; const unindexed = parseAll(unindexedRows, toUnindexedRow, 'unindexed'); if (unindexed.length === 0) { - const found = parseAll(holderRows, toPoolHolderRow, 'holders'); - if (indexedAny) { - log.info('gcp_wif_pool_index.reconciled', { poolKey: pool.key, holders: found.length }); - } - return found; + if (indexedAny) log.info('gcp_wif_pool_index.reconciled', { context }); + return holderRows; } - if (!settings) { - settings = await readIndexSettings(env); - deadline = Date.now() + settings.budgetMs; - } else if ( - Date.now() >= deadline || - queries + queriesPerPage(settings.pageSize) > settings.maxQueries - ) { + // Up to two statements per row, and two more for the probe that must follow. + const fits = Math.min(unindexed.length, Math.floor((settings.maxQueries - queries - 2) / 2)); + if (fits < 1 || Date.now() >= deadline) { log.error('gcp_wif_pool_index.budget_exhausted', { - poolKey: pool.key, + context, budgetMs: settings.budgetMs, queries, maxQueries: settings.maxQueries, @@ -402,10 +413,10 @@ async function listPoolHolders(env: Env, pool: GcpWifPoolIdentity): Promise { + await reconcileIndex(env, null, context); +} + function refuse( context: string, pool: GcpWifPoolIdentity, @@ -453,28 +473,46 @@ export async function assertGcpWifPoolOwnership( }); throw new GcpWifPoolInvalidError(); } - const holders = await listPoolHolders(env, identity); + const [ownerKind, ownerUserId] = ownerColumns(owner); + const holderRows = await reconcileIndex( + env, + env.DATABASE.prepare(POOL_HOLDERS_SQL).bind( + identity.key, + identity.key, + ...ownerBinds(ownerKind, ownerUserId), + identity.gcpProjectNumber, + identity.wifPoolId, + ...ownerBinds(ownerKind, ownerUserId) + ), + context + ); + const holders = parseAll(holderRows, toPoolHolderRow, 'holders'); const foreign = holders.filter((row) => !heldBy(row, owner)); if (foreign.length > 0) refuse(context, identity, owner, foreign); if (holders.some((row) => row.sourceTable === 'gcp_wif_pool_claims')) return; // Unclaimed: claim it. The primary key decides a concurrent claim, so re-read the winner. - const [ownerKind, ownerUserId] = ownerColumns(owner); - const [, claimRows] = batchRows( - await env.DATABASE.batch>([ - env.DATABASE.prepare(CLAIM_POOL_SQL).bind( - identity.key, - ownerKind, - ownerUserId, - new Date().toISOString() - ), + const [, claimRows] = await runPair( + env, + [ + claimStatement(env, identity.key, ownerKind, ownerUserId, new Date().toISOString()), env.DATABASE.prepare(READ_CLAIM_SQL).bind(identity.key), - ]), - 'claim' + ], + `${context}:claim` ); const claim = parseAll(claimRows, toPoolHolderRow, 'claim'); const [winner] = claim; - if (!winner || claim.length !== 1) throw new GcpWifPoolIndexUnavailableError(); + if (!winner) { + // No claim was written: another owner's credential is unreadable and might name this pool. + log.warn('gcp_wif_pool.claim_withheld_unreadable', { + context, + poolKey: identity.key, + owner: ownerLabel(owner), + action: 'refused', + }); + throw new GcpWifPoolIndexUnavailableError(); + } + if (claim.length !== 1) throw new GcpWifPoolIndexUnavailableError(); if (!heldBy(winner, owner)) refuse(context, identity, owner, claim); } diff --git a/apps/api/src/services/gcp-wif-setup.ts b/apps/api/src/services/gcp-wif-setup.ts index 035d39d8b0..5e9de9f129 100644 --- a/apps/api/src/services/gcp-wif-setup.ts +++ b/apps/api/src/services/gcp-wif-setup.ts @@ -366,7 +366,10 @@ export async function grantWifUserOnSa( Authorization: `Bearer ${oauthToken}`, 'Content-Type': 'application/json', }, - body: '{}', + // Version 3 returns conditional bindings under their real role with a `condition` field. + // Without it Google appends `_withcond_` to the role, and a conditional `pool/*` + // grant would escape the removal below. + body: JSON.stringify({ options: { requestedPolicyVersion: 3 } }), }, timeoutMs ); @@ -425,7 +428,12 @@ export async function grantWifUserOnSa( policy: { bindings: nonEmptyBindings, etag: policy.etag, - ...(policy.version !== undefined ? { version: policy.version } : {}), + // Conditional bindings can only be written back in a version 3 policy. + ...(nonEmptyBindings.some((b) => b.condition !== undefined) + ? { version: 3 } + : policy.version !== undefined + ? { version: policy.version } + : {}), }, }), }, diff --git a/apps/api/tests/unit/gcp-deploy-setup.test.ts b/apps/api/tests/unit/gcp-deploy-setup.test.ts index 63ee073374..1f61c20182 100644 --- a/apps/api/tests/unit/gcp-deploy-setup.test.ts +++ b/apps/api/tests/unit/gcp-deploy-setup.test.ts @@ -68,7 +68,7 @@ describe('runGcpDeploySetup', () => { 'my-project', mockEnv(), 'sam-project-123', - (step, status) => progressSteps.push({ step, status }) + { onProgress: (step, status) => progressSteps.push({ step, status }) } ); // Verify result diff --git a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts index a533884d3e..b89002d644 100644 --- a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -42,6 +42,8 @@ const { GcpWifPoolInvalidError, GcpWifPoolOwnedByAnotherOwnerError, } = await import('../../../src/services/gcp-wif-pool-ownership'); +const { handleAppError } = await import('../../../src/middleware/app-error-handler'); +const { runGcpDeploySetup } = await import('../../../src/services/gcp-deploy-setup'); const { serializeCredentialToken, createProviderForUser } = await import('../../../src/services/provider-credentials'); const { UNINDEXED_ROWS_SQL } = await import('../../../src/services/gcp-wif-pool-ownership-sql'); @@ -158,16 +160,8 @@ function indexRows() { function testApp() { const app = new Hono<{ Bindings: Env }>(); - app.onError((err, c) => { - const appError = err as { statusCode?: number; error?: string; message?: string }; - if (typeof appError.statusCode === 'number' && typeof appError.error === 'string') { - return c.json( - { error: appError.error, message: appError.message }, - appError.statusCode as 400 - ); - } - return c.json({ error: 'INTERNAL_ERROR', message: err.message }, 500); - }); + // The production handler, so a refusal that stopped being an AppError would surface as 500. + app.onError(handleAppError); app.route('/api/credentials', credentialsRoutes); app.route('/api/cc', ccRoutes); return app; @@ -198,6 +192,7 @@ beforeEach(() => { createAllSchemaTables(sqlite, schema); // Exercise the real migration (its CHECK constraints and indexes), not only the drizzle shape. sqlite.exec('DROP TABLE gcp_wif_pool_index'); + sqlite.exec('DROP TABLE gcp_wif_pool_claims'); sqlite.exec( readFileSync( new URL('../../../src/db/migrations/0262_gcp_wif_pool_index.sql', import.meta.url), @@ -916,3 +911,164 @@ describe('the check fails closed on its own limits', () => { ); }); }); + +describe('review round 3: unresolved rows, budgets, deletes and deployments', () => { + afterEach(async () => { + const { __resetAdminSettingsCacheForTest } = + await import('../../../src/services/admin-settings-resolution'); + __resetAdminSettingsCacheForTest(); + }); + + async function setSetting(key: string, value: string) { + const { __resetAdminSettingsCacheForTest } = + await import('../../../src/services/admin-settings-resolution'); + __resetAdminSettingsCacheForTest(); + sqlite + .prepare('INSERT INTO platform_settings (key, value, updated_at) VALUES (?, ?, ?)') + .run(key, value, NOW); + } + + async function storeUnreadableCc(id: string, ownerId: string, pool = POOL_A) { + const otherKey = Buffer.from('fedcba9876543210fedcba9876543210').toString('base64'); + const foreign = await encrypt(JSON.stringify(wif(pool)), otherKey); + sqlite + .prepare( + `INSERT INTO cc_credentials (id, owner_id, name, kind, encrypted_token, iv, is_active, created_at, updated_at) + VALUES (?, ?, 'x', 'cloud-provider', ?, ?, 1, ?, ?)` + ) + .run(id, ownerId, foreign.ciphertext, foreign.iv, NOW, NOW); + } + + it('withholds a first claim while another owner’s credential is unreadable', async () => { + // A's credential for POOL_A cannot be decrypted (for example a key misconfiguration). + await storeUnreadableCc('cc-a-unreadable', 'user-a'); + vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolIndexUnavailableError + ); + expect(signIdentityToken).not.toHaveBeenCalled(); + expect(sqlite.prepare('SELECT count(*) AS n FROM gcp_wif_pool_claims').get()).toEqual({ + n: 0, + }); + // Owner control: the unreadable row's own owner is not blocked by it. + await expect(exchange(user('user-a'), wif(POOL_B))).resolves.toBe('sa-token'); + await expect(exchange(user('user-a'), wif(POOL_B))).resolves.toBe('sa-token'); + }); + + it('never issues more statements than the per-check budget, even on the first page', async () => { + await setSetting('gcpWif.poolIndexPageSize', '50'); + await setSetting('gcpWif.poolIndexMaxQueriesPerCheck', '6'); + for (let i = 0; i < 3; i++) await storeCcRow(`cc-other-${i}`, 'user-b', `token-${i}`); + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + vi.spyOn(console, 'error').mockImplementation(() => {}); + const batch = vi.spyOn(env.DATABASE, 'batch'); + + await expect(exchange(user('user-a'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolIndexUnavailableError + ); + const statements = batch.mock.calls.reduce((sum, [list]) => sum + list.length, 0); + expect(statements).toBeLessThanOrEqual(6); + expect( + (sqlite.prepare('SELECT count(*) AS n FROM gcp_wif_pool_index').get() as { n: number }).n + ).toBe(1); + }); + + it('a rejected probe becomes the retryable 503, not an upstream error', async () => { + vi.spyOn(env.DATABASE, 'batch').mockRejectedValueOnce(new Error('D1_ERROR: overloaded')); + vi.spyOn(console, 'error').mockImplementation(() => {}); + await expect(exchange(user('user-a'), wif(POOL_A))).rejects.toBeInstanceOf( + GcpWifPoolIndexUnavailableError + ); + // Liveness control: the next check succeeds. + await expect(exchange(user('user-a'), wif(POOL_A))).resolves.toBe('sa-token'); + }); + + it('a disconnect before any other check still leaves the pool claimed', async () => { + // A connected before this release: the row exists, nothing is indexed or claimed yet. + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + auth.userId = 'user-a'; + const removed = await testApp().request('/api/credentials/gcp', { method: 'DELETE' }, env); + expect(removed.status).toBe(200); + expect( + sqlite.prepare('SELECT count(*) AS n FROM credentials WHERE user_id = ?').get('user-a') + ).toEqual({ n: 0 }); + + auth.userId = 'user-b'; + const attack = await postGcpCredential(wif(POOL_A)); + expect(attack.status).toBe(409); + // Control: B can still save a pool nobody holds. + expect((await postGcpCredential(wif(POOL_B))).status).toBe(201); + }); + + it('the production error handler keeps unrelated failures distinct', async () => { + auth.userId = 'user-b'; + const invalid = await testApp().request( + '/api/credentials', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ provider: 'gcp', gcpProjectId: 'x' }), + }, + env + ); + expect(invalid.status).toBe(400); + expect(await invalid.json()).not.toMatchObject({ + error: 'GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER', + }); + }); + + it('migration 0262 claims existing deployment pools with one owner, and none with two', () => { + const deployment = (id: string, userId: string, projectNumber: string, pool: string) => + sqlite + .prepare( + `INSERT INTO project_deployment_credentials (id, project_id, user_id, provider, gcp_project_id, + gcp_project_number, service_account_email, wif_pool_id, wif_provider_id, created_at, updated_at) + VALUES (?, ?, ?, 'gcp', 'gcp-x', ?, 'deployer@x', ?, 'p', ?, ?)` + ) + .run(id, `proj-${id}`, userId, projectNumber, pool, NOW, NOW); + sqlite.pragma('foreign_keys = OFF'); + deployment('dep-1', 'user-a', '444444444444', 'Sam-Deploy-Pool'); + deployment('dep-2', 'user-a', '555555555555', 'sam-deploy-pool'); + deployment('dep-3', 'user-b', '555555555555', 'sam-deploy-pool'); + sqlite.exec( + readFileSync( + new URL('../../../src/db/migrations/0262_gcp_wif_pool_index.sql', import.meta.url), + 'utf8' + ) + ); + expect( + sqlite + .prepare('SELECT pool_key, owner_user_id FROM gcp_wif_pool_claims ORDER BY pool_key') + .all() + ).toEqual([{ pool_key: '444444444444/sam-deploy-pool', owner_user_id: 'user-a' }]); + }); + + it('deployment setup stops before changing anything in Google when the pool is taken', async () => { + await storeLegacyRow( + 'cred-a', + 'user-a', + wif({ gcpProjectNumber: POOL_A.gcpProjectNumber, wifPoolId: 'sam-deploy-pool' }) + ); + const google = vi.fn(async () => + Response.json({ projectNumber: POOL_A.gcpProjectNumber, projectId: 'gcp-a' }) + ); + vi.stubGlobal('fetch', google); + const { assertGcpWifPoolOwnership } = + await import('../../../src/services/gcp-wif-pool-ownership'); + + await expect( + runGcpDeploySetup('oauth', 'gcp-a', env, 'proj-b', { + assertPoolAvailable: (pool) => + assertGcpWifPoolOwnership( + env, + pool, + { kind: 'user', userId: 'user-b' }, + 'gcp_deploy_setup' + ), + }) + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + expect(google).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/tests/unit/services/gcp-wif-scoping.test.ts b/apps/api/tests/unit/services/gcp-wif-scoping.test.ts index 09331d2011..834103bd45 100644 --- a/apps/api/tests/unit/services/gcp-wif-scoping.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-scoping.test.ts @@ -232,6 +232,47 @@ describe('WIF trust scoping (cross-owner impersonation prevention)', () => { ]); }); + it('reads the policy as version 3 and removes a conditional pool-wide grant', async () => { + const keepCondition = { + title: 'business-hours', + expression: 'request.time < timestamp("2030-01-01T00:00:00Z")', + }; + mockFetch.mockResolvedValueOnce( + mockGcpResponse({ + version: 3, + etag: 'abc', + bindings: [ + { + role: WIF_ROLE, + members: [`principalSet://${POOL_PATH}/*`], + condition: { title: 'legacy', expression: 'true' }, + }, + { role: WIF_ROLE, members: ['user:ops@example.com'], condition: keepCondition }, + ], + }) + ); + mockFetch.mockResolvedValueOnce(mockGcpResponse({ etag: 'def' })); + + await grantWifUserOnSa( + 'token', + 'my-gcp-project', + '123456', + 'sa@my-gcp-project.iam.gserviceaccount.com', + 'sam-pool', + 5000, + USER_SCOPE + ); + + expect(requestBody(0)).toEqual({ options: { requestedPolicyVersion: 3 } }); + const policy = (requestBody(1) as { policy: Record }).policy; + expect(policy.version).toBe(3); + expect(policy.bindings).toEqual([ + { role: WIF_ROLE, members: ['user:ops@example.com'], condition: keepCondition }, + // Never added under another binding's condition. + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`] }, + ]); + }); + it('leaves the policy untouched when already scoped and no wildcard remains', async () => { mockFetch.mockResolvedValueOnce( mockGcpResponse({ diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index e3e9e5ae83..f519c09e8c 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -305,11 +305,12 @@ SAM signs an identity token for whatever pool a stored WIF credential names, so Where it is enforced: -- **At save**: `POST /api/credentials`, the Google setup routes, project cloud credentials, composable credentials and admin platform credentials return `409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`. Guided setup checks the pool after reading the project number and before it changes anything in Google. +- **At save**: `POST /api/credentials`, the Google setup routes, project cloud credentials, composable credentials and admin platform credentials return `409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`. Guided setup and deployment setup check the pool after reading the project number and before they change anything in Google. Deployment pools are claimed when their setup runs; migration 0262 claims existing ones (a pool with more than one owner gets no claim and stays refused for both). +- **Before a delete**: removing a user, project, composable or platform cloud credential first indexes every unseen credential (`reconcileGcpWifPoolIndex()`), so a disconnect made before any other check after this release still leaves its pool claimed. - **At token exchange**: the same check runs before SAM signs the identity token (`exchangeGcpWifAccessToken()` in `gcp-sts.ts`), so credentials saved before the check existed are refused too. The owner is the stored credential's owner, so a project member using another member's project credential still works. Refusals log `gcp_wif_pool.cross_owner_refused` at warn level. The exchange also refuses a project number with a leading zero, and a provider ID or service-account email that could alter the STS audience or the impersonation URL. -- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the read of the pool's holders, so a writer that skips the index, a rotation or a deletion cannot leave it stale. With nothing new to index a check is one D1 round trip with no decryption. A row that cannot be decrypted is recorded as unreadable, logged, and tried again after `gcpWif.poolIndexUnreadableRetryMinutes`; it does not affect other credentials. If newly saved rows cannot be indexed within `gcpWif.poolIndexBudgetMs` and `gcpWif.poolIndexMaxQueriesPerCheck`, or D1 fails or returns an unexpected result while the check runs, it refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index; progress is kept, so the next check continues. +- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the read of the pool's holders, so a writer that skips the index, a rotation or a deletion cannot leave it stale. With nothing new to index a check is one D1 round trip with no decryption. A row that cannot be decrypted is recorded as unreadable, logged, and tried again after `gcpWif.poolIndexUnreadableRetryMinutes`. Until it is read, it might name any pool, so no other owner may make a first claim (they get the retryable 503); pools already claimed are unaffected, and an operator removes a permanently corrupt row. If newly saved rows cannot be indexed within `gcpWif.poolIndexMaxQueriesPerCheck` SQL statements (a page shrinks to fit) or before `gcpWif.poolIndexBudgetMs` (a soft limit on starting another page), or D1 fails or returns an unexpected result while the check runs, it refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index; progress is kept, so the next check continues. -The Google side is scoped as well. User-level guided setup creates a provider whose condition is `assertion.iss == '' && assertion.user_id == ''` and grants the service account only to `principalSet://.../workloadIdentityPools//attribute.sam_user/`. Deployment setup uses `assertion.project_id` and `principal://.../subject/project:` (`wifAttributeCondition()`, `wifServiceAccountMember()` in `gcp-wif-setup.ts`). For a user's own credential, user-level or project-scoped, SAM signs `user_id` as the credential owner's id (`gcpIdentityTokenUserId()`), so both match the user-scoped provider. `project_id` (and `sub = project:`) is a SAM project the caller acts for; when the token acts for no SAM project, SAM signs the credential's own Google project as `gcp-project:` (`gcpIdentityTokenProjectId()`), so a value the credential's owner typed can never pass for another user's SAM project at a deployment provider. Platform credentials sign `platform:` and need a pool their installation configured; guided setup does not create one. Setups before this change used an issuer-only condition and a `pool/*` binding. Re-running setup rewrites the provider's condition and removes the `pool/*` member from the service account, keeping other members and IAM conditions. +The Google side is scoped as well. User-level guided setup creates a provider whose condition is `assertion.iss == '' && assertion.user_id == ''` and grants the service account only to `principalSet://.../workloadIdentityPools//attribute.sam_user/`. Deployment setup uses `assertion.project_id` and `principal://.../subject/project:` (`wifAttributeCondition()`, `wifServiceAccountMember()` in `gcp-wif-setup.ts`). For a user's own credential, user-level or project-scoped, SAM signs `user_id` as the credential owner's id (`gcpIdentityTokenUserId()`), so both match the user-scoped provider. `project_id` (and `sub = project:`) is a SAM project the caller acts for; when the token acts for no SAM project, SAM signs the credential's own Google project as `gcp-project:` (`gcpIdentityTokenProjectId()`), so a value the credential's owner typed can never pass for another user's SAM project at a deployment provider. Platform credentials sign `platform:` and need a pool their installation configured; guided setup does not create one. Setups before this change used an issuer-only condition and a `pool/*` binding. Re-running setup rewrites the provider's condition and removes the `pool/*` member from the service account, including a conditional grant (the policy is read as version 3), keeping other members and IAM conditions. Residual risks: diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index d9fc7120b2..0f19db9b86 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -1105,9 +1105,9 @@ These control the live Google Cloud catalog described in [Google Cloud](/docs/gu | `gcpCatalog.bootDiskGbPerVcpu` | 20 | 1–256 | GB of boot disk a new Google Cloud node gets per vCPU, used by the catalog, prices and new nodes from the next catalog refresh; running nodes keep their disk. | | `gcpCatalog.bootDiskMinGb` | 50 | 10–4096 | Smallest boot disk, in GB, a new Google Cloud node gets whatever its vCPU count; same refresh rule. | | `gcpWif.poolIndexPageSize` | 25 | 5–50 | Stored cloud credentials decrypted per step when indexing which workload identity pool each one names (only new or re-saved credentials are indexed). | -| `gcpWif.poolIndexBudgetMs` | 10000 | 1000–25000 | Most time one token exchange or credential save may spend indexing new credentials before it refuses and asks to retry, rather than trust a partial index. | -| `gcpWif.poolIndexUnreadableRetryMinutes` | 60 | 1–1440 | Wait before SAM tries again to read a stored cloud credential it could not decrypt while indexing workload identity pools. | -| `gcpWif.poolIndexMaxQueriesPerCheck` | 500 | 12–900 | Most D1 queries one check may spend indexing. Keep it under your Workers plan's per-request D1 query limit; on the free plan use 40 with a page size of 5. | +| `gcpWif.poolIndexBudgetMs` | 10000 | 1000–25000 | Soft time limit on indexing in one token exchange or credential save: no page starts after it, and the check refuses and asks to retry rather than trust a partial index. | +| `gcpWif.poolIndexUnreadableRetryMinutes` | 10 | 1–1440 | Wait before SAM tries again to read a stored cloud credential it could not decrypt while indexing workload identity pools. Until then it stops other owners from claiming new pools. | +| `gcpWif.poolIndexMaxQueriesPerCheck` | 500 | 6–900 | Most SQL statements one check may issue while indexing (a probe batch per page plus up to two statements per credential; a page shrinks to fit). Past it the check returns a retryable 503 and the next one continues. | ### Infomaniak boot volume diff --git a/tasks/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md b/tasks/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md index e7a5964769..f5af683640 100644 --- a/tasks/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md +++ b/tasks/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md @@ -35,7 +35,7 @@ User-level guided GCP setup created a pool provider whose attribute condition ch - [x] Review round 2 fixes: namespaced fallback `project_id` (`gcpIdentityTokenProjectId`, `gcp-project:`); per-check D1 query cap (`gcpWif.poolIndexMaxQueriesPerCheck`, exact statement count); fail closed (503) on malformed batch results and D1 faults while indexing - [x] Composable (`cc_credentials:`) exact-path owner test (G23); reverted an accidental `tokenUserId` log-key rename in four unrelated MCP files - [x] Deferred (MEDIUM, with justification): open issuer-only providers on pools SAM never recorded, and claims without proof of Google control → `tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md` -- [ ] Full quality suite +- [x] Full quality suite: check:fast passes; API suite 17,869 tests, 0 failures - [ ] Reviews: security-auditor (re-verify), task-completion-validator, cloudflare-specialist - [ ] Staging: live save-time and exchange-time refusals diff --git a/tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md b/tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md index ec887d7cdc..46945b92e4 100644 --- a/tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md +++ b/tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md @@ -14,7 +14,10 @@ Related: claim squatting with no proof of control (cloudflare-specialist M3, sec ## Proposed fix -Before the first claim of a pool (no claim, no holder), mint a probe identity token with a synthetic foreign `user_id`/`project_id` for the named provider and call Google STS. If STS accepts it, the provider trusts SAM's issuer alone: refuse the save/exchange and tell the owner to re-run guided setup. Treat any STS failure as "not open". +Before the first claim of a pool (no claim, no holder), mint a probe identity token with a synthetic foreign `user_id`/`project_id` for the named provider and call Google STS. Three outcomes: +- STS **accepts** it: the provider trusts SAM's issuer alone. Refuse the save/exchange and tell the owner to re-run guided setup. +- STS **rejects it on the attribute condition** (a verified scope rejection): the provider is scoped; record the claim. +- **Anything inconclusive** (timeout, 5xx, network error, unparseable response, an error that does not identify a condition rejection): do not claim and do not sign. Return a retryable error. An outage must never be read as "this provider is safe", or the documented attack works whenever Google is slow. Decide with Raphaël whether the probe should also run on exchanges of already-claimed pools (closes legacy issuer-only providers fleet-wide, but would refuse production's one legacy guided connection until its owner re-runs setup). @@ -24,6 +27,6 @@ Also consider: a per-owner cap on claims, and recording a claim when a deploymen - [ ] A first claim of a pool whose named provider accepts a foreign `user_id` is refused, with a message telling the owner to re-run setup - [ ] A user-scoped (guided) provider passes the probe -- [ ] STS errors other than acceptance do not block the claim +- [ ] Only a verified attribute-condition rejection permits the claim; inconclusive probe results refuse with a retryable error and sign nothing - [ ] Decision recorded on probing already-claimed pools -- [ ] Tests: attack (open provider refused), owner control (scoped provider claimed), STS error control +- [ ] Tests: attack (open provider refused), owner control (scoped provider claimed), inconclusive control (timeout/5xx refused, retryable) From aa73b644097bdfd8cc461d3ad3f8cffbcd6aba7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 09:56:01 +0000 Subject: [PATCH 08/13] fix(security): claim stored WIF credentials unconditionally; withhold only new first claims Delta review: one unreadable row must not refuse existing users, and a delete must leave its pool claimed. Stored credentials now claim at index time; only a new credential's first claim waits while another owner's row is unreadable (GCP_WIF_POOL_OWNERSHIP_UNRESOLVED, logged at error level with the rows). Switching a WIF connection to a key records the outgoing pool first. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/services/gcp-credential-store.ts | 6 +- .../services/gcp-wif-pool-ownership-sql.ts | 51 ++++++++---- .../src/services/gcp-wif-pool-ownership.ts | 53 ++++++++++--- .../services/gcp-wif-pool-ownership.test.ts | 77 ++++++++++++++++++- .../docs/docs/architecture/security.md | 4 +- 5 files changed, 159 insertions(+), 32 deletions(-) diff --git a/apps/api/src/services/gcp-credential-store.ts b/apps/api/src/services/gcp-credential-store.ts index c0ca401adc..de96a072c2 100644 --- a/apps/api/src/services/gcp-credential-store.ts +++ b/apps/api/src/services/gcp-credential-store.ts @@ -4,7 +4,7 @@ import type { Env } from '../env'; import { getCredentialEncryptionKey } from '../lib/secrets'; import { ulid } from '../lib/ulid'; import { encrypt } from './encryption'; -import { assertGcpWifPoolOwnership } from './gcp-wif-pool-ownership'; +import { assertGcpWifPoolOwnership, reconcileGcpWifPoolIndex } from './gcp-wif-pool-ownership'; import { serializeGcpCredential } from './provider-credentials'; export interface StoredGcpCredentialResult { @@ -118,6 +118,10 @@ export async function replaceUserGcpCredential( { kind: 'user', userId }, 'save_user_gcp_credential' ); + } else { + // Replacing a WIF connection with a key: record the outgoing pool's claim first, because + // Google may still trust it after the SAM row changes. + await reconcileGcpWifPoolIndex(env, 'replace_user_gcp_credential'); } const now = new Date().toISOString(); const legacyId = ulid(); diff --git a/apps/api/src/services/gcp-wif-pool-ownership-sql.ts b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts index cee639733e..cad871a57c 100644 --- a/apps/api/src/services/gcp-wif-pool-ownership-sql.ts +++ b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts @@ -96,28 +96,45 @@ ON CONFLICT (source_table, source_id) DO UPDATE SET iv = excluded.iv, owner_kind = excluded.owner_kind, owner_user_id = excluded.owner_user_id, pool_key = excluded.pool_key, unreadable = excluded.unreadable, indexed_at = excluded.indexed_at`; -// First owner wins: the primary key makes concurrent claims race-free. A claim is withheld while -// a live credential of a different owner could not be decrypted: it might name this pool, and a -// claim granted now would outlive the key fix. The unreadable row is retried after -// `gcpWif.poolIndexUnreadableRetryMinutes`; an operator removes a permanently corrupt row. +// Live credentials of a different owner that could not be decrypted, at their indexed IV. +const UNREADABLE_FOREIGN_ROWS = ` +SELECT u.source_table AS sourceTable, u.source_id AS sourceId + FROM gcp_wif_pool_index u + WHERE u.unreadable = 1 + AND NOT (u.owner_kind = ? AND COALESCE(u.owner_user_id, '') = ?) + AND ( + (u.source_table = 'credentials' AND EXISTS ( + SELECT 1 FROM credentials c WHERE c.id = u.source_id AND c.iv = u.iv)) + OR (u.source_table = 'platform_credentials' AND EXISTS ( + SELECT 1 FROM platform_credentials p WHERE p.id = u.source_id AND p.iv = u.iv)) + OR (u.source_table = 'cc_credentials' AND EXISTS ( + SELECT 1 FROM cc_credentials cc WHERE cc.id = u.source_id AND cc.iv = u.iv)) + )`; + +// Index-time claim for a credential that is already stored: first owner wins. Stored rows predate +// the check, so their claims are recorded unconditionally; withholding them would turn one +// unreadable row into refused exchanges for every existing user (rule 41). +// Binds: pool key, owner kind, owner user id, claimed at. +export const CLAIM_STORED_POOL_SQL = ` +INSERT INTO gcp_wif_pool_claims (pool_key, owner_kind, owner_user_id, claimed_at) +VALUES (?, ?, ?, ?) +ON CONFLICT (pool_key) DO NOTHING`; + +// Check-time first claim (a new credential naming an unclaimed pool). The primary key makes +// concurrent claims race-free. It is withheld while a live credential of a DIFFERENT owner could +// not be decrypted: that row might name this pool, and a claim granted now would outlive the key +// fix. The unreadable row is retried after `gcpWif.poolIndexUnreadableRetryMinutes`; an operator +// removes a permanently corrupt row. // Binds: pool key, owner kind, owner user id, claimed at, owner kind, owner user id or ''. -export const CLAIM_POOL_SQL = ` +export const CLAIM_NEW_POOL_SQL = ` INSERT INTO gcp_wif_pool_claims (pool_key, owner_kind, owner_user_id, claimed_at) SELECT ?, ?, ?, ? - WHERE NOT EXISTS ( - SELECT 1 FROM gcp_wif_pool_index u - WHERE u.unreadable = 1 - AND NOT (u.owner_kind = ? AND COALESCE(u.owner_user_id, '') = ?) - AND ( - (u.source_table = 'credentials' AND EXISTS ( - SELECT 1 FROM credentials c WHERE c.id = u.source_id AND c.iv = u.iv)) - OR (u.source_table = 'platform_credentials' AND EXISTS ( - SELECT 1 FROM platform_credentials p WHERE p.id = u.source_id AND p.iv = u.iv)) - OR (u.source_table = 'cc_credentials' AND EXISTS ( - SELECT 1 FROM cc_credentials cc WHERE cc.id = u.source_id AND cc.iv = u.iv)) - )) + WHERE NOT EXISTS (${UNREADABLE_FOREIGN_ROWS}) ON CONFLICT (pool_key) DO NOTHING`; +// Binds: owner kind, owner user id or ''. +export const LIST_UNREADABLE_FOREIGN_ROWS_SQL = `${UNREADABLE_FOREIGN_ROWS} LIMIT 5`; + // Binds: pool key. export const READ_CLAIM_SQL = ` SELECT 'gcp_wif_pool_claims' AS sourceTable, pool_key AS sourceId, owner_kind AS ownerKind, diff --git a/apps/api/src/services/gcp-wif-pool-ownership.ts b/apps/api/src/services/gcp-wif-pool-ownership.ts index c4a610c294..3c4eae96a7 100644 --- a/apps/api/src/services/gcp-wif-pool-ownership.ts +++ b/apps/api/src/services/gcp-wif-pool-ownership.ts @@ -37,7 +37,9 @@ import { AppError } from '../middleware/error'; import { resolveAdminSetting } from './admin-settings-resolution'; import { decrypt } from './encryption'; import { - CLAIM_POOL_SQL, + CLAIM_NEW_POOL_SQL, + CLAIM_STORED_POOL_SQL, + LIST_UNREADABLE_FOREIGN_ROWS_SQL, POOL_HOLDERS_SQL, READ_CLAIM_SQL, UNINDEXED_ROWS_SQL, @@ -147,12 +149,24 @@ export class GcpWifPoolIndexUnavailableError extends AppError { } } +export class GcpWifPoolOwnershipUnresolvedError extends AppError { + constructor() { + super( + 503, + 'GCP_WIF_POOL_OWNERSHIP_UNRESOLVED', + 'SAM cannot read a stored Google Cloud credential that might use this workload identity pool, so it cannot record a new owner for the pool yet. An administrator must fix the encryption key or remove that credential.' + ); + this.name = 'GcpWifPoolOwnershipUnresolvedError'; + } +} + /** True for the refusals this module raises, which callers must surface unchanged. */ export function isGcpWifPoolOwnershipError(err: unknown): boolean { return ( err instanceof GcpWifPoolOwnedByAnotherOwnerError || err instanceof GcpWifPoolInvalidError || - err instanceof GcpWifPoolIndexUnavailableError + err instanceof GcpWifPoolIndexUnavailableError || + err instanceof GcpWifPoolOwnershipUnresolvedError ); } @@ -254,14 +268,14 @@ function ownerBinds(kind: 'user' | 'platform', userId: string | null): [string, return [kind, userId ?? '']; } -function claimStatement( +function newClaimStatement( env: Env, poolKey: string, kind: 'user' | 'platform', userId: string | null, now: string ): D1PreparedStatement { - return env.DATABASE.prepare(CLAIM_POOL_SQL).bind( + return env.DATABASE.prepare(CLAIM_NEW_POOL_SQL).bind( poolKey, kind, userId, @@ -287,8 +301,8 @@ async function indexRows(env: Env, rows: UnindexedRow[]): Promise { } catch (err) { // An unreadable row cannot be exchanged either. It is retried after // `gcpWif.poolIndexUnreadableRetryMinutes` (a key fix makes it readable without a new IV), - // not on every check. Until then it withholds first claims for other owners - // (CLAIM_POOL_SQL), because it might name the pool being claimed (rule 41, rule 47). + // not on every check. Until then it withholds NEW first claims by other owners + // (CLAIM_NEW_POOL_SQL), because it might name the pool being claimed (rule 41, rule 47). unreadable = 1; log.error('gcp_wif_pool_index.row_unreadable', { sourceTable: row.sourceTable, @@ -309,7 +323,16 @@ async function indexRows(env: Env, rows: UnindexedRow[]): Promise { now ) ); - if (poolKey) statements.push(claimStatement(env, poolKey, row.ownerKind, row.ownerUserId, now)); + if (poolKey) { + statements.push( + env.DATABASE.prepare(CLAIM_STORED_POOL_SQL).bind( + poolKey, + row.ownerKind, + row.ownerUserId, + now + ) + ); + } } if (statements.length > 0) await env.DATABASE.batch(statements); return statements.length; @@ -495,7 +518,7 @@ export async function assertGcpWifPoolOwnership( const [, claimRows] = await runPair( env, [ - claimStatement(env, identity.key, ownerKind, ownerUserId, new Date().toISOString()), + newClaimStatement(env, identity.key, ownerKind, ownerUserId, new Date().toISOString()), env.DATABASE.prepare(READ_CLAIM_SQL).bind(identity.key), ], `${context}:claim` @@ -504,13 +527,23 @@ export async function assertGcpWifPoolOwnership( const [winner] = claim; if (!winner) { // No claim was written: another owner's credential is unreadable and might name this pool. - log.warn('gcp_wif_pool.claim_withheld_unreadable', { + // Needs an operator (fix the key, or remove the corrupt credential), so log it at error level + // with the rows to look at. + const unreadable = await env.DATABASE.prepare(LIST_UNREADABLE_FOREIGN_ROWS_SQL) + .bind(...ownerBinds(ownerKind, ownerUserId)) + .all>() + .then((result) => result.results ?? []) + .catch(() => []); + log.error('gcp_wif_pool.claim_withheld_unreadable', { context, poolKey: identity.key, owner: ownerLabel(owner), + unreadableCredentials: unreadable.map( + (row) => `${String(row.sourceTable)}:${String(row.sourceId)}` + ), action: 'refused', }); - throw new GcpWifPoolIndexUnavailableError(); + throw new GcpWifPoolOwnershipUnresolvedError(); } if (claim.length !== 1) throw new GcpWifPoolIndexUnavailableError(); if (!heldBy(winner, owner)) refuse(context, identity, owner, claim); diff --git a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts index b89002d644..728ce24dea 100644 --- a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -37,6 +37,7 @@ const { credentialsRoutes } = await import('../../../src/routes/credentials'); const { ccRoutes } = await import('../../../src/routes/composable-credentials'); const { runGcpSetup } = await import('../../../src/services/gcp-setup'); const { + GcpWifPoolOwnershipUnresolvedError, assertGcpWifPayloadOwnership, GcpWifPoolIndexUnavailableError, GcpWifPoolInvalidError, @@ -939,14 +940,15 @@ describe('review round 3: unresolved rows, budgets, deletes and deployments', () .run(id, ownerId, foreign.ciphertext, foreign.iv, NOW, NOW); } - it('withholds a first claim while another owner’s credential is unreadable', async () => { + it('withholds a NEW first claim while another owner’s credential is unreadable', async () => { // A's credential for POOL_A cannot be decrypted (for example a key misconfiguration). await storeUnreadableCc('cc-a-unreadable', 'user-a'); vi.spyOn(console, 'error').mockImplementation(() => {}); vi.spyOn(console, 'warn').mockImplementation(() => {}); + // B names POOL_A with a credential SAM has not stored: a new first claim. await expect(exchange(user('user-b'), wif(POOL_A))).rejects.toBeInstanceOf( - GcpWifPoolIndexUnavailableError + GcpWifPoolOwnershipUnresolvedError ); expect(signIdentityToken).not.toHaveBeenCalled(); expect(sqlite.prepare('SELECT count(*) AS n FROM gcp_wif_pool_claims').get()).toEqual({ @@ -1072,3 +1074,74 @@ describe('review round 3: unresolved rows, budgets, deletes and deployments', () expect(google).toHaveBeenCalledTimes(1); }); }); + +describe('an unreadable row does not refuse stored credentials (rule 41)', () => { + it('claims every stored readable credential in the page, before and after the unreadable one', async () => { + const otherKey = Buffer.from('fedcba9876543210fedcba9876543210').toString('base64'); + // Insert order puts the unreadable row between two readable ones of other owners. + await storeCcRow('cc-1-a', 'user-a', JSON.stringify(wif(POOL_A))); + const bad = await encrypt(JSON.stringify(wif(POOL_PLATFORM)), otherKey); + sqlite + .prepare( + `INSERT INTO cc_credentials (id, owner_id, name, kind, encrypted_token, iv, is_active, created_at, updated_at) + VALUES ('cc-2-m', 'user-m', 'x', 'cloud-provider', ?, ?, 1, ?, ?)` + ) + .run(bad.ciphertext, bad.iv, NOW, NOW); + await storeCcRow('cc-3-b', 'user-b', JSON.stringify(wif(POOL_B))); + vi.spyOn(console, 'error').mockImplementation(() => {}); + + // Both stored owners exchange normally despite user-m's unreadable row. + await expect(exchange(user('user-a'), wif(POOL_A))).resolves.toBe('sa-token'); + await expect(exchange(user('user-b'), wif(POOL_B))).resolves.toBe('sa-token'); + expect( + sqlite + .prepare('SELECT pool_key, owner_user_id FROM gcp_wif_pool_claims ORDER BY pool_key') + .all() + ).toEqual([ + { pool_key: '111111111111/sam-pool', owner_user_id: 'user-a' }, + { pool_key: '333333333333/sam-pool', owner_user_id: 'user-b' }, + ]); + }); + + it('a disconnect with another owner’s unreadable row present still leaves the pool claimed', async () => { + const otherKey = Buffer.from('fedcba9876543210fedcba9876543210').toString('base64'); + const bad = await encrypt(JSON.stringify(wif(POOL_PLATFORM)), otherKey); + sqlite + .prepare( + `INSERT INTO cc_credentials (id, owner_id, name, kind, encrypted_token, iv, is_active, created_at, updated_at) + VALUES ('cc-m-bad', 'user-m', 'x', 'cloud-provider', ?, ?, 1, ?, ?)` + ) + .run(bad.ciphertext, bad.iv, NOW, NOW); + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + vi.spyOn(console, 'error').mockImplementation(() => {}); + auth.userId = 'user-a'; + expect( + (await testApp().request('/api/credentials/gcp', { method: 'DELETE' }, env)).status + ).toBe(200); + + auth.userId = 'user-b'; + expect((await postGcpCredential(wif(POOL_A))).status).toBe(409); + }); + + it('replacing a WIF connection with a service-account key keeps the old pool claimed', async () => { + await storeLegacyRow('cred-a', 'user-a', wif(POOL_A)); + await replaceUserGcpCredential(env, 'user-a', { + version: GCP_CREDENTIAL_VERSION, + provider: 'gcp', + authType: 'service-account-key', + gcpProjectId: 'gcp-a', + serviceAccountEmail: 'sa@gcp-a.iam.gserviceaccount.com', + privateKeyId: 'kid', + privateKey: 'not-a-real-key', + defaultZone: 'us-central1-a', + }); + await expect( + assertGcpWifPayloadOwnership( + env, + JSON.stringify(wif(POOL_A)), + { kind: 'user', userId: 'user-b' }, + 't' + ) + ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); + }); +}); diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index f519c09e8c..decda0fc1f 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -306,9 +306,9 @@ SAM signs an identity token for whatever pool a stored WIF credential names, so Where it is enforced: - **At save**: `POST /api/credentials`, the Google setup routes, project cloud credentials, composable credentials and admin platform credentials return `409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`. Guided setup and deployment setup check the pool after reading the project number and before they change anything in Google. Deployment pools are claimed when their setup runs; migration 0262 claims existing ones (a pool with more than one owner gets no claim and stays refused for both). -- **Before a delete**: removing a user, project, composable or platform cloud credential first indexes every unseen credential (`reconcileGcpWifPoolIndex()`), so a disconnect made before any other check after this release still leaves its pool claimed. +- **Before a delete or a switch to a key**: removing a user, project, composable or platform cloud credential, or replacing a user's WIF connection with a service-account key, first indexes and claims every unseen credential (`reconcileGcpWifPoolIndex()`), so a disconnect made before any other check after this release still leaves its pool claimed. Deleting a whole user account or project is not hooked; those credentials are claimed if any check ran first. - **At token exchange**: the same check runs before SAM signs the identity token (`exchangeGcpWifAccessToken()` in `gcp-sts.ts`), so credentials saved before the check existed are refused too. The owner is the stored credential's owner, so a project member using another member's project credential still works. Refusals log `gcp_wif_pool.cross_owner_refused` at warn level. The exchange also refuses a project number with a leading zero, and a provider ID or service-account email that could alter the STS audience or the impersonation URL. -- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the read of the pool's holders, so a writer that skips the index, a rotation or a deletion cannot leave it stale. With nothing new to index a check is one D1 round trip with no decryption. A row that cannot be decrypted is recorded as unreadable, logged, and tried again after `gcpWif.poolIndexUnreadableRetryMinutes`. Until it is read, it might name any pool, so no other owner may make a first claim (they get the retryable 503); pools already claimed are unaffected, and an operator removes a permanently corrupt row. If newly saved rows cannot be indexed within `gcpWif.poolIndexMaxQueriesPerCheck` SQL statements (a page shrinks to fit) or before `gcpWif.poolIndexBudgetMs` (a soft limit on starting another page), or D1 fails or returns an unexpected result while the check runs, it refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index; progress is kept, so the next check continues. +- Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the read of the pool's holders, so a writer that skips the index, a rotation or a deletion cannot leave it stale. With nothing new to index a check is one D1 round trip with no decryption. A row that cannot be decrypted is recorded as unreadable, logged, and tried again after `gcpWif.poolIndexUnreadableRetryMinutes`. Until it is read, it might name any pool, so a new credential of another owner cannot make the first claim of an unclaimed pool (`503 GCP_WIF_POOL_OWNERSHIP_UNRESOLVED`, logged at error level with the unreadable rows). Credentials that are already stored are claimed when they are indexed and keep working, so one bad row cannot refuse existing users. An operator fixes the key or removes a permanently corrupt row. If newly saved rows cannot be indexed within `gcpWif.poolIndexMaxQueriesPerCheck` SQL statements (a page shrinks to fit) or before `gcpWif.poolIndexBudgetMs` (a soft limit on starting another page), or D1 fails or returns an unexpected result while the check runs, it refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index; progress is kept, so the next check continues. The Google side is scoped as well. User-level guided setup creates a provider whose condition is `assertion.iss == '' && assertion.user_id == ''` and grants the service account only to `principalSet://.../workloadIdentityPools//attribute.sam_user/`. Deployment setup uses `assertion.project_id` and `principal://.../subject/project:` (`wifAttributeCondition()`, `wifServiceAccountMember()` in `gcp-wif-setup.ts`). For a user's own credential, user-level or project-scoped, SAM signs `user_id` as the credential owner's id (`gcpIdentityTokenUserId()`), so both match the user-scoped provider. `project_id` (and `sub = project:`) is a SAM project the caller acts for; when the token acts for no SAM project, SAM signs the credential's own Google project as `gcp-project:` (`gcpIdentityTokenProjectId()`), so a value the credential's owner typed can never pass for another user's SAM project at a deployment provider. Platform credentials sign `platform:` and need a pool their installation configured; guided setup does not create one. Setups before this change used an issuer-only condition and a `pool/*` binding. Re-running setup rewrites the provider's condition and removes the `pool/*` member from the service account, including a conditional grant (the policy is read as version 3), keeping other members and IAM conditions. From c422b72e858f90b4d11ed77f2fa42a05ca99b28f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 10:20:10 +0000 Subject: [PATCH 09/13] fix(security): narrow the unreadable-row withhold to GCP rows; fix fixtures - Only an unreadable credential that could be GCP (legacy/platform rows, or a composable row a GCP configuration uses) withholds new claims, so a corrupt credential of another provider cannot block GCP setup. - /api/gcp/verify shows the ownership refusal instead of a generic Google error. - Fixtures: shared migration helper for hand-built SQLite schemas; real ciphertext for placeholder rows in the shared-D1 Workers suite; reconcile spy in the mocked project-credentials route test. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/routes/gcp.ts | 5 ++- .../services/gcp-wif-pool-ownership-sql.ts | 9 ++++-- apps/api/tests/helpers/gcp-wif-pool-tables.ts | 32 +++++++++++++++++++ .../gcp-service-account-vertical.test.ts | 2 ++ .../unit/routes/project-credentials.test.ts | 11 +++++++ .../services/gcp-credential-store.test.ts | 2 ++ .../services/gcp-wif-pool-ownership.test.ts | 24 ++++++++++++-- ...dential-resave-capacity-provenance.test.ts | 20 +++++++++--- 8 files changed, 96 insertions(+), 9 deletions(-) create mode 100644 apps/api/tests/helpers/gcp-wif-pool-tables.ts diff --git a/apps/api/src/routes/gcp.ts b/apps/api/src/routes/gcp.ts index 10d2b0cd07..2cab6daece 100644 --- a/apps/api/src/routes/gcp.ts +++ b/apps/api/src/routes/gcp.ts @@ -303,7 +303,10 @@ gcpRoutes.post('/verify', async (c) => { return c.json({ success: false, verified: false, - error: sanitizeGcpError(err, 'gcp-verify'), + // An ownership refusal is the reason, not a Google failure: say so. + error: isGcpWifPoolOwnershipError(err) + ? (err as Error).message + : sanitizeGcpError(err, 'gcp-verify'), apiIssues: await listGcpApiIssuesSafely(c.env, credentialId, gcpCredential), }); } diff --git a/apps/api/src/services/gcp-wif-pool-ownership-sql.ts b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts index cad871a57c..847878590c 100644 --- a/apps/api/src/services/gcp-wif-pool-ownership-sql.ts +++ b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts @@ -96,7 +96,10 @@ ON CONFLICT (source_table, source_id) DO UPDATE SET iv = excluded.iv, owner_kind = excluded.owner_kind, owner_user_id = excluded.owner_user_id, pool_key = excluded.pool_key, unreadable = excluded.unreadable, indexed_at = excluded.indexed_at`; -// Live credentials of a different owner that could not be decrypted, at their indexed IV. +// Live credentials of a different owner that could not be decrypted, at their indexed IV, and that +// could be GCP credentials: legacy and platform rows are indexed only for provider 'gcp'; a +// composable row counts only when a GCP compute configuration uses it, so a corrupt credential of +// another provider never withholds GCP claims. const UNREADABLE_FOREIGN_ROWS = ` SELECT u.source_table AS sourceTable, u.source_id AS sourceId FROM gcp_wif_pool_index u @@ -108,7 +111,9 @@ SELECT u.source_table AS sourceTable, u.source_id AS sourceId OR (u.source_table = 'platform_credentials' AND EXISTS ( SELECT 1 FROM platform_credentials p WHERE p.id = u.source_id AND p.iv = u.iv)) OR (u.source_table = 'cc_credentials' AND EXISTS ( - SELECT 1 FROM cc_credentials cc WHERE cc.id = u.source_id AND cc.iv = u.iv)) + SELECT 1 FROM cc_credentials cc WHERE cc.id = u.source_id AND cc.iv = u.iv + AND EXISTS (SELECT 1 FROM cc_configurations g + WHERE g.credential_id = cc.id AND g.consumer_target = 'gcp'))) )`; // Index-time claim for a credential that is already stored: first owner wins. Stored rows predate diff --git a/apps/api/tests/helpers/gcp-wif-pool-tables.ts b/apps/api/tests/helpers/gcp-wif-pool-tables.ts new file mode 100644 index 0000000000..9f0e7484ba --- /dev/null +++ b/apps/api/tests/helpers/gcp-wif-pool-tables.ts @@ -0,0 +1,32 @@ +import type Database from 'better-sqlite3'; +import { getTableConfig } from 'drizzle-orm/sqlite-core'; + +import * as schema from '../../src/db/schema'; +import { applySqliteMigration, createSchemaTables } from './sqlite-d1'; + +/** + * Give a hand-built fixture what GCP workload identity pool ownership reads + * (`gcp-wif-pool-ownership.ts`): the real migration 0262, plus any table it or the ownership check + * depends on that the fixture did not create. Tables the fixture already made are left alone. + */ +export function applyGcpWifPoolOwnershipMigration(sqlite: Database.Database): void { + const existing = new Set( + (sqlite.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as Array<{ + name: string; + }>).map((row) => row.name) + ); + const prerequisites = [ + schema.credentials, + schema.platformCredentials, + schema.ccCredentials, + schema.ccConfigurations, + schema.projectDeploymentCredentials, + schema.platformSettings, + ].filter((table) => !existing.has(getTableConfig(table).name)); + createSchemaTables(sqlite, prerequisites); + applySqliteMigration( + sqlite, + new URL('../../src/db/migrations/0262_gcp_wif_pool_index.sql', import.meta.url) + ); +} + diff --git a/apps/api/tests/unit/routes/gcp-service-account-vertical.test.ts b/apps/api/tests/unit/routes/gcp-service-account-vertical.test.ts index e13fc6d5cd..2b26ec5de0 100644 --- a/apps/api/tests/unit/routes/gcp-service-account-vertical.test.ts +++ b/apps/api/tests/unit/routes/gcp-service-account-vertical.test.ts @@ -13,6 +13,7 @@ import type { Env } from '../../../src/env'; import { gcpRoutes } from '../../../src/routes/gcp'; import { decrypt } from '../../../src/services/encryption'; import { parseGcpCredential } from '../../../src/services/provider-credentials'; +import { applyGcpWifPoolOwnershipMigration } from '../../helpers/gcp-wif-pool-tables'; import { googleErrorResponse, googleServiceDisabledBody } from '../../helpers/google-api-errors'; import { createSqliteD1 } from '../../helpers/sqlite-d1'; @@ -58,6 +59,7 @@ function setupDatabase(): Database.Database { ');', ].join('\n') ); + applyGcpWifPoolOwnershipMigration(sqlite); return sqlite; } diff --git a/apps/api/tests/unit/routes/project-credentials.test.ts b/apps/api/tests/unit/routes/project-credentials.test.ts index 8628a0854c..09bf14d295 100644 --- a/apps/api/tests/unit/routes/project-credentials.test.ts +++ b/apps/api/tests/unit/routes/project-credentials.test.ts @@ -21,6 +21,12 @@ import { } from '../../../src/services/composable-credentials/resolve'; vi.mock('drizzle-orm/d1'); +// Pool ownership has its own real-SQL suite; here the database is mocked, so spy on the +// pre-delete reconcile and assert it runs. +vi.mock('../../../src/services/gcp-wif-pool-ownership', async (importOriginal) => ({ + ...(await importOriginal()), + reconcileGcpWifPoolIndex: vi.fn(async () => undefined), +})); vi.mock('../../../src/middleware/auth', () => ({ requireAuth: () => vi.fn((_c: unknown, next: () => unknown) => next()), requireApproved: () => vi.fn((_c: unknown, next: () => unknown) => next()), @@ -487,6 +493,11 @@ describe('Project Credentials Routes', () => { expect(res.status).toBe(200); expect(kv.delete).toHaveBeenCalledWith('gcp-api-health:v1:project-gcp-cred'); + const { reconcileGcpWifPoolIndex } = await import( + '../../../src/services/gcp-wif-pool-ownership' + ); + // The outgoing pool is recorded before the row is deleted (Google may still trust it). + expect(reconcileGcpWifPoolIndex).toHaveBeenCalledWith(env, 'delete_project_gcp_credential'); }); it('does not touch API health records for other providers', async () => { diff --git a/apps/api/tests/unit/services/gcp-credential-store.test.ts b/apps/api/tests/unit/services/gcp-credential-store.test.ts index 380cc81fcd..baec05c887 100644 --- a/apps/api/tests/unit/services/gcp-credential-store.test.ts +++ b/apps/api/tests/unit/services/gcp-credential-store.test.ts @@ -12,6 +12,7 @@ import { replaceUserGcpCredential, } from '../../../src/services/gcp-credential-store'; import { parseGcpCredential } from '../../../src/services/provider-credentials'; +import { applyGcpWifPoolOwnershipMigration } from '../../helpers/gcp-wif-pool-tables'; import { createSqliteD1 } from '../../helpers/sqlite-d1'; const ENCRYPTION_KEY = 'SK4ihJazAK3GIWUQcM6nZ1odR6KQHrqRAVSp6HdPxrg='; @@ -89,6 +90,7 @@ function setupDatabase(): Database.Database { updated_at TEXT NOT NULL ); `); + applyGcpWifPoolOwnershipMigration(sqlite); return sqlite; } diff --git a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts index 728ce24dea..44b839ed1a 100644 --- a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -929,15 +929,26 @@ describe('review round 3: unresolved rows, budgets, deletes and deployments', () .run(key, value, NOW); } - async function storeUnreadableCc(id: string, ownerId: string, pool = POOL_A) { + async function storeUnreadableCc( + id: string, + ownerId: string, + options: { gcpConfiguration: boolean } = { gcpConfiguration: true } + ) { const otherKey = Buffer.from('fedcba9876543210fedcba9876543210').toString('base64'); - const foreign = await encrypt(JSON.stringify(wif(pool)), otherKey); + const foreign = await encrypt(JSON.stringify(wif(POOL_A)), otherKey); sqlite .prepare( `INSERT INTO cc_credentials (id, owner_id, name, kind, encrypted_token, iv, is_active, created_at, updated_at) VALUES (?, ?, 'x', 'cloud-provider', ?, ?, 1, ?, ?)` ) .run(id, ownerId, foreign.ciphertext, foreign.iv, NOW, NOW); + sqlite + .prepare( + `INSERT INTO cc_configurations (id, owner_id, name, consumer_kind, consumer_target, credential_id, + settings_json, is_active, created_at, updated_at) + VALUES (?, ?, 'c', 'compute', ?, ?, NULL, 1, ?, ?)` + ) + .run(`cfg-${id}`, ownerId, options.gcpConfiguration ? 'gcp' : 'hetzner', id, NOW, NOW); } it('withholds a NEW first claim while another owner’s credential is unreadable', async () => { @@ -954,6 +965,15 @@ describe('review round 3: unresolved rows, budgets, deletes and deployments', () expect(sqlite.prepare('SELECT count(*) AS n FROM gcp_wif_pool_claims').get()).toEqual({ n: 0, }); + // Control: an unreadable credential of another provider does not withhold GCP claims. + sqlite.prepare('DELETE FROM cc_configurations').run(); + sqlite.prepare('DELETE FROM cc_credentials').run(); + await storeUnreadableCc('cc-a-hetzner', 'user-a', { gcpConfiguration: false }); + await expect(exchange(user('user-b'), wif(POOL_A))).resolves.toBe('sa-token'); + sqlite.prepare('DELETE FROM gcp_wif_pool_claims').run(); + sqlite.prepare('DELETE FROM cc_configurations').run(); + sqlite.prepare('DELETE FROM cc_credentials').run(); + await storeUnreadableCc('cc-a-unreadable', 'user-a'); // Owner control: the unreadable row's own owner is not blocked by it. await expect(exchange(user('user-a'), wif(POOL_B))).resolves.toBe('sa-token'); await expect(exchange(user('user-a'), wif(POOL_B))).resolves.toBe('sa-token'); diff --git a/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts b/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts index 56528086cf..d47fef9c07 100644 --- a/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts +++ b/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts @@ -32,6 +32,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as schema from '../../src/db/schema'; import type { Env } from '../../src/env'; +import { getCredentialEncryptionKey } from '../../src/lib/secrets'; import { adminPlatformCredentialRoutes } from '../../src/routes/admin-platform-credentials'; import { credentialsRoutes } from '../../src/routes/credentials'; import { gcpRoutes } from '../../src/routes/gcp'; @@ -44,6 +45,7 @@ import { } from '../../src/services/capacity-placement-snapshot'; import { updateDefaultCapacityPool } from '../../src/services/default-capacity-pool-updates'; import { ensureDefaultCapacityPoolsForExistingCredentials } from '../../src/services/default-capacity-pools'; +import { encrypt } from '../../src/services/encryption'; import { handOffEmptyWorkspaceNode } from '../../src/services/node-warm-handoff'; import { resolveTaskStartCapacityPoolSelection, @@ -54,6 +56,16 @@ import { deleteNodeResourcesStrict } from '../../src/services/strict-node-deleti import { seedInstallation, seedNode, seedProject, seedUser } from './helpers/seed-d1'; const workerEnv = env as unknown as Env; + +/** + * Ciphertext for a credential row that exists only for its foreign keys. It must decrypt: the + * suite shares one D1, and an undecryptable GCP row of another owner rightly withholds new + * workload identity pool claims (gcp-wif-pool-ownership.ts). + */ +async function sealedPlaceholder(): Promise<[string, string]> { + const { ciphertext, iv } = await encrypt('placeholder', getCredentialEncryptionKey(workerEnv)); + return [ciphertext, iv]; +} const db = drizzle(env.DATABASE, { schema }); const DAY = 24 * 60 * 60 * 1000; @@ -665,9 +677,9 @@ describe('rows already damaged in the production shape', () => { await env.DATABASE.prepare( `INSERT INTO credentials (id, user_id, provider, credential_type, credential_kind, is_active, encrypted_token, iv, created_at, updated_at) - VALUES (?, ?, 'gcp', 'cloud-provider', 'api-key', 1, 'x', 'y', datetime('now'), datetime('now'))` + VALUES (?, ?, 'gcp', 'cloud-provider', 'api-key', 1, ?, ?, datetime('now'), datetime('now'))` ) - .bind(`${prefix}-cred`, ownerId) + .bind(`${prefix}-cred`, ownerId, ...(await sealedPlaceholder())) .run(); await env.DATABASE.prepare( `INSERT INTO capacity_sources (id, scope, owner_user_id, source_kind, provider, @@ -738,9 +750,9 @@ describe('rows already damaged in the production shape', () => { await env.DATABASE.prepare( `INSERT INTO credentials (id, user_id, provider, credential_type, credential_kind, is_active, encrypted_token, iv, created_at, updated_at) - VALUES (?, ?, 'gcp', 'cloud-provider', 'api-key', 1, 'x', 'y', datetime('now'), datetime('now'))` + VALUES (?, ?, 'gcp', 'cloud-provider', 'api-key', 1, ?, ?, datetime('now'), datetime('now'))` ) - .bind(`${prefix}-proven-cred`, ownerId) + .bind(`${prefix}-proven-cred`, ownerId, ...(await sealedPlaceholder())) .run(); await env.DATABASE.prepare( `INSERT INTO capacity_sources (id, scope, owner_user_id, source_kind, provider, From b7545dac34af769612c270aa3be429b452404f0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 10:25:13 +0000 Subject: [PATCH 10/13] test: keep a reviewed secret-scan fixture line in place The gitleaks baseline digest includes the line number; reuse the existing sqlite-d1 import line instead of adding one above the fixture constant. Co-Authored-By: Claude Opus 5.5 --- .../services/gcp-credential-store.test.ts | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/api/tests/unit/services/gcp-credential-store.test.ts b/apps/api/tests/unit/services/gcp-credential-store.test.ts index baec05c887..564dbfe575 100644 --- a/apps/api/tests/unit/services/gcp-credential-store.test.ts +++ b/apps/api/tests/unit/services/gcp-credential-store.test.ts @@ -12,8 +12,7 @@ import { replaceUserGcpCredential, } from '../../../src/services/gcp-credential-store'; import { parseGcpCredential } from '../../../src/services/provider-credentials'; -import { applyGcpWifPoolOwnershipMigration } from '../../helpers/gcp-wif-pool-tables'; -import { createSqliteD1 } from '../../helpers/sqlite-d1'; +import { applySqliteMigration, createSqliteD1 } from '../../helpers/sqlite-d1'; const ENCRYPTION_KEY = 'SK4ihJazAK3GIWUQcM6nZ1odR6KQHrqRAVSp6HdPxrg='; const USER_ID = 'user-gcp-store'; @@ -89,8 +88,24 @@ function setupDatabase(): Database.Database { created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); + + -- What GCP workload identity pool ownership reads besides the tables above. + CREATE TABLE platform_credentials ( + id TEXT PRIMARY KEY, credential_type TEXT NOT NULL, provider TEXT, + encrypted_token TEXT NOT NULL, iv TEXT NOT NULL + ); + CREATE TABLE project_deployment_credentials ( + id TEXT PRIMARY KEY, project_id TEXT NOT NULL, user_id TEXT NOT NULL, provider TEXT NOT NULL, + gcp_project_number TEXT NOT NULL, wif_pool_id TEXT NOT NULL + ); + CREATE TABLE platform_settings ( + key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL, updated_by TEXT + ); `); - applyGcpWifPoolOwnershipMigration(sqlite); + applySqliteMigration( + sqlite, + new URL('../../../src/db/migrations/0262_gcp_wif_pool_index.sql', import.meta.url) + ); return sqlite; } From 5dff4f10a59c4a805ee711cfef280c790d2d57a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 10:43:07 +0000 Subject: [PATCH 11/13] fix(security): unconditional WIF grant check; deployment owner on persist - grantWifUserOnSa counts the scoped member as granted only in an unconditional binding, so a conditional grant cannot satisfy setup. - Deployment setup persists the owner whose pool claim it checked, so a concurrent first setup by another member cannot leave a mismatched row. - Docs: deployment-pool ownership per Google Cloud project; residual for the first reconciliation after an upgrade with an unreadable row. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/routes/project-deployment.ts | 5 +++- apps/api/src/services/gcp-wif-setup.ts | 3 ++- .../unit/services/gcp-wif-scoping.test.ts | 24 +++++++++++++++++++ .../docs/docs/architecture/security.md | 1 + .../content/docs/docs/guides/self-hosting.mdx | 2 +- 5 files changed, 32 insertions(+), 3 deletions(-) diff --git a/apps/api/src/routes/project-deployment.ts b/apps/api/src/routes/project-deployment.ts index b9b993e148..79dc0b47b1 100644 --- a/apps/api/src/routes/project-deployment.ts +++ b/apps/api/src/routes/project-deployment.ts @@ -237,6 +237,9 @@ projectDeploymentRoutes.post( await db .update(schema.projectDeploymentCredentials) .set({ + // The owner whose pool claim was checked above, so a concurrent first setup by + // another member cannot leave this row naming a pool its owner does not hold. + userId: poolOwnerUserId, gcpProjectId: result.gcpProjectId, gcpProjectNumber: result.gcpProjectNumber, serviceAccountEmail: result.serviceAccountEmail, @@ -249,7 +252,7 @@ projectDeploymentRoutes.post( await db.insert(schema.projectDeploymentCredentials).values({ id: ulid(), projectId, - userId, + userId: poolOwnerUserId, provider: 'gcp', gcpProjectId: result.gcpProjectId, gcpProjectNumber: result.gcpProjectNumber, diff --git a/apps/api/src/services/gcp-wif-setup.ts b/apps/api/src/services/gcp-wif-setup.ts index 5e9de9f129..3469168f7a 100644 --- a/apps/api/src/services/gcp-wif-setup.ts +++ b/apps/api/src/services/gcp-wif-setup.ts @@ -396,7 +396,8 @@ export async function grantWifUserOnSa( // while `pool/*` stays, any provider in the pool that still trusts SAM's issuer alone lets // every SAM user impersonate this service account. const roleBindings = (policy.bindings || []).filter((b) => b.role === role); - const granted = roleBindings.some((b) => b.members.includes(member)); + // Only an unconditional grant counts: a member under someone's IAM condition may be denied. + const granted = roleBindings.some((b) => b.condition === undefined && b.members.includes(member)); const legacyPresent = roleBindings.some((b) => b.members.includes(legacyMember)); if (granted && !legacyPresent) { return; // Already granted, nothing to remove diff --git a/apps/api/tests/unit/services/gcp-wif-scoping.test.ts b/apps/api/tests/unit/services/gcp-wif-scoping.test.ts index 834103bd45..5c63cabd99 100644 --- a/apps/api/tests/unit/services/gcp-wif-scoping.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-scoping.test.ts @@ -273,6 +273,30 @@ describe('WIF trust scoping (cross-owner impersonation prevention)', () => { ]); }); + it('a conditional grant of the scoped member does not count as granted', async () => { + const condition = { + title: 'expires', + expression: 'request.time < timestamp("2030-01-01T00:00:00Z")', + }; + await grant([ + { + role: WIF_ROLE, + members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`], + condition, + } as PolicyBinding, + ]); + + expect(mockFetch).toHaveBeenCalledTimes(2); + expect(setPolicyBindings(1)).toEqual([ + { + role: WIF_ROLE, + members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`], + condition, + }, + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`] }, + ]); + }); + it('leaves the policy untouched when already scoped and no wildcard remains', async () => { mockFetch.mockResolvedValueOnce( mockGcpResponse({ diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index decda0fc1f..9a40f7581b 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -316,6 +316,7 @@ Residual risks: - **Pools SAM has never recorded.** The Worker check protects every pool a stored credential has ever named, including after a disconnect. It cannot protect a pool SAM has no record of whose Google trust is still issuer-only with `pool/*` (a guided setup from before this change whose credential was removed before this release, or a platform pool created in Google before the platform credential is saved). Whoever names such a pool first claims it, and that is impersonation, not only denial of service. Re-run setup for old connections, and save a platform credential as soon as its pool exists. Probing Google for issuer-only trust before a first claim is tracked in `tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md`. - **First claim wins.** A user who knows another person's Google Cloud project number can save a credential naming that pool before its owner connects, which blocks the owner's setup or the platform credential. The `409` also tells the caller that another SAM owner uses that project. An operator resolves a squat by deleting the squatting credential and then the claim. +- **First reconciliation after an upgrade.** Stored credentials are claimed in the order SAM indexes them. If a cross-owner pair already existed before this release and the victim's row cannot be decrypted at that moment, the other owner's row can take the claim. The production audit for this release found no cross-owner pairs. Self-hosters upgrading with a broken encryption key should fix the key before the first GCP use. - **Cached tokens.** The check runs when SAM mints a token, not on a token-cache hit, so a token minted before a conflict appeared stays usable until `GCP_TOKEN_CACHE_TTL_SECONDS` ends. ## Terminal Authentication diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index 08143515a6..9be14e5c2c 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -456,7 +456,7 @@ Several SAM installations can connect the same Google Cloud project. A workload Each user-level connection is scoped to the SAM user who made it. The provider's condition requires `assertion.user_id == ''`, and the service account is granted to `principalSet://iam.googleapis.com/projects//locations/global/workloadIdentityPools//attribute.sam_user/` (`wifAttributeCondition()` and `wifServiceAccountMember()` in `apps/api/src/services/gcp-wif-setup.ts`). Connections made before this scoping used an issuer-only condition and a `pool/*` binding, which let any user of the installation who named the pool act as its service account. **Re-run Google setup** on each such connection: it rewrites the provider's condition and removes the `pool/*` member. If another installation shared that service account through `pool/*`, re-run that installation's setup too, so it gets its own scoped binding. A platform GCP workload identity credential needs a pool the installation configures for it; the guided setup only creates user-scoped pools. -Within one installation a pool has one owner: one user, or the installation for platform credentials. SAM refuses to save, or to exchange tokens for, a credential naming a pool that another owner claimed or that a different owner's credential names (`409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`; see [Security](/docs/architecture/security/#one-owner-per-workload-identity-pool)). Give every user and the platform credential its own Google Cloud project or pool. +Within one installation a pool has one owner: one user, or the installation for platform credentials. SAM refuses to save, or to exchange tokens for, a credential naming a pool that another owner claimed or that a different owner's credential names (`409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`; see [Security](/docs/architecture/security/#one-owner-per-workload-identity-pool)). Give every user and the platform credential its own Google Cloud project or pool. The same applies to app deployments: the first SAM user to connect deployments in a Google Cloud project owns that project's deployment pool (`GCP_DEPLOY_WIF_POOL_ID`), and a different user's deployment setup in the same project is refused before it changes anything in Google. Project members re-running setup act as the original owner. A claim stays after its credential is deleted, because the Google-side trust may stay too. Deleting a SAM account leaves its claims behind for the same reason. To hand a pool to a different owner (for example after a Google Cloud project changes hands): From a162c1a76aa605de5d62d8b4d616600c4a9de885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 11:04:10 +0000 Subject: [PATCH 12/13] fix: reconcile WIF pools only before deleting a credential that can name one Agent keys and non-GCP platform credentials no longer pay for, or wait on, pool reconciliation when deleted. Co-Authored-By: Claude Opus 5.5 --- .../src/routes/admin-platform-credentials.ts | 14 +++++++-- apps/api/src/routes/composable-credentials.ts | 13 ++++++-- .../services/gcp-wif-pool-ownership.test.ts | 31 +++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/apps/api/src/routes/admin-platform-credentials.ts b/apps/api/src/routes/admin-platform-credentials.ts index 244cab4598..4bc397b197 100644 --- a/apps/api/src/routes/admin-platform-credentials.ts +++ b/apps/api/src/routes/admin-platform-credentials.ts @@ -246,8 +246,18 @@ adminPlatformCredentialRoutes.patch( adminPlatformCredentialRoutes.delete('/:id', async (c) => { const credentialId = c.req.param('id'); const db = drizzle(c.env.DATABASE, { schema }); - // Record the pool a GCP platform credential names before it goes: Google may still trust it. - await reconcileGcpWifPoolIndex(c.env, 'delete_platform_credential'); + const [target] = await db + .select({ + credentialType: schema.platformCredentials.credentialType, + provider: schema.platformCredentials.provider, + }) + .from(schema.platformCredentials) + .where(eq(schema.platformCredentials.id, credentialId)) + .limit(1); + if (target?.credentialType === 'cloud-provider' && target.provider === 'gcp') { + // Record the pool a GCP platform credential names before it goes: Google may still trust it. + await reconcileGcpWifPoolIndex(c.env, 'delete_platform_credential'); + } const result = await db .delete(schema.platformCredentials) diff --git a/apps/api/src/routes/composable-credentials.ts b/apps/api/src/routes/composable-credentials.ts index 41abda79dc..e385197fa3 100644 --- a/apps/api/src/routes/composable-credentials.ts +++ b/apps/api/src/routes/composable-credentials.ts @@ -246,9 +246,16 @@ ccRoutes.delete('/credentials/:id', async (c) => { const { id } = c.req.param(); const affectedProjectIds = await listAffectedCredentialProjectIds(db, userId, id); - // A cloud credential may name a GCP pool; record it before the row goes (Google may still - // trust it). One D1 batch when nothing is unindexed. - await reconcileGcpWifPoolIndex(c.env, 'delete_composable_credential'); + const [target] = await db + .select({ kind: schema.ccCredentials.kind }) + .from(schema.ccCredentials) + .where(and(eq(schema.ccCredentials.id, id), eq(schema.ccCredentials.ownerId, userId))) + .limit(1); + if (target?.kind === 'cloud-provider') { + // A cloud credential may name a GCP pool; record it before the row goes (Google may still + // trust it). Agent keys and other kinds skip this. + await reconcileGcpWifPoolIndex(c.env, 'delete_composable_credential'); + } const result = await db .delete(schema.ccCredentials) diff --git a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts index 44b839ed1a..ab87557051 100644 --- a/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -1165,3 +1165,34 @@ describe('an unreadable row does not refuse stored credentials (rule 41)', () => ).rejects.toBeInstanceOf(GcpWifPoolOwnedByAnotherOwnerError); }); }); + +describe('deletes reconcile only for credentials that can name a GCP pool', () => { + it('an agent-key delete never waits on pool reconciliation', async () => { + sqlite + .prepare( + `INSERT INTO cc_credentials (id, owner_id, name, kind, encrypted_token, iv, is_active, created_at, updated_at) + VALUES ('cc-agent', 'user-a', 'claude', 'api-key', 'x', 'y', 1, ?, ?)` + ) + .run(NOW, NOW); + // Pool reconciliation would fail closed (503) if it ran. + vi.spyOn(env.DATABASE, 'batch').mockRejectedValue(new Error('D1 unavailable')); + vi.spyOn(console, 'error').mockImplementation(() => {}); + auth.userId = 'user-a'; + + const res = await testApp().request('/api/cc/credentials/cc-agent', { method: 'DELETE' }, env); + expect(res.status).toBe(200); + }); + + it('control: a cloud-provider composable delete still reconciles first (and refuses while it cannot)', async () => { + await storeCcRow('cc-cloud', 'user-a', JSON.stringify(wif(POOL_A))); + vi.spyOn(env.DATABASE, 'batch').mockRejectedValue(new Error('D1 unavailable')); + vi.spyOn(console, 'error').mockImplementation(() => {}); + auth.userId = 'user-a'; + + const res = await testApp().request('/api/cc/credentials/cc-cloud', { method: 'DELETE' }, env); + expect(res.status).toBe(503); + expect( + sqlite.prepare("SELECT count(*) AS n FROM cc_credentials WHERE id = 'cc-cloud'").get() + ).toEqual({ n: 1 }); + }); +}); From cdffcc99bdf9fcf10857b04a187239f61cfa4155 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 11:23:03 +0000 Subject: [PATCH 13/13] fix(security): record GCP pools before a project deletion cascades its credentials Co-Authored-By: Claude Opus 5.5 --- apps/api/src/routes/projects/crud.ts | 15 +++++++ .../routes/project-delete-real-sql.test.ts | 40 +++++++++++++++++++ .../tests/unit/routes/project-delete.test.ts | 6 ++- .../docs/docs/architecture/security.md | 2 +- 4 files changed, 61 insertions(+), 2 deletions(-) diff --git a/apps/api/src/routes/projects/crud.ts b/apps/api/src/routes/projects/crud.ts index 37ab252899..588ab9dc21 100644 --- a/apps/api/src/routes/projects/crud.ts +++ b/apps/api/src/routes/projects/crud.ts @@ -17,6 +17,7 @@ import { deleteProjectLibraryObjects, getProjectDeleteCleanupBatchSize, } from '../../services/file-library'; +import { reconcileGcpWifPoolIndex } from '../../services/gcp-wif-pool-ownership'; import { resolveArtifactsBackendForCleanup } from '../../services/hosted-git/backend'; import { getRuntimeLimits } from '../../services/limits'; import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history'; @@ -160,6 +161,20 @@ crudRoutes.delete('/:id', async (c) => { const project = await requireProjectCapability(db, projectId, userId, 'project:delete'); await assertNoReservedCloudflareBuilds(db, { projectId }); + // Deleting the project deletes its GCP cloud credentials. Record the pools they name first: + // Google may still trust them after the rows are gone (gcp-wif-pool-ownership.ts). + const [gcpCredential] = await db + .select({ id: schema.credentials.id }) + .from(schema.credentials) + .where( + and( + eq(schema.credentials.projectId, projectId), + eq(schema.credentials.provider, 'gcp'), + eq(schema.credentials.credentialType, 'cloud-provider') + ) + ) + .limit(1); + if (gcpCredential) await reconcileGcpWifPoolIndex(c.env, 'delete_project'); // Explicitly delete child records instead of relying on D1 CASCADE. // SQLite ignores REFERENCES constraints added via ALTER TABLE, so diff --git a/apps/api/tests/unit/routes/project-delete-real-sql.test.ts b/apps/api/tests/unit/routes/project-delete-real-sql.test.ts index 2e92f4c52e..d52ad6077e 100644 --- a/apps/api/tests/unit/routes/project-delete-real-sql.test.ts +++ b/apps/api/tests/unit/routes/project-delete-real-sql.test.ts @@ -139,6 +139,46 @@ describe('DELETE /api/projects/:id library cleanup — real SQL vertical slice', expect(deletedObjects).toEqual([]); }); + it('records the GCP pool a deleted project credential names before the cascade', async () => { + addProject(PROJECT_A, OWNER_A); + const key = Buffer.from('0123456789abcdef0123456789abcdef').toString('base64'); + (env as { ENCRYPTION_KEY?: string }).ENCRYPTION_KEY = key; + const { encrypt } = await import('../../../src/services/encryption'); + const sealed = await encrypt( + JSON.stringify({ + version: 1, + provider: 'gcp', + authType: 'workload-identity', + gcpProjectId: 'gcp-a', + gcpProjectNumber: '111111111111', + serviceAccountEmail: 'sam@gcp-a.iam.gserviceaccount.com', + wifPoolId: 'sam-pool', + wifProviderId: 'sam-provider', + defaultZone: 'us-central1-a', + }), + key + ); + sqlite + .prepare( + `INSERT INTO credentials (id, user_id, project_id, provider, credential_type, credential_kind, + is_active, encrypted_token, iv, created_at, updated_at) + VALUES ('cred-project-a', ?, ?, 'gcp', 'cloud-provider', 'api-key', 1, ?, ?, 'now', 'now')` + ) + .run(OWNER_A, PROJECT_A, sealed.ciphertext, sealed.iv); + + const response = await app.fetch( + new Request(`https://api.test/api/projects/${PROJECT_A}`, { method: 'DELETE' }), + env, + { waitUntil: () => undefined, passThroughOnException: vi.fn() } as unknown as ExecutionContext + ); + + expect(response.status).toBe(200); + // Google may still trust this pool after the row is gone, so it stays claimed by its owner. + expect(sqlite.prepare('SELECT pool_key, owner_user_id FROM gcp_wif_pool_claims').all()).toEqual( + [{ pool_key: '111111111111/sam-pool', owner_user_id: OWNER_A }] + ); + }); + it('deletes project A rows and R2 keys through the route while project B is untouched', async () => { addProject(PROJECT_A, OWNER_A); addProject(PROJECT_B, 'user-b'); diff --git a/apps/api/tests/unit/routes/project-delete.test.ts b/apps/api/tests/unit/routes/project-delete.test.ts index 14a66c1a2d..4958096502 100644 --- a/apps/api/tests/unit/routes/project-delete.test.ts +++ b/apps/api/tests/unit/routes/project-delete.test.ts @@ -48,7 +48,11 @@ describe('DELETE /api/projects/:id', () => { const selectChain: any = {}; let reservationQuery = false; selectChain.from = vi.fn((table: any) => { - reservationQuery = table?.[Symbol.for('drizzle:Name')] === 'deployment_publish_jobs'; + // Reservation and GCP-credential pre-checks answer "none" and do not consume the + // queued results the task queries expect. + reservationQuery = ['deployment_publish_jobs', 'credentials'].includes( + table?.[Symbol.for('drizzle:Name')] + ); return selectChain; }); selectChain.where = vi.fn(() => selectChain); diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index 9a40f7581b..3d1bb56ebb 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -306,7 +306,7 @@ SAM signs an identity token for whatever pool a stored WIF credential names, so Where it is enforced: - **At save**: `POST /api/credentials`, the Google setup routes, project cloud credentials, composable credentials and admin platform credentials return `409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER`. Guided setup and deployment setup check the pool after reading the project number and before they change anything in Google. Deployment pools are claimed when their setup runs; migration 0262 claims existing ones (a pool with more than one owner gets no claim and stays refused for both). -- **Before a delete or a switch to a key**: removing a user, project, composable or platform cloud credential, or replacing a user's WIF connection with a service-account key, first indexes and claims every unseen credential (`reconcileGcpWifPoolIndex()`), so a disconnect made before any other check after this release still leaves its pool claimed. Deleting a whole user account or project is not hooked; those credentials are claimed if any check ran first. +- **Before a delete or a switch to a key**: removing a user, project, composable (cloud-provider) or GCP platform cloud credential, or replacing a user's WIF connection with a service-account key, first indexes and claims every unseen credential (`reconcileGcpWifPoolIndex()`), so a disconnect made before any other check after this release still leaves its pool claimed. Deleting a project that holds GCP cloud credentials does the same before the cascade. SAM has no account-deletion route. - **At token exchange**: the same check runs before SAM signs the identity token (`exchangeGcpWifAccessToken()` in `gcp-sts.ts`), so credentials saved before the check existed are refused too. The owner is the stored credential's owner, so a project member using another member's project credential still works. Refusals log `gcp_wif_pool.cross_owner_refused` at warn level. The exchange also refuses a project number with a leading zero, and a provider ID or service-account email that could alter the STS audience or the impersonation URL. - Pool identities sit inside encrypted payloads, so the Worker keeps an index (`gcp_wif_pool_index`, migration 0262) of the pool each stored credential names, keyed by the row's IV. Each check first indexes rows it has not seen, in the same D1 batch as the read of the pool's holders, so a writer that skips the index, a rotation or a deletion cannot leave it stale. With nothing new to index a check is one D1 round trip with no decryption. A row that cannot be decrypted is recorded as unreadable, logged, and tried again after `gcpWif.poolIndexUnreadableRetryMinutes`. Until it is read, it might name any pool, so a new credential of another owner cannot make the first claim of an unclaimed pool (`503 GCP_WIF_POOL_OWNERSHIP_UNRESOLVED`, logged at error level with the unreadable rows). Credentials that are already stored are claimed when they are indexed and keep working, so one bad row cannot refuse existing users. An operator fixes the key or removes a permanently corrupt row. If newly saved rows cannot be indexed within `gcpWif.poolIndexMaxQueriesPerCheck` SQL statements (a page shrinks to fit) or before `gcpWif.poolIndexBudgetMs` (a soft limit on starting another page), or D1 fails or returns an unexpected result while the check runs, it refuses (`503 GCP_WIF_POOL_INDEX_UNAVAILABLE`) rather than trust a partial index; progress is kept, so the next check continues.