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
38 changes: 38 additions & 0 deletions packages/api/migrations/0034_run_enrollments.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
CREATE TABLE app.credential_proxy_states (
tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE,
proxy_identity text NOT NULL,
boot_epoch uuid NOT NULL,
disabled_at timestamptz,
revoked_at timestamptz,
updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE app.credential_run_grants (
tenant_id uuid NOT NULL,
run_id uuid NOT NULL,
vm_identity text NOT NULL,
proxy_identity text NOT NULL,
boot_epoch uuid NOT NULL,
grant_revision bigint NOT NULL CHECK (grant_revision > 0),
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, run_id),
FOREIGN KEY (tenant_id, run_id) REFERENCES app.job_runs(tenant_id, id) ON DELETE CASCADE
);

CREATE TABLE app.credential_run_enrollments (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
run_id uuid NOT NULL,
token_digest bytea NOT NULL UNIQUE,
vm_identity text NOT NULL,
proxy_identity text NOT NULL,
boot_epoch uuid NOT NULL,
grant_revision bigint NOT NULL CHECK (grant_revision > 0),
expires_at timestamptz NOT NULL,
consumed_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, run_id) REFERENCES app.credential_run_grants(tenant_id, run_id) ON DELETE CASCADE
);
CREATE INDEX credential_run_enrollments_expiry ON app.credential_run_enrollments(expires_at) WHERE consumed_at IS NULL;
103 changes: 103 additions & 0 deletions packages/api/src/postgres/run-enrollment-repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import type { Database } from "./database";

export type RunEnrollmentBinding = {
tenantId: string;
runId: string;
vmIdentity: string;
proxyIdentity: string;
bootEpoch: string;
};

export type ConsumedRunEnrollment = RunEnrollmentBinding & { grantRevision: number; enrollmentId: string };

const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function validateBinding(binding: RunEnrollmentBinding): void {
if (!uuid.test(binding.tenantId) || !uuid.test(binding.runId) || !uuid.test(binding.bootEpoch)) throw new TypeError("Enrollment tenant, run, and boot epoch must be UUIDs");
for (const [name, value] of [["vmIdentity", binding.vmIdentity], ["proxyIdentity", binding.proxyIdentity]] as const) {
if (typeof value !== "string" || !value.trim() || value.length > 255) throw new TypeError(`${name} must contain 1 to 255 characters`);
}
}

const digest = async (token: string) => new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)));
const activeStates = "('starting','running','blocked')";

