diff --git a/.claude/rules/75-external-api-check-then-act.md b/.claude/rules/75-external-api-check-then-act.md index 981557791b..2137f0b497 100644 --- a/.claude/rules/75-external-api-check-then-act.md +++ b/.claude/rules/75-external-api-check-then-act.md @@ -117,6 +117,8 @@ Tells: (`packages/repo-hosting/src/github-app-branches.ts`) already solved this class against the GitHub API, treating a `422` on create as `status: 'exists'`. Match the existing shape. +- A setup conflict must read and validate the existing resource's installation identity before updating it. For OIDC providers, refuse a different issuer; never repoint another installation's trust after an HTTP 409. Test two installations sharing one cloud project and provider name, alongside a same-installation retry. + ## Required Tests - **The race, per tolerated code:** lookup returns empty, create returns the conflict, diff --git a/apps/api/.env.example b/apps/api/.env.example index a726c3fd3e..b79a5d9319 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -908,7 +908,7 @@ INFOMANIAK_IP_POLL_INTERVAL_MS=3000 # GCP OIDC configuration defaults (all optional — sensible defaults provided) # GCP_WIF_POOL_ID=sam-pool # Workload Identity Federation pool ID -# GCP_WIF_PROVIDER_ID=sam-oidc # OIDC provider ID within the WIF pool +# GCP_WIF_PROVIDER_ID= # OIDC provider ID within the pool (default: derived per installation from BASE_DOMAIN) # GCP_SERVICE_ACCOUNT_ID=sam-vm-manager # Service account created for VM management # GCP_SERVICE_ACCOUNT_JSON_MAX_BYTES=65536 # Maximum pasted/uploaded service-account JSON size # GCP_DEFAULT_ZONE=us-central1-a # Default GCP zone for VM provisioning @@ -924,7 +924,7 @@ INFOMANIAK_IP_POLL_INTERVAL_MS=3000 # GCP deployment (project-level OIDC for Defang — all optional, sensible defaults provided) # GCP_DEPLOY_WIF_POOL_ID=sam-deploy-pool # WIF pool ID for deployment auth -# GCP_DEPLOY_WIF_PROVIDER_ID=sam-oidc # OIDC provider ID within the deploy pool +# GCP_DEPLOY_WIF_PROVIDER_ID= # OIDC provider ID within the deploy pool (default: derived per installation from BASE_DOMAIN) # GCP_DEPLOY_SERVICE_ACCOUNT_ID=sam-deployer # Service account for deployment operations # GCP_DEPLOY_IDENTITY_TOKEN_EXPIRY_SECONDS=600 # SAM→GCP identity token lifetime (10 min) # GCP_DEPLOY_OAUTH_STATE_TTL_SECONDS=600 # OAuth CSRF state KV TTL (10 min) diff --git a/apps/api/src/services/gcp-deploy-setup.ts b/apps/api/src/services/gcp-deploy-setup.ts index 7812a9b321..df7181603f 100644 --- a/apps/api/src/services/gcp-deploy-setup.ts +++ b/apps/api/src/services/gcp-deploy-setup.ts @@ -3,7 +3,6 @@ import { DEFAULT_GCP_API_TIMEOUT_MS, DEFAULT_GCP_DEPLOY_SERVICE_ACCOUNT_ID, DEFAULT_GCP_DEPLOY_WIF_POOL_ID, - DEFAULT_GCP_DEPLOY_WIF_PROVIDER_ID, } from '@simple-agent-manager/shared'; import type { Env } from '../env'; @@ -15,6 +14,7 @@ import { getProjectNumber, grantProjectRoles, grantWifUserOnSa, + installationWifProviderId, type SetupProgressCallback, } from './gcp-setup'; @@ -49,13 +49,15 @@ export async function runGcpDeploySetup( gcpProjectId: string, env: Env, onProgress?: SetupProgressCallback, - samProjectId?: string, + samProjectId?: string ): Promise> { const timeoutMs = env.GCP_API_TIMEOUT_MS ? parseInt(env.GCP_API_TIMEOUT_MS, 10) : DEFAULT_GCP_API_TIMEOUT_MS; const poolId = env.GCP_DEPLOY_WIF_POOL_ID || DEFAULT_GCP_DEPLOY_WIF_POOL_ID; - const providerId = env.GCP_DEPLOY_WIF_PROVIDER_ID || DEFAULT_GCP_DEPLOY_WIF_PROVIDER_ID; + // Per installation: a provider trusts one issuer, and installations may share a project. + const providerId = + env.GCP_DEPLOY_WIF_PROVIDER_ID || (await installationWifProviderId(env.BASE_DOMAIN)); const saAccountId = env.GCP_DEPLOY_SERVICE_ACCOUNT_ID || DEFAULT_GCP_DEPLOY_SERVICE_ACCOUNT_ID; const issuerUri = `https://api.${env.BASE_DOMAIN}`; @@ -76,21 +78,40 @@ export async function runGcpDeploySetup( // Step 4: Create OIDC provider onProgress?.('create_oidc_provider', 'in_progress'); - await createOidcProvider(oauthToken, projectNumber, poolId, providerId, issuerUri, timeoutMs, samProjectId); + await createOidcProvider( + oauthToken, + projectNumber, + poolId, + providerId, + issuerUri, + timeoutMs, + samProjectId + ); onProgress?.('create_oidc_provider', 'done'); // Step 5: Create service account onProgress?.('create_service_account', 'in_progress'); const saEmail = await createServiceAccount( - oauthToken, gcpProjectId, saAccountId, timeoutMs, + oauthToken, + gcpProjectId, + saAccountId, + timeoutMs, 'SAM Deployer', - 'Service account for SAM deployment via Defang', + 'Service account for SAM deployment via Defang' ); onProgress?.('create_service_account', 'done'); // Step 6: Grant WIF user on SA onProgress?.('grant_wif_user', 'in_progress'); - await grantWifUserOnSa(oauthToken, gcpProjectId, projectNumber, saEmail, poolId, timeoutMs, samProjectId); + await grantWifUserOnSa( + oauthToken, + gcpProjectId, + projectNumber, + saEmail, + poolId, + timeoutMs, + samProjectId + ); onProgress?.('grant_wif_user', 'done'); // Step 7: Grant deployment roles diff --git a/apps/api/src/services/gcp-errors.ts b/apps/api/src/services/gcp-errors.ts index 080f0a10b6..84b5edd26e 100644 --- a/apps/api/src/services/gcp-errors.ts +++ b/apps/api/src/services/gcp-errors.ts @@ -62,6 +62,8 @@ const STEP_HINTS: Record = { 'Failed to configure workload identity. Ensure your account has the IAM Admin role.', create_oidc_provider: 'Failed to configure the identity provider.', update_oidc_provider: 'Failed to update the identity provider.', + oidc_provider_issuer_mismatch: + 'This identity provider belongs to another SAM installation. Ask an administrator to configure a separate workload identity pool or provider, then reconnect.', create_service_account: 'Failed to create the service account. Ensure your account has the IAM Admin role.', grant_wif_user: 'Failed to configure identity federation on the service account.', diff --git a/apps/api/src/services/gcp-setup-transport.ts b/apps/api/src/services/gcp-setup-transport.ts index bbe90ba125..ace3478901 100644 --- a/apps/api/src/services/gcp-setup-transport.ts +++ b/apps/api/src/services/gcp-setup-transport.ts @@ -83,3 +83,21 @@ export async function fetchWithTimeout( clearTimeout(timeoutId); } } + +export const gcpOperationSchema = v.object({ + name: v.optional(v.string()), + done: v.optional(v.boolean()), + error: v.optional(v.object({ message: v.optional(v.string()) })), +}); + +export const iamBindingSchema = v.object({ + role: v.string(), + members: v.array(v.string()), +}); + +export function requireOperationName(op: { name?: string }, context: string): string { + if (!op.name) { + throw new GcpApiError({ step: context, message: 'GCP operation response missing name' }); + } + return op.name; +} diff --git a/apps/api/src/services/gcp-setup.ts b/apps/api/src/services/gcp-setup.ts index 2ae3720bbe..40b090a920 100644 --- a/apps/api/src/services/gcp-setup.ts +++ b/apps/api/src/services/gcp-setup.ts @@ -3,7 +3,6 @@ import { DEFAULT_GCP_API_TIMEOUT_MS, DEFAULT_GCP_SERVICE_ACCOUNT_ID, DEFAULT_GCP_WIF_POOL_ID, - DEFAULT_GCP_WIF_PROVIDER_ID, GCP_CREDENTIAL_VERSION, GCP_REQUIRED_APIS, } from '@simple-agent-manager/shared'; @@ -12,9 +11,29 @@ import * as v from 'valibot'; import type { Env } from '../env'; import { readResponseJson } from '../lib/runtime-validation'; import { GcpApiError } from './gcp-errors'; -import { fetchWithTimeout, IAM_URL, pollOperation, SERVICE_USAGE_URL } from './gcp-setup-transport'; - +import { + fetchWithTimeout, + gcpOperationSchema, + IAM_URL, + iamBindingSchema, + pollOperation, + requireOperationName, + SERVICE_USAGE_URL, +} from './gcp-setup-transport'; +import { + createOidcProvider, + createWifPool, + grantWifUserOnSa, + installationWifProviderId, +} from './gcp-wif-setup'; export { fetchWithTimeout, pollOperation } from './gcp-setup-transport'; +export { + createOidcProvider, + createWifPool, + grantWifUserOnSa, + installationWifProviderId, + updateOidcProvider, +} from './gcp-wif-setup'; const RESOURCE_MANAGER_URL = 'https://cloudresourcemanager.googleapis.com/v1'; @@ -46,46 +65,12 @@ const gcpProjectListResponseSchema = v.object({ nextPageToken: v.optional(v.string()), }); -const gcpOperationSchema = v.object({ - name: v.optional(v.string()), - done: v.optional(v.boolean()), - error: v.optional(v.object({ message: v.optional(v.string()) })), -}); - -const iamBindingSchema = v.object({ - role: v.string(), - members: v.array(v.string()), -}); - -const serviceAccountPolicySchema = v.object({ - bindings: v.optional(v.array(iamBindingSchema)), - etag: v.string(), -}); - const projectPolicySchema = v.object({ bindings: v.optional(v.array(iamBindingSchema)), etag: v.string(), version: v.optional(v.number()), }); -function requireOperationName(op: { name?: string }, context: string): string { - if (!op.name) { - throw new GcpApiError({ step: context, message: 'GCP operation response missing name' }); - } - return op.name; -} - -/** - * 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. - */ -function assertSafeCelValue(value: string, fieldName: string): void { - if (!/^[a-zA-Z0-9_:.-]+$/.test(value)) { - throw new Error(`${fieldName} contains characters unsafe for CEL interpolation`); - } -} - /** Status callback for setup progress reporting */ export type SetupProgressCallback = ( step: string, @@ -228,201 +213,6 @@ export async function enableApis( } } -/** - * Create a Workload Identity Pool. - * Returns the pool name or reuses an existing one if it already exists. - */ -export async function createWifPool( - oauthToken: string, - projectNumber: string, - poolId: string, - timeoutMs: number -): Promise { - const url = `${IAM_URL}/projects/${projectNumber}/locations/global/workloadIdentityPools?workloadIdentityPoolId=${poolId}`; - const res = await fetchWithTimeout( - url, - { - method: 'POST', - headers: { - Authorization: `Bearer ${oauthToken}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - displayName: 'Simple Agent Manager', - description: 'Workload identity pool for SAM platform', - }), - }, - timeoutMs - ); - - if (res.status === 409) { - // Already exists — reuse - return `projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}`; - } - - if (!res.ok) { - const body = await res.text(); - throw new GcpApiError({ - step: 'create_wif_pool', - message: `Failed to create WIF pool (${res.status})`, - statusCode: res.status, - rawBody: body, - }); - } - - const op = await readResponseJson(res, gcpOperationSchema, 'gcp.iam.create_wif_pool'); - if (!op.done) { - await pollOperation(oauthToken, requireOperationName(op, 'create_wif_pool'), timeoutMs); - } - - return `projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}`; -} - -/** - * Create an OIDC provider in the WIF pool. - */ -export async function createOidcProvider( - oauthToken: string, - projectNumber: string, - poolId: string, - providerId: string, - issuerUri: string, - timeoutMs: number, - samProjectId?: string -): 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}'`; - - const url = `${IAM_URL}/projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/providers?workloadIdentityPoolProviderId=${providerId}`; - const res = await fetchWithTimeout( - url, - { - method: 'POST', - headers: { - Authorization: `Bearer ${oauthToken}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - displayName: 'SAM OIDC Provider', - description: 'OIDC provider for Simple Agent Manager', - attributeMapping: { - 'google.subject': 'assertion.sub', - 'attribute.sam_user': 'assertion.user_id', - 'attribute.sam_project': 'assertion.project_id', - }, - attributeCondition, - oidc: { - issuerUri, - allowedAudiences: [wifAudience], - }, - }), - }, - timeoutMs - ); - - if (res.status === 409) { - // Already exists — update instead - await updateOidcProvider( - oauthToken, - projectNumber, - poolId, - providerId, - issuerUri, - timeoutMs, - samProjectId - ); - return; - } - - if (!res.ok) { - const body = await res.text(); - throw new GcpApiError({ - step: 'create_oidc_provider', - message: `Failed to create OIDC provider (${res.status})`, - statusCode: res.status, - rawBody: body, - }); - } - - const op = await readResponseJson(res, gcpOperationSchema, 'gcp.iam.create_oidc_provider'); - if (!op.done) { - await pollOperation(oauthToken, requireOperationName(op, 'create_oidc_provider'), timeoutMs); - } -} - -/** - * Update an existing OIDC provider (if it already existed). - */ -export async function updateOidcProvider( - oauthToken: string, - projectNumber: string, - poolId: string, - providerId: string, - issuerUri: string, - timeoutMs: number, - samProjectId?: string -): 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}'`; - - const name = `projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`; - const url = `${IAM_URL}/${name}?updateMask=attributeMapping,attributeCondition,oidc`; - const res = await fetchWithTimeout( - url, - { - method: 'PATCH', - headers: { - Authorization: `Bearer ${oauthToken}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - attributeMapping: { - 'google.subject': 'assertion.sub', - 'attribute.sam_user': 'assertion.user_id', - 'attribute.sam_project': 'assertion.project_id', - }, - attributeCondition, - oidc: { - issuerUri, - allowedAudiences: [wifAudience], - }, - }), - }, - timeoutMs - ); - - if (!res.ok) { - const body = await res.text(); - throw new GcpApiError({ - step: 'update_oidc_provider', - message: `Failed to update OIDC provider (${res.status})`, - statusCode: res.status, - rawBody: body, - }); - } - - const op = await readResponseJson(res, gcpOperationSchema, 'gcp.iam.update_oidc_provider'); - if (!op.done) { - await pollOperation(oauthToken, requireOperationName(op, 'update_oidc_provider'), timeoutMs); - } -} - /** * Create a service account for VM management. */ @@ -471,104 +261,6 @@ export async function createServiceAccount( return email; } -/** - * Grant Workload Identity User on the service account (read-modify-write pattern). - */ -export async function grantWifUserOnSa( - oauthToken: string, - projectId: string, - projectNumber: string, - saEmail: string, - poolId: string, - timeoutMs: number, - samProjectId?: string -): Promise { - // Validate early, before any network calls (fail-fast pattern). - if (samProjectId) { - assertSafeCelValue(samProjectId, 'samProjectId'); - } - - const saResource = `projects/${projectId}/serviceAccounts/${saEmail}`; - - // Read current policy - const getUrl = `${IAM_URL}/${saResource}:getIamPolicy`; - const getRes = await fetchWithTimeout( - getUrl, - { - method: 'POST', - headers: { - Authorization: `Bearer ${oauthToken}`, - 'Content-Type': 'application/json', - }, - body: '{}', - }, - timeoutMs - ); - - if (!getRes.ok) { - const body = await getRes.text(); - throw new GcpApiError({ - step: 'grant_wif_user', - message: `Failed to get SA IAM policy (${getRes.status})`, - statusCode: getRes.status, - rawBody: body, - }); - } - - const policy = await readResponseJson( - getRes, - serviceAccountPolicySchema, - '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 - } - - // Add our binding - const bindings = [...(policy.bindings || [])]; - if (existingBinding) { - existingBinding.members.push(member); - } else { - bindings.push({ role, members: [member] }); - } - - // Write updated policy - const setUrl = `${IAM_URL}/${saResource}:setIamPolicy`; - const setRes = await fetchWithTimeout( - setUrl, - { - method: 'POST', - headers: { - Authorization: `Bearer ${oauthToken}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ policy: { bindings, etag: policy.etag } }), - }, - timeoutMs - ); - - if (!setRes.ok) { - const body = await setRes.text(); - throw new GcpApiError({ - step: 'grant_wif_user', - message: `Failed to set SA IAM policy (${setRes.status})`, - statusCode: setRes.status, - rawBody: body, - }); - } -} - /** * Grant Compute Instance Admin to the service account on the project (read-modify-write). */ @@ -678,7 +370,8 @@ export async function runGcpSetup( ? parseInt(env.GCP_API_TIMEOUT_MS, 10) : DEFAULT_GCP_API_TIMEOUT_MS; const poolId = env.GCP_WIF_POOL_ID || DEFAULT_GCP_WIF_POOL_ID; - const providerId = env.GCP_WIF_PROVIDER_ID || DEFAULT_GCP_WIF_PROVIDER_ID; + // Per installation: a provider trusts one issuer, and installations may share a project. + const providerId = env.GCP_WIF_PROVIDER_ID || (await installationWifProviderId(env.BASE_DOMAIN)); const saAccountId = env.GCP_SERVICE_ACCOUNT_ID || DEFAULT_GCP_SERVICE_ACCOUNT_ID; const issuerUri = `https://api.${env.BASE_DOMAIN}`; diff --git a/apps/api/src/services/gcp-wif-setup.ts b/apps/api/src/services/gcp-wif-setup.ts new file mode 100644 index 0000000000..b9124d98c4 --- /dev/null +++ b/apps/api/src/services/gcp-wif-setup.ts @@ -0,0 +1,391 @@ +import * as v from 'valibot'; + +import { readResponseJson } from '../lib/runtime-validation'; +import { GcpApiError } from './gcp-errors'; +import { + fetchWithTimeout, + gcpOperationSchema, + IAM_URL, + iamBindingSchema, + pollOperation, + requireOperationName, +} from './gcp-setup-transport'; + +const serviceAccountPolicySchema = v.object({ + bindings: v.optional(v.array(iamBindingSchema)), + etag: v.string(), +}); + +/** + * 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. + */ +function assertSafeCelValue(value: string, fieldName: string): void { + if (!/^[a-zA-Z0-9_:.-]+$/.test(value)) { + throw new Error(`${fieldName} contains characters unsafe for CEL interpolation`); + } +} + +/** 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-'; +const WIF_PROVIDER_ID_HASH_LENGTH = 6; + +/** + * Workload identity provider ID for one SAM installation. + * + * A provider trusts exactly one issuer, so installations that share a Google Cloud + * project need distinct providers. The ID is a readable slug of the installation's + * base domain plus a hash of it, so two domains that slug alike still differ: + * `sammy2.party` → `sam-sammy2-party-`. Saved credentials keep the IDs they + * were created with; this only names providers created by a new setup run. + */ +export async function installationWifProviderId(baseDomain: string): Promise { + const normalized = baseDomain.trim().toLowerCase(); + if (!normalized) { + throw new Error('BASE_DOMAIN is required to name the workload identity provider'); + } + const digest = new Uint8Array( + await crypto.subtle.digest('SHA-256', new TextEncoder().encode(normalized)) + ); + const hash = Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')) + .join('') + .slice(0, WIF_PROVIDER_ID_HASH_LENGTH); + const slugBudget = + WIF_PROVIDER_ID_MAX_LENGTH - WIF_PROVIDER_ID_PREFIX.length - 1 - WIF_PROVIDER_ID_HASH_LENGTH; + const slug = normalized + .replace(/[^a-z0-9]+/g, '-') + .slice(0, slugBudget) + // Normalization collapses each separator run to one hyphen. + .replace(/^-|-$/g, ''); + return slug ? `${WIF_PROVIDER_ID_PREFIX}${slug}-${hash}` : `${WIF_PROVIDER_ID_PREFIX}${hash}`; +} + +/** + * Create a Workload Identity Pool. + * Returns the pool name or reuses an existing one if it already exists. + */ +export async function createWifPool( + oauthToken: string, + projectNumber: string, + poolId: string, + timeoutMs: number +): Promise { + const url = `${IAM_URL}/projects/${projectNumber}/locations/global/workloadIdentityPools?workloadIdentityPoolId=${poolId}`; + const res = await fetchWithTimeout( + url, + { + method: 'POST', + headers: { + Authorization: `Bearer ${oauthToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + displayName: 'Simple Agent Manager', + description: 'Workload identity pool for SAM platform', + }), + }, + timeoutMs + ); + + if (res.status === 409) { + // Already exists — reuse + return `projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}`; + } + + if (!res.ok) { + const body = await res.text(); + throw new GcpApiError({ + step: 'create_wif_pool', + message: `Failed to create WIF pool (${res.status})`, + statusCode: res.status, + rawBody: body, + }); + } + + const op = await readResponseJson(res, gcpOperationSchema, 'gcp.iam.create_wif_pool'); + if (!op.done) { + await pollOperation(oauthToken, requireOperationName(op, 'create_wif_pool'), timeoutMs); + } + + return `projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}`; +} + +/** + * Create an OIDC provider in the WIF pool. + */ +export async function createOidcProvider( + oauthToken: string, + projectNumber: string, + poolId: string, + providerId: string, + issuerUri: string, + timeoutMs: number, + samProjectId?: string +): 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}'`; + + const url = `${IAM_URL}/projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/providers?workloadIdentityPoolProviderId=${providerId}`; + const res = await fetchWithTimeout( + url, + { + method: 'POST', + headers: { + Authorization: `Bearer ${oauthToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + displayName: 'SAM OIDC Provider', + description: 'OIDC provider for Simple Agent Manager', + attributeMapping: { + 'google.subject': 'assertion.sub', + 'attribute.sam_user': 'assertion.user_id', + 'attribute.sam_project': 'assertion.project_id', + }, + attributeCondition, + oidc: { + issuerUri, + allowedAudiences: [wifAudience], + }, + }), + }, + timeoutMs + ); + + if (res.status === 409) { + // Already exists — update instead + await updateOidcProvider( + oauthToken, + projectNumber, + poolId, + providerId, + issuerUri, + timeoutMs, + samProjectId + ); + return; + } + + if (!res.ok) { + const body = await res.text(); + throw new GcpApiError({ + step: 'create_oidc_provider', + message: `Failed to create OIDC provider (${res.status})`, + statusCode: res.status, + rawBody: body, + }); + } + + const op = await readResponseJson(res, gcpOperationSchema, 'gcp.iam.create_oidc_provider'); + if (!op.done) { + await pollOperation(oauthToken, requireOperationName(op, 'create_oidc_provider'), timeoutMs); + } +} + +/** A setup retry may update its own provider, never a different installation's trust. */ +async function requireOidcProviderIssuer( + oauthToken: string, + name: string, + issuerUri: string, + timeoutMs: number +): Promise { + const res = await fetchWithTimeout( + `${IAM_URL}/${name}`, + { headers: { Authorization: `Bearer ${oauthToken}` } }, + timeoutMs + ); + if (!res.ok) { + throw new GcpApiError({ + step: 'update_oidc_provider', + message: `Failed to read existing OIDC provider (${res.status})`, + statusCode: res.status, + rawBody: await res.text(), + }); + } + const current = await readResponseJson( + res, + v.object({ name: v.string(), oidc: v.object({ issuerUri: v.string() }) }), + 'gcp.iam.existing_oidc_provider' + ); + if (current.name !== name || current.oidc.issuerUri !== issuerUri) { + throw new GcpApiError({ + step: 'oidc_provider_issuer_mismatch', + statusCode: 409, + message: 'Existing workload identity provider belongs to a different SAM installation', + }); + } +} + +/** + * Update an existing OIDC provider (if it already existed). + */ +export async function updateOidcProvider( + oauthToken: string, + projectNumber: string, + poolId: string, + providerId: string, + issuerUri: string, + timeoutMs: number, + samProjectId?: string +): 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}'`; + + const name = `projects/${projectNumber}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`; + await requireOidcProviderIssuer(oauthToken, name, issuerUri, timeoutMs); + const url = `${IAM_URL}/${name}?updateMask=attributeMapping,attributeCondition,oidc`; + const res = await fetchWithTimeout( + url, + { + method: 'PATCH', + headers: { + Authorization: `Bearer ${oauthToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + attributeMapping: { + 'google.subject': 'assertion.sub', + 'attribute.sam_user': 'assertion.user_id', + 'attribute.sam_project': 'assertion.project_id', + }, + attributeCondition, + oidc: { + issuerUri, + allowedAudiences: [wifAudience], + }, + }), + }, + timeoutMs + ); + + if (!res.ok) { + const body = await res.text(); + throw new GcpApiError({ + step: 'update_oidc_provider', + message: `Failed to update OIDC provider (${res.status})`, + statusCode: res.status, + rawBody: body, + }); + } + + const op = await readResponseJson(res, gcpOperationSchema, 'gcp.iam.update_oidc_provider'); + if (!op.done) { + await pollOperation(oauthToken, requireOperationName(op, 'update_oidc_provider'), timeoutMs); + } +} + +/** + * Grant Workload Identity User on the service account (read-modify-write pattern). + */ +export async function grantWifUserOnSa( + oauthToken: string, + projectId: string, + projectNumber: string, + saEmail: string, + poolId: string, + timeoutMs: number, + samProjectId?: string +): Promise { + // Validate early, before any network calls (fail-fast pattern). + if (samProjectId) { + assertSafeCelValue(samProjectId, 'samProjectId'); + } + + const saResource = `projects/${projectId}/serviceAccounts/${saEmail}`; + + // Read current policy + const getUrl = `${IAM_URL}/${saResource}:getIamPolicy`; + const getRes = await fetchWithTimeout( + getUrl, + { + method: 'POST', + headers: { + Authorization: `Bearer ${oauthToken}`, + 'Content-Type': 'application/json', + }, + body: '{}', + }, + timeoutMs + ); + + if (!getRes.ok) { + const body = await getRes.text(); + throw new GcpApiError({ + step: 'grant_wif_user', + message: `Failed to get SA IAM policy (${getRes.status})`, + statusCode: getRes.status, + rawBody: body, + }); + } + + const policy = await readResponseJson( + getRes, + serviceAccountPolicySchema, + '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 + } + + // Add our binding + const bindings = [...(policy.bindings || [])]; + if (existingBinding) { + existingBinding.members.push(member); + } else { + bindings.push({ role, members: [member] }); + } + + // Write updated policy + const setUrl = `${IAM_URL}/${saResource}:setIamPolicy`; + const setRes = await fetchWithTimeout( + setUrl, + { + method: 'POST', + headers: { + Authorization: `Bearer ${oauthToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ policy: { bindings, etag: policy.etag } }), + }, + timeoutMs + ); + + if (!setRes.ok) { + const body = await setRes.text(); + throw new GcpApiError({ + step: 'grant_wif_user', + message: `Failed to set SA IAM policy (${setRes.status})`, + statusCode: setRes.status, + rawBody: body, + }); + } +} diff --git a/apps/api/src/services/node-provisioning-failure.ts b/apps/api/src/services/node-provisioning-failure.ts index 055817434f..f586d530e5 100644 --- a/apps/api/src/services/node-provisioning-failure.ts +++ b/apps/api/src/services/node-provisioning-failure.ts @@ -1,4 +1,5 @@ import { + isProviderCreateNotDispatched, isTransientCapacityError, ProviderError, type ProviderRequestContext, @@ -23,9 +24,11 @@ import { releaseTunnelBeforeVm, truncateNodeErrorMessage, } from './node-provisioning-predicates'; +import { recordRejectedAllocationAbsence } from './node-rejection-proof'; import type { NodeTunnelProvisioningPhase } from './node-tunnel-provisioning'; import { recordTunnelProvisioningFailure } from './node-tunnel-provisioning-failure'; import { persistError } from './observability'; +import type { ExactProviderCredentialBinding } from './provider-credentials'; interface NodeProvisioningFailureInput { env: Env; @@ -39,6 +42,7 @@ interface NodeProvisioningFailureInput { providerCreateRequested: boolean; providerContext?: ProviderRequestContext; attemptedProvider?: CredentialProvider; + resolvedCredentialBinding?: ExactProviderCredentialBinding; providerCreateRejected: boolean; providerAllocationRejected: boolean; providerRejectionProofAt: string | null; @@ -148,6 +152,31 @@ async function finalizeNodeProvisioningFailure( err: unknown, input: NodeProvisioningFailureInput ): Promise { + // Only a terminal, fresh non-durable allocation may consume the adapter's positive + // pre-dispatch proof. Durable attempts retry the same incarnation; marking it terminated + // here would poison that retry. An initially unproven incarnation may have an earlier + // dispatched create, so it also stays unresolved (never infer absence from STS text). + if ( + !input.durable && + input.node.runtimeTerminationConfirmedAt !== null && + input.attemptedProvider && + isProviderCreateNotDispatched(err) + ) { + const proof = await recordRejectedAllocationAbsence( + input.db, + input.node, + { + providerName: input.attemptedProvider, + // Match the binding used by the identity claim, including a fresh binding upgrade. + // Never re-resolve a rotated credential or read current values to satisfy the CAS. + exactCredentialBinding: input.resolvedCredentialBinding, + }, + input.provisioningRuntimeIncarnationId + ); + input.providerAllocationRejected = !!proof; + input.providerRejectionProofAt = proof?.proofAt ?? null; + input.rejectedPlacementPredicate = proof?.placementPredicate; + } const { options, providerCreateRejected, providerAllocationRejected } = input; const errorMessage = provisioningFailureMessage(err); await recordNodeProvisioningError(err, input, errorMessage); @@ -215,13 +244,23 @@ async function recordFailedProvisioningNode( healthStatus: 'unhealthy', errorMessage: `[${providerName}] ${truncatedError}`, ...(providerAllocationRejected - ? { runtimeTerminationConfirmedAt: new Date().toISOString() } + ? { runtimeTerminationConfirmedAt: input.providerRejectionProofAt } : {}), updatedAt: new Date().toISOString(), cleanupBlockedSince: null, cleanupBlockedReason: null, cleanupBlockedAlertedAt: null, }) - .where(creatingProvisioningPredicate(node, provisioningRuntimeIncarnationId)) + .where( + and( + creatingProvisioningPredicate(node, provisioningRuntimeIncarnationId), + ...(providerAllocationRejected + ? [ + sql`${schema.nodes.runtimeTerminationConfirmedAt} IS ${input.providerRejectionProofAt}`, + input.rejectedPlacementPredicate, + ] + : []) + ) + ) .run(); } diff --git a/apps/api/src/services/node-provisioning.ts b/apps/api/src/services/node-provisioning.ts index c6a2790666..a56a397239 100644 --- a/apps/api/src/services/node-provisioning.ts +++ b/apps/api/src/services/node-provisioning.ts @@ -51,6 +51,7 @@ import { resolveManagedNodeTransport, type TunnelEnv } from './node-tunnel-confi import type { NodeTunnelProvisioningPhase } from './node-tunnel-provisioning'; import { createProviderForUser, + type ExactProviderCredentialBinding, exactProviderCredentialBindingFromPlacementSnapshot, } from './provider-credentials'; import { @@ -133,6 +134,7 @@ export async function provisionNode( const targetProvider = (node.cloudProvider as CredentialProvider | null) ?? undefined; let attemptedProvider = targetProvider; + let resolvedCredentialBinding: ExactProviderCredentialBinding | undefined; let provisioningRuntimeIncarnationId = node.runtimeIncarnationId; let providerCreateRejected = false; let providerAllocationRejected = false; @@ -209,6 +211,7 @@ export async function provisionNode( } throwIfProviderRequestAborted(providerContext); attemptedProvider = providerResult.providerName; + resolvedCredentialBinding = providerResult.exactCredentialBinding; assertNativePlanConcrete(providerResult.providerName, node); // Persist the resolved provider identity before external provisioning so @@ -583,7 +586,7 @@ export async function provisionNode( return { allocationConfirmed: true }; } catch (err) { await handleNodeProvisioningFailure(err, { - env, node, options, durable, db, tunnelJournaled, provisioningRuntimeIncarnationId, tunnelPhase, providerCreateRequested, providerContext, attemptedProvider, providerCreateRejected, providerAllocationRejected, providerRejectionProofAt, rejectedPlacementPredicate, + env, node, options, durable, db, tunnelJournaled, provisioningRuntimeIncarnationId, tunnelPhase, providerCreateRequested, providerContext, attemptedProvider, resolvedCredentialBinding, providerCreateRejected, providerAllocationRejected, providerRejectionProofAt, rejectedPlacementPredicate, }); } } diff --git a/apps/api/src/services/node-rejection-proof.ts b/apps/api/src/services/node-rejection-proof.ts index 498c5de7b8..288597468f 100644 --- a/apps/api/src/services/node-rejection-proof.ts +++ b/apps/api/src/services/node-rejection-proof.ts @@ -7,7 +7,10 @@ import type { createProviderForUser } from './provider-credentials'; type Node = typeof schema.nodes.$inferSelect; type Db = ReturnType>; -type ResolvedProvider = NonNullable>>; +type ResolvedProvider = Pick< + NonNullable>>, + 'providerName' | 'exactCredentialBinding' +>; export function rejectedAllocationPlacementPredicate(node: Node, provider: ResolvedProvider) { const binding = provider.exactCredentialBinding; diff --git a/apps/api/tests/unit/gcp-deploy-setup.test.ts b/apps/api/tests/unit/gcp-deploy-setup.test.ts index 36cec8d4aa..62950114e2 100644 --- a/apps/api/tests/unit/gcp-deploy-setup.test.ts +++ b/apps/api/tests/unit/gcp-deploy-setup.test.ts @@ -1,4 +1,4 @@ -import { beforeEach,describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { GcpApiError, sanitizeGcpError } from '../../src/services/gcp-errors'; @@ -42,7 +42,7 @@ describe('runGcpDeploySetup', () => { // Mock responses in order: // 1. getProjectNumber mockFetch.mockResolvedValueOnce( - mockGcpResponse({ projectId: 'my-project', projectNumber: '123456789' }), + mockGcpResponse({ projectId: 'my-project', projectNumber: '123456789' }) ); // 2. enableApis (returns done operation) mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'operations/op1', done: true })); @@ -52,16 +52,14 @@ describe('runGcpDeploySetup', () => { mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'operations/op3', done: true })); // 5. createServiceAccount mockFetch.mockResolvedValueOnce( - mockGcpResponse({ email: 'sam-deployer@my-project.iam.gserviceaccount.com' }), + mockGcpResponse({ email: 'sam-deployer@my-project.iam.gserviceaccount.com' }) ); // 6. grantWifUserOnSa - getIamPolicy mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'abc' })); // 7. grantWifUserOnSa - setIamPolicy mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'def' })); // 8. grantProjectRoles - getIamPolicy - mockFetch.mockResolvedValueOnce( - mockGcpResponse({ bindings: [], etag: 'ghi', version: 3 }), - ); + mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'ghi', version: 3 })); // 9. grantProjectRoles - setIamPolicy mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'jkl' })); @@ -70,7 +68,7 @@ describe('runGcpDeploySetup', () => { 'my-project', mockEnv(), (step, status) => progressSteps.push({ step, status }), - 'sam-project-123', + 'sam-project-123' ); // Verify result @@ -79,12 +77,11 @@ describe('runGcpDeploySetup', () => { expect(result.gcpProjectNumber).toBe('123456789'); expect(result.serviceAccountEmail).toBe('sam-deployer@my-project.iam.gserviceaccount.com'); expect(result.wifPoolId).toBe('sam-deploy-pool'); - expect(result.wifProviderId).toBe('sam-oidc'); + // Derived from BASE_DOMAIN 'example.com'; pinned because a change renames every new provider. + expect(result.wifProviderId).toBe('sam-example-com-a379a6'); // Verify all progress steps completed - const completedSteps = progressSteps - .filter((s) => s.status === 'done') - .map((s) => s.step); + const completedSteps = progressSteps.filter((s) => s.status === 'done').map((s) => s.step); expect(completedSteps).toEqual([ 'get_project_number', 'enable_apis', @@ -112,14 +109,14 @@ describe('runGcpDeploySetup', () => { const oidcProviderCall = mockFetch.mock.calls[3]; const oidcBody = JSON.parse(oidcProviderCall![1]!.body as string); expect(oidcBody.attributeCondition).toBe( - "assertion.iss == 'https://api.example.com' && assertion.project_id == 'sam-project-123'", + "assertion.iss == 'https://api.example.com' && assertion.project_id == 'sam-project-123'" ); // Verify IAM binding uses subject-scoped principal (not wildcard) const setIamCall = mockFetch.mock.calls[6]; const iamBody = JSON.parse(setIamCall![1]!.body as string); const wifBinding = iamBody.policy.bindings.find( - (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser', + (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser' ); expect(wifBinding.members[0]).toContain('subject/project:sam-project-123'); expect(wifBinding.members[0]).not.toContain('/*'); @@ -128,21 +125,23 @@ describe('runGcpDeploySetup', () => { const grantRolesSetIamCall = mockFetch.mock.calls[8]; const grantRolesBody = JSON.parse(grantRolesSetIamCall![1]!.body as string); const ownerBinding = grantRolesBody.policy.bindings.find( - (b: { role: string }) => b.role === 'roles/owner', + (b: { role: string }) => b.role === 'roles/owner' ); expect(ownerBinding).toBeDefined(); - expect(ownerBinding.members).toContain(`serviceAccount:sam-deployer@my-project.iam.gserviceaccount.com`); + expect(ownerBinding.members).toContain( + `serviceAccount:sam-deployer@my-project.iam.gserviceaccount.com` + ); }); it('uses configurable env vars for pool/provider/sa IDs', async () => { // Mock all responses as before - mockFetch.mockResolvedValueOnce( - mockGcpResponse({ projectId: 'p1', projectNumber: '111' }), - ); + mockFetch.mockResolvedValueOnce(mockGcpResponse({ projectId: 'p1', projectNumber: '111' })); mockFetch.mockResolvedValueOnce(mockGcpResponse({ done: true })); mockFetch.mockResolvedValueOnce(mockGcpResponse({ done: true })); mockFetch.mockResolvedValueOnce(mockGcpResponse({ done: true })); - mockFetch.mockResolvedValueOnce(mockGcpResponse({ email: 'custom@p1.iam.gserviceaccount.com' })); + mockFetch.mockResolvedValueOnce( + mockGcpResponse({ email: 'custom@p1.iam.gserviceaccount.com' }) + ); mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'a' })); mockFetch.mockResolvedValueOnce(mockGcpResponse({ etag: 'b' })); mockFetch.mockResolvedValueOnce(mockGcpResponse({ bindings: [], etag: 'c' })); @@ -155,7 +154,7 @@ describe('runGcpDeploySetup', () => { GCP_DEPLOY_WIF_POOL_ID: 'custom-pool', GCP_DEPLOY_WIF_PROVIDER_ID: 'custom-provider', GCP_DEPLOY_SERVICE_ACCOUNT_ID: 'custom', - }), + }) ); expect(result.wifPoolId).toBe('custom-pool'); @@ -166,7 +165,7 @@ describe('runGcpDeploySetup', () => { it('propagates GcpApiError when getProjectNumber fails', async () => { vi.spyOn(console, 'error').mockImplementation(() => {}); const rawBody = JSON.stringify({ - error: { code: 403, message: "Permission denied on projects/secret-project-id" }, + error: { code: 403, message: 'Permission denied on projects/secret-project-id' }, }); mockFetch.mockResolvedValueOnce(mockGcpResponse(JSON.parse(rawBody), 403)); @@ -194,7 +193,11 @@ describe('runGcpDeploySetup', () => { mockFetch.mockResolvedValueOnce(mockGcpResponse({ done: true })); // 3. createWifPool fails with 403 const rawBody = JSON.stringify({ - error: { code: 403, message: "Permission 'iam.workloadIdentityPools.create' denied on 'projects/999/locations/global'" }, + error: { + code: 403, + message: + "Permission 'iam.workloadIdentityPools.create' denied on 'projects/999/locations/global'", + }, }); mockFetch.mockResolvedValueOnce(mockGcpResponse(JSON.parse(rawBody), 403)); 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 a0c725763c..f52c02df31 100644 --- a/apps/api/tests/unit/services/gcp-api-health.test.ts +++ b/apps/api/tests/unit/services/gcp-api-health.test.ts @@ -281,6 +281,16 @@ describe('runGcpSetup', () => { ) { return existing ? json({ error: { code: 409 } }, 409) : json({ done: true }); } + if ( + url.includes('/workloadIdentityPools/sam-pool/providers/') && + (init?.method ?? 'GET') === 'GET' + ) { + // This installation's own provider from an earlier run. + return json({ + name: url.slice(url.indexOf('projects/')), + oidc: { issuerUri: 'https://api.example.com' }, + }); + } if (init?.method === 'PATCH') return json({ done: true }); if (url.endsWith(':getIamPolicy')) return json({ bindings: [], etag: 'etag-1' }); if (url.endsWith(':setIamPolicy')) return json({ etag: 'etag-2' }); 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 new file mode 100644 index 0000000000..88fcef6234 --- /dev/null +++ b/apps/api/tests/unit/services/gcp-wif-installation-isolation.test.ts @@ -0,0 +1,81 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createOidcProvider, updateOidcProvider } from '../../../src/services/gcp-setup'; + +const name = 'projects/123456/locations/global/workloadIdentityPools/shared/providers/sam-oidc'; +const issuer = 'https://api.primary.example'; +let fetchMock: ReturnType; + +function existingProvider(body: unknown) { + fetchMock.mockImplementation(async (_url, init) => { + if (init?.method === 'POST') return Response.json({}, { status: 409 }); + if (init?.method === 'PATCH') return Response.json({ name: 'operations/update', done: true }); + return Response.json(body); + }); +} + +async function create() { + return createOidcProvider('oauth-token', '123456', 'shared', 'sam-oidc', issuer, 5000); +} + +beforeEach(() => { + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); +}); +afterEach(() => vi.unstubAllGlobals()); + +describe('OIDC provider conflicts preserve the other installation', () => { + it('refuses the staging2 issuer after a create conflict without sending a PATCH', async () => { + existingProvider({ name, oidc: { issuerUri: 'https://api.secondary.example' } }); + await expect(create()).rejects.toMatchObject({ + name: 'GcpApiError', + step: 'oidc_provider_issuer_mismatch', + }); + expect(fetchMock.mock.calls.map(([, init]) => init?.method ?? 'GET')).toEqual(['POST', 'GET']); + }); + + 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) + ).rejects.toMatchObject({ step: 'oidc_provider_issuer_mismatch' }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('updates an existing provider for the same installation (upgrade control)', async () => { + existingProvider({ name, oidc: { issuerUri: issuer } }); + await expect(create()).resolves.toBeUndefined(); + expect(fetchMock.mock.calls.map(([, init]) => init?.method ?? 'GET')).toEqual([ + 'POST', + 'GET', + 'PATCH', + ]); + const patch = JSON.parse(fetchMock.mock.calls[2]![1].body); + expect(patch.oidc.issuerUri).toBe(issuer); + }); + + it('creates a new provider without an extra lookup (clean-install control)', async () => { + fetchMock.mockResolvedValueOnce(Response.json({ name: 'operations/create', done: true })); + await expect(create()).resolves.toBeUndefined(); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it.each([ + { name }, + { name, oidc: {} }, + { name, oidc: { issuerUri: null } }, + { name: 'projects/foreign/provider', oidc: { issuerUri: issuer } }, + ])('refuses malformed or different provider identity without PATCH: %j', async (body) => { + existingProvider(body); + await expect(create()).rejects.toThrow(); + expect(fetchMock.mock.calls.some(([, init]) => init?.method === 'PATCH')).toBe(false); + }); + + it('preserves a failed lookup instead of updating an unknown provider', async () => { + fetchMock.mockImplementation(async (_url, init) => + Response.json({}, { status: init?.method === 'POST' ? 409 : 403 }) + ); + await expect(create()).rejects.toThrow(); + expect(fetchMock.mock.calls.map(([, init]) => init?.method ?? 'GET')).toEqual(['POST', 'GET']); + }); +}); 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 e112b07e8b..ab7cb75c97 100644 --- a/apps/api/tests/unit/services/gcp-wif-scoping.test.ts +++ b/apps/api/tests/unit/services/gcp-wif-scoping.test.ts @@ -1,4 +1,4 @@ -import { beforeEach,describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * Security tests for WIF pool IAM binding scoping. @@ -9,9 +9,8 @@ import { beforeEach,describe, expect, it, vi } from 'vitest'; const mockFetch = vi.fn(); vi.stubGlobal('fetch', mockFetch); -const { createOidcProvider, updateOidcProvider, grantWifUserOnSa } = await import( - '../../../src/services/gcp-setup' -); +const { createOidcProvider, updateOidcProvider, grantWifUserOnSa } = + await import('../../../src/services/gcp-setup'); function mockGcpResponse(body: unknown, status = 200) { return { @@ -38,13 +37,13 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sam-oidc', 'https://api.example.com', 5000, - 'proj-abc-123', + 'proj-abc-123' ); 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' && assertion.project_id == 'proj-abc-123'", + "assertion.iss == 'https://api.example.com' && assertion.project_id == 'proj-abc-123'" ); }); @@ -57,7 +56,7 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sam-pool', 'sam-oidc', 'https://api.example.com', - 5000, + 5000 ); const call = mockFetch.mock.calls[0]; @@ -68,7 +67,13 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { it('passes samProjectId to updateOidcProvider on 409 conflict', async () => { // First call returns 409 (already exists) mockFetch.mockResolvedValueOnce(mockGcpResponse({}, 409)); - // Second call is the PATCH update + mockFetch.mockResolvedValueOnce( + mockGcpResponse({ + name: 'projects/123456/locations/global/workloadIdentityPools/sam-pool/providers/sam-oidc', + oidc: { issuerUri: 'https://api.example.com' }, + }) + ); + // Third call is the PATCH update mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); await createOidcProvider( @@ -78,20 +83,26 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sam-oidc', 'https://api.example.com', 5000, - 'proj-abc-123', + 'proj-abc-123' ); // The update call (second fetch) should have project-scoped condition - const updateCall = mockFetch.mock.calls[1]; + const updateCall = mockFetch.mock.calls[2]; const updateBody = JSON.parse(updateCall![1]!.body as string); expect(updateBody.attributeCondition).toBe( - "assertion.iss == 'https://api.example.com' && assertion.project_id == 'proj-abc-123'", + "assertion.iss == 'https://api.example.com' && assertion.project_id == 'proj-abc-123'" ); }); }); describe('updateOidcProvider', () => { it('enforces project-scoped attributeCondition when samProjectId is provided', async () => { + mockFetch.mockResolvedValueOnce( + mockGcpResponse({ + name: 'projects/123456/locations/global/workloadIdentityPools/sam-pool/providers/sam-oidc', + oidc: { issuerUri: 'https://api.example.com' }, + }) + ); mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); await updateOidcProvider( @@ -101,17 +112,23 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sam-oidc', 'https://api.example.com', 5000, - 'proj-xyz-789', + 'proj-xyz-789' ); - const call = mockFetch.mock.calls[0]; + 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'", + "assertion.iss == 'https://api.example.com' && assertion.project_id == 'proj-xyz-789'" ); }); it('uses issuer-only attributeCondition when samProjectId is not provided', async () => { + mockFetch.mockResolvedValueOnce( + mockGcpResponse({ + name: 'projects/123456/locations/global/workloadIdentityPools/sam-pool/providers/sam-oidc', + oidc: { issuerUri: 'https://api.example.com' }, + }) + ); mockFetch.mockResolvedValueOnce(mockGcpResponse({ name: 'op/1', done: true })); await updateOidcProvider( @@ -120,10 +137,10 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sam-pool', 'sam-oidc', 'https://api.example.com', - 5000, + 5000 ); - const call = mockFetch.mock.calls[0]; + 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'"); }); @@ -143,18 +160,18 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sa@my-gcp-project.iam.gserviceaccount.com', 'sam-pool', 5000, - 'proj-abc-123', + 'proj-abc-123' ); 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', + (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser' ); // 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', + 'principal://iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/sam-pool/subject/project:proj-abc-123' ); expect(binding.members[0]).not.toContain('/*'); }); @@ -171,17 +188,17 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { '123456', 'sa@my-gcp-project.iam.gserviceaccount.com', 'sam-pool', - 5000, + 5000 ); const setCall = mockFetch.mock.calls[1]; const setBody = JSON.parse(setCall![1]!.body as string); const binding = setBody.policy.bindings.find( - (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser', + (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser' ); expect(binding.members[0]).toBe( - 'principalSet://iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/sam-pool/*', + 'principalSet://iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/sam-pool/*' ); }); @@ -201,13 +218,13 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sa@my-gcp-project.iam.gserviceaccount.com', 'sam-pool', 5000, - projectId, + 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', + (b: { role: string }) => b.role === 'roles/iam.workloadIdentityUser' ); members.push(binding.members[0]); } @@ -234,8 +251,8 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sam-oidc', 'https://api.example.com', 5000, - "x' || true || 'y", - ), + "x' || true || 'y" + ) ).rejects.toThrow('unsafe for CEL interpolation'); }); @@ -248,8 +265,8 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sa@x.com', 'sam-pool', 5000, - 'project with spaces', - ), + 'project with spaces' + ) ).rejects.toThrow('unsafe for CEL interpolation'); }); @@ -265,8 +282,8 @@ describe('WIF pool scoping (cross-project impersonation prevention)', () => { 'sam-oidc', 'https://api.example.com', 5000, - '01KHRJGANBBWGDY1NZ0KVF0D4J', - ), + '01KHRJGANBBWGDY1NZ0KVF0D4J' + ) ).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 new file mode 100644 index 0000000000..15619d9181 --- /dev/null +++ b/apps/api/tests/unit/services/gcp-wif-shared-project.test.ts @@ -0,0 +1,196 @@ +/** + * Two SAM installations connecting one Google Cloud project. + * + * Reproduces the 2026-11-17 incident: staging2's setup PATCHed the shared `sam-pool/sam-oidc` + * provider to its own issuer and primary staging's STS exchange failed. Setup now names a + * provider per installation, so both installations coexist in one pool. The fake below keeps + * Google's provider state, answers create conflicts with 409 and records every PATCH. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { runGcpDeploySetup } from '../../../src/services/gcp-deploy-setup'; +import { installationWifProviderId, runGcpSetup } from '../../../src/services/gcp-setup'; + +const PROJECT_NUMBER = '353771248703'; +const PRIMARY = 'sammy.party'; +const STAGING2 = 'sammy2.party'; + +interface FakeProvider { + issuerUri: string; +} + +let providers: Map; +let patched: string[]; + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +/** Google IAM with real provider state for the endpoints setup calls. */ +function fakeGoogle(input: string | URL, init?: RequestInit): Response { + const url = String(input); + const method = init?.method ?? 'GET'; + if (url.includes('cloudresourcemanager.googleapis.com/v1/projects/') && method === 'GET') { + return json({ projectNumber: PROJECT_NUMBER }); + } + if (url.endsWith(':batchEnable')) return json({ done: true }); + if (url.endsWith(':getIamPolicy')) return json({ bindings: [], etag: 'etag-1' }); + if (url.endsWith(':setIamPolicy')) return json({ etag: 'etag-2' }); + if (url.includes('/workloadIdentityPools?') || url.endsWith('/serviceAccounts')) { + return json({ error: { code: 409 } }, 409); + } + const create = url.match(/\/(projects\/.+\/providers)\?workloadIdentityPoolProviderId=([^&]+)/); + if (create && method === 'POST') { + const name = `${create[1]}/${create[2]}`; + if (providers.has(name)) return json({ error: { code: 409 } }, 409); + const body = JSON.parse(String(init?.body)) as { oidc: FakeProvider }; + providers.set(name, { issuerUri: body.oidc.issuerUri }); + return json({ done: true }); + } + const resource = url.match(/\/v1\/(projects\/[^?]+\/providers\/[^?/]+)/); + if (resource) { + const name = resource[1]!; + const existing = providers.get(name); + if (!existing) return json({ error: { code: 404 } }, 404); + if (method === 'GET') return json({ name, oidc: existing }); + if (method === 'PATCH') { + patched.push(name); + const body = JSON.parse(String(init?.body)) as { oidc: FakeProvider }; + providers.set(name, { issuerUri: body.oidc.issuerUri }); + return json({ done: true }); + } + } + throw new Error(`Unexpected Google request: ${method} ${url}`); +} + +function providerName(pool: string, provider: string): string { + return `projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${pool}/providers/${provider}`; +} + +function envFor(baseDomain: string, extra: Partial = {}): Env { + return { BASE_DOMAIN: baseDomain, ...extra } as unknown as Env; +} + +async function connect(baseDomain: string, extra: Partial = {}) { + return runGcpSetup( + 'oauth-token', + 'sam-staging-infra', + 'us-central1-a', + envFor(baseDomain, extra) + ); +} + +beforeEach(() => { + providers = new Map(); + patched = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL, init?: RequestInit) => fakeGoogle(input, init)) + ); +}); +afterEach(() => vi.unstubAllGlobals()); + +describe('installations sharing one Google Cloud project', () => { + it('connects primary while the legacy shared provider trusts staging2 (incident shape)', async () => { + // State after 2026-11-17 12:00:31Z: staging2's setup owns the legacy provider name. + providers.set(providerName('sam-pool', 'sam-oidc'), { issuerUri: `https://api.${STAGING2}` }); + + const credential = await connect(PRIMARY); + + expect(credential.wifProviderId).toBe(await installationWifProviderId(PRIMARY)); + expect(credential.wifProviderId).not.toBe('sam-oidc'); + expect(providers.get(providerName('sam-pool', credential.wifProviderId))).toEqual({ + issuerUri: `https://api.${PRIMARY}`, + }); + // staging2's trust is untouched. + expect(providers.get(providerName('sam-pool', 'sam-oidc'))).toEqual({ + issuerUri: `https://api.${STAGING2}`, + }); + expect(patched).toEqual([]); + }); + + it('keeps both installations trusted when each connects and then re-runs setup', async () => { + const primary = await connect(PRIMARY); + const staging2 = await connect(STAGING2); + // A re-run (for example after a new required API) updates only its own provider. + const primaryAgain = await connect(PRIMARY); + + expect(primary.wifPoolId).toBe(staging2.wifPoolId); + expect(primary.wifProviderId).not.toBe(staging2.wifProviderId); + expect(primaryAgain.wifProviderId).toBe(primary.wifProviderId); + expect(providers.get(providerName('sam-pool', primary.wifProviderId))?.issuerUri).toBe( + `https://api.${PRIMARY}` + ); + expect(providers.get(providerName('sam-pool', staging2.wifProviderId))?.issuerUri).toBe( + `https://api.${STAGING2}` + ); + expect(patched).toEqual([providerName('sam-pool', primary.wifProviderId)]); + }); + + 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)); + + expect(primary.wifPoolId).toBe('sam-deploy-pool'); + expect(primary.wifProviderId).not.toBe(staging2.wifProviderId); + expect(providers.get(providerName('sam-deploy-pool', primary.wifProviderId))?.issuerUri).toBe( + `https://api.${PRIMARY}` + ); + expect(providers.get(providerName('sam-deploy-pool', staging2.wifProviderId))?.issuerUri).toBe( + `https://api.${STAGING2}` + ); + }); + + it('honours an explicit provider override', async () => { + const credential = await connect(PRIMARY, { GCP_WIF_PROVIDER_ID: 'operator-chosen' }); + expect(credential.wifProviderId).toBe('operator-chosen'); + }); + + it('still refuses to take over a foreign provider that has the derived name', async () => { + const derived = await installationWifProviderId(PRIMARY); + providers.set(providerName('sam-pool', derived), { + issuerUri: 'https://api.elsewhere.example', + }); + + await expect(connect(PRIMARY)).rejects.toMatchObject({ step: 'oidc_provider_issuer_mismatch' }); + expect(patched).toEqual([]); + }); +}); + +describe('installationWifProviderId', () => { + const GOOGLE_PROVIDER_ID = /^[a-z0-9-]{4,32}$/; + + it.each([ + 'sammy.party', + 'sammy2.party', + 'simple-agent-manager.org', + 'a.very.long.self-hosted.subdomain.of.some-company.example.co.uk', + 'X', + '...', + ])('produces a valid Google provider ID for %s', async (domain) => { + const id = await installationWifProviderId(domain); + expect(id).toMatch(GOOGLE_PROVIDER_ID); + expect(id.startsWith('gcp-')).toBe(false); + expect(id.endsWith('-')).toBe(false); + }); + + it('is readable, deterministic and case-insensitive', async () => { + const id = await installationWifProviderId('sammy2.party'); + expect(id).toMatch(/^sam-sammy2-party-[0-9a-f]{6}$/); + expect(await installationWifProviderId('SAMMY2.party')).toBe(id); + }); + + it('separates domains whose slugs collide', async () => { + expect(await installationWifProviderId('a-b.org')).not.toBe( + await installationWifProviderId('a.b.org') + ); + }); + + it('refuses an empty base domain instead of naming a shared provider', async () => { + await expect(installationWifProviderId(' ')).rejects.toThrow(/BASE_DOMAIN/); + }); +}); diff --git a/apps/api/tests/unit/services/node-tunnel-hardening.test.ts b/apps/api/tests/unit/services/node-tunnel-hardening.test.ts index d54b1387d2..1d0be628cb 100644 --- a/apps/api/tests/unit/services/node-tunnel-hardening.test.ts +++ b/apps/api/tests/unit/services/node-tunnel-hardening.test.ts @@ -4,6 +4,7 @@ import './node-tunnel-fixture'; import { markProviderCreateNotDispatched, ProviderError } from '@simple-agent-manager/providers'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { GcpApiError } from '../../../src/services/gcp-errors'; import { NodeAllocationUncertainError } from '../../../src/services/node-allocation-recovery'; import { releaseDurableTunnelBeforeVm } from '../../../src/services/node-provisioning-predicates'; import { @@ -639,3 +640,163 @@ describe('a durable allocation that ends before any create POST releases its tun expect(cf.liveTunnels()).toHaveLength(1); }); }); + +describe('terminal GCP failures before the provider create was dispatched', () => { + it('records exact absence after a resolved binding upgrade and strict teardown needs no new token', async () => { + const node = await freshNode(); + mocks.createProvider.mockResolvedValue({ + ...provider, providerName: 'gcp', + exactCredentialBinding: { credentialSource: 'user', credentialReference: 'credentials:resolved', credentialVersion: 7, credentialFingerprint: 'sha256:resolved' }, + }); + const failure = markProviderCreateNotDispatched( + new GcpApiError({ + step: 'sts_exchange', + statusCode: 400, + message: 'GCP STS token exchange failed (400)', + rawBody: JSON.stringify({ error: 'invalid_grant' }), + }) + ); + mocks.createVM.mockRejectedValueOnce(failure); + await provisionNode(node.id, env); + expect(readNode(node.id)).toMatchObject({ + status: 'error', + providerInstanceId: null, + proof: expect.any(String), + }); + expect(mocks.createVM).toHaveBeenCalledTimes(1); + expect(mocks.deleteVM).not.toHaveBeenCalled(); + // The proof is server-written on this exact incarnation, not inferred from error text. + const { deleteNodeResourcesStrict } = + await import('../../../src/services/strict-node-deletion'); + mocks.createProvider.mockRejectedValue(new Error('credential can no longer mint a token')); + const calls = mocks.createProvider.mock.calls.length; + await expect(deleteNodeResourcesStrict(node.id, 'user-1', env)).resolves.toMatchObject({ + providerVm: 'no-instance', + }); + expect(mocks.createProvider).toHaveBeenCalledTimes(calls); + }); + + it('refuses absence when the resolved binding changes after the identity claim', async () => { + const node = await freshNode(); + mocks.createProvider.mockResolvedValue({ + ...provider, providerName: 'gcp', + exactCredentialBinding: { credentialSource: 'user', credentialReference: 'credentials:resolved', credentialVersion: 7, credentialFingerprint: 'sha256:resolved' }, + }); + mocks.createVM.mockImplementationOnce(async () => { + const bound = sqlite.prepare('SELECT placement_credential_fingerprint AS fingerprint FROM nodes WHERE id=?').get(node.id); + expect(bound).toEqual({ fingerprint: 'sha256:resolved' }); + sqlite.prepare('UPDATE nodes SET placement_credential_fingerprint=? WHERE id=?').run('sha256:rotated', node.id); + throw markProviderCreateNotDispatched(new GcpApiError({ step: 'sts_exchange', statusCode: 400, message: 'STS refused' })); + }); + await provisionNode(node.id, env); + expect(mocks.createVM).toHaveBeenCalledTimes(1); + expect(readNode(node.id)).toMatchObject({ status: 'error', proof: null }); + }); + + it.each([ + ['fully absent', null, null, false], + ['weak proof only', 1, null, false], + ['strong proof present', 1, 'sha256:original', false], + ['strong proof mismatched', 1, 'sha256:original', true], + ] as const)( + 'fences terminal absence for binding state: %s', + async (_state, version, fingerprint, mutate) => { + const node = await freshNode(); + sqlite + .prepare( + 'UPDATE nodes SET placement_credential_source=?, placement_credential_reference=?, placement_credential_version=?, placement_credential_fingerprint=? WHERE id=?' + ) + .run( + version === null ? null : 'user', + version === null ? null : 'credentials:cred-1', + version, + fingerprint, + node.id + ); + mocks.createProvider.mockResolvedValue({ ...provider, providerName: 'gcp' }); + mocks.createVM.mockImplementationOnce(async () => { + if (mutate) + sqlite + .prepare('UPDATE nodes SET placement_credential_fingerprint=? WHERE id=?') + .run('sha256:rotated', node.id); + throw markProviderCreateNotDispatched( + new GcpApiError({ step: 'sts_exchange', statusCode: 400, message: 'STS refused' }) + ); + }); + await provisionNode(node.id, env); + expect(mocks.createVM).toHaveBeenCalledTimes(1); + expect(readNode(node.id)).toMatchObject({ + status: 'error', + proof: mutate ? null : expect.any(String), + }); + } + ); + + it('a previously unproven incarnation cannot gain absence from a later unsent failure', async () => { + const node = await freshNode(); + sqlite + .prepare('UPDATE nodes SET runtime_termination_confirmed_at=NULL WHERE id=?') + .run(node.id); + mocks.createProvider.mockResolvedValue({ ...provider, providerName: 'gcp' }); + mocks.createVM.mockRejectedValueOnce( + markProviderCreateNotDispatched( + new GcpApiError({ step: 'sts_exchange', statusCode: 400, message: 'STS refused' }) + ) + ); + await provisionNode(node.id, env); + expect(mocks.createVM).toHaveBeenCalledTimes(1); + expect(readNode(node.id)).toMatchObject({ status: 'error', proof: null }); + }); + + it.each(['proof', 'placement'] as const)( + 'does not overwrite a changed %s after recording absence but before recording failure', + async (changed) => { + const node = await freshNode(); + mocks.createProvider.mockResolvedValue({ ...provider, providerName: 'gcp' }); + mocks.createVM.mockRejectedValueOnce( + markProviderCreateNotDispatched( + new GcpApiError({ step: 'sts_exchange', statusCode: 400, message: 'STS refused' }) + ) + ); + const { persistError } = await import('../../../src/services/observability'); + let proofBefore: string | null = null; + vi.mocked(persistError).mockImplementationOnce(async () => { + // Production awaits this durable error report between the two real D1 writes. + // Mutate only the field the final guard must protect; keep the original incarnation. + proofBefore = readNode(node.id)!.proof; + expect(proofBefore).toEqual(expect.any(String)); + if (changed === 'proof') { + sqlite + .prepare('UPDATE nodes SET runtime_termination_confirmed_at=NULL WHERE id=?') + .run(node.id); + } else { + sqlite + .prepare('UPDATE nodes SET placement_credential_fingerprint=? WHERE id=?') + .run('sha256:concurrent', node.id); + } + }); + await provisionNode(node.id, env); + expect(proofBefore).toEqual(expect.any(String)); + expect(mocks.createVM).toHaveBeenCalledTimes(1); + expect(readNode(node.id)).toMatchObject({ + status: 'creating', + proof: changed === 'proof' ? null : proofBefore, + }); + } + ); + + it('an unmarked STS 400 remains uncertain despite matching error text', async () => { + const node = await freshNode(); + mocks.createProvider.mockResolvedValue({ ...provider, providerName: 'gcp' }); + mocks.createVM.mockRejectedValueOnce( + new GcpApiError({ + step: 'sts_exchange', + statusCode: 400, + message: 'GCP STS token exchange failed (400)', + }) + ); + await provisionNode(node.id, env); + expect(readNode(node.id)).toMatchObject({ status: 'error', proof: null }); + expect(mocks.createVM).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/tests/workers/node-manual-deletion.test.ts b/apps/api/tests/workers/node-manual-deletion.test.ts index c03d5d8d61..fa79f8fd54 100644 --- a/apps/api/tests/workers/node-manual-deletion.test.ts +++ b/apps/api/tests/workers/node-manual-deletion.test.ts @@ -413,6 +413,45 @@ describe('owner-confirmed removal of a node SAM cannot delete', () => { ).toEqual({ status: 'cleanup_pending', cleanup_reason: 'owner_attested_termination' }); }); + it.each([ + ['fully absent', null, null], + ['weak proof only', 1, null], + ['strong proof present', 1, 'sha256:recorded'], + ['strong proof mismatched', 1, 'sha256:rotated'], + ] as const)( + 'keeps owner-attested provenance for providerless GCP binding: %s', + async (state, version, fingerprint) => { + const seeded = await seedStuckDeploymentNode(`binding-${state.replaceAll(' ', '-')}`); + await env.DATABASE.prepare( + `UPDATE nodes SET provider_instance_id=NULL, cloud_provider='gcp', + placement_credential_source=?, placement_credential_reference=?, + placement_credential_version=?, placement_credential_fingerprint=? WHERE id=?` + ) + .bind( + version === null ? null : 'user', + version === null ? null : 'credentials:old', + version, + fingerprint, + seeded.nodeId + ) + .run(); + const fetchSpy = vi.fn(async () => { + throw new Error('token exchange must not be attempted'); + }); + vi.stubGlobal('fetch', fetchSpy); + const response = await confirmManualDeletion(seeded.userId, seeded.nodeId); + expect(response.status).toBe(200); + const node = await readNode(seeded.nodeId); + expect(node).toMatchObject({ + status: 'deleted', + runtime_termination_confirmed_at: expect.any(String), + }); + expect(node?.runtime_termination_attested_at).toBe(node?.runtime_termination_confirmed_at); + expect(await ownerRemovalReason(seeded.nodeId)).toBe('owner_attested_manual_deletion'); + expect(fetchSpy).not.toHaveBeenCalled(); + } + ); + it('sends a machine the owner enrolled to Delete instead, and changes nothing', async () => { const seeded = await seedStuckDeploymentNode('user-owned'); await env.DATABASE.prepare(`UPDATE nodes SET node_class = 'user-owned' WHERE id = ?`) 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 88241ec6dd..149e9b4e03 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -83,13 +83,13 @@ reverse-tunnel node is never chosen as a snapshot-upload relay, since it has no The self-host build supplies these bootstrap settings; they are not Cloudflare Worker bindings: -| Setting | Default and contract | -| --- | --- | -| `REVERSE_TUNNEL_GATEWAY_SECRET` | Required random secret, at least 32 characters, shared with the frps/plugin gateway. | -| `REVERSE_TUNNEL_GATEWAY_SECRET_ALTERNATE` | Unset; optional second gateway secret during a coordinated rotation. | +| Setting | Default and contract | +| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `REVERSE_TUNNEL_GATEWAY_SECRET` | Required random secret, at least 32 characters, shared with the frps/plugin gateway. | +| `REVERSE_TUNNEL_GATEWAY_SECRET_ALTERNATE` | Unset; optional second gateway secret during a coordinated rotation. | | `REVERSE_TUNNEL_PORT_RANGE_START` / `REVERSE_TUNNEL_PORT_RANGE_END` | `20000` / `29999`; ports 1024–65535, at most 20,000 ports; must match frps `allowPorts`. | -| `REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS` | `90`; 60–3600 seconds; the build must supply the same timeout to frps. | -| `REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS` | `180`; cannot be shorter than twice the heartbeat timeout; maximum 86400 seconds. | +| `REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS` | `90`; 60–3600 seconds; the build must supply the same timeout to frps. | +| `REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS` | `180`; cannot be shorter than twice the heartbeat timeout; maximum 86400 seconds. | Allocation considers the whole bounded port range in one atomic SQL statement, with indexed history lookups. Release checks all active leases in one local statement, without network calls @@ -98,7 +98,6 @@ eligible leases; the self-host entry runs that backstop every five minutes. A ne freed port still waits for its cooling interval. A full range and a cooling range have distinct errors so operators can distinguish capacity exhaustion from a wait for safe reuse. - ## Speech endpoints on a single-box build This is a build integration foundation for the single-box runtime. Its entry must call @@ -119,13 +118,13 @@ Once your single-box build includes that integration: Use a base URL such as `https://speech.example.com/v1`; SAM appends the audio route, so do not include `/audio/transcriptions` or `/audio/speech`, credentials, a query, or a fragment. - | Voice input setting | Read-aloud setting | Value | - | --- | --- | --- | - | `speech.transcription.baseUrl` | `speech.synthesis.baseUrl` | The provider's API base URL. | - | `speech.transcription.model` | `speech.synthesis.model` | A model ID supported by that endpoint. | - | — | `speech.synthesis.voice` | A voice ID supported by the synthesis model; required. | - | `speech.transcription.apiKey` | `speech.synthesis.apiKey` | Optional Bearer API key; required when the provider requires authentication. | - | `speech.transcription.allowPrivateNetwork` | `speech.synthesis.allowPrivateNetwork` | Defaults to `false`; opt in only for a trusted private endpoint. | + | Voice input setting | Read-aloud setting | Value | + | ------------------------------------------ | -------------------------------------- | ---------------------------------------------------------------------------- | + | `speech.transcription.baseUrl` | `speech.synthesis.baseUrl` | The provider's API base URL. | + | `speech.transcription.model` | `speech.synthesis.model` | A model ID supported by that endpoint. | + | — | `speech.synthesis.voice` | A voice ID supported by the synthesis model; required. | + | `speech.transcription.apiKey` | `speech.synthesis.apiKey` | Optional Bearer API key; required when the provider requires authentication. | + | `speech.transcription.allowPrivateNetwork` | `speech.synthesis.allowPrivateNetwork` | Defaults to `false`; opt in only for a trusted private endpoint. | 3. Enter keys in the secret setting fields, never in the URL, repository, or GitHub Actions logs. SAM stores them encrypted in its credential store and sends them as Bearer tokens. @@ -453,6 +452,10 @@ Register both static redirect URIs on that infrastructure client: The flow requests the Google `cloud-platform` scope. Runtime values saved by a superadmin are encrypted in D1 and take precedence over the environment pair; removing the runtime pair reveals the environment fallback, if present. This client is never used for user login. Google sign-in uses a different client, different variable names (`GOOGLE_LOGIN_*`), and only `https://api.yourdomain.com/api/auth/callback/google`. +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. + +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) If the installation has no infrastructure OAuth client, a user can paste or choose a dedicated Google service-account JSON key. SAM ignores endpoint fields from the upload, signs RS256 assertions, exchanges them only at Google's fixed token endpoint, and verifies access to the selected Compute zone before replacing a working credential. diff --git a/packages/shared/src/constants/gcp-deployment.ts b/packages/shared/src/constants/gcp-deployment.ts index b62f2975a6..92e9bbbe0d 100644 --- a/packages/shared/src/constants/gcp-deployment.ts +++ b/packages/shared/src/constants/gcp-deployment.ts @@ -5,7 +5,10 @@ /** Default WIF pool ID for deployment. Override via GCP_DEPLOY_WIF_POOL_ID env var. */ export const DEFAULT_GCP_DEPLOY_WIF_POOL_ID = 'sam-deploy-pool'; -/** Default WIF provider ID for deployment. Override via GCP_DEPLOY_WIF_PROVIDER_ID env var. */ +/** + * Provider ID that deployment credentials saved without a recorded provider were created with. + * New setup runs derive a per-installation ID (`installationWifProviderId`). + */ export const DEFAULT_GCP_DEPLOY_WIF_PROVIDER_ID = 'sam-oidc'; /** Default service account ID for deployment. Override via GCP_DEPLOY_SERVICE_ACCOUNT_ID env var. */ diff --git a/packages/shared/src/constants/hetzner.ts b/packages/shared/src/constants/hetzner.ts index cb1626dd89..100269cba5 100644 --- a/packages/shared/src/constants/hetzner.ts +++ b/packages/shared/src/constants/hetzner.ts @@ -82,9 +82,6 @@ export const INFOMANIAK_BOOT_VOLUME_MAX_GB = 4_096; /** Default GCP WIF pool ID. Override via GCP_WIF_POOL_ID env var. */ export const DEFAULT_GCP_WIF_POOL_ID = 'sam-pool'; -/** Default GCP WIF provider ID. Override via GCP_WIF_PROVIDER_ID env var. */ -export const DEFAULT_GCP_WIF_PROVIDER_ID = 'sam-oidc'; - /** Default GCP service account ID. Override via GCP_SERVICE_ACCOUNT_ID env var. */ export const DEFAULT_GCP_SERVICE_ACCOUNT_ID = 'sam-vm-manager'; diff --git a/packages/shared/src/constants/index.ts b/packages/shared/src/constants/index.ts index 5347baa82a..7c4dd7b695 100644 --- a/packages/shared/src/constants/index.ts +++ b/packages/shared/src/constants/index.ts @@ -332,7 +332,6 @@ export { DEFAULT_GCP_STS_SCOPE, DEFAULT_GCP_TOKEN_CACHE_TTL_SECONDS, DEFAULT_GCP_WIF_POOL_ID, - DEFAULT_GCP_WIF_PROVIDER_ID, DEFAULT_GCP_ZONE, DEFAULT_HETZNER_DATACENTER, DEFAULT_HETZNER_IMAGE, diff --git a/tasks/archive/2026-11-18-primary-staging-gcp-provisioning.md b/tasks/archive/2026-11-18-primary-staging-gcp-provisioning.md new file mode 100644 index 0000000000..065b546d6e --- /dev/null +++ b/tasks/archive/2026-11-18-primary-staging-gcp-provisioning.md @@ -0,0 +1,63 @@ +# Repair primary staging GCP provisioning and stranded nodes + +SAM task 01M7NZTWT6AC98R70CGYJJZE0A; branch sam/repair-primary-staging-gcp-jjze0a. +Idea 01M7N20Z6P4VWCGG2C6VMZ4QQA. Merge authorized after /do gates. + +## Verified research + +Fresh primary /api/gcp/verify and Worker log at 2026-11-18T00:20Z: STS invalid_grant, issuer https://api.sammy.party differs from expected https://api.sammy2.party. GCP read-only IAM and audit: sam-staging-infra (353771248703), sam-pool/sam-oidc was updated by staging2 setup at Nov 17 12:00:31Z. createOidcProvider blindly PATCHes after 409. Do not repoint shared trust or widen issuers. + +D1: three affected nodes bind user GCP credential 01M7BS2M65D5PK3XBMMKPV463P, last updated Nov 14 10:23Z. No platform GCP exists. User pool explicitly ranks GCP before Hetzner (balanced/queue). All provider IDs/proofs null, no linked workspaces or provisioning leases. Independent reader inventory found zero VMs. Existing owner-attested manual removal returned 200 for all three at 00:25Z. Retain attested provenance; never call it strict termination proof. + +## Preflight + +Classes: external-api-change, business-logic-change, security-sensitive-change, docs-sync-change. +GCP setup conflict must read provider and compare issuer before same-issuer update. Unknown/malformed config refuses. No endpoint, callback, secret or identifier default changes. Existing static OAuth callback unchanged. One installation must not overwrite another's trust. +Positive GCP create-not-dispatched sentinel may establish absence only for terminal non-durable allocation, fenced to original placement/incarnation. Intermediate durable retries retain semantics. Never infer absence from STS text or empty inventory. +References: rules19/28/56/62/71, PR2715; official Google WIF configuration and best-practices docs (docs.cloud.google.com/iam/). + +## Checklist + +- [x] Verify original claims; publish root cause and coordinator status. +- [x] One nonblocking exact IAM task: ask:01M7P0M7X3R0WCA84941B07T4N (read-only identity). +- [x] Supported owner-attested removal for historical nodes, no D1 edits. +- [x] Confirm final node/tunnel state and independent provider absence. +- [x] Prevent foreign-issuer WIF overwrite, with regression controls. +- [x] Safe absence proof for unsent terminal allocations; preserve uncertain/durable cases. +- [x] Separate binding-state tests for owner escape against real D1. +- [x] Public setup/troubleshooting docs. +- [x] Local lint/typecheck/test/build and specialist reviews. +- [x] Primary staging deploy/live verification, maximum two test VMs cleaned promptly. +- [x] Canonical 24h noise gate passes; preserve historical evidence while it ages naturally. +- [ ] CI, CodeRabbit, merge and read-only production deploy monitoring. + +## Acceptance + +Primary trust repaired without breaking staging2 when human IAM task completes; GCP VM provisioning verified. Existing nodes removed via supported escape with named provenance. New unsent allocations reclaimable. Foreign/malformed trust refuses before PATCH. Ownership and durable retry controls pass. New primary deploy passes canonical noise gate; any external blocker remains explicit. + +## Local validation and review + +WIF isolation regression: original behavior failed 8/9; the fresh-create control passed. Candidate focused 60 tests and 24 Workers tests pass; additional final-write race controls bring node hardening to 38 tests. In an isolated mutation worktree, removing only the final proof/placement predicates makes both races fail (cleared proof resurrected and status overwritten). Removing only the strong binding predicate fails the mismatch case while three other binding controls pass. All six mutation controls pass after restoring the candidate. + +Security, Cloudflare, constitution, docs and test reviews pass. API lint, typecheck/build and the 298-page docs build pass. Full API suite running. Context budget passes. Task-completion implementation audit found no additional code/test gaps (A/B/E/F pass, D not applicable); overall WARN because live IAM/provisioning and canonical noise verification remain unfulfilled. This is not completion or archive approval. + +PR2880 https://github.com/raphaeltm/simple-agent-manager/pull/2880. Task-file directmainpush rejected by protected Durable Object Workers check, so taskrecord travels in thisPR. No implementation bypass. Primary staging reservation position4; turn01:36:59Z, durable wake4c1e8738-08b7-4a41-bfa2-79423add4fa4. + +The first complete candidate was marked ready at approximately 00:47Z, with full CI and the trusted CodeRabbit label request running in parallel. CI/review subscriptions and a bounded scheduled fallback resume this chat; staging has its separate scheduled turn. No test VMs have been created. The single dedicated-WIF IAM inbox task remains open. + +Canonical24h gateaftercleanup: historical nodeerrors67/57/47, sessionverification59, snapshot33, price10; preserve evidence and wait for natural aging after recurrence is fixed. Never claim a shorter windowclears thisgate. + +Review follow-up: automated reviews identified a real direct-placement binding upgrade omission. The identity claim persisted the resolved exact credential, while the failure handler compared the original null snapshot. Capture and thread that same resolved binding; never re-resolve. The upgraded-binding strict-cleanup regression fails before this fix, while rotation refusal remains green. Focused four-file suite now passes 83 tests; candidate typecheck and lint pass. Security re-review approves; test re-review approves binding threading and its setup-fixture finding is corrected (omitted HTTP method means GET). The first full API run reported success=false, 16,737 passed/1 failed/16,742 total; its only failed setup fixture lacked the new identity GET. A second full run is required; do not report the first as passing. + +## Per-installation provider IDs (added 2026-11-18 at Raphaël's request) + +The issuer guard alone makes the second installation in a shared Google Cloud project fail instead of coexisting, and leaves primary staging unable to reconnect (the legacy `sam-pool/sam-oidc` now trusts staging2). Setup now derives the provider ID per installation from `BASE_DOMAIN` (`installationWifProviderId()` in `apps/api/src/services/gcp-wif-setup.ts`, used by `runGcpSetup()` and `runGcpDeploySetup()`); explicit `GCP_WIF_PROVIDER_ID` / `GCP_DEPLOY_WIF_PROVIDER_ID` overrides still win, and saved credentials keep their recorded IDs. Primary staging's repair is therefore a normal Connect GCP reconnect, which creates `sam-sammy-party-` beside staging2's provider; no hand-built IAM pool is needed. Covered by `apps/api/tests/unit/services/gcp-wif-shared-project.test.ts` (incident shape, two-installation re-run, deploy setup, override, foreign-name refusal); the incident and coexistence tests fail when the provider ID is fixed to `sam-oidc`. + +## Final verification (takeover task 01M7RHQ9Q0RCA8J8EF8RYF3AX5, 2026-11-19) + +- Primary canonical `pnpm quality:observability-noise` (unchanged script, 24h, threshold 10) at 03:14:54Z: exit 0, no findings. The last group (session verification 23x, all 01:00-02:37Z Nov 18) aged out naturally. +- Live isolation across both installations: staging2 ran 12a53 when the owner re-ran Connect GCP at 17:05Z Nov 18 (new credential `01M7QSX782RCKCFK359R9R9BKQ`). That credential strictly deleted real VM `01M7PXK8QYGWKBANPSN6JCT9R1` at 17:10:48Z and refreshed staging2's GCP price table at 17:40:58Z. Afterwards, primary `POST /api/gcp/verify` at 03:16:45Z Nov 19 returned verified=true, billingCheck ok, apiIssues []. Primary trust survived the second installation's setup. +- A staging2 VM create was not run. Provisioning, heartbeat and strict teardown of the same code were already proven on primary (09:11-09:19Z Nov 18), and staging2 token minting was proven by the strict delete above. Test VMs used by the takeover: 0. +- staging2 stuck uncertain-allocation fixtures `01M7QDJNF4AZ44BBH2B2411502` and `01M7QKWQDZK50ZX0YTXZG0S8VW` (staging2-test-user, user credential, provider_instance_id NULL, created during the shared-issuer breakage): removed at 00:42Z via the existing owner-attested `POST /api/nodes/:id/manual-deletion` (200, then GET 404). This was coordinator-authorized, after a read-only inventory of sam-staging-infra found 0 instances across 132 zones. Attested provenance, not strict proof. +- staging2 gate: remaining groups are pre-existing (the owner-exempted node `01M7MTMV89F5ZV23VSF0ZVPJPS`, STS 400 groups that ended at 17:00:59Z, the two removed fixtures aging out, and a periodic KV 429 burst across many builds). There were no new groups and no GCP errors during this PR's staging2 window (00:40-01:45Z Nov 19). Pre-existing noise waived per Raphaël 2026-11-18. +- Branch refreshed with main (da4aea30): API typecheck, 101 focused tests and changed-file lint pass; all runtime CI passes; staging2 deploy 44430979075 of da4aea30 succeeded, including smoke.