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..1fd98b0f98 --- /dev/null +++ b/apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql @@ -0,0 +1,62 @@ +-- 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, + iv TEXT NOT NULL, + 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; +-- 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 +-- 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; + +-- 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 + 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/admin-platform-credentials.ts b/apps/api/src/routes/admin-platform-credentials.ts index 49dfe9d961..4bc397b197 100644 --- a/apps/api/src/routes/admin-platform-credentials.ts +++ b/apps/api/src/routes/admin-platform-credentials.ts @@ -25,6 +25,8 @@ 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 { reconcileGcpWifPoolIndex } from '../services/gcp-wif-pool-ownership'; import { buildProviderConfig } from '../services/provider-credentials'; import { CredentialValidator } from '../services/validation'; @@ -124,6 +126,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); @@ -233,6 +246,18 @@ adminPlatformCredentialRoutes.patch( adminPlatformCredentialRoutes.delete('/:id', async (c) => { const credentialId = c.req.param('id'); const db = drizzle(c.env.DATABASE, { schema }); + 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 9ccc22fcce..e385197fa3 100644 --- a/apps/api/src/routes/composable-credentials.ts +++ b/apps/api/src/routes/composable-credentials.ts @@ -24,6 +24,8 @@ 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 { reconcileGcpWifPoolIndex } from '../services/gcp-wif-pool-ownership'; import { registerCCAttachmentRoutes, uniqueProjectIds } from './composable-credentials-attachments'; import { registerCCProfileAttachmentRoutes } from './composable-credentials-profile-attachments'; @@ -186,6 +188,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()}`; @@ -236,6 +246,16 @@ ccRoutes.delete('/credentials/:id', async (c) => { const { id } = c.req.param(); const affectedProjectIds = await listAffectedCredentialProjectIds(db, userId, id); + 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/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/gcp.ts b/apps/api/src/routes/gcp.ts index d6b9b4750b..2cab6daece 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 { cacheUserId: 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,16 +289,24 @@ 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({ 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/routes/project-deployment.ts b/apps/api/src/routes/project-deployment.ts index 22b257823b..79dc0b47b1 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, undefined, 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'); } @@ -212,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, @@ -224,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/routes/projects/credentials.ts b/apps/api/src/routes/projects/credentials.ts index 971f061913..584a5d8952 100644 --- a/apps/api/src/routes/projects/credentials.ts +++ b/apps/api/src/routes/projects/credentials.ts @@ -53,6 +53,8 @@ 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 { reconcileGcpWifPoolIndex } from '../../services/gcp-wif-pool-ownership'; import { serializeCredentialToken } from '../../services/provider-credentials'; import { CredentialValidator, @@ -299,6 +301,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 @@ -403,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/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/src/services/admin-settings-gcp-catalog-definitions.ts b/apps/api/src/services/admin-settings-gcp-catalog-definitions.ts index c7beb44a41..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,6 +8,13 @@ import { import { type AdminSettingDefinition, integerDefinition } from './admin-setting-definitions'; +/** Defaults for the workload identity pool index (`gcp-wif-pool-ownership.ts`). */ +export const DEFAULT_GCP_WIF_POOL_INDEX_PAGE_SIZE = 25; +/** 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; +export const DEFAULT_GCP_WIF_POOL_INDEX_MAX_QUERIES_PER_CHECK = 500; + export type GcpCatalogSettingName = | 'gcpCatalog.machineTypes' | 'gcpCatalog.priceTableTtlMinutes' @@ -18,7 +25,11 @@ export type GcpCatalogSettingName = | 'gcpCatalog.priceRefreshBudgetMs' | 'gcpCatalog.apiIssueTtlMinutes' | 'gcpCatalog.bootDiskGbPerVcpu' - | 'gcpCatalog.bootDiskMinGb'; + | 'gcpCatalog.bootDiskMinGb' + | 'gcpWif.poolIndexPageSize' + | 'gcpWif.poolIndexBudgetMs' + | 'gcpWif.poolIndexUnreadableRetryMinutes' + | 'gcpWif.poolIndexMaxQueriesPerCheck'; /** * General-purpose shapes SAM offers from Google Cloud by default: shared-core e2-medium, and the @@ -123,4 +134,37 @@ 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. 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, + 'Operations', + 'Stored cloud credentials SAM decrypts per step when indexing which Google Cloud workload identity pool each one names.', + { min: 5, max: 50 } + ), + integerDefinition( + 'gcpWif.poolIndexBudgetMs', + 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 } + ), + 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. 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 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-credential-store.ts b/apps/api/src/services/gcp-credential-store.ts index abecd537d0..de96a072c2 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, reconcileGcpWifPoolIndex } from './gcp-wif-pool-ownership'; import { serializeGcpCredential } from './provider-credentials'; export interface StoredGcpCredentialResult { @@ -110,6 +111,18 @@ 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' + ); + } 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(); 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..ed75e73fbf 100644 --- a/apps/api/src/services/gcp-deploy-setup.ts +++ b/apps/api/src/services/gcp-deploy-setup.ts @@ -48,9 +48,18 @@ export async function runGcpDeploySetup( oauthToken: string, gcpProjectId: string, env: Env, - onProgress?: SetupProgressCallback, - samProjectId?: string + samProjectId: string, + 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) : DEFAULT_GCP_API_TIMEOUT_MS; @@ -65,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'); @@ -85,7 +95,7 @@ export async function runGcpDeploySetup( providerId, issuerUri, timeoutMs, - samProjectId + trustScope ); onProgress?.('create_oidc_provider', 'done'); @@ -110,7 +120,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..8f677b28d9 100644 --- a/apps/api/src/services/gcp-sts.ts +++ b/apps/api/src/services/gcp-sts.ts @@ -23,8 +23,50 @@ import { exchangeGcpServiceAccountAccessToken, type GcpAccessTokenResult, } from './gcp-service-account'; +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 the token cache is keyed on: the user id, `project::` or + * `platform:`. For platform credentials it is also the token's `user_id` claim. + */ + 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; +} + +/** + * 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; @@ -129,7 +171,7 @@ export interface GcpAccessTokenOptions { * encrypted D1 storage. */ export async function getGcpAccessToken( - userId: string, + requester: GcpTokenRequester, projectId: string, credential: GcpCredential, env: Env, @@ -137,6 +179,7 @@ export async function getGcpAccessToken( options: GcpAccessTokenOptions = {} ): Promise { throwIfProviderRequestAborted(context); + 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 @@ -149,7 +192,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 +211,7 @@ export async function getGcpAccessToken( } async function exchangeGcpWifAccessToken( - userId: string, + requester: GcpTokenRequester, projectId: string, credential: GcpOidcCredential, env: Env, @@ -188,7 +231,19 @@ 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. + assertGcpWifCredentialShape(credential); + await assertGcpWifPoolOwnership(env, credential, requester.poolOwner, 'token_exchange'); + throwIfProviderRequestAborted(context); + const identityToken = await signIdentityToken( + { + userId: gcpIdentityTokenUserId(requester), + projectId: gcpIdentityTokenProjectId(projectId, credential), + audience: jwtAudience, + }, + env + ); const stsResponse = await fetchWithTimeout( gcpStsUrl, @@ -272,12 +327,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..e047cb2c82 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 cacheUserId = + owner.credentialSource === 'platform' + ? `platform:${owner.userId}` + : owner.credentialSource === 'project' && owner.projectId + ? `project:${owner.projectId}:${owner.userId}` + : owner.userId; + return { + cacheUserId, + 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-sql.ts b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts new file mode 100644 index 0000000000..847878590c --- /dev/null +++ b/apps/api/src/services/gcp-wif-pool-ownership-sql.ts @@ -0,0 +1,147 @@ +/** + * 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 ?`; + +// 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; 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 * 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 * 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 = ` +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`; + +// 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 + 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 + 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 +// 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_NEW_POOL_SQL = ` +INSERT INTO gcp_wif_pool_claims (pool_key, owner_kind, owner_user_id, claimed_at) +SELECT ?, ?, ?, ? + 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, + 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 new file mode 100644 index 0000000000..3c4eae96a7 --- /dev/null +++ b/apps/api/src/services/gcp-wif-pool-ownership.ts @@ -0,0 +1,571 @@ +/** + * 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. + * 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, 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. + * + * 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 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 { resolveAdminSetting } from './admin-settings-resolution'; +import { decrypt } from './encryption'; +import { + CLAIM_NEW_POOL_SQL, + CLAIM_STORED_POOL_SQL, + LIST_UNREADABLE_FOREIGN_ROWS_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. */ +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 and claim key. */ + key: string; +} + +// 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 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 + * (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 already 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, 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'; + } +} + +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'; + } +} + +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 GcpWifPoolOwnershipUnresolvedError + ); +} + +type SourceTable = 'credentials' | 'platform_credentials' | 'cc_credentials'; + +interface UnindexedRow { + sourceTable: SourceTable; + sourceId: string; + ownerKind: 'user' | 'platform'; + ownerUserId: string | null; + encryptedToken: string; + iv: string; +} + +interface PoolHolderRow { + sourceTable: string; + sourceId: string; + ownerKind: 'user' | 'platform'; + ownerUserId: string | null; +} + +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' || + typeof encryptedToken !== 'string' || + typeof iv !== 'string' + ) { + return null; + } + 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 toPoolHolderRow(row: Record): PoolHolderRow | 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 }; +} + +/** + * 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[], + 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 heldBy(row: PoolHolderRow, owner: GcpWifPoolOwner): boolean { + if (owner.kind === 'platform') return row.ownerKind === 'platform'; + return row.ownerKind === 'user' && row.ownerUserId === owner.userId; +} + +function ownerColumns(owner: GcpWifPoolOwner): ['user' | 'platform', string | null] { + return owner.kind === 'platform' ? ['platform', null] : ['user', owner.userId]; +} + +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 newClaimStatement( + env: Env, + poolKey: string, + kind: 'user' | 'platform', + userId: string | null, + now: string +): D1PreparedStatement { + return env.DATABASE.prepare(CLAIM_NEW_POOL_SQL).bind( + poolKey, + kind, + userId, + now, + ...ownerBinds(kind, userId) + ); +} + +/** + * 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 { + 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. It is retried after + // `gcpWif.poolIndexUnreadableRetryMinutes` (a key fix makes it readable without a new IV), + // 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, + sourceId: row.sourceId, + error: err instanceof Error ? err.message : String(err), + action: 'indexed_unreadable', + }); + } + statements.push( + env.DATABASE.prepare(UPSERT_INDEX_SQL).bind( + row.sourceTable, + row.sourceId, + row.iv, + row.ownerKind, + row.ownerUserId, + poolKey, + unreadable, + 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; +} + +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'), + resolveAdminSetting(env, 'gcpWif.poolIndexUnreadableRetryMinutes'), + resolveAdminSetting(env, 'gcpWif.poolIndexMaxQueriesPerCheck'), + ]); + return { + pageSize: Number(pageSize), + budgetMs: Number(budgetMs), + retryMinutes: Number(retryMinutes), + maxQueries: Number(maxQueries), + }; +} + +/** A two-statement batch whose statements both returned row arrays; anything else fails closed. */ +async function runPair( + env: Env, + statements: [D1PreparedStatement, D1PreparedStatement], + context: string +): 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)) { + log.error('gcp_wif_pool_index.batch_malformed', { context, action: 'refused' }); + throw new GcpWifPoolIndexUnavailableError(); + } + return [first, second]; +} + +// 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 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 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 [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) { + if (indexedAny) log.info('gcp_wif_pool_index.reconciled', { context }); + return holderRows; + } + // 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', { + context, + budgetMs: settings.budgetMs, + queries, + maxQueries: settings.maxQueries, + remainingPage: unindexed.length, + action: 'refused', + }); + throw new GcpWifPoolIndexUnavailableError(); + } + try { + queries += await indexRows(env, unindexed.slice(0, fits)); + } catch (err) { + log.error('gcp_wif_pool_index.index_write_failed', { + context, + error: err instanceof Error ? err.message : String(err), + action: 'refused', + }); + throw new GcpWifPoolIndexUnavailableError(); + } + indexedAny = true; + } +} + +/** + * Index every stored cloud credential SAM has not seen, recording claims for the pools they + * name. Credential removal routes call this before they delete a row, so a disconnect made before + * any other check after this release still leaves its pool claimed (Google may still trust it). + */ +export async function reconcileGcpWifPoolIndex(env: Env, context: string): Promise { + await reconcileIndex(env, null, context); +} + +function refuse( + context: string, + pool: GcpWifPoolIdentity, + owner: GcpWifPoolOwner, + foreign: PoolHolderRow[] +): never { + // A designed refusal, logged at warn (rule 34): one line per refused attempt. + log.warn('gcp_wif_pool.cross_owner_refused', { + context, + poolKey: pool.key, + owner: ownerLabel(owner), + conflicting: foreign.map((row) => `${row.sourceTable}:${row.sourceId}`), + conflictingOwnerKinds: [...new Set(foreign.map((row) => row.ownerKind))], + action: 'refused', + }); + throw new GcpWifPoolOwnedByAnotherOwnerError(); +} + +/** + * 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, + pool: { gcpProjectNumber: string; wifPoolId: string }, + owner: GcpWifPoolOwner, + context: string +): Promise { + const identity = gcpWifPoolIdentity(pool.gcpProjectNumber, pool.wifPoolId); + if (!identity) { + log.warn('gcp_wif_pool.invalid_identity', { + context, + owner: ownerLabel(owner), + action: 'refused', + }); + throw new GcpWifPoolInvalidError(); + } + 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 [, claimRows] = await runPair( + env, + [ + newClaimStatement(env, identity.key, ownerKind, ownerUserId, new Date().toISOString()), + env.DATABASE.prepare(READ_CLAIM_SQL).bind(identity.key), + ], + `${context}:claim` + ); + const claim = parseAll(claimRows, toPoolHolderRow, 'claim'); + const [winner] = claim; + if (!winner) { + // No claim was written: another owner's credential is unreadable and might name this pool. + // 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 GcpWifPoolOwnershipUnresolvedError(); + } + if (claim.length !== 1) throw new GcpWifPoolIndexUnavailableError(); + if (!heldBy(winner, owner)) refuse(context, identity, owner, claim); +} + +/** + * 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..3469168f7a 100644 --- a/apps/api/src/services/gcp-wif-setup.ts +++ b/apps/api/src/services/gcp-wif-setup.ts @@ -11,22 +11,77 @@ 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()), }); /** - * 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 +177,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 +222,7 @@ export async function createOidcProvider( providerId, issuerUri, timeoutMs, - samProjectId + scope ); return; } @@ -238,16 +287,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 +348,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}`; @@ -321,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 ); @@ -342,27 +390,30 @@ 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); + // 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 } - // 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) { + // 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] }); } + // 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 +425,18 @@ 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, + // 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 } + : {}), + }, + }), }, 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..e30f95bc2a 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 + ? { cacheUserId: `platform:${userId}`, poolOwner: { kind: 'platform' } } + : { cacheUserId: 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( + { + cacheUserId: `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( + { cacheUserId: 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( + { cacheUserId: `platform:${userId}`, poolOwner: { kind: 'platform' } }, + cacheProjectId, + gcpCred, + env, + context + ); const provider = await createGcpProviderForEnv(env, gcpCred, tokenProvider); return { 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/gcp-deploy-setup.test.ts b/apps/api/tests/unit/gcp-deploy-setup.test.ts index 62950114e2..1f61c20182 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', + { onProgress: (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-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/gcp.test.ts b/apps/api/tests/unit/routes/gcp.test.ts index 3d5132059f..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( - '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( - '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/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/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/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts b/apps/api/tests/unit/scheduled/provider-orphan-platform-gcp.test.ts index be19e279b1..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 @@ -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,13 +169,26 @@ 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); 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/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-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-credential-store.test.ts b/apps/api/tests/unit/services/gcp-credential-store.test.ts index 380cc81fcd..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,7 +12,7 @@ import { replaceUserGcpCredential, } from '../../../src/services/gcp-credential-store'; import { parseGcpCredential } from '../../../src/services/provider-credentials'; -import { createSqliteD1 } from '../../helpers/sqlite-d1'; +import { applySqliteMigration, createSqliteD1 } from '../../helpers/sqlite-d1'; const ENCRYPTION_KEY = 'SK4ihJazAK3GIWUQcM6nZ1odR6KQHrqRAVSp6HdPxrg='; const USER_ID = 'user-gcp-store'; @@ -88,7 +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 + ); `); + applySqliteMigration( + sqlite, + new URL('../../../src/db/migrations/0262_gcp_wif_pool_index.sql', import.meta.url) + ); return sqlite; } 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..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 @@ -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: { cacheUserId: string; poolOwner: unknown }, + projectId: string + ) => { + tokenCalls.push({ userId: requester.cacheUserId, 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..5701adb1e8 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: { cacheUserId: 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.cacheUserId, + 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..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(); }, - expectedCacheUserId: USER_ID, + expectedRequester: { cacheUserId: USER_ID, poolOwner: { kind: 'user', userId: USER_ID } }, expectedSource: 'user', }, { name: 'legacy user credential', setup: () => makeCredentialDbMock(legacyGcpCredential()), - expectedCacheUserId: USER_ID, + expectedRequester: { cacheUserId: 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: { cacheUserId: `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..19881fec7a 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,14 @@ 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', async (importOriginal) => ({ + ...(await importOriginal()), + assertGcpWifPoolOwnership: vi.fn().mockResolvedValue(undefined), +})); + +const USER_1 = { cacheUserId: 'user-1', poolOwner: { kind: 'user', userId: 'user-1' } } as const; let privateKey: string; @@ -201,7 +209,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 +250,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 +280,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( + { cacheUserId: '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 +328,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 +369,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 +405,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 +481,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 +493,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 +505,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..ab87557051 --- /dev/null +++ b/apps/api/tests/unit/services/gcp-wif-pool-ownership.test.ts @@ -0,0 +1,1198 @@ +/** + * 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 { drizzle } from 'drizzle-orm/d1'; +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 { + GcpWifPoolOwnershipUnresolvedError, + assertGcpWifPayloadOwnership, + GcpWifPoolIndexUnavailableError, + 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'); + +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 { cacheUserId: 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 }>(); + // 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; +} + +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('DROP TABLE gcp_wif_pool_claims'); + 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' }, + { 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)); + + 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( + { cacheUserId: '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({ cacheUserId: '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( + { cacheUserId: '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( + { cacheUserId: 'project:proj-a:user-m', poolOwner: { kind: 'user', userId: 'user-a' } }, + wif(POOL_A), + 'proj-a' + ) + ).resolves.toBe('sa-token'); + }); + + 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): 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))).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_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('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( + GcpWifPoolOwnedByAnotherOwnerError + ); + 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 }, + ]); + }); + + 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 () => { + 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 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}`); + } + 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)); + // 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(); + 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); + }); +}); + +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('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( + 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 + ); + }); +}); + +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 + ); + }); +}); + +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, + options: { gcpConfiguration: boolean } = { gcpConfiguration: true } + ) { + const otherKey = Buffer.from('fedcba9876543210fedcba9876543210').toString('base64'); + 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 () => { + // 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( + GcpWifPoolOwnershipUnresolvedError + ); + expect(signIdentityToken).not.toHaveBeenCalled(); + 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'); + }); + + 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); + }); +}); + +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); + }); +}); + +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 }); + }); +}); 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..5c63cabd99 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,26 +167,90 @@ 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('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('uses pool-wide wildcard when samProjectId is not provided (user-level setup)', async () => { - // getIamPolicy - mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'abc' })); - // setIamPolicy + 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('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( @@ -188,102 +259,114 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { '123456', 'sa@my-gcp-project.iam.gserviceaccount.com', 'sam-pool', - 5000 + 5000, + USER_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' + 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('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({ + bindings: [ + { role: WIF_ROLE, members: [`principalSet://${POOL_PATH}/attribute.sam_user/user-a`] }, + ], + etag: 'abc', + }) ); - expect(binding.members[0]).toBe( - 'principalSet://iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/sam-pool/*' + await grantWifUserOnSa( + 'token', + 'my-gcp-project', + '123456', + 'sa@my-gcp-project.iam.gserviceaccount.com', + '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( - grantWifUserOnSa( - 'token', - 'my-gcp-project', - '123456', - 'sa@x.com', - 'sam-pool', - 5000, - 'project with spaces' - ) + 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', '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/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/api/tests/workers/credential-resave-capacity-provenance.test.ts b/apps/api/tests/workers/credential-resave-capacity-provenance.test.ts index 572b527fb3..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; @@ -121,15 +133,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 +347,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 +359,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 +376,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 +389,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 +576,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', }), @@ -659,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, @@ -732,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, @@ -821,7 +839,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', diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index bfd8642a56..3d1bb56ebb 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -296,6 +296,29 @@ 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 (`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: + +- 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). + +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 (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. + +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: + +- **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 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..0f19db9b86 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,10 @@ 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` | 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 | 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/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..9be14e5c2c 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,21 @@ 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. 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. 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): + +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 \ + --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. ### Service account JSON (OAuth-free alternative) diff --git a/packages/worker-core/src/schema.ts b/packages/worker-core/src/schema.ts index 1c3bebf4cf..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'`), }) ); @@ -1121,9 +1125,48 @@ 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 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', + { + 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'), + unreadable: integer('unreadable').notNull().default(0), + 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`), + }) +); + +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) // ============================================================================= @@ -5871,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/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md b/tasks/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md new file mode 100644 index 0000000000..f5af683640 --- /dev/null +++ b/tasks/archive/2026-11-19-gcp-wif-cross-owner-pool-impersonation.md @@ -0,0 +1,66 @@ +# 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 +- [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 +- [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` +- [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 + +## 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. + +## 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 + +- [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 + +## 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` 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..46945b92e4 --- /dev/null +++ b/tasks/backlog/2026-11-19-gcp-wif-probe-open-providers-before-claim.md @@ -0,0 +1,32 @@ +# 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. 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). + +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 +- [ ] 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), inconclusive control (timeout/5xx refused, retryable)