/** Durable, one-use enrollments. Only a SHA-256 digest of each random token is stored. */
export class RunEnrollmentRepository {
constructor(private database: Database) {}

async setProxyState(input: { tenantId: string; proxyIdentity: string; bootEpoch: string; disabled?: boolean; revoked?: boolean }): Promise<void> {
if (!uuid.test(input.tenantId) || !uuid.test(input.bootEpoch)) throw new TypeError("tenantId and bootEpoch must be UUIDs");
if (!input.proxyIdentity.trim() || input.proxyIdentity.length > 255) throw new TypeError("proxyIdentity must contain 1 to 255 characters");
await this.database.pool.query(`INSERT INTO app.credential_proxy_states(tenant_id,proxy_identity,boot_epoch,disabled_at,revoked_at)
VALUES ($1,$2,$3,CASE WHEN $4 THEN now() END,CASE WHEN $5 THEN now() END)
ON CONFLICT (tenant_id) DO UPDATE SET proxy_identity=excluded.proxy_identity,boot_epoch=excluded.boot_epoch,disabled_at=excluded.disabled_at,revoked_at=excluded.revoked_at,updated_at=now()`,
[input.tenantId, input.proxyIdentity, input.bootEpoch, input.disabled ?? false, input.revoked ?? false]);
}

async authorizeRun(binding: RunEnrollmentBinding, grantRevision: number): Promise<boolean> {
validateBinding(binding);
if (!Number.isSafeInteger(grantRevision) || grantRevision < 1) throw new TypeError("grantRevision must be a positive safe integer");
return this.database.transaction(async client => {
const valid = await client.query(`SELECT 1 FROM app.job_runs r JOIN app.credential_proxy_states p ON p.tenant_id=r.tenant_id
WHERE r.tenant_id=$1 AND r.id=$2 AND r.state IN ${activeStates} AND p.proxy_identity=$3 AND p.boot_epoch=$4 AND p.disabled_at IS NULL AND p.revoked_at IS NULL`,
[binding.tenantId, binding.runId, binding.proxyIdentity, binding.bootEpoch]);
if (!valid.rowCount) return false;
const saved = await client.query(`INSERT INTO app.credential_run_grants(tenant_id,run_id,vm_identity,proxy_identity,boot_epoch,grant_revision,revoked_at)
VALUES ($1,$2,$3,$4,$5,$6,NULL) ON CONFLICT (tenant_id,run_id) DO UPDATE SET vm_identity=excluded.vm_identity,proxy_identity=excluded.proxy_identity,boot_epoch=excluded.boot_epoch,grant_revision=excluded.grant_revision,revoked_at=NULL
WHERE app.credential_run_grants.grant_revision < excluded.grant_revision RETURNING grant_revision`,
[binding.tenantId, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, grantRevision]);
if (saved.rowCount) return true;
const current = await client.query(`SELECT 1 FROM app.credential_run_grants WHERE tenant_id=$1 AND run_id=$2 AND vm_identity=$3 AND proxy_identity=$4 AND boot_epoch=$5 AND grant_revision=$6 AND revoked_at IS NULL`,
[binding.tenantId, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, grantRevision]);
return Boolean(current.rowCount);
});
}

async revokeRun(tenantId: string, runId: string): Promise<boolean> {
const result = await this.database.pool.query("UPDATE app.credential_run_grants SET revoked_at=now() WHERE tenant_id=$1 AND run_id=$2 AND revoked_at IS NULL", [tenantId, runId]);
return Boolean(result.rowCount);
}

async issue(binding: RunEnrollmentBinding, expiresAt: Date, now = new Date()): Promise<{ enrollmentId: string; token: string; grantRevision: number } | null> {
validateBinding(binding);
if (!(expiresAt instanceof Date) || !Number.isFinite(expiresAt.getTime()) || expiresAt <= now) throw new TypeError("expiresAt must be in the future");
const token = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
const tokenDigest = await digest(token), enrollmentId = crypto.randomUUID();
const result = await this.database.transaction(async client => {
const rows = await client.query<{ grant_revision: string | number }>(`SELECT g.grant_revision FROM app.credential_run_grants g
JOIN app.credential_proxy_states p ON p.tenant_id=g.tenant_id
JOIN app.job_runs r ON r.tenant_id=g.tenant_id AND r.id=g.run_id
WHERE g.tenant_id=$1 AND g.run_id=$2 AND g.vm_identity=$3 AND g.proxy_identity=$4 AND g.boot_epoch=$5
AND g.revoked_at IS NULL AND p.proxy_identity=g.proxy_identity AND p.boot_epoch=g.boot_epoch
AND p.disabled_at IS NULL AND p.revoked_at IS NULL AND r.state IN ${activeStates}
FOR UPDATE OF g,p,r`, [binding.tenantId, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch]);
const revision = rows.rows[0]?.grant_revision;
if (revision === undefined) return null;
await client.query("UPDATE app.credential_run_enrollments SET consumed_at=$3 WHERE tenant_id=$1 AND run_id=$2 AND consumed_at IS NULL", [binding.tenantId, binding.runId, now]);
await client.query(`INSERT INTO app.credential_run_enrollments(tenant_id,id,run_id,token_digest,vm_identity,proxy_identity,boot_epoch,grant_revision,expires_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [binding.tenantId, enrollmentId, binding.runId, Buffer.from(tokenDigest), binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, revision, expiresAt]);
return Number(revision);
});
return result === null ? null : { enrollmentId, token, grantRevision: result };
}

async consume(token: string, binding: RunEnrollmentBinding, now = new Date()): Promise<ConsumedRunEnrollment | null> {
validateBinding(binding);
if (typeof token !== "string" || token.length < 32 || token.length > 128 || !Number.isFinite(now.getTime())) return null;
const tokenDigest = Buffer.from(await digest(token));
return this.database.transaction(async client => {
const result = await client.query<{ id: string; grant_revision: string | number }>(`UPDATE app.credential_run_enrollments e
SET consumed_at=$7
FROM app.credential_run_grants g, app.credential_proxy_states p, app.job_runs r
WHERE e.tenant_id=$1 AND e.token_digest=$2 AND e.run_id=$3 AND e.vm_identity=$4 AND e.proxy_identity=$5 AND e.boot_epoch=$6
AND e.consumed_at IS NULL AND e.expires_at>$7
AND g.tenant_id=e.tenant_id AND g.run_id=e.run_id AND g.vm_identity=e.vm_identity AND g.proxy_identity=e.proxy_identity AND g.boot_epoch=e.boot_epoch
AND g.grant_revision=e.grant_revision AND g.revoked_at IS NULL
AND p.tenant_id=e.tenant_id AND p.proxy_identity=e.proxy_identity AND p.boot_epoch=e.boot_epoch AND p.disabled_at IS NULL AND p.revoked_at IS NULL
AND r.tenant_id=e.tenant_id AND r.id=e.run_id AND r.state IN ${activeStates}
RETURNING e.id,e.grant_revision`, [binding.tenantId, tokenDigest, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, now]);
const row = result.rows[0];
return row ? { ...binding, enrollmentId: row.id, grantRevision: Number(row.grant_revision) } : null;
});
}
}
11 changes: 10 additions & 1 deletion packages/api/src/postgres/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ export const integrationRecords = app.table("integration_records", {
export const integrationChanges = app.table("integration_changes", {
tenantId: uuid("tenant_id").notNull().references(() => integrationCollections.tenantId, { onDelete: "cascade" }), revision: bigint("revision", { mode: "number" }).notNull(), id: uuid("id").notNull(), idempotencyKey: uuid("idempotency_key").notNull(), operation: text("operation").$type<"upsert" | "delete">().notNull(), recordId: uuid("record_id").notNull(), kind: text("kind").$type<"bearer" | "model">().notNull(), name: text("name").notNull(), origin: text("origin"), description: text("description"), encryptedPayload: text("encrypted_payload"), createdAt: createdAt(),
}, t => [primaryKey({ columns: [t.tenantId, t.revision] }), unique().on(t.tenantId, t.idempotencyKey), index("integration_changes_page").on(t.tenantId, t.revision), check("integration_changes_operation_check", sql`${t.operation} IN ('upsert','delete')`), check("integration_changes_kind_check", sql`${t.kind} IN ('bearer','model')`), check("integration_changes_origin_check", sql`(${t.kind} = 'bearer' AND ${t.origin} IS NOT NULL) OR (${t.kind} = 'model' AND ${t.origin} IS NULL)`), check("integration_changes_payload_check", sql`(${t.operation} = 'upsert' AND ${t.encryptedPayload} IS NOT NULL) OR (${t.operation} = 'delete' AND ${t.encryptedPayload} IS NULL)`)]);
export const credentialProxyStates = app.table("credential_proxy_states", {
tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), proxyIdentity: text("proxy_identity").notNull(), bootEpoch: uuid("boot_epoch").notNull(), disabledAt: timestamp("disabled_at", { withTimezone: true }), revokedAt: timestamp("revoked_at", { withTimezone: true }), updatedAt: updatedAt(),
});
export const credentialRunGrants = app.table("credential_run_grants", {
tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), vmIdentity: text("vm_identity").notNull(), proxyIdentity: text("proxy_identity").notNull(), bootEpoch: uuid("boot_epoch").notNull(), grantRevision: bigint("grant_revision", { mode: "number" }).notNull(), revokedAt: timestamp("revoked_at", { withTimezone: true }), createdAt: createdAt(),
}, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [jobRuns.tenantId, jobRuns.id] }).onDelete("cascade"), check("credential_run_grants_revision_check", sql`${t.grantRevision} > 0`)]);
export const credentialRunEnrollments = app.table("credential_run_enrollments", {
tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), runId: uuid("run_id").notNull(), tokenDigest: bytea("token_digest").notNull(), vmIdentity: text("vm_identity").notNull(), proxyIdentity: text("proxy_identity").notNull(), bootEpoch: uuid("boot_epoch").notNull(), grantRevision: bigint("grant_revision", { mode: "number" }).notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), consumedAt: timestamp("consumed_at", { withTimezone: true }), createdAt: createdAt(),
}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tokenDigest), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [credentialRunGrants.tenantId, credentialRunGrants.runId] }).onDelete("cascade"), index("credential_run_enrollments_expiry").on(t.expiresAt).where(sql`${t.consumedAt} is null`), check("credential_run_enrollments_revision_check", sql`${t.grantRevision} > 0`)]);
export const linearWorkspaces = app.table("linear_workspaces", { organizationId: uuid("organization_id").primaryKey(), tenantId: uuid("tenant_id").notNull().unique().references(() => tenants.id, { onDelete: "cascade" }) });
export const githubInstallations = app.table("github_installations", { installationId: bigint("installation_id", { mode: "number" }).primaryKey(), tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), accountLogin: text("account_login").notNull(), accountType: text("account_type").notNull(), state: text("state").$type<"active" | "suspended">().notNull(), updatedAt: updatedAt() }, t => [unique().on(t.tenantId, t.installationId), check("github_installations_state_check", sql`${t.state} in ('active','suspended')`)]);
export const githubSetupStates = app.table("github_setup_states", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), nonce: text("nonce").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), usedAt: timestamp("used_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.nonce] })]);
Expand Down Expand Up @@ -146,7 +155,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({

export const databaseSchema = {
schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens,
connections, integrationCollections, integrationRecords, integrationChanges, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts,
connections, integrationCollections, integrationRecords, integrationChanges, credentialProxyStates, credentialRunGrants, credentialRunEnrollments, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts,
runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, lifecycleEvents, jobEditDeliveries, jobEvents,
webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks,
runTraceProjections, traceReplayLimits, traceReplayOperations,
Expand Down
22 changes: 22 additions & 0 deletions packages/api/src/run-enrollment-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { RunEnrollmentBinding, ConsumedRunEnrollment, RunEnrollmentRepository } from "./postgres/run-enrollment-repository";

export class RunEnrollmentUnavailableError extends Error {
constructor() { super("Run enrollment is expired, revoked, disabled, or no longer active"); this.name = "RunEnrollmentUnavailableError"; }
}

/** Control path used by Factorize to issue a one-use token and authenticate its proxy redemption. */
export class RunEnrollmentService {
constructor(private repository: RunEnrollmentRepository) {}

async enroll(binding: RunEnrollmentBinding, expiresAt: Date, now = new Date()): Promise<{ enrollmentId: string; token: string; grantRevision: number }> {
const enrollment = await this.repository.issue(binding, expiresAt, now);
if (!enrollment) throw new RunEnrollmentUnavailableError();
return enrollment;
}

async authenticate(token: string, binding: RunEnrollmentBinding, now = new Date()): Promise<ConsumedRunEnrollment> {
const enrollment = await this.repository.consume(token, binding, now);
if (!enrollment) throw new RunEnrollmentUnavailableError();
return enrollment;
}
}
18 changes: 8 additions & 10 deletions packages/api/test/fly-machines-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,31 +116,29 @@ describe("bounded Fly Machines client", () => {
it("times out a stalled response and reconciles an ambiguous create by operation id", async () => {
const machines: FlyMachine[] = [];
let createCount = 0;
let markCreateReceived!: () => void;
const createReceived = new Promise<void>(resolve => { markCreateReceived = resolve; });
let markCommitted!: () => void;
const committed = new Promise<void>(resolve => { markCommitted = resolve; });
const origin = await fakeFly(async (req, res) => {
if (req.method === "GET") return json(res, 200, machines);
if (req.method === "POST") {
createCount++;
markCreateReceived();
let raw = ""; for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw);
const machine = { id: "m-created", config: body.config };
machines.push(machine);
markCommitted();
markCommitted();
// Commit the resource but leave the response stalled past the client's deadline.
res.writeHead(200, { "content-type": "application/json" });
}
});
const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 1_000, maxRetries: 0 });
const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 250, maxRetries: 0 });
const creation = client.createMachine("app", { image: "image" }, "op-ambiguous");
let deadline: ReturnType<typeof setTimeout> | undefined;
let created: FlyMachine;
try {
const creation = client.createMachine("app", { image: "image" }, "op-ambiguous");
await Promise.race([createReceived, new Promise<never>((_, reject) => {
deadline = setTimeout(() => reject(new Error("Fake Fly server did not receive the ambiguous create")), 5_000);
})]);
created = await creation;
await Promise.race([committed, new Promise<never>((_, reject) => { deadline = setTimeout(() => reject(new Error("Fake Fly server did not commit the bounded create")), 5_000); })]);
} finally { if (deadline) clearTimeout(deadline); }
const created = await creation;
expect(created.id).toBe("m-created");
expect(createCount).toBe(1);
});
Expand Down
Loading
Loading