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
62 changes: 62 additions & 0 deletions apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
-- One owner per Google Cloud workload identity pool. See services/gcp-wif-pool-ownership.ts.
-- No secret material is stored: an IV identifies a ciphertext generation, and a pool key is
-- `<projectNumber>/<poolId>`. No foreign keys: an index row references one of three tables, and
-- a claim deliberately outlives the credential that made it.
--
-- Existing credentials: pool identities are inside encrypted payloads, which SQL cannot read.
-- The Worker indexes every existing cloud credential, and claims the pools they name, on the first
-- ownership check after deploy (a token exchange or a GCP credential save). Until then the tables
-- are empty and no check trusts them: each check indexes unseen rows before it reads.
Comment thread
simple-agent-manager[bot] marked this conversation as resolved.
Resolved

-- The pool each stored cloud credential names, keyed by source row and indexed IV.
CREATE TABLE IF NOT EXISTS gcp_wif_pool_index (
source_table TEXT NOT NULL CHECK (source_table IN ('credentials', 'platform_credentials', 'cc_credentials')),
source_id TEXT NOT NULL,
iv TEXT NOT NULL,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('user', 'platform')),

Check failure on line 16 in apps/api/src/db/migrations/0262_gcp_wif_pool_index.sql

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of duplicating this literal 4 times.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHzBt6Lc21n98mLlM1o&open=AaHzBt6Lc21n98mLlM1o&pullRequest=2905
owner_user_id TEXT,
pool_key TEXT,
-- 1 when the row could not be decrypted; retried after gcpWif.poolIndexUnreadableRetryMinutes.
unreadable INTEGER NOT NULL DEFAULT 0 CHECK (unreadable IN (0, 1)),
indexed_at TEXT NOT NULL,
PRIMARY KEY (source_table, source_id),
CHECK ((owner_kind = 'user' AND owner_user_id IS NOT NULL) OR (owner_kind = 'platform' AND owner_user_id IS NULL))
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS idx_gcp_wif_pool_index_pool
ON gcp_wif_pool_index (pool_key) WHERE pool_key IS NOT NULL;
-- Unreadable rows withhold first claims for other owners; keep that lookup off a table scan.
CREATE INDEX IF NOT EXISTS idx_gcp_wif_pool_index_unreadable
ON gcp_wif_pool_index (source_table, source_id) WHERE unreadable = 1;

-- The first owner whose credential named a pool. Never released by deleting or re-pointing a
-- credential: the trust an earlier setup granted in Google outlives the SAM row. An operator
-- releases a claim by deleting its row once that Google-side trust is gone.
CREATE TABLE IF NOT EXISTS gcp_wif_pool_claims (
pool_key TEXT PRIMARY KEY NOT NULL,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('user', 'platform')),
owner_user_id TEXT,
claimed_at TEXT NOT NULL,
CHECK ((owner_kind = 'user' AND owner_user_id IS NOT NULL) OR (owner_kind = 'platform' AND owner_user_id IS NULL))
) WITHOUT ROWID;
Comment thread
simple-agent-manager[bot] marked this conversation as resolved.
Resolved

-- Deployment credentials store their pool in plaintext, so their claims are recorded here, before
-- any check runs: deleting a deployment credential must not free its pool. A pool named by more
-- than one owner gets no claim; the live rows keep refusing every owner until an operator decides.
INSERT INTO gcp_wif_pool_claims (pool_key, owner_kind, owner_user_id, claimed_at)
SELECT trim(gcp_project_number) || '/' || lower(trim(wif_pool_id)), 'user', min(user_id),
strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
FROM project_deployment_credentials
WHERE provider = 'gcp'
GROUP BY trim(gcp_project_number) || '/' || lower(trim(wif_pool_id))
HAVING count(DISTINCT user_id) = 1
ON CONFLICT (pool_key) DO NOTHING;

