Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .claude/rules/75-external-api-check-then-act.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
35 changes: 28 additions & 7 deletions apps/api/src/services/gcp-deploy-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -15,6 +14,7 @@ import {
getProjectNumber,
grantProjectRoles,
grantWifUserOnSa,
installationWifProviderId,
type SetupProgressCallback,
} from './gcp-setup';

Expand Down Expand Up @@ -49,13 +49,15 @@ export async function runGcpDeploySetup(
gcpProjectId: string,
env: Env,
onProgress?: SetupProgressCallback,
samProjectId?: string,
samProjectId?: string
): Promise<Omit<ProjectDeploymentCredential, 'id' | 'userId' | 'createdAt' | 'updatedAt'>> {
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}`;

Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/services/gcp-errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ const STEP_HINTS: Record<string, string> = {
'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.',
Expand Down
18 changes: 18 additions & 0 deletions apps/api/src/services/gcp-setup-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Loading
Loading