-- Keep the unindexed-row probe proportional to cloud credentials, not to every stored
-- credential (agent keys share these tables).
CREATE INDEX IF NOT EXISTS idx_credentials_gcp_cloud
ON credentials (id) WHERE provider = 'gcp' AND credential_type = 'cloud-provider';
CREATE INDEX IF NOT EXISTS idx_cc_credentials_cloud
Comment thread
simple-agent-manager[bot] marked this conversation as resolved.
Resolved
ON cc_credentials (id) WHERE kind = 'cloud-provider';
-- Deployment credentials store their pool in plaintext; the ownership check reads them directly.
CREATE INDEX IF NOT EXISTS idx_project_deployment_creds_gcp_project_number
ON project_deployment_credentials (gcp_project_number);
25 changes: 25 additions & 0 deletions apps/api/src/routes/admin-platform-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import { reconcileCapacityPoolsForCredentialMutation } from '../services/capacity-pool-credential-lifecycle';
import { decrypt, encrypt } from '../services/encryption';
import { deleteGcpApiHealthSafely } from '../services/gcp-api-health';
import { assertGcpWifPayloadOwnership } from '../services/gcp-wif-pool-ownership';

Check warning on line 28 in apps/api/src/routes/admin-platform-credentials.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'../services/gcp-wif-pool-ownership' imported multiple times.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHzOep-gB3MPlMYBynt&open=AaHzOep-gB3MPlMYBynt&pullRequest=2905
import { reconcileGcpWifPoolIndex } from '../services/gcp-wif-pool-ownership';

Check warning on line 29 in apps/api/src/routes/admin-platform-credentials.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'../services/gcp-wif-pool-ownership' imported multiple times.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHzOep-gB3MPlMYBynu&open=AaHzOep-gB3MPlMYBynu&pullRequest=2905
import { buildProviderConfig } from '../services/provider-credentials';
import { CredentialValidator } from '../services/validation';

Expand Down Expand Up @@ -124,6 +126,17 @@
}
}

if (body.credentialType === 'cloud-provider' && body.provider === 'gcp') {
// The installation owns platform credentials: a pool a user's credential names is not
// available to them, and the reverse is refused when users save.
await assertGcpWifPayloadOwnership(
c.env,
body.credential,
{ kind: 'platform' },
'save_platform_credential'
);
}

// Encrypt and store
const encryptionKey = getCredentialEncryptionKey(c.env);
const { ciphertext, iv } = await encrypt(body.credential, encryptionKey);
Expand Down Expand Up @@ -233,6 +246,18 @@
adminPlatformCredentialRoutes.delete('/:id', async (c) => {
const credentialId = c.req.param('id');
const db = drizzle(c.env.DATABASE, { schema });
const [target] = await db
.select({
credentialType: schema.platformCredentials.credentialType,
provider: schema.platformCredentials.provider,
})
.from(schema.platformCredentials)
.where(eq(schema.platformCredentials.id, credentialId))
.limit(1);
if (target?.credentialType === 'cloud-provider' && target.provider === 'gcp') {
// Record the pool a GCP platform credential names before it goes: Google may still trust it.
await reconcileGcpWifPoolIndex(c.env, 'delete_platform_credential');
}

const result = await db
.delete(schema.platformCredentials)
Expand Down
20 changes: 20 additions & 0 deletions apps/api/src/routes/composable-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import { errors } from '../middleware/error';
import { reconcileCapacityPoolsForCredentialMutation } from '../services/capacity-pool-credential-lifecycle';
import { encrypt } from '../services/encryption';
import { assertGcpWifPayloadOwnership } from '../services/gcp-wif-pool-ownership';

Check warning on line 27 in apps/api/src/routes/composable-credentials.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'../services/gcp-wif-pool-ownership' imported multiple times.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHzOepegB3MPlMYBynr&open=AaHzOepegB3MPlMYBynr&pullRequest=2905
import { reconcileGcpWifPoolIndex } from '../services/gcp-wif-pool-ownership';

Check warning on line 28 in apps/api/src/routes/composable-credentials.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'../services/gcp-wif-pool-ownership' imported multiple times.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHzOepegB3MPlMYByns&open=AaHzOepegB3MPlMYByns&pullRequest=2905
import { registerCCAttachmentRoutes, uniqueProjectIds } from './composable-credentials-attachments';
import { registerCCProfileAttachmentRoutes } from './composable-credentials-profile-attachments';

Expand Down Expand Up @@ -186,6 +188,14 @@

const encryptionKey = getCredentialEncryptionKey(c.env);
const tokenToEncrypt = typeof secret === 'string' ? secret : JSON.stringify(secret);
if (kind === 'cloud-provider') {
await assertGcpWifPayloadOwnership(
c.env,
tokenToEncrypt,
{ kind: 'user', userId },
'save_composable_credential'
);
}
const { ciphertext, iv } = await encrypt(tokenToEncrypt, encryptionKey);

const id = `cc-cred-${ulid()}`;
Expand Down Expand Up @@ -236,6 +246,16 @@
const { id } = c.req.param();

const affectedProjectIds = await listAffectedCredentialProjectIds(db, userId, id);
const [target] = await db
.select({ kind: schema.ccCredentials.kind })
.from(schema.ccCredentials)
.where(and(eq(schema.ccCredentials.id, id), eq(schema.ccCredentials.ownerId, userId)))
.limit(1);
if (target?.kind === 'cloud-provider') {
// A cloud credential may name a GCP pool; record it before the row goes (Google may still
// trust it). Agent keys and other kinds skip this.
await reconcileGcpWifPoolIndex(c.env, 'delete_composable_credential');
}

const result = await db
.delete(schema.ccCredentials)
Expand Down
3 changes: 3 additions & 0 deletions apps/api/src/routes/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
replaceUserGcpCredential,
} from '../services/gcp-credential-store';
import { clearGcpAccessTokenCache } from '../services/gcp-sts';
import { reconcileGcpWifPoolIndex } from '../services/gcp-wif-pool-ownership';
import { parseGcpCredential, serializeCredentialToken } from '../services/provider-credentials';
import {
CredentialValidator,
Expand Down Expand Up @@ -448,6 +449,8 @@ credentialsRoutes.delete('/:provider', async (c) => {
)
.limit(1);
if (!stored) throw errors.notFound('Credential');
// Record the pool this credential names before it goes: Google may still trust it.
await reconcileGcpWifPoolIndex(c.env, 'delete_user_gcp_credential');

let credential;
try {
Expand Down
37 changes: 31 additions & 6 deletions apps/api/src/routes/gcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,24 @@ import {
import { listGcpProjects, runGcpSetup } from '../services/gcp-setup';
import {
clearGcpAccessTokenCache,
type GcpTokenRequester,
getGcpAccessToken,
verifyGcpOidcSetup,
} from '../services/gcp-sts';
import {
assertGcpWifPoolOwnership,
isGcpWifPoolOwnershipError,
} from '../services/gcp-wif-pool-ownership';
import { getGoogleInfraOAuthConfig } from '../services/platform-config';
import { parseGcpCredential } from '../services/provider-credentials';

const gcpRoutes = new Hono<{ Bindings: Env }>();

/** A user acting on their own user-level GCP credential. */
function userTokenRequester(userId: string): GcpTokenRequester {
return { cacheUserId: userId, poolOwner: { kind: 'user', userId } };
}

gcpRoutes.use('*', requireAuth(), requireApproved());

async function resolveOAuthToken(handle: string, kv: KVNamespace): Promise<string> {
Expand Down Expand Up @@ -171,7 +181,7 @@ gcpRoutes.put(

try {
const accessToken = await getGcpAccessToken(
userId,
userTokenRequester(userId),
'service-account-setup',
credential,
c.env
Expand Down Expand Up @@ -212,8 +222,15 @@ gcpRoutes.post('/setup', jsonValidator(GcpSetupSchema), async (c) => {
const previous = await getStoredGcpCredential(c.env, userId).catch(() => null);
let credential: Awaited<ReturnType<typeof runGcpSetup>>;
try {
credential = await runGcpSetup(oauthToken, body.gcpProjectId, body.defaultZone, c.env);
credential = await runGcpSetup(oauthToken, body.gcpProjectId, body.defaultZone, c.env, {
userId,
// Runs once the project number is known and before SAM creates or changes anything in
// Google: a pool another owner already uses must not be re-pointed at this user.
assertPoolAvailable: (pool) =>
assertGcpWifPoolOwnership(c.env, pool, { kind: 'user', userId }, 'gcp_setup'),
});
} catch (err) {
if (isGcpWifPoolOwnershipError(err)) throw err;
throw toSanitizedAppError(err, 'gcp-setup');
}

Expand All @@ -224,7 +241,7 @@ gcpRoutes.post('/setup', jsonValidator(GcpSetupSchema), async (c) => {
await reconcileCapacityPoolsForCredentialMutation(c.env, { scope: 'user', userId });

try {
await verifyGcpOidcSetup(userId, 'setup-verification', credential, c.env);
await verifyGcpOidcSetup(userTokenRequester(userId), 'setup-verification', credential, c.env);
} catch (verifyErr) {
log.warn('gcp.oidc_verification_failed', {
error: verifyErr instanceof Error ? verifyErr.message : String(verifyErr),
Expand Down Expand Up @@ -272,16 +289,24 @@ gcpRoutes.post('/verify', async (c) => {

try {
if (gcpCredential.authType === 'service-account-key') {
const token = await getGcpAccessToken(userId, 'verification', gcpCredential, c.env);
const token = await getGcpAccessToken(
userTokenRequester(userId),
'verification',
gcpCredential,
c.env
);
await verifyGcpServiceAccountAccess(gcpCredential, token, c.env);
} else {
await verifyGcpOidcSetup(userId, 'verification', gcpCredential, c.env);
await verifyGcpOidcSetup(userTokenRequester(userId), 'verification', gcpCredential, c.env);
}
} catch (err) {
return c.json({
success: false,
verified: false,
error: sanitizeGcpError(err, 'gcp-verify'),
// An ownership refusal is the reason, not a Google failure: say so.
error: isGcpWifPoolOwnershipError(err)
? (err as Error).message
: sanitizeGcpError(err, 'gcp-verify'),
apiIssues: await listGcpApiIssuesSafely(c.env, credentialId, gcpCredential),
});
}
Expand Down
32 changes: 30 additions & 2 deletions apps/api/src/routes/project-deployment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { GcpOAuthHandleSchema, jsonValidator, ProjectDeploymentSetupSchema } fro
import { runGcpDeploySetup } from '../services/gcp-deploy-setup';
import { toSanitizedAppError } from '../services/gcp-errors';
import { listGcpProjects } from '../services/gcp-setup';
import { assertGcpWifPoolOwnership, isGcpWifPoolOwnershipError } from '../services/gcp-wif-pool-ownership';
import { signIdentityToken } from '../services/jwt';
import { validateActiveWorkspaceMcpToken } from '../services/mcp-token-lifecycle';
import { getGoogleInfraOAuthConfig } from '../services/platform-config';
Expand Down Expand Up @@ -185,10 +186,34 @@ projectDeploymentRoutes.post(

const oauthToken = await resolveDeployOAuthToken(body.oauthHandle, c.env.KV);

// The deployment credential belongs to whoever first connected it; a project member who
// re-runs setup keeps that owner (the row's user_id is never rewritten below).
const [currentCredential] = await db
.select({ userId: schema.projectDeploymentCredentials.userId })
.from(schema.projectDeploymentCredentials)
.where(
and(
eq(schema.projectDeploymentCredentials.projectId, projectId),
eq(schema.projectDeploymentCredentials.provider, 'gcp'),
),
)
.limit(1);
const poolOwnerUserId = currentCredential?.userId ?? userId;
Comment thread
simple-agent-manager[bot] marked this conversation as resolved.
Resolved

let result;
try {
result = await runGcpDeploySetup(oauthToken, body.gcpProjectId, c.env, undefined, projectId);
result = await runGcpDeploySetup(oauthToken, body.gcpProjectId, c.env, projectId, {
// Before any Google change: a pool another owner holds must not be re-pointed here.
assertPoolAvailable: (pool) =>
assertGcpWifPoolOwnership(
c.env,
pool,
{ kind: 'user', userId: poolOwnerUserId },
'gcp_deploy_setup',
),
});
} catch (err) {
if (isGcpWifPoolOwnershipError(err)) throw err;
throw toSanitizedAppError(err, 'deploy-setup');
}

Expand All @@ -212,6 +237,9 @@ projectDeploymentRoutes.post(
await db
.update(schema.projectDeploymentCredentials)
.set({
// The owner whose pool claim was checked above, so a concurrent first setup by
// another member cannot leave this row naming a pool its owner does not hold.
userId: poolOwnerUserId,
gcpProjectId: result.gcpProjectId,
gcpProjectNumber: result.gcpProjectNumber,
serviceAccountEmail: result.serviceAccountEmail,
Expand All @@ -224,7 +252,7 @@ projectDeploymentRoutes.post(
await db.insert(schema.projectDeploymentCredentials).values({
id: ulid(),
projectId,
userId,
userId: poolOwnerUserId,
provider: 'gcp',
gcpProjectId: result.gcpProjectId,
gcpProjectNumber: result.gcpProjectNumber,
Expand Down
14 changes: 14 additions & 0 deletions apps/api/src/routes/projects/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
import { decrypt, encrypt } from '../../services/encryption';
import { getTimeoutMs } from '../../services/fetch-timeout';
import { deleteGcpApiHealthSafely } from '../../services/gcp-api-health';
import { assertGcpWifPayloadOwnership } from '../../services/gcp-wif-pool-ownership';

Check warning on line 56 in apps/api/src/routes/projects/credentials.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'../../services/gcp-wif-pool-ownership' imported multiple times.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHzOepFgB3MPlMYBynp&open=AaHzOepFgB3MPlMYBynp&pullRequest=2905
import { reconcileGcpWifPoolIndex } from '../../services/gcp-wif-pool-ownership';

Check warning on line 57 in apps/api/src/routes/projects/credentials.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'../../services/gcp-wif-pool-ownership' imported multiple times.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHzOepFgB3MPlMYBynq&open=AaHzOepFgB3MPlMYBynq&pullRequest=2905
import { serializeCredentialToken } from '../../services/provider-credentials';
import {
CredentialValidator,
Expand Down Expand Up @@ -299,6 +301,14 @@
const requestBody = c.req.valid('json');
const { providerName, tokenToValidate: tokenToEncrypt } = getCloudCredentialFields(requestBody);
const validation = await validateCloudCredentialRequest(requestBody, c.env);
// Same owner as the user's own credentials: a user may reuse their pool per project, but
// never name a pool another user or the installation uses.
await assertGcpWifPayloadOwnership(
c.env,
tokenToEncrypt,
{ kind: 'user', userId },
'save_project_cloud_credential'
);
const { ciphertext, iv } = await encrypt(tokenToEncrypt, getCredentialEncryptionKey(c.env));

const existing = await db
Expand Down Expand Up @@ -403,6 +413,10 @@
}

const providerName = provider as CredentialProvider;
if (providerName === 'gcp') {
// Record the pool this credential names before it goes: Google may still trust it.
await reconcileGcpWifPoolIndex(c.env, 'delete_project_gcp_credential');
}
const deleted = await db
.delete(schema.credentials)
.where(
Expand Down
15 changes: 15 additions & 0 deletions apps/api/src/routes/projects/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
deleteProjectLibraryObjects,
getProjectDeleteCleanupBatchSize,
} from '../../services/file-library';
import { reconcileGcpWifPoolIndex } from '../../services/gcp-wif-pool-ownership';
import { resolveArtifactsBackendForCleanup } from '../../services/hosted-git/backend';
import { getRuntimeLimits } from '../../services/limits';
import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history';
Expand Down Expand Up @@ -160,6 +161,20 @@ crudRoutes.delete('/:id', async (c) => {

const project = await requireProjectCapability(db, projectId, userId, 'project:delete');
await assertNoReservedCloudflareBuilds(db, { projectId });
// Deleting the project deletes its GCP cloud credentials. Record the pools they name first:
// Google may still trust them after the rows are gone (gcp-wif-pool-ownership.ts).
const [gcpCredential] = await db
.select({ id: schema.credentials.id })
.from(schema.credentials)
.where(
and(
eq(schema.credentials.projectId, projectId),
eq(schema.credentials.provider, 'gcp'),
eq(schema.credentials.credentialType, 'cloud-provider')
)
)
.limit(1);
if (gcpCredential) await reconcileGcpWifPoolIndex(c.env, 'delete_project');

// Explicitly delete child records instead of relying on D1 CASCADE.
// SQLite ignores REFERENCES constraints added via ALTER TABLE, so
Expand Down
Loading
Loading