diff --git a/docs/guide/deployment.md b/docs/guide/deployment.md index 11f2ebd9f..996537bef 100644 --- a/docs/guide/deployment.md +++ b/docs/guide/deployment.md @@ -150,7 +150,7 @@ void github join void github connect --executor container ``` -Organization installations always require a browser proof for the specific repository, including for the person who installed the App. Void does not reveal the installation's full private repository list. If an upgraded platform marks an older organization connection as requiring reconnection, run the same `void github connect` command again to renew that repository-scoped authorization before builds resume. +Organization installations always require a browser proof for the specific repository, including for the person who installed the App. Void does not reveal the installation's full private repository list. 4. Verify the connection diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 87b54854e..6130ffcca 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -1400,7 +1400,7 @@ void github connect my-app \ For every organization installation, `void github connect` confirms that you personally have access to the specific repository, including when you originally installed the App. Interactively (TTY), it opens your browser once to authorize access to that repo on GitHub (a localhost + PKCE handshake), then completes the connection automatically. Without a TTY, this per-repo authorization never opens a browser: connect fails closed with an error explaining that the installation requires per-repo authorization and telling you to run `void github connect` locally. Interactively, connect joins the shared installation automatically when your account has no active installations linked, so running `void github join` first is optional. You can only connect repositories you can access on GitHub; seeing the organization installation never grants access to its other private repositories. -After upgrading from a platform version that treated an organization installer as an owner, existing organization connections show **Reconnect required** and stop starting builds until their repository access is proven. Run `void github connect --repo ` again. The command reauthorizes the same connection in place after the browser proof; if the repository or installation changed, disconnect it first and connect the intended repository. +A project has one GitHub connection. Running `void github connect` on a project that is already connected fails. To connect a different repository, run `void github disconnect` first. ### `void github update` @@ -1433,7 +1433,7 @@ void github update my-app --executor github_actions void github status [project] ``` -Show a project's current GitHub connection: the connected **repository**, the deploy **branch**, the **build executor** (`container` or `github_actions`), and the authorized **deploy workflow file**. Read-only — it never changes anything. The workflow file is the OIDC pin used only for `github_actions` builds; on a `container` connection it is still shown but marked unused. Legacy organization connections also show **Reconnect required** until `void github connect` proves current access to that repository. The project must already be connected (run `void github connect` first, otherwise it reports that and exits). +Show a project's current GitHub connection: the connected **repository**, the deploy **branch**, the **build executor** (`container` or `github_actions`), and the authorized **deploy workflow file**. Read-only — it never changes anything. The workflow file is the OIDC pin used only for `github_actions` builds; on a `container` connection it is still shown but marked unused. The project must already be connected (run `void github connect` first, otherwise it reports that and exits). **Options** diff --git a/packages/void/src/cli/client.ts b/packages/void/src/cli/client.ts index 59c8fc72f..d1d5a997e 100644 --- a/packages/void/src/cli/client.ts +++ b/packages/void/src/cli/client.ts @@ -435,7 +435,6 @@ export type GithubConnection = { branch: string; build_executor: 'container' | 'github_actions'; workflow_path: string; - requires_reconnect?: boolean; created_at: string; updated_at: string; }; diff --git a/packages/void/src/cli/github-cmd.ts b/packages/void/src/cli/github-cmd.ts index 59f9e8ce9..ea6ed8ddb 100644 --- a/packages/void/src/cli/github-cmd.ts +++ b/packages/void/src/cli/github-cmd.ts @@ -161,11 +161,6 @@ export function formatConnection(connection: GithubConnection): string { row('Build executor', connection.build_executor), row('Deploy workflow', workflow), ]; - if (connection.requires_reconnect) { - rows.push( - row('Authorization', 'Reconnect required: run `void github connect` for this repository'), - ); - } return rows.join('\n'); } diff --git a/packages/void/test/unit/github-cmd.test.ts b/packages/void/test/unit/github-cmd.test.ts index 3aae869ad..5f1e97ff7 100644 --- a/packages/void/test/unit/github-cmd.test.ts +++ b/packages/void/test/unit/github-cmd.test.ts @@ -147,12 +147,6 @@ describe('formatConnection', () => { expect(out).toContain('Build executor'); expect(out).toContain('Deploy workflow'); }); - - it('shows the organization reconnect action when authorization is unproven', () => { - const out = formatConnection(makeConnection({ requires_reconnect: true })); - expect(out).toContain('Reconnect required'); - expect(out).toContain('void github connect'); - }); }); describe('parseGithubRepoFullName', () => { diff --git a/platform/meta/design-docs/0074-github-deploy-identity-linking.md b/platform/meta/design-docs/0074-github-deploy-identity-linking.md index 27b865acb..23ab1f9aa 100644 --- a/platform/meta/design-docs/0074-github-deploy-identity-linking.md +++ b/platform/meta/design-docs/0074-github-deploy-identity-linking.md @@ -59,9 +59,8 @@ installed the App, requires a separate browser proof that the connecting GitHub user can access that specific repository. The signed connect grant carries the repository's immutable GitHub ID and is redeemed under the connecting user's Void identity. The platform records the authorizing Void user on the project -connection. A legacy organization connection without that proof must be -reconnected before builds resume. Personal installations retain their -installation-owner path. +connection. Organization installations have no owner. Personal installations +retain their installation-owner path. An installation membership permits a user to see and select an organization installation; it does not disclose the installation's private repository list @@ -71,7 +70,7 @@ when a repository is connected. ## Revocation and missed webhooks On `organization/member_removed`, the platform deletes the affected membership, -clears applicable legacy owner access, severs affected repository connections, +severs the repository connections that member authorized, and cancels their active builds. A durable revocation mark keyed by the GitHub account and installation rejects join or connect artifacts minted before the removal, including artifacts created before a Void account was linked. The diff --git a/platform/packages/api/drizzle/0052_github_connection_authority.sql b/platform/packages/api/drizzle/0052_github_connection_authority.sql new file mode 100644 index 000000000..a68652734 --- /dev/null +++ b/platform/packages/api/drizzle/0052_github_connection_authority.sql @@ -0,0 +1,65 @@ +UPDATE "github_installations" +SET "user_id" = NULL +WHERE "account_type" = 'Organization' AND "user_id" IS NOT NULL; +--> statement-breakpoint +UPDATE "github_connections" +SET "authorized_by_user_id" = "projects"."user_id" +FROM "projects", "github_installations" +WHERE + "github_connections"."authorized_by_user_id" IS NULL + AND "projects"."id" = "github_connections"."project_id" + AND "github_installations"."installation_id" = "github_connections"."installation_id" + AND "github_installations"."account_type" = 'User' + AND "github_installations"."user_id" = "projects"."user_id"; +--> statement-breakpoint +UPDATE "builds" +SET + "status" = 'cancelled', + "error" = COALESCE("builds"."error", 'github repository authorization is no longer valid; reconnect the repository'), + "completed_at" = COALESCE("builds"."completed_at", now()) +FROM "github_connections", "projects" +WHERE + "github_connections"."project_id" = "builds"."project_id" + AND "projects"."id" = "github_connections"."project_id" + AND ( + "github_connections"."authorized_by_user_id" IS NULL + OR "github_connections"."repository_id" IS NULL + OR NOT ( + "github_connections"."authorized_by_user_id" = "projects"."user_id" + OR EXISTS ( + SELECT 1 + FROM "project_members" + WHERE + "project_members"."project_id" = "projects"."id" + AND "project_members"."user_id" = "github_connections"."authorized_by_user_id" + AND "project_members"."role" = 'admin' + ) + ) + ) + AND "builds"."status" IN ('queued', 'starting', 'building', 'deploying'); +--> statement-breakpoint +DELETE FROM "github_connections" +USING "projects" +WHERE + "projects"."id" = "github_connections"."project_id" + AND ( + "github_connections"."authorized_by_user_id" IS NULL + OR "github_connections"."repository_id" IS NULL + OR NOT ( + "github_connections"."authorized_by_user_id" = "projects"."user_id" + OR EXISTS ( + SELECT 1 + FROM "project_members" + WHERE + "project_members"."project_id" = "projects"."id" + AND "project_members"."user_id" = "github_connections"."authorized_by_user_id" + AND "project_members"."role" = 'admin' + ) + ) + ); +--> statement-breakpoint +DELETE FROM "github_installation_members" +USING "github_installations" +WHERE + "github_installations"."installation_id" = "github_installation_members"."installation_id" + AND "github_installations"."account_type" = 'User'; diff --git a/platform/packages/api/drizzle/compatibility.json b/platform/packages/api/drizzle/compatibility.json index 7d80fce1d..b04738add 100644 --- a/platform/packages/api/drizzle/compatibility.json +++ b/platform/packages/api/drizzle/compatibility.json @@ -41,6 +41,10 @@ { "platformVersion": "0.21.2", "schemaDigest": "9a9ae6677b795debd4ffaa20a05f533727063c7a21366310a2fe4b17bd918edd" + }, + { + "platformVersion": "0.21.9", + "schemaDigest": "ac70deb5847c71ece9938edd27e5dbc50ce41e16771926c78e757850baf15bfa" } ] } diff --git a/platform/packages/api/drizzle/meta/_journal.json b/platform/packages/api/drizzle/meta/_journal.json index dd10c66bf..43f2a1319 100644 --- a/platform/packages/api/drizzle/meta/_journal.json +++ b/platform/packages/api/drizzle/meta/_journal.json @@ -316,6 +316,13 @@ "when": 1790721898182, "tag": "0051_icy_psylocke", "breakpoints": true + }, + { + "idx": 52, + "version": "7", + "when": 1790827715142, + "tag": "0052_github_connection_authority", + "breakpoints": true } ] } diff --git a/platform/packages/api/src/build-manager.ts b/platform/packages/api/src/build-manager.ts index bc2b3bd29..2a18d046d 100644 --- a/platform/packages/api/src/build-manager.ts +++ b/platform/packages/api/src/build-manager.ts @@ -1522,18 +1522,21 @@ export class BuildManager extends Container { // the enqueue-time check is stale. A fresh plain (non-locking) Postgres // read here observes the committed revocation and fails closed before we // mint a live deploy token, rather than relying solely on the installation - // token mint failing once its ~55-min cache expires. A null repositoryId - // (unprovable membership) fails closed by construction. Treat an + // token mint failing once its ~55-min cache expires. A missing connection + // or repository id fails closed. Treat an // uncovered build like the non-identical freshness branch: cancel (not a // build failure), don't mint or start. Nothing is started yet, so there is // no container to tear down. - const covered = await installationCoversRepo( - this.db(), - config.connectionId, - config.projectId, - config.installationId, - config.repositoryId, - ); + const repositoryId = config.repositoryId; + const covered = + repositoryId !== null && + (await installationCoversRepo( + this.db(), + config.connectionId, + config.projectId, + config.installationId, + repositoryId, + )); if (!covered) { const won = await markBuildTerminalIfActive(this.db(), config.buildId, 'cancelled', { error: 'github repository authorization is no longer valid; reconnect the repository', @@ -1711,16 +1714,11 @@ export class BuildManager extends Container { // but it's injected into the container env where an untrusted dependency // `postinstall` could read it — a repo-scoped `{ contents: 'read' }` token // caps that blast radius to this single repo instead of every repo the - // install covers. A null repositoryId (legacy/partial connection) can't be - // scoped, so fall back to the unscoped installation-wide mint to preserve - // compatibility; coverage is already re-verified above. - const sourceToken = - config.repositoryId !== null - ? await getInstallationToken(this.env, config.installationId, { - repositoryIds: [config.repositoryId], - permissions: { contents: 'read' }, - }) - : await getInstallationToken(this.env, config.installationId); + // install covers. + const sourceToken = await getInstallationToken(this.env, config.installationId, { + repositoryIds: [repositoryId], + permissions: { contents: 'read' }, + }); // The installation-token fetch is the longest pre-launch await and was the // original orphan window: cancellation observed no live container, returned, // and this continuation launched afterward. The generation fence closes it. diff --git a/platform/packages/api/src/build-scheduler.ts b/platform/packages/api/src/build-scheduler.ts index ff6c3ca96..44ad9ceef 100644 --- a/platform/packages/api/src/build-scheduler.ts +++ b/platform/packages/api/src/build-scheduler.ts @@ -159,7 +159,7 @@ export class BuildScheduler extends DurableObject { } if (!(await hasGitHubConnectionAuthority(db, connection.id, build.project_id))) { await updateBuildStatus(db, build.id, 'cancelled', { - error: 'github organization repository must be reconnected to renew authorization', + error: 'github repository authorization is no longer valid; reconnect the repository', completedAt: new Date().toISOString(), }); continue; @@ -242,7 +242,7 @@ export class BuildScheduler extends DurableObject { // project (resolved above by the UNIQUE project_id) is the source of // truth — mirrors webhooks.ts / auth-oidc.ts. startBuild re-verifies the // App installation still covers this repo before minting the deploy - // token; a null id fails that check closed. + // token; a missing id fails that check closed. repositoryId: connection.repository_id, instanceType, timeoutMinutes: getPlanLimits(claimed.ownerPlan).buildTimeoutMinutes, diff --git a/platform/packages/api/src/build-types.ts b/platform/packages/api/src/build-types.ts index 317e59ebe..556b46a3d 100644 --- a/platform/packages/api/src/build-types.ts +++ b/platform/packages/api/src/build-types.ts @@ -21,17 +21,16 @@ export type BuildConfig = { repoFullName: string; installationId: string; /** - * Exact connection row authorized at enqueue. Older persisted manager state - * may omit it; the final authority check treats that as unproven and cancels. + * Exact connection row authorized at enqueue. The final authority check + * cancels the build when it is missing. */ - connectionId?: string; + connectionId: string; /** - * The connection's immutable numeric GitHub repository id (as text), or null - * for a legacy/partial connection that never populated it. Carried so - * `BuildManager.startBuild` can re-verify the App installation still covers - * this repo at token-mint time (a null id fails that check closed). Sourced - * from the github connection bound to this build (the build row itself does - * not store a repository id). + * The connection's immutable numeric GitHub repository id (as text). Carried + * so `BuildManager.startBuild` can re-verify the App installation still + * covers this repo at token-mint time; a missing id fails that check closed. + * Sourced from the github connection bound to this build (the build row + * itself does not store a repository id). */ repositoryId: string | null; instanceType: string; diff --git a/platform/packages/api/src/db.ts b/platform/packages/api/src/db.ts index b33a059ce..b624798cf 100644 --- a/platform/packages/api/src/db.ts +++ b/platform/packages/api/src/db.ts @@ -3314,7 +3314,7 @@ export async function deleteUser(db: Db, id: string): Promise { * and the plain read avoids any lock-order concern on `github_installations`. * * FAILS CLOSED unless the exact connection still belongs to the project, has - * durable authority, and its active installation still covers the repo. New - * connections record the project owner/admin who completed the repository proof; - * that authorizer must still be the owner or an admin. Legacy personal-install - * rows without provenance retain their former owner-match behavior; legacy - * organization rows are null and stop here. + * durable authority, and its active installation still covers the repo. Every + * connection records the project owner/admin who completed the repository proof; + * that authorizer must still be the owner or an admin. A connection without an + * authorizer (its user was deleted) has no authority. * An `all` install covers every repo; a `selected` install requires the immutable * repo id in its cache. This is the shared predicate used by webhook and OIDC * resolvers as well as enqueue and final startup checks. @@ -4343,11 +4342,6 @@ function githubConnectionAuthorityClause() { and ${projectMembers.user_id} = ${githubConnections.authorized_by_user_id} and ${projectMembers.role} = 'admin' )`, - and( - isNull(githubConnections.authorized_by_user_id), - eq(githubInstallations.account_type, 'User'), - eq(githubInstallations.user_id, projects.user_id), - ), ); } @@ -4355,8 +4349,7 @@ function githubConnectionAuthorityClause() { * Invalidate provenance that no longer names a project owner/admin. Membership * mutations call this while holding the project row lock, so they serialize with * connection CRUD/build creation (which use the same project-first order). - * Reauthorization by another admin changes `authorized_by_user_id`, making this - * a no-op. Active build rows are terminalized before the connection is removed, + * Active build rows are terminalized before the connection is removed, * which immediately revokes their build-bound deploy tokens. */ async function invalidateGitHubConnectionAuthorizedBy( @@ -4391,11 +4384,11 @@ async function installationCoversRepoInTx( installationId: string, repositoryId: string | null, ): Promise { - // An `all`-repos install grants every repo regardless of id; only a `selected` - // install needs the immutable numeric id in the cached set, so a null repo id - // can't match there and fails closed via the `false` arm below. Checking null - // BEFORE the `all` branch (the old unconditional `return false`) wrongly treated - // a legacy null-id connection on an `all` install as install-revoked. + // Every connection records its immutable repository id; a row without one + // cannot prove coverage. + if (repositoryId === null) { + return false; + } const [row] = await tx .select({ id: githubConnections.id }) .from(githubConnections) @@ -4413,9 +4406,7 @@ async function installationCoversRepoInTx( githubConnectionAuthorityClause(), or( eq(githubInstallations.repository_selection, 'all'), - repositoryId === null - ? sql`false` - : sql`${githubInstallations.repositories} @> ${JSON.stringify([{ id: Number(repositoryId) }])}::jsonb`, + sql`${githubInstallations.repositories} @> ${JSON.stringify([{ id: Number(repositoryId) }])}::jsonb`, ), ), ) @@ -4429,9 +4420,8 @@ async function installationCoversRepoInTx( * repo. Identical fail-closed predicate — returns false unless the * `github_installations` row exists AND `status === 'active'` AND the repo is * still in the install's selection (`repository_selection === 'all'`, or the - * immutable numeric repo id is in the cached `repositories` set). A null - * `repositoryId` fails closed for a `selected` install (membership unprovable by - * id) but an active `all` install still grants coverage (id irrelevant). + * immutable numeric repo id is in the cached `repositories` set). A missing + * connection id or repository id fails closed. * * Used by the container `BuildManager.startBuild` to re-verify coverage at token * mint, AFTER a queue wait during which an uninstall/suspension/repo-removal @@ -4442,19 +4432,14 @@ async function installationCoversRepoInTx( */ export async function installationCoversRepo( db: Db, - connectionId: string | null | undefined, + connectionId: string, projectId: string, installationId: string, repositoryId: string | null, ): Promise { - if (!connectionId) { + if (!connectionId || !repositoryId) { return false; } - // An `all`-repos install grants every repo regardless of id; only a `selected` - // install needs the immutable numeric id in the cached set, so a null repo id - // can't match there and fails closed via the `false` arm below. Checking null - // BEFORE the `all` branch (the old unconditional `return false`) wrongly treated - // a legacy null-id connection on an `all` install as install-revoked. const [row] = await db .select({ id: githubConnections.id }) .from(githubConnections) @@ -4472,9 +4457,7 @@ export async function installationCoversRepo( githubConnectionAuthorityClause(), or( eq(githubInstallations.repository_selection, 'all'), - repositoryId === null - ? sql`false` - : sql`${githubInstallations.repositories} @> ${JSON.stringify([{ id: Number(repositoryId) }])}::jsonb`, + sql`${githubInstallations.repositories} @> ${JSON.stringify([{ id: Number(repositoryId) }])}::jsonb`, ), ), ) @@ -5269,15 +5252,13 @@ export async function createGitHubConnection( projectId: string; installationId: string; repoFullName: string; - // The repo's immutable numeric GitHub id (as text), captured from the - // installation's cached repository list at connect time. Optional only so - // pre-existing callers/tests compile; the connect handler always supplies it - // and webhook/OIDC resolution keys on it (full_name is mutable). - repositoryId?: string | null; - // Set after repository access was proven with the project owner or - // administrator's own GitHub OAuth token. Legacy organization connections - // remain null and are rejected by every runtime resolver until reconnected. - authorizedByUserId?: string | null; + // The repo's immutable numeric GitHub id (as text), resolved at connect time. + // Webhook/OIDC resolution keys on it (full_name is mutable). + repositoryId: string; + // The project owner or administrator who proved repository access while + // connecting. Runtime authority requires this user to remain the owner or + // an administrator. + authorizedByUserId: string; branch?: string; buildExecutor?: GitHubConnection['build_executor']; // The `.github/workflows/*.yml` file the OIDC exchange binds the deploy @@ -5295,8 +5276,8 @@ export async function createGitHubConnection( project_id: args.projectId, installation_id: args.installationId, repo_full_name: args.repoFullName, - repository_id: args.repositoryId ?? null, - authorized_by_user_id: args.authorizedByUserId ?? null, + repository_id: args.repositoryId, + authorized_by_user_id: args.authorizedByUserId, branch: args.branch ?? 'main', build_executor: args.buildExecutor ?? 'container', ...(args.workflowPath !== undefined ? { workflow_path: args.workflowPath } : {}), @@ -5341,50 +5322,16 @@ export async function hasGitHubConnectionAuthority( return row !== undefined; } -export async function authorizeGitHubOrganizationConnection( - db: Db, - args: { - projectId: string; - installationId: string; - repoFullName: string; - repositoryId: string; - userId: string; - }, -): Promise { - const [row] = await db - .update(githubConnections) - .set({ - authorized_by_user_id: args.userId, - repository_id: args.repositoryId, - updated_at: sql`now()`, - }) - .where( - and( - eq(githubConnections.project_id, args.projectId), - eq(githubConnections.installation_id, args.installationId), - eq(githubConnections.repo_full_name, args.repoFullName), - ), - ) - .returning(); - return row ?? null; -} - /** * Look up the connection for a webhook-delivered repo within an installation, * joining `projects` to surface the owning `user_id` (needed to attribute a * build and enforce that user's tier concurrency). Returns the connection * fields plus `user_id`, or null when no project is connected to that repo. * - * Resolution keys on the IMMUTABLE numeric repository id (`repository.id` in - * webhook payloads) so a repo rename/delete/name-reuse under the same - * installation can't match a DIFFERENT repository to this connection. When the - * caller has a `repositoryId`, a connection is matched ONLY by that id — it - * FAILS CLOSED: a `repository_id IS NULL` row is NOT matched by name fallback, - * because a deleted/renamed-and-reused repo name under the same installation - * could otherwise match a stale null-id connection and authorize the WRONG - * project. Only when the caller has no `repositoryId` (malformed/partial - * webhook) does every connection fall back to a `repo_full_name` match — the - * pre-id behavior. + * Resolution keys ONLY on the IMMUTABLE numeric repository id (`repository.id` + * in webhook payloads) so a repo rename/delete/name-reuse under the same + * installation can't match a DIFFERENT repository to this connection. The + * mutable `repo_full_name` is never a routing key. * * Returns ALL connections for the repo within the installation: a repo may back * multiple projects (only `project_id` is unique), so the caller disambiguates @@ -5409,13 +5356,8 @@ export async function authorizeGitHubOrganizationConnection( export async function getGitHubConnectionsByRepo( db: Db, installationId: string, - repoFullName: string, - repositoryId?: string | null, + repositoryId: string, ): Promise> { - const matchClause = - repositoryId === undefined || repositoryId === null - ? eq(githubConnections.repo_full_name, repoFullName) - : eq(githubConnections.repository_id, repositoryId); const rows = await db .select({ ...getTableColumns(githubConnections), @@ -5430,19 +5372,16 @@ export async function getGitHubConnectionsByRepo( .where( and( eq(githubConnections.installation_id, installationId), - matchClause, + eq(githubConnections.repository_id, repositoryId), eq(githubInstallations.status, 'active'), githubConnectionAuthorityClause(), or( // "all repositories" install => every repo is granted. eq(githubInstallations.repository_selection, 'all'), // "selected" install => enforce the repo is in the cached set. The - // `repositories` jsonb stores `id` as a NUMBER, so when the caller has - // the immutable repo id, check membership by id (rename-safe). Fall - // back to name membership only when no id is available. - repositoryId === undefined || repositoryId === null - ? sql`${githubInstallations.repositories} @> ${JSON.stringify([{ full_name: repoFullName }])}::jsonb` - : sql`${githubInstallations.repositories} @> ${JSON.stringify([{ id: Number(repositoryId) }])}::jsonb`, + // `repositories` jsonb stores `id` as a NUMBER; check membership by + // the immutable id (rename-safe). + sql`${githubInstallations.repositories} @> ${JSON.stringify([{ id: Number(repositoryId) }])}::jsonb`, ), ), ); @@ -5477,10 +5416,10 @@ export async function updateGitHubConnectionRepoNamesByRepoId( * Resolve the GitHub Actions connection for a repo at OIDC-exchange time. * * The Actions executor authenticates by presenting a GitHub OIDC token whose - * `repository` claim names the repo; there is no installation id in that flow, - * so we look up by `repo_full_name` alone and require `build_executor = - * 'github_actions'` (a `container`-executor connection must never be driven by - * the OIDC endpoint). Joins `projects` to surface the owning `user_id` (to + * `repository_id` claim names the repo; there is no installation id in that + * flow, so we look up by the immutable repository id and require + * `build_executor = 'github_actions'` (a `container`-executor connection must + * never be driven by the OIDC endpoint). Joins `projects` to surface the owning `user_id` (to * attribute the build) and `slug` (to cross-check the workflow's declared * `--project `). When multiple connections name the same repo, the * newest by `created_at` wins. @@ -5502,31 +5441,17 @@ export async function updateGitHubConnectionRepoNamesByRepoId( * projects (only `project_id` is unique). The caller disambiguates by the * workflow's requested project slug. * - * When `repositoryOwnerId` (the OIDC `repository_owner_id` claim) is supplied, - * an OIDC match additionally requires the repo's CURRENT owner account to equal - * the installation's `account_id`. The `repository_id` is immutable across a - * repo TRANSFER, so without this an org→org transfer (same id, new owner) would - * match the OLD owner's stale `all`-repos connection and mint a deploy token for - * the wrong project. A null/undefined owner id (legacy, no claim) skips the - * owner check to preserve pre-claim behavior; the OIDC route always passes it. + * A match also requires the repo's CURRENT owner account (the OIDC + * `repository_owner_id` claim) to equal the installation's `account_id`. The + * `repository_id` is immutable across a repo TRANSFER, so without this an + * org→org transfer (same id, new owner) would match the OLD owner's stale + * `all`-repos connection and mint a deploy token for the wrong project. */ export async function getGitHubActionsConnectionsByRepo( db: Db, - repoFullName: string, - repositoryId?: string | null, - repositoryOwnerId?: string | null, + repositoryId: string, + repositoryOwnerId: string, ): Promise> { - // Key on the IMMUTABLE numeric repository id (`claims.repository_id`) so a - // rename/name-reuse can't point a stale `repo_full_name` at this connection. - // When the claim carries an id, connections are matched ONLY by id and the - // lookup FAILS CLOSED: a null-id row is NOT matched by name fallback, since a - // renamed-and-reused repo name could otherwise match a stale null-id - // connection and mint a deploy token for the WRONG project. Only a missing - // claim id falls back to `repo_full_name` for every row (pre-id behavior). - const repoMatch = - repositoryId === undefined || repositoryId === null - ? eq(githubConnections.repo_full_name, repoFullName) - : eq(githubConnections.repository_id, repositoryId); const rows = await db .select({ ...getTableColumns(githubConnections), @@ -5541,16 +5466,13 @@ export async function getGitHubActionsConnectionsByRepo( ) .where( and( - repoMatch, + eq(githubConnections.repository_id, repositoryId), // Bind the connection's installation account to the OIDC repo owner. The // `repository_id` is immutable across a repo TRANSFER, so this top-level // condition (applies to BOTH the 'all' and 'selected' branches below) // rejects a transferred repo (same id, NEW owner) that would otherwise - // match the old owner's stale connection. Skipped when no owner id is - // supplied (legacy/no-claim). - repositoryOwnerId === undefined || repositoryOwnerId === null || repositoryOwnerId === '' - ? undefined - : eq(githubInstallations.account_id, repositoryOwnerId), + // match the old owner's stale connection. + eq(githubInstallations.account_id, repositoryOwnerId), eq(githubConnections.build_executor, 'github_actions'), eq(githubInstallations.status, 'active'), githubConnectionAuthorityClause(), @@ -5559,13 +5481,9 @@ export async function getGitHubActionsConnectionsByRepo( eq(githubInstallations.repository_selection, 'all'), // "selected" install => enforce the repo is in the cached set. The // `repositories` jsonb stores `id` as a NUMBER (see - // `GitHubInstallationRepository.id: number` and `normalizeRepositories`), - // so when the caller has the immutable repo id, check membership by id - // (rename-safe). Fall back to name membership only when no id is - // available (legacy/no-claim). - repositoryId === undefined || repositoryId === null - ? sql`${githubInstallations.repositories} @> ${JSON.stringify([{ full_name: repoFullName }])}::jsonb` - : sql`${githubInstallations.repositories} @> ${JSON.stringify([{ id: Number(repositoryId) }])}::jsonb`, + // `GitHubInstallationRepository.id: number` and `normalizeRepositories`); + // check membership by the immutable id (rename-safe). + sql`${githubInstallations.repositories} @> ${JSON.stringify([{ id: Number(repositoryId) }])}::jsonb`, ), ), ); @@ -5645,13 +5563,13 @@ export async function upsertGitHubInstallation( .onConflictDoUpdate({ target: githubInstallations.installation_id, set: { - // Preserve an already-linked user_id when a webhook upsert arrives with - // no user (install-before-signin can be backfilled later). When a user - // is provided, adopt it ONLY if the row is unowned or already owned by - // the same user — never re-own a row linked to a DIFFERENT user. This - // guards the concurrent-callback race (realistic for org installs) that - // the non-transactional read-then-write backstop in routes/github.ts - // cannot catch. (Done in the column expression, not setWhere: setWhere + // Only personal (account_type='User') installs carry an owner; + // organization installs always pass a null user. Preserve an + // already-linked user_id when a webhook upsert arrives with no user + // (install-before-signin can be backfilled later). When a user is + // provided, adopt it ONLY if the row is unowned or already owned by the + // same user — never re-own a row linked to a DIFFERENT user, even if two + // callbacks race. (Done in the column expression, not setWhere: setWhere // would freeze repositories/status refreshes on the webhook re-upsert, // and `user_id = NULL` is never true.) user_id: @@ -5725,9 +5643,9 @@ export async function getGitHubInstallationsByUser( db: Db, userId: string, ): Promise> { - // Personal-account owner OR active member. Organization `user_id` values - // written by older code are visibility hints, not authority, so they never - // satisfy this query without a live membership. The EXISTS correlates on the NUMERIC + // Personal-account owner OR active member. Organization installs have no + // owner (`user_id` is null), so they are visible only through a live + // membership. The EXISTS correlates on the NUMERIC // `installation_id` (githubInstallations.installation_id) — the key the // membership cache is stored under — NOT the surrogate `.id`. The membership // arm honors the TTL (`expires_at > now()`, DB clock). owner-OR-EXISTS yields @@ -5871,35 +5789,6 @@ export async function getGitHubInstallationsByAccount( ); } -/** - * Guarded clear of the installer/owner pointer for a removed user. The - * `user_id = userId` guard means a concurrent re-own or a different owner is - * never clobbered. Membership rows are removed separately - * (`deleteGitHubInstallationMembers`); this only nulls the single owner pointer. - * No-op returning 0 on an empty id list so we never emit a `WHERE ... IN ()`. - * The count is read through `updatedRowCount` so it is correct on both the - * production pg driver (`rowCount`) and the PGlite test driver (`affectedRows`). - */ -export async function clearGitHubInstallationOwnerForUser( - db: Db, - installationIds: ReadonlyArray, - userId: string, -): Promise { - if (installationIds.length === 0) { - return 0; - } - const result = await db - .update(githubInstallations) - .set({ user_id: null, updated_at: sql`now()` }) - .where( - and( - inArray(githubInstallations.installation_id, installationIds), - eq(githubInstallations.user_id, userId), - ), - ); - return updatedRowCount(result); -} - // --------------------------------------------------------------------------- // github_installation_members — cached org co-membership (TTL, no stored token) // diff --git a/platform/packages/api/src/routes/auth-oidc.ts b/platform/packages/api/src/routes/auth-oidc.ts index 0893bd958..f59abe9dc 100644 --- a/platform/packages/api/src/routes/auth-oidc.ts +++ b/platform/packages/api/src/routes/auth-oidc.ts @@ -119,16 +119,12 @@ app.post('/github-oidc', async (context) => { const db = context.get('db'); const connections = await getGitHubActionsConnectionsByRepo( db, - claims.repository, claims.repository_id, claims.repository_owner_id, ); if (connections.length === 0) { return context.json( - { - error: - 'no authorized github actions connection for repository; reconnect the organization repository', - }, + { error: 'no authorized github actions connection for repository; reconnect the repository' }, 401, ); } diff --git a/platform/packages/api/src/routes/github.ts b/platform/packages/api/src/routes/github.ts index 776d9e469..90c60e0aa 100644 --- a/platform/packages/api/src/routes/github.ts +++ b/platform/packages/api/src/routes/github.ts @@ -11,7 +11,6 @@ import { capabilityMiddleware } from '../capabilities.ts'; import { DEFAULT_DASHBOARD_URL, MEMBERSHIP_TTL_SECONDS } from '../constants.ts'; import type { Db } from '../db.ts'; import { - authorizeGitHubOrganizationConnection, createGitHubConnection, deleteGitHubConnection, getGitHubAccountIdForUser, @@ -19,7 +18,6 @@ import { getDbNowMs, getGitHubInstallation, getGitHubInstallationsByUser, - hasGitHubConnectionAuthority, getInstallationRevocationAt, getInstallationRevocationsForAccount, GitHubIdentityAlreadyLinkedError, @@ -131,10 +129,8 @@ type JoinCode = { // The moment GitHub access was PROVEN (the public callback ran). Compared // against the per-install revocation tombstone at /join/complete: a join_code // minted at or before a revocation is a stale replay from a removed member and - // is skipped (monotonic revocation, Task 14). Optional because a legacy code - // minted before this field existed carries none — the redemption treats a - // missing iat as 0 (predates every tombstone → fail closed). - iat?: number; + // is skipped (monotonic revocation, Task 14). A code without it is invalid. + iat: number; exp: number; }; @@ -182,9 +178,8 @@ type ConnectGrant = { // ran). Compared against the install's revocation tombstone inside the connect // gate's go-live transaction: a grant minted at or before a revocation is a // stale replay from a removed member and is rejected (monotonic, Task 14). - // Optional because a legacy grant minted before this field existed carries none - // — the redemption treats a missing iat as 0 (predates every tombstone). - iat?: number; + // A grant without it is invalid. + iat: number; exp: number; }; @@ -820,7 +815,11 @@ export const githubRoutes = new Hono() if (!joinCode || joinCode.purpose !== 'join' || !Array.isArray(joinCode.installationIds)) { return context.json({ error: 'invalid join_code' }, 400); } - if (typeof joinCode.exp !== 'number' || Date.now() >= joinCode.exp) { + if ( + typeof joinCode.exp !== 'number' || + Date.now() >= joinCode.exp || + typeof joinCode.iat !== 'number' + ) { return context.json({ error: 'invalid join_code' }, 400); } @@ -875,25 +874,16 @@ export const githubRoutes = new Hono() if (install === null) { continue; } - // Org-share is Organization-only (mirrors the eligibility gate). A join_code - // that somehow carries a personal (account_type='User') install id is skipped - // fail-soft — never counted, never minted. account_type is immutable, so this - // re-read is authoritative under the install-row lock held above. - if (install.account_type !== 'Organization') { - continue; - } - // Skip installs the caller already OWNS — they already have full access, so - // a membership row would be redundant (and is not counted). - if (install.user_id === user.id) { - continue; - } + // The signed join_code lists only Organization installs (the callback's + // eligibility gate), and account_type is immutable, so every install here + // is an organization install with no owner. The installer joins like any + // other member. + // // Skip installs whose join_code predates a revocation (stale replay). A // legit re-join AFTER re-add mints a fresh join_code with iat > revoked_at, - // which is NOT skipped (the tombstone is a high-water mark, not a ban). A - // legacy join_code minted before this field existed has no iat — treat it - // as 0 so ANY tombstone rejects it (fail closed). + // which is NOT skipped (the tombstone is a high-water mark, not a ban). const revokedAtMs = revocations.get(installationId); - if (revokedAtMs !== undefined && revokedAtMs >= (joinCode.iat ?? 0)) { + if (revokedAtMs !== undefined && revokedAtMs >= joinCode.iat) { continue; } // Threat L1: keyed on the AUTHENTICATED bearer-token holder, never on the @@ -1270,13 +1260,11 @@ export const githubRoutes = new Hono() .for('update'); const existing = await getGitHubInstallation(txDb, installationId); - // Organization installation visibility never confers repository authority. - // Record every org participant as a TTL membership, including the person - // who completed a fresh installation and users that older code marked as - // owner. The project connect gate consequently requires a fresh per-repo - // OAuth grant for every organization path. Persist the installation with a - // null proposed owner; on conflict this also preserves any legacy pointer, - // which remains inert for organization authorization. + // Organization installs have no owner, and installation visibility never + // confers repository authority. Record every org participant, including + // the person who completed a fresh installation, as a TTL membership. The + // project connect gate consequently requires a fresh per-repo OAuth grant + // for every organization path. if (account.type === 'Organization') { if (!authResult.authorized || authResult.callerAccountId === null) { return { kind: 'conflict' as const }; @@ -1450,11 +1438,11 @@ export const githubProjectRoutes = new Hono() if (!isMember) { return context.json({ error: 'installation not found' }, 404); } - // Defense-in-depth: org-share connect is Organization-only. A membership on a - // personal-account install cannot be minted after Task 28, but a pre-existing/stale - // one must still be rejected here with the SAME opaque 404 (never reveal the install - // exists / its type to a non-member). account_type is immutable, so the pre-lock row - // is authoritative (no locked re-read). + // Org-share connect is Organization-only. Memberships are only ever written for + // organization installs; this gate keeps a personal install unreachable through + // membership even if one existed, with the SAME opaque 404 (never reveal the + // install exists / its type to a non-member). account_type is immutable, so the + // pre-lock row is authoritative (no locked re-read). if (installation.account_type !== 'Organization') { return context.json({ error: 'installation not found' }, 404); } @@ -1548,6 +1536,7 @@ export const githubProjectRoutes = new Hono() grant.purpose !== 'connect' || typeof grant.exp !== 'number' || Date.now() >= grant.exp || + typeof grant.iat !== 'number' || grant.installationId !== body.installationId || grant.repoFullName !== body.repoFullName ) { @@ -1649,7 +1638,7 @@ export const githubProjectRoutes = new Hono() return context.json({ error: 'project is being deleted' }, 409); } // Re-derive ownership from the LOCKED row, not the stale pre-tx snapshot. If - // member_removed cleared the owner pointer while we waited on the lock, the + // the personal owner pointer changed while we waited on the lock, the // pre-tx owner path is stale: we already resolved repositoryId via the // installation token and carry NO grant, so we must NOT fall through to the // member insert (that would be a confused-deputy on the install token). Reject; @@ -1672,20 +1661,18 @@ export const githubProjectRoutes = new Hono() // the durable identity `member_removed` always tombstones. A non-owner // path always carries a grant (the member branch above set // memberGrantAccountId after Threat-L1); a missing one is fail-closed to - // the same opaque 403 (the F2 `isOwner && !lockedIsOwner` guard already + // the same opaque 403 (the `isOwner && !lockedIsOwner` guard already // rejected the owner-turned-non-owner case above, so this is only ever a // defensive belt). - if (memberGrantAccountId === undefined) { + if (memberGrantAccountId === undefined || memberGrantIat === undefined) { return { ok: false as const, status: 403 as const, error: 'invalid connect grant' }; } - // A legacy grant minted before the iat field existed has memberGrantIat - // undefined — treat it as 0 so ANY tombstone rejects it (fail closed). const revokedAtMs = await getInstallationRevocationAt( txDb, installationId, memberGrantAccountId, ); - if (revokedAtMs !== null && revokedAtMs >= (memberGrantIat ?? 0)) { + if (revokedAtMs !== null && revokedAtMs >= memberGrantIat) { return { ok: false as const, status: 403 as const, error: 'invalid connect grant' }; } } @@ -1719,24 +1706,6 @@ export const githubProjectRoutes = new Hono() } const existing = await getGitHubConnection(txDb, projectId); if (existing) { - if (lockedInstall.account_type === 'Organization') { - const reauthorized = await authorizeGitHubOrganizationConnection(txDb, { - projectId, - installationId, - repoFullName, - repositoryId: String(repositoryId), - userId: caller, - }); - if (reauthorized) { - return { ok: true as const, connection: reauthorized }; - } - return { - ok: false as const, - status: 409 as const, - error: - 'organization repository authorization changed; disconnect and reconnect the repository', - }; - } return { ok: false as const, status: 409 as const, error: 'project already connected' }; } const connection = await createGitHubConnection(txDb, { @@ -1773,15 +1742,7 @@ export const githubProjectRoutes = new Hono() return context.json({ error: 'connection not found' }, 404); } - const authorized = await hasGitHubConnectionAuthority( - context.get('db'), - connection.id, - projectId, - ); - return context.json({ - ...publicGitHubConnection(connection), - requires_reconnect: !authorized, - }); + return context.json(publicGitHubConnection(connection)); }) // Update branch / build executor. diff --git a/platform/packages/api/src/routes/webhooks.ts b/platform/packages/api/src/routes/webhooks.ts index d3fce8e43..d2d126b64 100644 --- a/platform/packages/api/src/routes/webhooks.ts +++ b/platform/packages/api/src/routes/webhooks.ts @@ -1,9 +1,8 @@ -import { and, eq, inArray, isNull, or, sql } from 'drizzle-orm'; +import { and, eq, inArray, sql } from 'drizzle-orm'; import { Hono } from 'hono'; import type { Context } from 'hono'; import { ACTIVE_BUILD_STATUSES, - clearGitHubInstallationOwnerForUser, deleteGitHubConnection, deleteGitHubInstallationMembers, deleteGitHubInstallationMembersByGithubAccount, @@ -13,7 +12,6 @@ import { getGitHubConnectionsByRepo, getGitHubInstallation, getGitHubInstallationsByAccount, - getOwnedProjectsByUserId, getUserByOAuthAccount, markBuildTerminalIfActive, markGitHubInstallationStatus, @@ -313,35 +311,27 @@ async function rerunBuildForCommit( installationId === undefined || installationId === null || !repoFullName || + repoId === undefined || + repoId === null || typeof headSha !== 'string' || headSha === '' ) { return context.json({ ok: true, ignored: `missing ${event} routing fields` }); } - const repoIdStr = repoId === undefined || repoId === null ? null : String(repoId); - const connections = await getGitHubConnectionsByRepo( - db, - String(installationId), - repoFullName, - repoIdStr, - ); + const repoIdStr = String(repoId); + const connections = await getGitHubConnectionsByRepo(db, String(installationId), repoIdStr); // Same self-heal as the push path: a connection matched by immutable id may // carry a stale name, and the container build uses that name as its tarball // source. - if (repoIdStr !== null) { - const hasStaleName = connections.some( - (c) => c.repository_id === repoIdStr && c.repo_full_name !== repoFullName, + if (connections.some((c) => c.repo_full_name !== repoFullName)) { + await updateGitHubConnectionRepoNamesByRepoId( + db, + String(installationId), + repoIdStr, + repoFullName, ); - if (hasStaleName) { - await updateGitHubConnectionRepoNamesByRepoId( - db, - String(installationId), - repoIdStr, - repoFullName, - ); - } } // `head_branch` is NOT a filter. GitHub keeps one suite per app per commit even @@ -553,8 +543,8 @@ export async function handleVerifiedGitHubWebhook( const push = payload as PushPayload; const installationId = push.installation?.id; const repoFullName = push.repository?.full_name; - // Immutable repo id (when present) keys connection resolution so a rename/ - // name-reuse can't deploy to the wrong project; full_name is the fallback. + // The immutable repo id keys connection resolution so a rename/name-reuse + // can't deploy to the wrong project. const repoId = push.repository?.id; const ref = push.ref; const after = push.after; @@ -564,12 +554,15 @@ export async function handleVerifiedGitHubWebhook( installationId === undefined || installationId === null || !repoFullName || + repoId === undefined || + repoId === null || typeof ref !== 'string' || !ref.startsWith('refs/heads/') || typeof after !== 'string' ) { return context.json({ ok: true, ignored: 'unhandled push' }); } + const repoIdStr = String(repoId); // Branch delete — no source to build, but an in-flight build for the // now-deleted branch still holds a live deploy token: the middleware @@ -583,7 +576,6 @@ export async function handleVerifiedGitHubWebhook( // here — a delete carries no source to build.) if (after === ZERO_SHA) { const deletedBranch = ref.slice('refs/heads/'.length); - const repoIdStr = repoId === undefined || repoId === null ? null : String(repoId); // Monotonic fence captured BEFORE the absence check: only builds that // already existed when we began confirming the branch is gone are eligible // for cancellation. A build enqueued during the check-to-cancel window (a @@ -623,7 +615,7 @@ export async function handleVerifiedGitHubWebhook( // // BOUNDED LIMITATION (rename + name-reuse): this proof keys on the // payload's `repoFullName`, while the cancellation below keys on the - // immutable `repository_id` (when BOTH sides carry one). They name the + // immutable `repository_id`. They name the // SAME repo at event time, but a delete delayed across a rename whose // freed name is then REUSED by a different repo can make this check // resolve to the wrong repo (or 404 → 'absent') while cancellation still @@ -651,7 +643,6 @@ export async function handleVerifiedGitHubWebhook( const conns = await tx .select({ project_id: githubConnections.project_id, - repo_full_name: githubConnections.repo_full_name, repository_id: githubConnections.repository_id, branch: githubConnections.branch, }) @@ -665,22 +656,8 @@ export async function handleVerifiedGitHubWebhook( instance_type: string | null; }> = []; for (const conn of conns) { - // Per-connection repo match. This is a REVOCATION path (terminalize - // an orphaned build's token), so the matcher is inclusive: match by - // the immutable repository_id ONLY when BOTH the connection AND the - // payload carry one; otherwise fall back to repo_full_name. A legacy - // connection whose repository_id IS NULL is therefore still revoked - // when its repo_full_name matches, even if the delete payload carries - // a repository.id (the id can't disqualify a row that never stored - // one). Note the asymmetry vs the build path - // (getGitHubConnectionsByRepo): there a null-id connection must NOT match an id-bearing push - // — deploying to the wrong project is worse than over-revoking — so it - // is exclusive; here, over-revoking a stale build is safe. - const repoMatched = - conn.repository_id != null && repoIdStr != null - ? conn.repository_id === repoIdStr - : conn.repo_full_name === repoFullName; - if (!repoMatched || conn.branch !== deletedBranch) { + // Match on the immutable repository id, like the build path. + if (conn.repository_id !== repoIdStr || conn.branch !== deletedBranch) { continue; } acc.push( @@ -698,29 +675,18 @@ export async function handleVerifiedGitHubWebhook( } const branch = ref.slice('refs/heads/'.length); - const connections = await getGitHubConnectionsByRepo( - db, - String(installationId), - repoFullName, - repoId === undefined || repoId === null ? null : String(repoId), - ); + const connections = await getGitHubConnectionsByRepo(db, String(installationId), repoIdStr); // Self-heal a renamed repo: connections matched by immutable id may carry a // stale repo_full_name, which the container build would use as the tarball // source. Correct them so the build fetches the right source. - if (repoId !== undefined && repoId !== null) { - const repoIdStr = String(repoId); - const hasStaleName = connections.some( - (c) => c.repository_id === repoIdStr && c.repo_full_name !== repoFullName, + if (connections.some((c) => c.repo_full_name !== repoFullName)) { + await updateGitHubConnectionRepoNamesByRepoId( + db, + String(installationId), + repoIdStr, + repoFullName, ); - if (hasStaleName) { - await updateGitHubConnectionRepoNamesByRepoId( - db, - String(installationId), - repoIdStr, - repoFullName, - ); - } } // A repo may back multiple projects (e.g. staging + prod on different @@ -864,7 +830,8 @@ export async function handleVerifiedGitHubWebhook( const accountType = account?.type === 'Organization' ? 'Organization' : 'User'; await upsertGitHubInstallation(db, { installationId: String(installationId), - // user_id is backfilled in the OAuth callback (install-before-signin). + // Organization installs never have an owner. A personal install's + // owner is linked by the install callback or a later sign-in. userId: null, accountLogin: account?.login ?? '', accountId: account?.id === undefined ? '' : String(account.id), @@ -1051,13 +1018,11 @@ export async function handleVerifiedGitHubWebhook( // in-flight OIDC exchange (which re-reads + locks the same rows before // inserting its build) is serialized. The DO cancel runs AFTER commit. const reason = 'repository removed from github app'; - const removedNames = new Set(removed.map((r) => r.full_name)); // `repo_full_name` is mutable (a repo can be renamed under the same // installation), so a rename-then-remove leaves the connection holding the // OLD name while the payload carries the current name + the IMMUTABLE id. - // Match on the immutable repository_id when present (mirroring - // getGitHubConnectionsByRepo), falling back to the name only for legacy rows - // that predate the column. Distinct from the numeric `removedIds` above — + // Match on the immutable repository_id (mirroring + // getGitHubConnectionsByRepo). Distinct from the numeric `removedIds` above — // this set holds the stringified ids that the text `repository_id` column // is compared against. const removedRepositoryIds = new Set(removed.map((r) => String(r.id))); @@ -1084,7 +1049,6 @@ export async function handleVerifiedGitHubWebhook( const connections = await tx .select({ project_id: githubConnections.project_id, - repo_full_name: githubConnections.repo_full_name, repository_id: githubConnections.repository_id, }) .from(githubConnections) @@ -1110,11 +1074,7 @@ export async function handleVerifiedGitHubWebhook( instance_type: string | null; }> = []; for (const conn of connections) { - const matched = - conn.repository_id != null - ? removedRepositoryIds.has(conn.repository_id) - : removedNames.has(conn.repo_full_name); - if (!matched) { + if (conn.repository_id === null || !removedRepositoryIds.has(conn.repository_id)) { continue; } acc.push(...(await terminateBuildsForProject(txDb, conn.project_id, { reason }))); @@ -1186,14 +1146,19 @@ export async function handleVerifiedGitHubWebhook( const installationId = data.installation?.id; const repoFullName = data.repository?.full_name; const repoId = data.repository?.id; - if (installationId === undefined || installationId === null || !repoFullName) { + if ( + installationId === undefined || + installationId === null || + !repoFullName || + repoId === undefined || + repoId === null + ) { return context.json({ ok: true, ignored: 'missing workflow_run routing fields' }); } const connections = await getGitHubConnectionsByRepo( db, String(installationId), - repoFullName, - repoId === undefined || repoId === null ? null : String(repoId), + String(repoId), ); if (connections.length === 0) { return context.json({ ok: true, ignored: 'no matching connection' }); @@ -1392,8 +1357,8 @@ export async function handleVerifiedGitHubWebhook( // rows serializes an in-flight OIDC exchange for the same rows (mirror // installation/uninstall). terminate = revoke in-flight build tokens // (build-row status is the token authority); delete = remove the future - // auto-deploy trigger. Membership cache + owner pointer are cleared - // regardless of connection count. The revocation tombstone is stamped ONCE, + // auto-deploy trigger. The membership cache is cleared regardless of + // connection count. The revocation tombstone is stamped ONCE, // keyed by the removed GitHub account id (durable, known from the payload // regardless of Void state) — user resolution drives only the sever. DO // cancel is AWAITED after commit. Idempotent in the steady state: a plain @@ -1413,9 +1378,9 @@ export async function handleVerifiedGitHubWebhook( // default. (Reachability: GitHub only auto-retries a FAILED delivery, or an // admin manually redelivers.) // - // Connections + install owner pointers are OAUTH-backed, so the affected - // user for SEVERING is exactly `getUserByOAuthAccount('github', X)` — the - // sole driver of connection-severing + owner-clearing. Browser-proof-X + // Connections are OAUTH-backed, so the affected user for SEVERING is + // exactly `getUserByOAuthAccount('github', X)` — the sole driver of + // connection-severing. Browser-proof-X // LISTING memberships (whose `github_account_id` is decoupled from the // bearer's oauth id) never back a connection, so X's removal only DELETES // them. That resolution is deliberately NOT done out here: it runs INSIDE the @@ -1458,8 +1423,8 @@ export async function handleVerifiedGitHubWebhook( // redemption) or the redemption commits first (this post-lock re-read sees // its freshly-inserted connection and severs it). // - // Connections record the owner/admin whose OAuth proof authorized them. - // Legacy rows have no provenance and retain the old owner-scoped behavior. + // Connections record the owner/admin whose OAuth proof authorized them, + // so the removed user's connections are exactly those they authorized. const removedUser = await getUserByOAuthAccount( txDb, 'github', @@ -1472,43 +1437,31 @@ export async function handleVerifiedGitHubWebhook( instance_type: string | null; }> = []; if (removedUser) { - const ownedProjectIds = (await getOwnedProjectsByUserId(txDb, removedUser.id)).map( - (project) => project.id, - ); - const authorizationClause = - ownedProjectIds.length > 0 - ? or( - eq(githubConnections.authorized_by_user_id, removedUser.id), - and( - isNull(githubConnections.authorized_by_user_id), - inArray(githubConnections.project_id, ownedProjectIds), - ), - ) - : eq(githubConnections.authorized_by_user_id, removedUser.id); const conns = await tx .select({ project_id: githubConnections.project_id }) .from(githubConnections) .where( - and(inArray(githubConnections.installation_id, orgInstallIds), authorizationClause), + and( + inArray(githubConnections.installation_id, orgInstallIds), + eq(githubConnections.authorized_by_user_id, removedUser.id), + ), ) .for('update'); for (const conn of conns) { acc.push(...(await terminateBuildsForProject(txDb, conn.project_id, { reason }))); await deleteGitHubConnection(txDb, conn.project_id); } - // Clear the removed user's membership cache + owner pointer across every - // org install (both guard on the user id, so a different owner/bearer is - // never clobbered). + // Clear the removed user's membership cache across every org install + // (guarded on the user id, so a different bearer is never clobbered). await deleteGitHubInstallationMembers(txDb, orgInstallIds, removedUser.id); - await clearGitHubInstallationOwnerForUser(txDb, orgInstallIds, removedUser.id); } // Void the BROWSER-PROOF-X LISTING memberships across every org install, // keyed by the GitHub id X (NOT a Void user id) so any bearer's X-keyed // row is removed. A membership's `github_account_id` is the browser proof // captured at JOIN, DECOUPLED from the bearer's oauth identity, so it never - // backs a connection or an owner pointer (proven oauth-backed above). This - // therefore deletes exactly the stale X listing entries and touches NO - // connection, NO owner pointer, and NO Z-keyed membership. The durable + // backs a connection (proven oauth-backed above). This therefore deletes + // exactly the stale X listing entries and touches NO connection and NO + // Z-keyed membership. The durable // tombstone is written once above (keyed by X), so a pre-mint replay is // caught even for a user that does not exist yet at removal time. await deleteGitHubInstallationMembersByGithubAccount( diff --git a/platform/packages/api/src/schema.ts b/platform/packages/api/src/schema.ts index 8ba882358..040b92dbf 100644 --- a/platform/packages/api/src/schema.ts +++ b/platform/packages/api/src/schema.ts @@ -1039,11 +1039,12 @@ export const projectDatabaseCredentials = pgTable('project_database_credentials' // --------------------------------------------------------------------------- // github_installations — GitHub App installations. // -// `user_id` is nullable to support install-before-signin: a user can install -// the GitHub App before (or instead of) signing in, in which case the -// installation lands here unlinked and is backfilled in the GitHub OAuth -// callback (`linkGitHubInstallationToUser`). `repositories` mirrors the -// installation's repository selection as a JSON array of `{ full_name, id }`. +// `user_id` is the owner of a personal (account_type='User') installation and +// is always null for organization installations, which are reached only +// through `github_installation_members`. A personal installation can also be +// unlinked (install-before-signin) until the GitHub OAuth callback backfills it +// (`linkGitHubInstallationToUser`). `repositories` mirrors the installation's +// repository selection as a JSON array of `{ full_name, id }`. // --------------------------------------------------------------------------- export type GitHubInstallationRepository = Readonly<{ full_name: string; @@ -1110,19 +1111,13 @@ export const githubConnections = pgTable( // could match a DIFFERENT repository to this connection and deploy to the // wrong project. Webhook (`repository.id`) and OIDC (`claims.repository_id`) // resolution match on this immutable id, treating `repo_full_name` as - // display/fetch metadata. Nominally nullable, but the resolvers FAIL CLOSED: - // when the caller has an id, a null-id row is NOT matched by `repo_full_name` - // fallback (a renamed-and-reused name could otherwise authorize the wrong - // project). New connections always populate it at connect time; the only - // name fallback left is for callers with no id at all (malformed/partial - // webhook). A `repo_full_name` match is used solely in that no-id case. + // display/fetch metadata. Every connection populates it at connect time; + // a row without one never matches a resolver (fail closed). repository_id: text('repository_id'), - // The project owner or administrator whose own GitHub OAuth token proved - // repository access during connect. NULL on legacy rows. Runtime - // authorization accepts a current row only while this still names the - // owner or a project administrator. Legacy organization rows without - // per-repository proof fail closed; legacy personal rows retain their - // owner-installation fallback. + // The project owner or administrator who proved repository access during + // connect. Runtime authorization accepts the row only while this still + // names the owner or a project administrator; a row without one has no + // authority. authorized_by_user_id: text('authorized_by_user_id').references(() => users.id, { onDelete: 'set null', }), diff --git a/platform/packages/api/test/integration/admin-dashboard.test.ts b/platform/packages/api/test/integration/admin-dashboard.test.ts index d3cdae1c7..4ca78c1d3 100644 --- a/platform/packages/api/test/integration/admin-dashboard.test.ts +++ b/platform/packages/api/test/integration/admin-dashboard.test.ts @@ -1210,9 +1210,9 @@ describe('POST /admin/users/:id/delete', () => { id: 'ghi_udel_test', installation_id: 'inst-udel-1', user_id: user.id, - account_login: 'octo-org', + account_login: 'octo', account_id: '4242', - account_type: 'Organization', + account_type: 'User', }); const res = await req(`/admin/users/${user.id}/delete`, admin.adminJwt, { diff --git a/platform/packages/api/test/integration/api-check-runs.test.ts b/platform/packages/api/test/integration/api-check-runs.test.ts index c889e2d52..47439f963 100644 --- a/platform/packages/api/test/integration/api-check-runs.test.ts +++ b/platform/packages/api/test/integration/api-check-runs.test.ts @@ -151,8 +151,14 @@ vi.mock('../../src/db.ts', () => ({ return true; }), installationCoversRepo: vi.fn( - async (_db: unknown, _installationId: string, repositoryId: string | null) => { - if (repositoryId === null) { + async ( + _db: unknown, + connectionId: string, + _projectId: string, + _installationId: string, + repositoryId: string | null, + ) => { + if (!connectionId || !repositoryId) { return false; } return dbState.installationCovered; @@ -281,6 +287,7 @@ function makeConfig(overrides: Partial = {}): BuildConfig { commitSha: 'sha1234567890', branch: 'main', repoFullName: 'owner/repo', + connectionId: 'c1', installationId: 'inst1', repositoryId: 'repo1', instanceType: 'standard-1', diff --git a/platform/packages/api/test/integration/api-github.test.ts b/platform/packages/api/test/integration/api-github.test.ts index f7dd02a35..5ff78c6fe 100644 --- a/platform/packages/api/test/integration/api-github.test.ts +++ b/platform/packages/api/test/integration/api-github.test.ts @@ -252,7 +252,7 @@ async function mintConnectGrant( } // Seed the org-shared install scenario a non-owner member connects against: -// an install OWNED by someone else, a project OWNED by the connecting member, and +// an install the member does not own, a project OWNED by the connecting member, and // (unless `seedMembership: false`) an active membership row binding the member to // the install. The member's linked GitHub id is seeded via createTestUser's // provider/providerId args so getGitHubAccountIdForUser returns a known value @@ -287,12 +287,14 @@ async function seedMemberScenario(opts: { opts.memberGithubId, ); const project = await createTestProject(env.db, member.id, `gh-member-${opts.installationId}`); + const accountType = opts.accountType ?? 'Organization'; await upsertGitHubInstallation(env.db, { installationId: opts.installationId, - userId: owner.id, + // Only a personal install has an owner. + userId: accountType === 'User' ? owner.id : null, accountLogin: 'org', accountId: `acc_${opts.installationId}`, - accountType: opts.accountType ?? 'Organization', + accountType, repositories: opts.repositories ?? [{ full_name: 'org/app', id: 1 }], repositorySelection: opts.repositorySelection, }); @@ -1410,96 +1412,34 @@ describe('POST /projects/:id/github — non-owner member connect grant', () => { expect((await getGitHubConnection(env.db, project.id))?.repository_id).toBe('4242'); }); - it('requires per-repo proof for a legacy organization owner and disables its old cross-repo connection', async () => { - const user = await createTestUser(env.db, 'legacy-org-owner', 'github', '5551234'); - const authorizedProject = await createTestProject(env.db, user.id, 'legacy-org-a'); - const inaccessibleProject = await createTestProject(env.db, user.id, 'legacy-org-b'); - await upsertGitHubInstallation(env.db, { - installationId: '3011', - // Older versions wrote this pointer after seeing the installation through - // /user/installations. It is discovery metadata, not org-wide authority. - userId: user.id, - accountLogin: 'org', - accountId: 'acc_3011', - accountType: 'Organization', - repositories: [ - { full_name: 'org/authorized-a', id: 301101 }, - { full_name: 'org/inaccessible-b', id: 301102 }, - ], - repositorySelection: 'selected', - }); - await upsertGitHubInstallationMember(env.db, { - installationId: '3011', - userId: user.id, - githubAccountId: '5551234', - ttlSeconds: 3600, - }); - await createGitHubConnection(env.db, { - projectId: inaccessibleProject.id, - installationId: '3011', - repoFullName: 'org/inaccessible-b', - repositoryId: '301102', - authorizedByUserId: null, - }); - await createGitHubConnection(env.db, { - projectId: authorizedProject.id, + // A connected project keeps its connection: a second organization connect is + // rejected exactly like a personal-install connect, and the row is unchanged. + it('returns 409 when an organization project is already connected', async () => { + const { member, project } = await seedMemberScenario({ installationId: '3011', - repoFullName: 'org/authorized-a', - repositoryId: '301101', - authorizedByUserId: null, + memberGithubId: '5551234', }); + const connect = async () => + memberConnect(member, project.id, { + installationId: '3011', + repoFullName: 'org/app', + connectGrant: await mintConnectGrant({ + installationId: '3011', + repoFullName: 'org/app', + githubAccountId: '5551234', + }), + codeVerifier: CONNECT_VERIFIER, + }); - const listed = await app.fetch( - new Request('http://localhost/github/installations', authed(user.jwt)), - env, - ); - const installation = ( - (await listed.json()) as Array<{ installation_id: string; repositories: Array }> - ).find((row) => row.installation_id === '3011'); - expect(installation?.repositories).toEqual([]); - - // The old unproven connection cannot resolve from a signed push, so it - // cannot enqueue a build or reach the installation-token clone path. - expect( - await getGitHubConnectionsByRepo(env.db, '3011', 'org/inaccessible-b', '301102'), - ).toEqual([]); - const status = await app.fetch( - new Request(`http://localhost/projects/${inaccessibleProject.id}/github`, authed(user.jwt)), - env, - ); - expect(status.status).toBe(200); - expect(((await status.json()) as { requires_reconnect: boolean }).requires_reconnect).toBe( - true, - ); - - const withoutProof = await memberConnect(user, authorizedProject.id, { - installationId: '3011', - repoFullName: 'org/authorized-a', - }); - expect(withoutProof.status).toBe(403); - expect(((await withoutProof.json()) as { error: string }).error).toBe( - 'connect_authorization_required', - ); + const first = await connect(); + expect(first.status).toBe(200); + const original = await getGitHubConnection(env.db, project.id); + expect(original?.authorized_by_user_id).toBe(member.id); - const grant = await mintConnectGrant({ - installationId: '3011', - repoFullName: 'org/authorized-a', - repositoryId: 301101, - githubAccountId: '5551234', - }); - const connected = await memberConnect(user, authorizedProject.id, { - installationId: '3011', - repoFullName: 'org/authorized-a', - connectGrant: grant, - codeVerifier: CONNECT_VERIFIER, - }); - expect(connected.status).toBe(200); - expect((await getGitHubConnection(env.db, authorizedProject.id))?.authorized_by_user_id).toBe( - user.id, - ); - expect( - await getGitHubConnectionsByRepo(env.db, '3011', 'org/authorized-a', '301101'), - ).toHaveLength(1); + const second = await connect(); + expect(second.status).toBe(409); + expect(await second.json()).toEqual({ error: 'project already connected' }); + expect(await getGitHubConnection(env.db, project.id)).toEqual(original); }); // A grant minted for a DIFFERENT repo than the one being connected is rejected. @@ -1835,7 +1775,7 @@ describe('POST /projects/:id/github — non-owner member connect grant', () => { const v = await createTestUser(env.db, 'f1-v', 'google', 'google-f1-v'); await upsertGitHubInstallation(env.db, { installationId: INSTALL, - userId: owner.id, + userId: null, accountLogin: 'org', accountId: ORG, accountType: 'Organization', @@ -1921,7 +1861,7 @@ describe('POST /projects/:id/github — non-owner member connect grant', () => { const owner = await createTestUser(env.db, 't19-owner', 'github', 'gh-owner-6200'); await upsertGitHubInstallation(env.db, { installationId: INSTALL, - userId: owner.id, + userId: null, accountLogin: 'org', accountId: ORG, accountType: 'Organization', @@ -2013,19 +1953,15 @@ describe('POST /projects/:id/github — non-owner member connect grant', () => { expect(await getGitHubConnection(env.db, project.id)).toBeNull(); }); - // Fail-closed hardening (Task 14): a LEGACY connect_grant minted before the - // `iat` field existed carries NO iat. The in-tx recheck treats a missing iat as - // 0 (predating every tombstone), so ANY recorded revocation rejects it with the - // FROZEN stable 'invalid connect grant' — no connection is created. Mint inline - // so the property is truly ABSENT from the signed payload (mintConnectGrant - // would inject one). If a missing iat leaked through (a NaN compare), a removed - // member could still connect — this test would then fail. - it('returns 403 invalid connect grant when a legacy grant carries no iat against a revocation (fail closed)', async () => { + // A connect_grant without `iat` cannot be compared with revocation tombstones, + // so it is rejected with the FROZEN stable 'invalid connect grant' even when no + // revocation exists — no connection is created. Mint inline so the property is + // truly ABSENT from the signed payload (mintConnectGrant would inject one). + it('returns 403 invalid connect grant when the grant carries no iat', async () => { const { member, project } = await seedMemberScenario({ installationId: '3019', memberGithubId: '5551234', }); - await recordInstallationRevocations(env.db, ['3019'], '5551234'); const encoded = btoa( JSON.stringify({ purpose: 'connect', @@ -2035,17 +1971,17 @@ describe('POST /projects/:id/github — non-owner member connect grant', () => { githubAccountId: '5551234', codeChallenge: await createCodeChallenge(CONNECT_VERIFIER), codeChallengeMethod: 'S256', - // NO `iat` field — a legacy artifact predating the monotonic gate. + // NO `iat` field. exp: Date.now() + 5 * 60 * 1000, }), ); const signature = await hmacSignState(encoded, JWT_SECRET); - const legacyGrant = `${encoded}.${signature}`; + const grantWithoutIat = `${encoded}.${signature}`; const res = await memberConnect(member, project.id, { installationId: '3019', repoFullName: 'org/app', - connectGrant: legacyGrant, + connectGrant: grantWithoutIat, codeVerifier: CONNECT_VERIFIER, }); @@ -2126,7 +2062,7 @@ describe('POST /projects/:id/github — non-owner member connect grant', () => { const owner = await createTestUser(env.db, 'r101-join-owner', 'github', 'gh-owner-7100'); await upsertGitHubInstallation(env.db, { installationId: INSTALL, - userId: owner.id, + userId: null, accountLogin: 'org', accountId: 'acc_7100', accountType: 'Organization', @@ -2238,42 +2174,35 @@ describe('POST /projects/:id/github — non-owner member connect grant', () => { }); // Task 15 — the connect gate re-derives ownership from the install row it locks -// FOR UPDATE inside the go-live transaction, not the stale pre-tx snapshot. If -// member_removed clears the owner pointer (nulls user_id) while a connect waits -// on that lock, the pre-tx owner path is stale: repositoryId was resolved via the -// installation token with NO member grant, so falling through to the member insert -// would be a confused-deputy. The re-read fails closed (opaque 404) on the -// `isOwner && !lockedIsOwner` transition, so the severed installer can no longer -// plant a fresh connection that would auto-deploy forever. +// FOR UPDATE inside the go-live transaction, not the stale pre-tx snapshot. If a +// personal install's owner pointer changes while a connect waits on that lock, +// the pre-tx owner path is stale: repositoryId was resolved via the installation +// token with NO member grant, so falling through to the member insert would be a +// confused-deputy. The re-read fails closed (opaque 404) on the +// `isOwner && !lockedIsOwner` transition. describe('POST /projects/:id/github — locked-row ownership re-derivation (Task 15)', () => { - // Sequential fail-closed: an install whose owner pointer is already cleared - // (user_id NULL) + a caller who is NOT a member fails closed with the opaque - // 404 and creates no connection. Pre-tx isOwner is false (null !== caller), so - // the owner path is never taken and the non-member gate rejects it. - it('returns opaque 404 for a cleared-owner install when the caller is not a member', async () => { - const owner = await createTestUser(env.db, 'owner-3020', 'github', 'gh-owner-3020'); + // Sequential fail-closed: a personal install with no linked owner (user_id + // NULL) + a caller who is NOT a member fails closed with the opaque 404 and + // creates no connection. Pre-tx isOwner is false (null !== caller), so the + // owner path is never taken and the non-member gate rejects it. + it('returns opaque 404 for an unlinked personal install when the caller is not a member', async () => { const caller = await createTestUser(env.db, 'caller-3020', 'github', 'gh-caller-3020'); const project = await createTestProject(env.db, caller.id, 'gh-cleared-3020'); await upsertGitHubInstallation(env.db, { installationId: '3020', - userId: owner.id, - accountLogin: 'org', + userId: null, + accountLogin: 'someone', accountId: 'acc_3020', - accountType: 'Organization', - repositories: [{ full_name: 'org/app', id: 1 }], + accountType: 'User', + repositories: [{ full_name: 'someone/app', id: 1 }], repositorySelection: 'selected', }); - // member_removed nulls the owner pointer (clearGitHubInstallationOwnerForUser). - await env.db - .update(githubInstallations) - .set({ user_id: null }) - .where(eq(githubInstallations.installation_id, '3020')); const res = await app.fetch( new Request(`http://localhost/projects/${project.id}/github`, { method: 'POST', headers: { Authorization: `Bearer ${caller.jwt}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ installationId: '3020', repoFullName: 'org/app' }), + body: JSON.stringify({ installationId: '3020', repoFullName: 'someone/app' }), }), // Non-owner path is gated on App user OAuth (R10-1); send the configured env // so this test reaches the membership gate (opaque 404), not the kill switch. @@ -2288,35 +2217,33 @@ describe('POST /projects/:id/github — locked-row ownership re-derivation (Task // The true race branch, driven deterministically. On the owner + all-repos // path the route resolves the repo id via a live GET /repos fetch BETWEEN the // pre-tx read (isOwner=true) and the go-live transaction's FOR UPDATE re-read. - // The stubbed fetch clears the owner pointer as its side effect — exactly what - // a concurrent member_removed commit would do while we waited on the lock — so - // the locked read sees user_id=NULL and `isOwner && !lockedIsOwner` fails - // closed with a 404 and NO connection. This is the deterministic seam the brief - // calls for: the fetch is a real await point in the owner path, so the locked - // read observes a change made after the pre-tx snapshot without any timing race. + // The stubbed fetch clears the owner pointer as its side effect, so the locked + // read sees user_id=NULL and `isOwner && !lockedIsOwner` fails closed with a + // 404 and NO connection. The fetch is a real await point in the owner path, so + // the locked read observes a change made after the pre-tx snapshot without any + // timing race. it('fails closed (404, no connection) when the owner pointer is cleared between the pre-tx read and the locked read', async () => { const owner = await createTestUser(env.db, 'owner-3021', 'github', 'gh-owner-3021'); const project = await createTestProject(env.db, owner.id, 'gh-race-3021'); await upsertGitHubInstallation(env.db, { installationId: '3021', userId: owner.id, - accountLogin: 'org', + accountLogin: 'owner-3021', accountId: 'acc_3021', - accountType: 'Organization', - repositories: [{ full_name: 'org/old', id: 1 }], + accountType: 'User', + repositories: [{ full_name: 'owner-3021/old', id: 1 }], // `all` forces the live GET /repos resolution — the interposition seam. repositorySelection: 'all', }); // The fetch stub interposes between the pre-tx owner read and the locked - // re-read: it nulls the owner pointer (mirroring member_removed committing - // while the connect blocked on the install-row lock) before returning the id. + // re-read: it nulls the owner pointer before returning the id. vi.stubGlobal( 'fetch', vi.fn(async (input: string | URL | Request) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; - if (url.includes('/repos/org/new')) { + if (url.includes('/repos/owner-3021/new')) { await env.db .update(githubInstallations) .set({ user_id: null }) @@ -2331,7 +2258,7 @@ describe('POST /projects/:id/github — locked-row ownership re-derivation (Task new Request(`http://localhost/projects/${project.id}/github`, { method: 'POST', headers: { Authorization: `Bearer ${owner.jwt}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ installationId: '3021', repoFullName: 'org/new' }), + body: JSON.stringify({ installationId: '3021', repoFullName: 'owner-3021/new' }), }), env, ); @@ -2340,6 +2267,8 @@ describe('POST /projects/:id/github — locked-row ownership re-derivation (Task expect(((await res.json()) as { error: string }).error).toBe('installation not found'); // The stale-owner connect must NOT have planted a connection. expect(await getGitHubConnection(env.db, project.id)).toBeNull(); + // The live repo id was actually resolved, so the owner path really ran. + expect(fetch).toHaveBeenCalled(); }); }); @@ -2526,8 +2455,9 @@ describe('GET /projects/:id/github', () => { env, ); expect(res.status).toBe(200); - const connection = (await res.json()) as { repo_full_name: string }; + const connection = (await res.json()) as Record; expect(connection.repo_full_name).toBe('acme/app'); + expect(connection).not.toHaveProperty('requires_reconnect'); }); it('returns 404 when there is no connection', async () => { @@ -3242,14 +3172,13 @@ describe('GET /github/installations', () => { expect(installations[0]!.installation_id).toBe('901'); }); - // (a) A member of a shared org installation (owned by userB) sees it via the - // broadened owner-OR-active-member gate. + // (a) A member of a shared org installation sees it via the + // owner-OR-active-member gate. it('includes an installation the caller has an active membership in', async () => { const userA = await createTestUser(env.db, 'member-a'); - const userB = await createTestUser(env.db, 'owner-b'); await upsertGitHubInstallation(env.db, { installationId: '910', - userId: userB.id, + userId: null, accountLogin: 'org', accountId: 'acc_910', accountType: 'Organization', @@ -3272,13 +3201,12 @@ describe('GET /github/installations', () => { expect(installations[0]!.installation_id).toBe('910'); }); - // (b) A non-member (no membership row) does NOT see userB's installation. + // (b) A non-member (no membership row) does NOT see the installation. it('excludes an installation the caller has no membership in', async () => { const userA = await createTestUser(env.db, 'stranger-a'); - const userB = await createTestUser(env.db, 'owner-b2'); await upsertGitHubInstallation(env.db, { installationId: '911', - userId: userB.id, + userId: null, accountLogin: 'org2', accountId: 'acc_911', accountType: 'Organization', @@ -3297,10 +3225,9 @@ describe('GET /github/installations', () => { // (c) An EXPIRED membership row is excluded (TTL honored via expires_at > now()). it('excludes an installation whose membership has expired', async () => { const userA = await createTestUser(env.db, 'expired-a'); - const userB = await createTestUser(env.db, 'owner-b3'); await upsertGitHubInstallation(env.db, { installationId: '912', - userId: userB.id, + userId: null, accountLogin: 'org3', accountId: 'acc_912', accountType: 'Organization', @@ -3323,40 +3250,11 @@ describe('GET /github/installations', () => { expect(installations).toHaveLength(0); }); - // A legacy organization owner pointer plus an active membership still yields - // one row. The membership is the authority; the old pointer adds no access. - it('returns a legacy-owned organization installation exactly once via membership', async () => { - const userA = await createTestUser(env.db, 'owner-member-a'); - await upsertGitHubInstallation(env.db, { - installationId: '913', - userId: userA.id, - accountLogin: 'org4', - accountId: 'acc_913', - accountType: 'Organization', - repositories: [], - }); - await upsertGitHubInstallationMember(env.db, { - installationId: '913', - userId: userA.id, - githubAccountId: 'gh_a', - ttlSeconds: 3600, - }); - - const res = await app.fetch( - new Request('http://localhost/github/installations', authed(userA.jwt)), - env, - ); - expect(res.status).toBe(200); - const installations = (await res.json()) as Array<{ installation_id: string }>; - const matching = installations.filter((i) => i.installation_id === '913'); - expect(matching).toHaveLength(1); - }); - - // Organization owner pointers written by older versions are not repository - // authority. The pointed-at user sees nothing without an active membership; - // once membership is proven, both that user and other members see only the - // installation metadata. Personal installation owners retain their repo list. - it('never exposes organization repositories through a legacy owner pointer', async () => { + // Installing the App on an organization confers no standing of its own. The + // installer sees nothing without an active membership; once membership is + // proven, the installer and other members see only the installation metadata. + // Personal installation owners retain their repo list. + it('never exposes organization repositories to the installer or members', async () => { const owner = await createTestUser(env.db, 'repo-owner'); const member = await createTestUser(env.db, 'repo-member'); const seededRepos = [ @@ -3365,7 +3263,7 @@ describe('GET /github/installations', () => { ]; await upsertGitHubInstallation(env.db, { installationId: '920', - userId: owner.id, + userId: null, accountLogin: 'org5', accountId: 'acc_920', accountType: 'Organization', @@ -3385,8 +3283,8 @@ describe('GET /github/installations', () => { repositories: Array<{ full_name: string; id: number }>; }; - // A stale organization owner pointer alone does not make the installation - // visible, much less disclose every private repository in its cache. + // Having installed the App does not make the installation visible, much + // less disclose every private repository in its cache. const ownerRes = await app.fetch( new Request('http://localhost/github/installations', authed(owner.jwt)), env, @@ -3800,20 +3698,18 @@ describe('GET /github/callback', () => { expect(members).toHaveLength(0); }); - // SECURITY (Task 4): a DIFFERENT Void user (A) who is a real org co-member - // reaches an installation the installer (B) already owns. On the PROVEN - // user-token path (GET /user/installations lists installation 5000 → - // authorized:true, and the code-holder id matches the signed state) the - // backstop GRANTS a cached membership row for A WITHOUT re-owning the - // installation — B stays the owner — and returns the owner-path redirect. - it('grants a cached membership (no re-own) when a co-member joins an owned org install via the user-token path', async () => { - const userB = await createTestUser(env.db, 'orgowner', 'github', '5555'); + // SECURITY (Task 4): a Void user (A) who is a real org co-member reaches an + // existing organization installation. On the PROVEN user-token path + // (GET /user/installations lists installation 5000 → authorized:true, and the + // code-holder id matches the signed state) the backstop GRANTS a cached + // membership row for A WITHOUT making A the owner, and returns the redirect. + it('grants a cached membership (no ownership) when a co-member joins an org install via the user-token path', async () => { const userA = await createTestUser(env.db, 'orgmember', 'github', '4242'); - // B already owns the ORG installation 5000 (account id 9001). + // The ORG installation 5000 (account id 9001) exists and has no owner. await upsertGitHubInstallation(env.db, { installationId: '5000', - userId: userB.id, + userId: null, accountLogin: 'acme-org', accountId: '9001', accountType: 'Organization', @@ -3849,9 +3745,9 @@ describe('GET /github/callback', () => { expect(members[0].user_id).toBe(userA.id); expect(members[0].github_account_id).toBe('4242'); - // The installation is NOT re-owned — B is still the owner. + // The organization installation stays ownerless — A is NOT made the owner. const persisted = await getGitHubInstallation(env.db, '5000'); - expect(persisted?.user_id).toBe(userB.id); + expect(persisted?.user_id).toBeNull(); }); // Guard (c) — the install-callback membership backstop is Organization-only. A @@ -3911,12 +3807,11 @@ describe('GET /github/callback', () => { // onConflict refreshes the existing row in place (exactly ONE row) and pushes // expires_at forward, rather than inserting duplicates. it('is idempotent across repeat token-path co-member joins: one refreshed membership row', async () => { - const userB = await createTestUser(env.db, 'orgowner', 'github', '5555'); const userA = await createTestUser(env.db, 'orgmember', 'github', '4242'); await upsertGitHubInstallation(env.db, { installationId: '5000', - userId: userB.id, + userId: null, accountLogin: 'acme-org', accountId: '9001', accountType: 'Organization', @@ -3971,8 +3866,8 @@ describe('GET /github/callback', () => { new Date(seeded.expires_at).getTime(), ); - // Still not re-owned. - expect((await getGitHubInstallation(env.db, '5000'))?.user_id).toBe(userB.id); + // Still ownerless. + expect((await getGitHubInstallation(env.db, '5000'))?.user_id).toBeNull(); }); // (d): personal install with NO code still succeeds via the account-id @@ -4148,15 +4043,13 @@ describe('GET /github/callback', () => { }); } - // Owner re-adopt, CONCURRENT: member_removed cleared the removed installer's - // owner pointer (user_id null) and tombstoned (install, ownerGithubId) AFTER - // the callback's proof. The re-authorizing owner must be rejected — NOT - // re-adopted (which would let the owner CONNECT path bypass the tombstone) — - // and no membership row is minted. + // Org re-authorize, CONCURRENT: member_removed tombstoned (install, + // installerGithubId) AFTER the callback's proof. The re-authorizing installer + // must be rejected, the install stays ownerless, and no membership row is + // minted. it('403s and does not re-adopt owner when the tombstone post-dates the proof (concurrent member_removed)', async () => { const owner = await createTestUser(env.db, 'org-owner', 'github', '7001'); - // Org install whose owner pointer was CLEARED (user_id null) but the row - // remains — exactly the state member_removed leaves for a removed installer. + // Organization installs have no owner. await upsertGitHubInstallation(env.db, { installationId: '9100', userId: null, @@ -4200,16 +4093,12 @@ describe('GET /github/callback', () => { expect(members).toHaveLength(0); }); - // Cleared-owner org installs are MEMBER-ONLY (R15-1 fix, Option A): a null-owner - // org install WITH a revocation tombstone was cleared by member_removed, so it is - // shared/member-only and must NEVER be re-owned by a completing member. Even the - // ORIGINAL owner re-authorizing does NOT reclaim ownership — the tombstone routes - // the callback into the membership arm, so the owner gets a MEMBERSHIP row and the - // owner pointer stays NULL (RFC default: clear owner → fall back to members; a - // re-added owner reconnects via the member path with per-repo proof). This is the - // intended behavior change, NOT a regression. The tombstone pre-dates the proof - // (legit re-add), so the membership grant itself is NOT over-blocked. - it('cleared-owner org install is member-only: re-added original owner gets membership, not ownership (R15-1)', async () => { + // Org installs are MEMBER-ONLY: even the original installer re-authorizing after + // a removal and re-add gets a MEMBERSHIP row and the owner pointer stays NULL (a + // re-added installer reconnects via the member path with per-repo proof). The + // tombstone pre-dates the proof (legit re-add), so the membership grant itself + // is NOT over-blocked. + it('org install is member-only: a re-added original installer gets membership, not ownership', async () => { const owner = await createTestUser(env.db, 'org-owner', 'github', '7002'); await upsertGitHubInstallation(env.db, { installationId: '9101', @@ -4237,7 +4126,7 @@ describe('GET /github/callback', () => { ); expect(res.status).toBe(302); - // Cleared install is member-only: the owner pointer stays NULL... + // Org install is member-only: the owner pointer stays NULL... expect((await getGitHubInstallation(env.db, '9101'))?.user_id).toBeNull(); // ...and the re-added owner is recorded as a MEMBER (per-repo-proof member path), // NOT re-adopted as owner. @@ -4250,19 +4139,16 @@ describe('GET /github/callback', () => { expect(members[0]?.github_account_id).toBe('7002'); }); - // R15-1 CLOSED — the confused-deputy: a CLEARED-owner org install (null owner + - // a revocation tombstone for the FORMER owner) reached by a DIFFERENT member B - // (own linked GitHub id, NO tombstone for B) must NOT be re-owned by B. Before - // the fix, the null-owner row fell through to the owner-adopt path and B (no - // tombstone) adopted ownership — which would let B's OWNER connect resolve org - // repos via the installation token and bypass the per-repo connect_grant proof. - // Now the tombstone routes the callback into the membership arm: B gets a - // MEMBERSHIP row (per-repo proof required to connect), the owner pointer stays - // NULL, and B is NOT the owner. - it('cleared-owner org install: a different member B gets membership, not ownership (R15-1 confused-deputy closed)', async () => { + // Confused-deputy guard: an org install (null owner + a revocation tombstone for + // a removed member) reached by a DIFFERENT member B (own linked GitHub id, NO + // tombstone for B) must NOT be owned by B — ownership would let B's OWNER + // connect resolve org repos via the installation token and bypass the per-repo + // connect_grant proof. B gets a MEMBERSHIP row (per-repo proof required to + // connect), the owner pointer stays NULL, and B is NOT the owner. + it('org install: a different member B gets membership, not ownership (confused-deputy closed)', async () => { const memberB = await createTestUser(env.db, 'org-member-b', 'github', '7011'); - // Cleared state member_removed leaves: null owner + tombstone for the FORMER - // owner's GitHub id (7010). Member B has NO tombstone. + // Null owner + tombstone for a removed member's GitHub id (7010). Member B + // has NO tombstone. await upsertGitHubInstallation(env.db, { installationId: '9110', userId: null, @@ -4343,16 +4229,14 @@ describe('GET /github/callback', () => { expect(members[0]?.user_id).toBe(installer.id); }); - // Membership backstop, CONCURRENT: a co-member (A) reaches an install the - // installer (B) owns; member_removed tombstoned (install, A's GitHub id) AFTER - // A's proof. A must be rejected and NO membership row minted (B keeps - // ownership untouched). + // Membership backstop, CONCURRENT: a co-member (A) reaches an org install; + // member_removed tombstoned (install, A's GitHub id) AFTER A's proof. A must be + // rejected and NO membership row minted. it('403s and grants no membership when the tombstone post-dates the proof (backstop concurrent member_removed)', async () => { - const ownerB = await createTestUser(env.db, 'org-owner', 'github', '5555'); const memberA = await createTestUser(env.db, 'org-member', 'github', '4242'); await upsertGitHubInstallation(env.db, { installationId: '9102', - userId: ownerB.id, + userId: null, accountLogin: 'acme-org', accountId: '9003', accountType: 'Organization', @@ -4381,18 +4265,17 @@ describe('GET /github/callback', () => { .from(githubInstallationMembers) .where(eq(githubInstallationMembers.installation_id, '9102')); expect(members).toHaveLength(0); - // B's ownership is untouched. - expect((await getGitHubInstallation(env.db, '9102'))?.user_id).toBe(ownerB.id); + // The installation stays ownerless. + expect((await getGitHubInstallation(env.db, '9102'))?.user_id).toBeNull(); }); // Membership backstop, DURABLE/legit re-add (accepted residual pass-through): // a tombstone that PRE-dates the proof must NOT over-block the co-member grant. it('grants membership when the tombstone pre-dates the proof (backstop legit re-add)', async () => { - const ownerB = await createTestUser(env.db, 'org-owner', 'github', '5556'); const memberA = await createTestUser(env.db, 'org-member', 'github', '4243'); await upsertGitHubInstallation(env.db, { installationId: '9103', - userId: ownerB.id, + userId: null, accountLogin: 'acme-org', accountId: '9004', accountType: 'Organization', @@ -4422,7 +4305,7 @@ describe('GET /github/callback', () => { expect(members).toHaveLength(1); expect(members[0].user_id).toBe(memberA.id); expect(members[0].github_account_id).toBe('4243'); - // B stays the owner — the backstop never re-owns. - expect((await getGitHubInstallation(env.db, '9103'))?.user_id).toBe(ownerB.id); + // The installation stays ownerless — the backstop never adopts it. + expect((await getGitHubInstallation(env.db, '9103'))?.user_id).toBeNull(); }); }); diff --git a/platform/packages/api/test/integration/api-oidc.test.ts b/platform/packages/api/test/integration/api-oidc.test.ts index adb9297e4..387b1d6d3 100644 --- a/platform/packages/api/test/integration/api-oidc.test.ts +++ b/platform/packages/api/test/integration/api-oidc.test.ts @@ -253,7 +253,9 @@ async function seedActiveInstallation( async function createGitHubConnection( db: Db, - args: Parameters[1], + args: Omit[1], 'authorizedByUserId'> & { + authorizedByUserId?: string; + }, ) { const project = await getProject(db, args.projectId); if (!project) { @@ -261,8 +263,7 @@ async function createGitHubConnection( } return createGitHubConnectionRecord(db, { ...args, - authorizedByUserId: - args.authorizedByUserId === undefined ? project.user_id : args.authorizedByUserId, + authorizedByUserId: args.authorizedByUserId ?? project.user_id, }); } @@ -383,9 +384,10 @@ describe('POST /auth/github-oidc', () => { expect(res.status).toBe(401); }); - it('returns 401 for a legacy organization connection without per-repo proof', async () => { + it('returns 401 when the user who authorized the connection is no longer owner or admin', async () => { const user = await createTestUser(env.db); - const project = await createTestProject(env.db, user.id, 'oidc-legacy-org'); + const former = await createTestUser(env.db, 'oidc-former-owner'); + const project = await createTestProject(env.db, user.id, 'oidc-stale-authorizer'); await seedActiveInstallation(env.db, '1'); await createGitHubConnection(env.db, { projectId: project.id, @@ -393,7 +395,7 @@ describe('POST /auth/github-oidc', () => { repoFullName: 'octo/repo', repositoryId: '42', buildExecutor: 'github_actions', - authorizedByUserId: null, + authorizedByUserId: former.id, }); const app = makeApp(env); setVerifyResult(makeClaims()); @@ -401,8 +403,8 @@ describe('POST /auth/github-oidc', () => { const res = await exchange(app, env, { oidcToken: 't', project: project.slug }); expect(res.status).toBe(401); - expect(((await res.json()) as { error: string }).error).toContain( - 'reconnect the organization repository', + expect(((await res.json()) as { error: string }).error).toBe( + 'no authorized github actions connection for repository; reconnect the repository', ); expect(await getProjectBuilds(env.db, project.id)).toEqual([]); }); @@ -451,6 +453,7 @@ describe('POST /auth/github-oidc', () => { projectId: project.id, installationId: '1', repoFullName: 'octo/repo', + repositoryId: '42', branch: 'main', buildExecutor: 'github_actions', }); @@ -1650,6 +1653,7 @@ describe('POST /auth/github-oidc', () => { projectId: project.id, installationId: '1', repoFullName: 'octo/repo', + repositoryId: '42', branch: 'main', buildExecutor: 'github_actions', }); @@ -1839,34 +1843,6 @@ describe('POST /auth/github-oidc', () => { expect((await getProjectBuilds(env.db, project.id)).length).toBe(1); }); - // Fail closed on a null `repository_id` row when the caller HAS an id. - // A connection that predates the id column (repository_id IS NULL) must NOT be - // matched by `repo_full_name` when the OIDC claim carries a repository_id: a - // deleted-then-recreated repo that reuses the old name would otherwise match - // the stale null-id connection and mint a deploy token for the WRONG project. - it('returns 401 for a null-repository_id connection when the OIDC claim carries an id (reused name)', async () => { - const user = await createTestUser(env.db); - const project = await createTestProject(env.db, user.id, 'oidc-null-id-reuse'); - await seedActiveInstallation(env.db, '1'); - // Legacy connection for octo/repo with NO repository_id (predates the column). - await createGitHubConnection(env.db, { - projectId: project.id, - installationId: '1', - repoFullName: 'octo/repo', - branch: 'main', - buildExecutor: 'github_actions', - }); - - const app = makeApp(env); - // A token for the SAME full_name but bearing an immutable id (the name was - // reused by a different/recreated repo) — the null-id row must NOT match. - setVerifyResult(makeClaims({ repository: 'octo/repo', repository_id: '777' })); - - const res = await exchange(app, env, { oidcToken: 'good', project: project.slug }); - expect(res.status).toBe(401); - expect((await getProjectBuilds(env.db, project.id)).length).toBe(0); - }); - // --------------------------------------------------------------------------- // A repo may back MULTIPLE github_actions projects (only project_id is // unique). Resolution must select the connection by the workflow's requested @@ -1952,6 +1928,7 @@ describe('POST /auth/github-oidc', () => { projectId: project.id, installationId: '1', repoFullName: 'octo/repo', + repositoryId: '42', branch: 'main', buildExecutor: 'github_actions', }); @@ -1972,6 +1949,7 @@ describe('POST /auth/github-oidc', () => { projectId: project.id, installationId: '1', repoFullName: 'octo/repo', + repositoryId: '42', branch: 'main', buildExecutor: 'github_actions', }); diff --git a/platform/packages/api/test/integration/api-webhooks.test.ts b/platform/packages/api/test/integration/api-webhooks.test.ts index 611a93b79..1972456f8 100644 --- a/platform/packages/api/test/integration/api-webhooks.test.ts +++ b/platform/packages/api/test/integration/api-webhooks.test.ts @@ -211,7 +211,9 @@ async function clearBuildTables(db: Db): Promise { async function createGitHubConnection( db: Db, - args: Parameters[1], + args: Omit[1], 'authorizedByUserId'> & { + authorizedByUserId?: string; + }, ) { const project = await getProject(db, args.projectId); if (!project) { @@ -219,8 +221,7 @@ async function createGitHubConnection( } return createGitHubConnectionRecord(db, { ...args, - authorizedByUserId: - args.authorizedByUserId === undefined ? project.user_id : args.authorizedByUserId, + authorizedByUserId: args.authorizedByUserId ?? project.user_id, }); } @@ -541,6 +542,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '555', repoFullName: 'octo/repo', + repositoryId: '715167', branch: 'main', buildExecutor: 'container', }); @@ -555,7 +557,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/main', after: 'oldsha1', installation: { id: 555 }, - repository: { full_name: 'octo/repo' }, + repository: { full_name: 'octo/repo', id: 715167 }, }); expect(res.status).toBe(200); @@ -617,6 +619,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '555', repoFullName: 'octo/repo', + repositoryId: '715167', branch: 'main', buildExecutor: 'container', }); @@ -640,7 +643,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/main', after: 'abandonedsha', installation: { id: 555 }, - repository: { full_name: 'octo/repo' }, + repository: { full_name: 'octo/repo', id: 715167 }, }); expect(res.status).toBe(200); @@ -662,6 +665,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '555', repoFullName: 'octo/repo', + repositoryId: '715167', branch: 'main', buildExecutor: 'container', }); @@ -685,7 +689,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/main', after: 'unverifiable', installation: { id: 555 }, - repository: { full_name: 'octo/repo' }, + repository: { full_name: 'octo/repo', id: 715167 }, }); expect(res.status).toBe(200); @@ -708,6 +712,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '555', repoFullName: 'octo/repo', + repositoryId: '715167', branch: 'main', buildExecutor: 'container', }); @@ -729,7 +734,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/main', after: 'orphansha', installation: { id: 555 }, - repository: { full_name: 'octo/repo' }, + repository: { full_name: 'octo/repo', id: 715167 }, }); expect(res.status).toBe(200); @@ -751,6 +756,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '555', repoFullName: 'octo/repo', + repositoryId: '715167', branch: 'main', buildExecutor: 'container', }); @@ -761,7 +767,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/feature', after: 'abc1234', installation: { id: 555 }, - repository: { full_name: 'octo/repo' }, + repository: { full_name: 'octo/repo', id: 715167 }, }); expect(res.status).toBe(200); @@ -776,6 +782,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '777', repoFullName: 'octo/actions-repo', + repositoryId: '886845', branch: 'main', buildExecutor: 'github_actions', }); @@ -786,7 +793,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/main', after: 'def5678', installation: { id: 777 }, - repository: { full_name: 'octo/actions-repo' }, + repository: { full_name: 'octo/actions-repo', id: 886845 }, }); expect(res.status).toBe(200); @@ -804,6 +811,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '555', repoFullName: 'octo/repo', + repositoryId: '715167', branch: 'main', buildExecutor: 'container', }); @@ -813,7 +821,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/main', after: '0000000000000000000000000000000000000000', installation: { id: 555 }, - repository: { full_name: 'octo/repo' }, + repository: { full_name: 'octo/repo', id: 715167 }, }); expect(res.status).toBe(200); @@ -1196,6 +1204,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '321', repoFullName: 'octo/wfr', + repositoryId: '855536', branch: 'main', buildExecutor: 'github_actions', }); @@ -1222,7 +1231,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 321 }, - repository: { full_name: 'octo/wfr' }, + repository: { full_name: 'octo/wfr', id: 855536 }, workflow_run: { id: 123456, conclusion: 'success', head_sha: 'sha-success' }, }); @@ -1240,6 +1249,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '322', repoFullName: 'octo/wfr-fail', + repositoryId: '871475', branch: 'main', buildExecutor: 'github_actions', }); @@ -1258,7 +1268,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 322 }, - repository: { full_name: 'octo/wfr-fail' }, + repository: { full_name: 'octo/wfr-fail', id: 871475 }, workflow_run: { id: 654321, conclusion: 'failure', head_sha: 'sha-fail' }, }); @@ -1278,6 +1288,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '331', repoFullName: 'octo/check-ok', + repositoryId: '766742', branch: 'main', buildExecutor: 'github_actions', }); @@ -1304,7 +1315,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 331 }, - repository: { full_name: 'octo/check-ok' }, + repository: { full_name: 'octo/check-ok', id: 766742 }, workflow_run: { id: 424250, conclusion: 'success', head_sha: 'sha-check-ok' }, }); @@ -1328,6 +1339,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '332', repoFullName: 'octo/check-fail', + repositoryId: '739072', branch: 'main', buildExecutor: 'github_actions', }); @@ -1352,7 +1364,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 332 }, - repository: { full_name: 'octo/check-fail' }, + repository: { full_name: 'octo/check-fail', id: 739072 }, workflow_run: { id: 424251, conclusion: 'failure', head_sha: 'sha-check-fail' }, }); @@ -1375,6 +1387,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '333', repoFullName: 'octo/check-none', + repositoryId: '811598', branch: 'main', buildExecutor: 'github_actions', }); @@ -1399,7 +1412,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 333 }, - repository: { full_name: 'octo/check-none' }, + repository: { full_name: 'octo/check-none', id: 811598 }, workflow_run: { id: 424252, conclusion: 'success', head_sha: 'sha-check-none' }, }); @@ -1417,6 +1430,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '334', repoFullName: 'octo/check-throw', + repositoryId: '870692', branch: 'main', buildExecutor: 'github_actions', }); @@ -1443,7 +1457,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 334 }, - repository: { full_name: 'octo/check-throw' }, + repository: { full_name: 'octo/check-throw', id: 870692 }, workflow_run: { id: 424253, conclusion: 'success', head_sha: 'sha-check-throw' }, }); @@ -1471,6 +1485,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '335', repoFullName: 'octo/check-terminal', + repositoryId: '796140', branch: 'main', buildExecutor: 'github_actions', }); @@ -1497,7 +1512,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 335 }, - repository: { full_name: 'octo/check-terminal' }, + repository: { full_name: 'octo/check-terminal', id: 796140 }, workflow_run: { id: 424260, conclusion: 'cancelled', head_sha: 'sha-check-terminal' }, }); @@ -1522,6 +1537,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '323', repoFullName: 'octo/wfr-throw', + repositoryId: '823577', branch: 'main', buildExecutor: 'github_actions', }); @@ -1554,7 +1570,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 323 }, - repository: { full_name: 'octo/wfr-throw' }, + repository: { full_name: 'octo/wfr-throw', id: 823577 }, workflow_run: { id: 777777, conclusion: 'success', head_sha: 'sha-throw' }, }); @@ -1584,6 +1600,7 @@ describe('POST /webhooks/github', () => { projectId: projectX.id, installationId: '900', repoFullName: 'octo/x', + repositoryId: '872525', branch: 'main', buildExecutor: 'github_actions', }); @@ -1591,6 +1608,7 @@ describe('POST /webhooks/github', () => { projectId: projectY.id, installationId: '901', repoFullName: 'octo/y', + repositoryId: '894906', branch: 'main', buildExecutor: 'github_actions', }); @@ -1622,7 +1640,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 900 }, - repository: { full_name: 'octo/x' }, + repository: { full_name: 'octo/x', id: 872525 }, workflow_run: { id: 500, conclusion: 'failure', head_sha: 'sha-x' }, }); @@ -1733,6 +1751,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '950', repoFullName: 'octo/rerun', + repositoryId: '889911', branch: 'main', buildExecutor: 'github_actions', }); @@ -1765,7 +1784,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 950 }, - repository: { full_name: 'octo/rerun' }, + repository: { full_name: 'octo/rerun', id: 889911 }, workflow_run: { id: 800, run_attempt: 2, conclusion: 'success', head_sha: 'sha-new' }, }); @@ -1795,6 +1814,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '951', repoFullName: 'octo/redeliver', + repositoryId: '874787', branch: 'main', buildExecutor: 'github_actions', }); @@ -1828,7 +1848,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 951 }, - repository: { full_name: 'octo/redeliver' }, + repository: { full_name: 'octo/redeliver', id: 874787 }, workflow_run: { id: 801, run_attempt: 1, conclusion: 'success', head_sha: 'sha-a1' }, }); @@ -1864,7 +1884,7 @@ describe('POST /webhooks/github', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 999 }, - repository: { full_name: 'octo/unknown' }, + repository: { full_name: 'octo/unknown', id: 881839 }, workflow_run: { id: 600, conclusion: 'success', head_sha: 'sha-z' }, }); @@ -1999,18 +2019,17 @@ describe('POST /webhooks/github', () => { expect(healed!.repo_full_name).toBe('octo/new'); }); - // A null-`repository_id` connection must NOT match an id-bearing push. - // When the push payload carries `repository.id`, resolution keys on the id only - // and fails closed: a legacy null-id connection sharing the repo name is not - // matched (a recreated/reused name could otherwise deploy to the wrong project). - it('does not match a null-repository_id connection when the push carries a repository id', async () => { + // Resolution keys on the immutable repository id only: a connection sharing the + // repo name but recording a different id is not matched (a recreated/reused + // name could otherwise deploy to the wrong project). + it('does not match a connection by name when the push carries a different repository id', async () => { const user = await createTestUser(env.db); const project = await createTestProject(env.db, user.id, 'wh-null-id'); - // Legacy connection with NO repository_id (predates the column). await createGitHubConnection(env.db, { projectId: project.id, installationId: '650', repoFullName: 'octo/legacy', + repositoryId: '722400', branch: 'main', buildExecutor: 'container', }); @@ -2200,6 +2219,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '7301', repoFullName: 'octo/susp', + repositoryId: '764776', branch: 'main', buildExecutor: 'container', }); @@ -2211,7 +2231,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/main', after: 'abc1234', installation: { id: 7301 }, - repository: { full_name: 'octo/susp' }, + repository: { full_name: 'octo/susp', id: 764776 }, }); expect(res.status).toBe(200); @@ -2228,6 +2248,7 @@ describe('POST /webhooks/github', () => { projectId: project.id, installationId: '7302', repoFullName: 'octo/del', + repositoryId: '873576', branch: 'main', buildExecutor: 'container', }); @@ -2239,7 +2260,7 @@ describe('POST /webhooks/github', () => { ref: 'refs/heads/main', after: 'abc1234', installation: { id: 7302 }, - repository: { full_name: 'octo/del' }, + repository: { full_name: 'octo/del', id: 873576 }, }); expect(res.status).toBe(200); @@ -2889,6 +2910,7 @@ describe('POST /webhooks/github — revoke builds on App removal', () => { projectId: project.id, installationId: '8001', repoFullName: 'octo/del', + repositoryId: '873576', branch: 'main', buildExecutor: 'container', }); @@ -3098,6 +3120,7 @@ describe('POST /webhooks/github — revoke builds on App removal', () => { projectId: project.id, installationId: '8004', repoFullName: 'octo/unsusp', + repositoryId: '763767', branch: 'main', buildExecutor: 'container', }); @@ -3632,44 +3655,6 @@ describe('POST /webhooks/github — repo removal matches immutable repository_id expect(cancelledIds).toContain(build.id); }); - it('cancels a legacy null-repository_id connection by name fallback', async () => { - const user = await createTestUser(env.db); - const project = await createTestProject(env.db, user.id, 'f19-2-legacy'); - await seedInstallation(env.db, '9202'); - // A legacy connection that predates the repository_id column. - await createGitHubConnection(env.db, { - projectId: project.id, - installationId: '9202', - repoFullName: 'octo/legacy', - repositoryId: undefined, - branch: 'main', - buildExecutor: 'container', - }); - const build = await createBuild(env.db, { - projectId: project.id, - userId: user.id, - executor: 'container', - status: 'building', - commitSha: 'sha-legacy', - branch: 'main', - }); - - const { app, appEnv, cancelledIds } = recordingApp(); - const res = await post(app, appEnv, 'installation_repositories', { - action: 'removed', - installation: { id: 9202 }, - repositories_added: [], - repositories_removed: [{ full_name: 'octo/legacy', id: 8402 }], - repository_selection: 'selected', - }); - - expect(res.status).toBe(200); - const updated = await getBuild(env.db, build.id); - expect(updated!.status).toBe('cancelled'); - expect(updated!.error).toBe('repository removed from github app'); - expect(cancelledIds).toContain(build.id); - }); - it('spares a connection whose repository_id is NOT in the removed set', async () => { const user = await createTestUser(env.db); const project = await createTestProject(env.db, user.id, 'f19-2-kept'); @@ -3722,6 +3707,7 @@ describe('POST /webhooks/github — CAS workflow_run completion', () => { projectId: project.id, installationId: '8201', repoFullName: 'octo/cas', + repositoryId: '791148', branch: 'main', buildExecutor: 'github_actions', }); @@ -3748,7 +3734,7 @@ describe('POST /webhooks/github — CAS workflow_run completion', () => { const res = await post(app, appEnv, 'workflow_run', { action: 'completed', installation: { id: 8201 }, - repository: { full_name: 'octo/cas' }, + repository: { full_name: 'octo/cas', id: 791148 }, workflow_run: { id: 87001, conclusion: 'success', head_sha: 'sha-cas' }, }); @@ -4038,51 +4024,6 @@ describe('POST /webhooks/github — revoke builds on branch delete', () => { expect(cancelledIds).not.toContain(inflight.id); }); - // a legacy connection whose repository_id IS NULL must still be - // revoked when its repo_full_name + branch match, even though the delete - // payload carries a repository.id. The revocation matcher is inclusive (id - // can't disqualify a row that never stored one). The old id-only matcher - // (`repoIdStr !== null ? conn.repository_id === repoIdStr : …`) skipped this - // connection because the payload had an id but the row's repository_id is null. - it('cancels a null-repository_id connection matched by name even when the delete payload carries an id', async () => { - const user = await createTestUser(env.db); - const project = await createTestProject(env.db, user.id, 'f18-4-legacy-null-id'); - await seedInstallation(env.db, '8607', [{ full_name: 'octo/legacy-del', id: 8617 }]); - // Legacy connection with NO repository_id (predates the column). - await createGitHubConnection(env.db, { - projectId: project.id, - installationId: '8607', - repoFullName: 'octo/legacy-del', - branch: 'main', - buildExecutor: 'container', - }); - const inflight = await createBuild(env.db, { - projectId: project.id, - userId: user.id, - executor: 'container', - status: 'building', - commitSha: 'sha-legacy-del', - branch: 'main', - }); - - const { app, appEnv, cancelledIds } = recordingApp(); - const res = await post(app, appEnv, 'push', { - ref: 'refs/heads/main', - after: '0000000000000000000000000000000000000000', - installation: { id: 8607 }, - // The delete payload DOES carry a repository.id — the null-id connection - // must still be matched by name and revoked. - repository: { full_name: 'octo/legacy-del', id: 8617 }, - }); - - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true, ignored: 'branch delete' }); - const updated = await getBuild(env.db, inflight.id); - expect(updated!.status).toBe('cancelled'); - expect(updated!.error).toBe('branch deleted'); - expect(cancelledIds).toContain(inflight.id); - }); - // TOCTOU fence — the absence check is point-in-time, so a build // enqueued in the window BETWEEN 'absent' being confirmed and the cancellation // UPDATE (a branch recreated + pushed in that gap) must not be cancelled. The @@ -4173,16 +4114,12 @@ describe('POST /webhooks/github — organization member_removed revocation', () return { app, appEnv, cancelledIds }; } - // Seed an Organization installation (account_id = orgId, 'Organization'), - // optionally owned by `ownerId`. - async function seedOrgInstall( - installationId: string, - orgId: string, - ownerId: string | null, - ): Promise { + // Seed an Organization installation (account_id = orgId, 'Organization'). + // Organization installs have no owner. + async function seedOrgInstall(installationId: string, orgId: string): Promise { await upsertGitHubInstallation(env.db, { installationId, - userId: ownerId, + userId: null, accountLogin: `org-${orgId}`, accountId: orgId, accountType: 'Organization', @@ -4195,10 +4132,9 @@ describe('POST /webhooks/github — organization member_removed revocation', () const ORG2 = '9200'; const G = '7777'; // removed user's linked GitHub id - it('severs the removed member: deletes connection, membership, owner pointer, and terminates the in-flight build', async () => { + it('severs the removed member: deletes the connection they authorized, membership, and terminates the in-flight build', async () => { const user = await createTestUser(env.db, 'org-removed', 'github', G); - // U owns this org install (installer/owner pointer set to U). - await seedOrgInstall('8100', ORG, user.id); + await seedOrgInstall('8100', ORG); const project = await createTestProject(env.db, user.id, 'org-sever'); await createGitHubConnection(env.db, { projectId: project.id, @@ -4207,7 +4143,6 @@ describe('POST /webhooks/github — organization member_removed revocation', () repositoryId: '81001', branch: 'main', buildExecutor: 'container', - authorizedByUserId: null, }); await upsertGitHubInstallationMember(env.db, { installationId: '8100', @@ -4238,8 +4173,6 @@ describe('POST /webhooks/github — organization member_removed revocation', () // Membership cache cleared. const members = await getGitHubInstallationMembers(env.db, '8100'); expect(members.some((m) => m.user_id === user.id)).toBe(false); - // Owner pointer cleared (U owned the install). - expect((await getGitHubInstallation(env.db, '8100'))!.user_id).toBeNull(); // In-flight build token revoked (build-row terminalized) + DO cancelled. const updated = await getBuild(env.db, build.id); expect(updated!.status).toBe('cancelled'); @@ -4250,7 +4183,7 @@ describe('POST /webhooks/github — organization member_removed revocation', () it('severs a shared-project connection authorized by the removed project admin', async () => { const owner = await createTestUser(env.db, 'org-shared-owner'); const admin = await createTestUser(env.db, 'org-shared-admin', 'github', G); - await seedOrgInstall('8101', ORG, owner.id); + await seedOrgInstall('8101', ORG); const project = await createTestProject(env.db, owner.id, 'org-shared-sever'); await env.db.insert(projectMembers).values({ project_id: project.id, @@ -4307,10 +4240,10 @@ describe('POST /webhooks/github — organization member_removed revocation', () const X = '99999'; // removed GitHub id: NO oauth link, NO membership proof-id // Two installs under ORG so we can assert the tombstone lands on EACH. const owner = await createTestUser(env.db, 'org-hole-owner', 'github', G); - await seedOrgInstall('8110', ORG, owner.id); - await seedOrgInstall('8111', ORG, owner.id); + await seedOrgInstall('8110', ORG); + await seedOrgInstall('8111', ORG); // A DIFFERENT org's install must NOT be tombstoned. - await seedOrgInstall('8112', ORG2, owner.id); + await seedOrgInstall('8112', ORG2); // An unrelated connection (owned by owner, not X) must survive — nothing to sever. const project = await createTestProject(env.db, owner.id, 'org-hole-survives'); await createGitHubConnection(env.db, { @@ -4359,7 +4292,7 @@ describe('POST /webhooks/github — organization member_removed revocation', () // no github oauth id), included here to prove it is NOT severed. const X = '6551234'; const v = await createTestUser(env.db, 'org-f1-v', 'google', 'google-f1-v'); - await seedOrgInstall('8190', ORG, null); + await seedOrgInstall('8190', ORG); const project = await createTestProject(env.db, v.id, 'org-f1-proj'); await createGitHubConnection(env.db, { projectId: project.id, @@ -4422,7 +4355,7 @@ describe('POST /webhooks/github — organization member_removed revocation', () const X = '7551234'; const u = await createTestUser(env.db, 'org-union-u', 'github', X); const v = await createTestUser(env.db, 'org-union-v', 'google', 'google-union-v'); - await seedOrgInstall('8200', ORG, null); + await seedOrgInstall('8200', ORG); const uProj = await createTestProject(env.db, u.id, 'org-union-u-proj'); const vProj = await createTestProject(env.db, v.id, 'org-union-v-proj'); await createGitHubConnection(env.db, { @@ -4486,11 +4419,11 @@ describe('POST /webhooks/github — organization member_removed revocation', () const X = '3330001'; const Z = '3330002'; const v = await createTestUser(env.db, 'org-r8-v', 'github', Z); - // I1: historical/uninstalled org install; I2: the reinstalled active one, owned - // by V. Same org account → BOTH resolve into orgInstallIds + // I1: historical/uninstalled org install; I2: the reinstalled active one. + // Same org account → BOTH resolve into orgInstallIds // (getGitHubInstallationsByAccount has NO status filter). - await seedOrgInstall('8210', ORG, null); // I1 - await seedOrgInstall('8211', ORG, v.id); // I2 (owned by V) + await seedOrgInstall('8210', ORG); // I1 + await seedOrgInstall('8211', ORG); // I2 // Mark I1 deleted to mirror uninstall→reinstall history. installation.deleted // does NOT remove membership rows, so V's stale X-membership persists on I1. await markGitHubInstallationStatus(env.db, '8210', 'deleted'); @@ -4560,7 +4493,7 @@ describe('POST /webhooks/github — organization member_removed revocation', () it('ignores member_removed when the org has no installs', async () => { const user = await createTestUser(env.db, 'org-noinstall', 'github', G); // A connection under a DIFFERENT org — must survive since ORG2 has no installs. - await seedOrgInstall('8120', ORG, user.id); + await seedOrgInstall('8120', ORG); const project = await createTestProject(env.db, user.id, 'org-other'); await createGitHubConnection(env.db, { projectId: project.id, @@ -4585,7 +4518,7 @@ describe('POST /webhooks/github — organization member_removed revocation', () it('ignores a non-removal action (member_added) — connection + membership survive', async () => { const user = await createTestUser(env.db, 'org-added', 'github', G); - await seedOrgInstall('8130', ORG, user.id); + await seedOrgInstall('8130', ORG); const project = await createTestProject(env.db, user.id, 'org-added-proj'); await createGitHubConnection(env.db, { projectId: project.id, @@ -4618,8 +4551,8 @@ describe('POST /webhooks/github — organization member_removed revocation', () it('SCOPE: does not sever the removed user’s connection under a DIFFERENT org', async () => { const user = await createTestUser(env.db, 'org-scope-org', 'github', G); - await seedOrgInstall('8140', ORG, user.id); - await seedOrgInstall('8141', ORG2, user.id); + await seedOrgInstall('8140', ORG); + await seedOrgInstall('8141', ORG2); const inOrg = await createTestProject(env.db, user.id, 'org-scope-in'); const inOrg2 = await createTestProject(env.db, user.id, 'org-scope-out'); await createGitHubConnection(env.db, { @@ -4656,7 +4589,7 @@ describe('POST /webhooks/github — organization member_removed revocation', () it('SCOPE: leaves another user’s connection + membership under the same org intact', async () => { const removed = await createTestUser(env.db, 'org-scope-u', 'github', G); const other = await createTestUser(env.db, 'org-scope-v', 'github', '8888'); - await seedOrgInstall('8150', ORG, removed.id); + await seedOrgInstall('8150', ORG); const removedProj = await createTestProject(env.db, removed.id, 'org-u-proj'); const otherProj = await createTestProject(env.db, other.id, 'org-v-proj'); await createGitHubConnection(env.db, { @@ -4706,30 +4639,9 @@ describe('POST /webhooks/github — organization member_removed revocation', () expect(members.some((m) => m.user_id === other.id)).toBe(true); }); - it('OWNER-CLEAR SCOPE: does not clear an install under the org owned by a DIFFERENT user', async () => { - const removed = await createTestUser(env.db, 'org-own-u', 'github', G); - const other = await createTestUser(env.db, 'org-own-v', 'github', '8888'); - // Two installs under ORG: one owned by U (cleared), one owned by V (kept). - await seedOrgInstall('8160', ORG, removed.id); - await seedOrgInstall('8161', ORG, other.id); - - const { app, appEnv } = recordingApp(); - const res = await post(app, appEnv, 'organization', { - action: 'member_removed', - organization: { id: Number(ORG) }, - membership: { user: { id: Number(G) } }, - }); - - expect(res.status).toBe(200); - // U's install owner pointer cleared… - expect((await getGitHubInstallation(env.db, '8160'))!.user_id).toBeNull(); - // …but V's install (same org, different owner) keeps its owner pointer. - expect((await getGitHubInstallation(env.db, '8161'))!.user_id).toBe(other.id); - }); - it('is idempotent on redelivery: two deliveries both 200, single net effect', async () => { const user = await createTestUser(env.db, 'org-idem', 'github', G); - await seedOrgInstall('8170', ORG, user.id); + await seedOrgInstall('8170', ORG); const project = await createTestProject(env.db, user.id, 'org-idem-proj'); await createGitHubConnection(env.db, { projectId: project.id, @@ -4771,12 +4683,11 @@ describe('POST /webhooks/github — organization member_removed revocation', () const members = await getGitHubInstallationMembers(env.db, '8170'); expect(members.some((m) => m.user_id === user.id)).toBe(false); expect((await getBuild(env.db, build.id))!.status).toBe('cancelled'); - expect((await getGitHubInstallation(env.db, '8170'))!.user_id).toBeNull(); }); it('ignores payloads missing organization.id or membership.user.id', async () => { const user = await createTestUser(env.db, 'org-missing', 'github', G); - await seedOrgInstall('8180', ORG, user.id); + await seedOrgInstall('8180', ORG); const { app, appEnv } = recordingApp(); @@ -4802,9 +4713,9 @@ describe('POST /webhooks/github — organization member_removed revocation', () it('records a revocation tombstone for every org install of the removed user', async () => { const user = await createTestUser(env.db, 'org-tomb', 'github', G); // Two installs under ORG (both should get a tombstone); one under ORG2 (must NOT). - await seedOrgInstall('8190', ORG, user.id); - await seedOrgInstall('8191', ORG, user.id); - await seedOrgInstall('8192', ORG2, user.id); + await seedOrgInstall('8190', ORG); + await seedOrgInstall('8191', ORG); + await seedOrgInstall('8192', ORG2); const before = Date.now(); const { app, appEnv } = recordingApp(); @@ -4828,7 +4739,7 @@ describe('POST /webhooks/github — organization member_removed revocation', () it('redelivery keeps a single tombstone and never regresses revoked_at (monotonic)', async () => { const user = await createTestUser(env.db, 'org-tomb-idem', 'github', G); - await seedOrgInstall('8195', ORG, user.id); + await seedOrgInstall('8195', ORG); const { app, appEnv } = recordingApp(); const payload = { diff --git a/platform/packages/api/test/integration/db-builds.test.ts b/platform/packages/api/test/integration/db-builds.test.ts index 013b9a1d9..83b12eba3 100644 --- a/platform/packages/api/test/integration/db-builds.test.ts +++ b/platform/packages/api/test/integration/db-builds.test.ts @@ -22,6 +22,7 @@ import { getQueuedBuilds, getUsersWithQueuedContainerBuilds, hasQueuedContainerBuilds, + installationCoversRepo, linkGitHubInstallationToUser, markBuildBuildingIfStarting, markBuildProgressIfActive, @@ -87,7 +88,9 @@ const DEFAULT_REPO_ID = '42'; async function createGitHubConnection( db: Db, - args: Parameters[1], + args: Omit[1], 'authorizedByUserId'> & { + authorizedByUserId?: string; + }, ) { const project = await getProject(db, args.projectId); if (!project) { @@ -95,8 +98,7 @@ async function createGitHubConnection( } return createGitHubConnectionRecord(db, { ...args, - authorizedByUserId: - args.authorizedByUserId === undefined ? project.user_id : args.authorizedByUserId, + authorizedByUserId: args.authorizedByUserId ?? project.user_id, }); } @@ -1431,56 +1433,21 @@ describe('builds', () => { expect(result.build!.commit_sha).toBe('aaa'); }); - // A legacy connection from the 0020→0023 migration window can carry a NULL - // repository_id. The in-tx re-check must NOT treat that as revoked when - // the install is `all`-repos: membership is not enforced for `all`, so the id - // is irrelevant. (Before the fix, a null id short-circuited to false BEFORE the - // `all` branch, wrongly skipping the build as `install-revoked`.) - it('supersedeAndCreateContainerBuild builds for a NULL repo id on an ALL install (legacy connection)', async () => { + // A missing repository id can't prove coverage, even on an `all`-repos install. + it('supersedeAndCreateContainerBuild skips a missing repo id even on an ALL install (fails closed)', async () => { const user = await createTestUser(env.db); const project = await createTestProject(env.db, user.id); await createGitHubConnection(env.db, { projectId: project.id, installationId: '12345', repoFullName: 'acme/app', - repositoryId: null, + repositoryId: DEFAULT_REPO_ID, branch: 'main', buildExecutor: 'container', }); // Default `all`-repos install (membership not enforced). await seedActiveInstall(env.db, '12345'); - const result = await supersedeAndCreateContainerBuild(env.db, { - projectId: project.id, - connectionId: (await getGitHubConnection(env.db, project.id))!.id, - branch: 'main', - commitSha: 'aaa', - installationId: '12345', - repositoryId: null, - }); - expect(result.skipped).toBeUndefined(); - expect(result.build!.status).toBe('queued'); - expect(result.build!.commit_sha).toBe('aaa'); - }); - - // GUARD: the null-id relaxation above is scoped to `all` installs only. A - // `selected` install can NOT prove membership of a null-id repo, so it must - // still fail closed — otherwise a legacy null-id row would deploy through an - // install that no longer selects the repo. - it('supersedeAndCreateContainerBuild skips a NULL repo id on a SELECTED install (fails closed)', async () => { - const user = await createTestUser(env.db); - const project = await createTestProject(env.db, user.id); - await createGitHubConnection(env.db, { - projectId: project.id, - installationId: '12345', - repoFullName: 'acme/app', - repositoryId: null, - branch: 'main', - buildExecutor: 'container', - }); - // A `selected` install: membership is enforced, and a null id can't match. - await seedActiveInstall(env.db, '12345', [{ full_name: 'acme/app', id: 42 }], 'selected'); - const result = await supersedeAndCreateContainerBuild(env.db, { projectId: project.id, connectionId: (await getGitHubConnection(env.db, project.id))!.id, @@ -2362,6 +2329,7 @@ describe('createGithubActionsBuildWithinLimit', () => { projectId: otherProject.id, installationId: 'inst-cap-other', repoFullName: 'acme/cap-other', + repositoryId: DEFAULT_REPO_ID, buildExecutor: 'github_actions', }); await seedActiveInstall(env.db, 'inst-cap-other'); @@ -2882,6 +2850,7 @@ describe('github_connections', () => { projectId: project.id, installationId: '12345', repoFullName: 'acme/app', + repositoryId: '42', }); expect(conn.id.startsWith('ghc_')).toBe(true); @@ -2899,7 +2868,7 @@ describe('github_connections', () => { // + repo membership, so an active 'all'-repos install must exist. await upsertGitHubInstallation(env.db, { installationId: '12345', - userId: user.id, + userId: null, accountLogin: 'acme', accountId: '111', accountType: 'Organization', @@ -2910,11 +2879,12 @@ describe('github_connections', () => { projectId: project.id, installationId: '12345', repoFullName: 'acme/app', + repositoryId: '42', branch: 'release', buildExecutor: 'github_actions', }); - const rows = await getGitHubConnectionsByRepo(env.db, '12345', 'acme/app'); + const rows = await getGitHubConnectionsByRepo(env.db, '12345', '42'); expect(rows).toHaveLength(1); expect(rows[0].user_id).toBe(user.id); expect(rows[0].project_id).toBe(project.id); @@ -2922,8 +2892,8 @@ describe('github_connections', () => { expect(rows[0].build_executor).toBe('github_actions'); // Wrong repo / wrong installation -> empty. - expect(await getGitHubConnectionsByRepo(env.db, '12345', 'acme/other')).toEqual([]); - expect(await getGitHubConnectionsByRepo(env.db, '99999', 'acme/app')).toEqual([]); + expect(await getGitHubConnectionsByRepo(env.db, '12345', '43')).toEqual([]); + expect(await getGitHubConnectionsByRepo(env.db, '99999', '42')).toEqual([]); }); // The push resolver is revocation-aware: a suspended/deleted install @@ -2934,7 +2904,7 @@ describe('github_connections', () => { const project = await createTestProject(env.db, user.id); await upsertGitHubInstallation(env.db, { installationId: '12345', - userId: user.id, + userId: null, accountLogin: 'acme', accountId: '111', accountType: 'Organization', @@ -2945,18 +2915,19 @@ describe('github_connections', () => { projectId: project.id, installationId: '12345', repoFullName: 'acme/app', + repositoryId: '42', }); // Active -> resolves. - expect(await getGitHubConnectionsByRepo(env.db, '12345', 'acme/app')).toHaveLength(1); + expect(await getGitHubConnectionsByRepo(env.db, '12345', '42')).toHaveLength(1); // Suspended -> empty. await markGitHubInstallationStatus(env.db, '12345', 'suspended'); - expect(await getGitHubConnectionsByRepo(env.db, '12345', 'acme/app')).toEqual([]); + expect(await getGitHubConnectionsByRepo(env.db, '12345', '42')).toEqual([]); // Deleted -> empty. await markGitHubInstallationStatus(env.db, '12345', 'deleted'); - expect(await getGitHubConnectionsByRepo(env.db, '12345', 'acme/app')).toEqual([]); + expect(await getGitHubConnectionsByRepo(env.db, '12345', '42')).toEqual([]); }); // A `selected` install enforces repo membership: a repo dropped from @@ -2967,7 +2938,7 @@ describe('github_connections', () => { // 'selected' install whose cached set does NOT include this repo. await upsertGitHubInstallation(env.db, { installationId: '12345', - userId: user.id, + userId: null, accountLogin: 'acme', accountId: '111', accountType: 'Organization', @@ -2981,8 +2952,8 @@ describe('github_connections', () => { repositoryId: '42', }); - // Repo is not a member -> empty (matched by id when a repositoryId is given). - expect(await getGitHubConnectionsByRepo(env.db, '12345', 'acme/app', '42')).toEqual([]); + // Repo is not a member -> empty. + expect(await getGitHubConnectionsByRepo(env.db, '12345', '42')).toEqual([]); // Add the repo to the cached set by id -> now a member -> resolves. await setGitHubInstallationRepositories( @@ -2994,43 +2965,11 @@ describe('github_connections', () => { ], 'selected', ); - const byId = await getGitHubConnectionsByRepo(env.db, '12345', 'acme/app', '42'); + const byId = await getGitHubConnectionsByRepo(env.db, '12345', '42'); expect(byId).toHaveLength(1); expect(byId[0].project_id).toBe(project.id); }); - // Name-fallback membership when the caller has no repositoryId (a - // malformed/partial webhook): membership is checked by `full_name` in the - // cached `repositories` set. - it('getGitHubConnectionsByRepo falls back to name membership without a repositoryId', async () => { - const user = await createTestUser(env.db); - const project = await createTestProject(env.db, user.id); - await upsertGitHubInstallation(env.db, { - installationId: '12345', - userId: user.id, - accountLogin: 'acme', - accountId: '111', - accountType: 'Organization', - repositories: [{ id: 42, full_name: 'acme/app' }], - repositorySelection: 'selected', - }); - await createGitHubConnection(env.db, { - projectId: project.id, - installationId: '12345', - repoFullName: 'acme/app', - repositoryId: '42', - }); - - // No repositoryId arg -> match the connection by repo_full_name AND check - // installation membership by full_name. - const byName = await getGitHubConnectionsByRepo(env.db, '12345', 'acme/app'); - expect(byName).toHaveLength(1); - expect(byName[0].project_id).toBe(project.id); - - // A non-member full_name resolves nothing. - expect(await getGitHubConnectionsByRepo(env.db, '12345', 'acme/missing')).toEqual([]); - }); - it('updateGitHubConnection patches only provided fields', async () => { const user = await createTestUser(env.db); const project = await createTestProject(env.db, user.id); @@ -3038,6 +2977,7 @@ describe('github_connections', () => { projectId: project.id, installationId: '12345', repoFullName: 'acme/app', + repositoryId: '42', }); await updateGitHubConnection(env.db, project.id, { branch: 'develop' }); @@ -3059,11 +2999,38 @@ describe('github_connections', () => { projectId: project.id, installationId: '12345', repoFullName: 'acme/app', + repositoryId: '42', }); await deleteGitHubConnection(env.db, project.id); expect(await getGitHubConnection(env.db, project.id)).toBeNull(); }); + + // The build manager re-checks coverage from stored build state, which may lack + // either id; both fail closed even on an `all`-repos install. + it('installationCoversRepo fails closed without a connection or repository id', async () => { + const user = await createTestUser(env.db); + const project = await createTestProject(env.db, user.id); + await seedActiveInstall(env.db, '12345'); + const conn = await createGitHubConnection(env.db, { + projectId: project.id, + installationId: '12345', + repoFullName: 'acme/app', + repositoryId: '42', + }); + + expect(await installationCoversRepo(env.db, conn.id, project.id, '12345', '42')).toBe(true); + expect( + await installationCoversRepo( + env.db, + undefined as unknown as string, + project.id, + '12345', + '42', + ), + ).toBe(false); + expect(await installationCoversRepo(env.db, conn.id, project.id, '12345', null)).toBe(false); + }); }); describe('github_installations', () => { @@ -3075,7 +3042,7 @@ describe('github_installations', () => { userId: user.id, accountLogin: 'acme', accountId: 'acc_1', - accountType: 'Organization', + accountType: 'User', repositories: [{ full_name: 'acme/app', id: 1 }], }); expect(inserted.id.startsWith('ghi_')).toBe(true); @@ -3093,7 +3060,7 @@ describe('github_installations', () => { installationId: '555', accountLogin: 'acme-renamed', accountId: 'acc_1', - accountType: 'Organization', + accountType: 'User', repositories: [ { full_name: 'acme/app', id: 1 }, { full_name: 'acme/web', id: 2 }, @@ -3117,7 +3084,7 @@ describe('github_installations', () => { userId: user.id, accountLogin: 'acme', accountId: 'acc_1', - accountType: 'Organization', + accountType: 'User', repositories: [{ full_name: 'acme/app', id: 1 }], repositorySelection: 'selected', }); @@ -3130,7 +3097,7 @@ describe('github_installations', () => { userId: user.id, accountLogin: 'acme', accountId: 'acc_1', - accountType: 'Organization', + accountType: 'User', repositories: [ { full_name: 'acme/app', id: 1 }, { full_name: 'acme/api', id: 2 }, @@ -3152,7 +3119,7 @@ describe('github_installations', () => { userId: user.id, accountLogin: 'acme', accountId: 'acc_1', - accountType: 'Organization', + accountType: 'User', repositories: [{ full_name: 'acme/app', id: 1 }], refreshMembership: true, }); @@ -3160,9 +3127,8 @@ describe('github_installations', () => { expect(refreshedNoSelection.repositories).toEqual([{ full_name: 'acme/app', id: 1 }]); }); - // the conflict handler must never re-own an installation already linked to - // a DIFFERENT user (the concurrent-callback race that the non-transactional - // read-then-write backstop in routes/github.ts cannot catch), but must still + // the conflict handler must never re-own a personal installation already + // linked to a DIFFERENT user (two install callbacks racing), but must still // adopt the user on an unowned (NULL) row. it('upsert never re-owns an installation linked to another user', async () => { const userA = await createTestUser(env.db); @@ -3173,7 +3139,7 @@ describe('github_installations', () => { userId: userA.id, accountLogin: 'acme', accountId: 'acc_x', - accountType: 'Organization', + accountType: 'User', repositories: [{ full_name: 'acme/app', id: 1 }], }); @@ -3183,7 +3149,7 @@ describe('github_installations', () => { userId: userB.id, accountLogin: 'acme', accountId: 'acc_x', - accountType: 'Organization', + accountType: 'User', repositories: [{ full_name: 'acme/app', id: 1 }], }); // Ownership stays with the original user; the second caller does not re-own. @@ -3198,7 +3164,7 @@ describe('github_installations', () => { installationId: '558', accountLogin: 'acme', accountId: 'acc_y', - accountType: 'Organization', + accountType: 'User', repositories: [], }); @@ -3207,7 +3173,7 @@ describe('github_installations', () => { userId: userB.id, accountLogin: 'acme', accountId: 'acc_y', - accountType: 'Organization', + accountType: 'User', repositories: [], }); expect(adopted.user_id).toBe(userB.id); @@ -3300,6 +3266,7 @@ describe('github_installations', () => { projectId: project.id, installationId: '12345', repoFullName: 'acme/app', + repositoryId: '42', }); // Delete the project row directly; the FK ON DELETE cascade should remove diff --git a/platform/packages/api/test/integration/db-github-members.test.ts b/platform/packages/api/test/integration/db-github-members.test.ts index ff5601397..77f5b63e7 100644 --- a/platform/packages/api/test/integration/db-github-members.test.ts +++ b/platform/packages/api/test/integration/db-github-members.test.ts @@ -2,12 +2,10 @@ import { eq, sql } from 'drizzle-orm'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vite-plus/test'; import { MEMBERSHIP_TTL_SECONDS } from '../../src/constants.ts'; import { - clearGitHubInstallationOwnerForUser, deleteGitHubInstallationMember, deleteGitHubInstallationMembers, deleteGitHubInstallationMembersByGithubAccount, getGitHubAccountIdForUser, - getGitHubInstallation, getGitHubInstallationMembers, getGitHubInstallationMembersByUser, getDbNowMs, @@ -392,17 +390,16 @@ describe('github_installation_members', () => { }); }); -// Seed an installation with an explicit account (id + type) and optional owner. +// Seed an unowned installation with an explicit account (id + type). async function seedInstallForAccount( db: Db, installationId: string, accountId: string, accountType: 'User' | 'Organization', - userId: string | null = null, ): Promise { await upsertGitHubInstallation(db, { installationId, - userId, + userId: null, accountLogin: `acct-${installationId}`, accountId, accountType, @@ -411,7 +408,7 @@ async function seedInstallForAccount( }); } -describe('github_installations account queries + guarded owner clear', () => { +describe('github_installations account queries', () => { it('getGitHubInstallationsByAccount scopes by BOTH account_id and account_type', async () => { // Two ORG1 org installs, one ORG2 org install, one ORG1 *User* install. await seedInstallForAccount(env.db, '100', 'ORG1', 'Organization'); @@ -436,47 +433,6 @@ describe('github_installations account queries + guarded owner clear', () => { // Right account, wrong type → still empty (type filter bites). expect(await getGitHubInstallationsByAccount(env.db, 'ORG1', 'User')).toEqual([]); }); - - it('clearGitHubInstallationOwnerForUser clears only caller-owned installs in the id list', async () => { - const alice = await createTestUser(env.db, 'alice'); - const bob = await createTestUser(env.db, 'bob', 'google', 'google-bob'); - - // alice owns 100, 200, 400; bob owns 300. All under ORG1 for realism. - await seedInstallForAccount(env.db, '100', 'ORG1', 'Organization', alice.id); - await seedInstallForAccount(env.db, '200', 'ORG1', 'Organization', alice.id); - await seedInstallForAccount(env.db, '300', 'ORG1', 'Organization', bob.id); - await seedInstallForAccount(env.db, '400', 'ORG1', 'Organization', alice.id); - - // Clear over [100, 200, 300] as alice: 300 is bob's (guard), 400 not listed. - const cleared = await clearGitHubInstallationOwnerForUser( - env.db, - ['100', '200', '300'], - alice.id, - ); - - // Driver-count correctness: return value equals the rows actually cleared - // (exactly 100 & 200). Reading the wrong rowCount/affectedRows field would - // surface as 0/undefined here under the PGlite test driver. - expect(cleared).toBe(2); - - expect((await getGitHubInstallation(env.db, '100'))!.user_id).toBeNull(); - expect((await getGitHubInstallation(env.db, '200'))!.user_id).toBeNull(); - // 300 owned by bob — guard (`user_id = alice`) held, not clobbered. - expect((await getGitHubInstallation(env.db, '300'))!.user_id).toBe(bob.id); - // 400 owned by alice but not in the id list — untouched. - expect((await getGitHubInstallation(env.db, '400'))!.user_id).toBe(alice.id); - }); - - it('clearGitHubInstallationOwnerForUser no-ops (returns 0) on an empty id list', async () => { - const alice = await createTestUser(env.db, 'alice'); - await seedInstallForAccount(env.db, '100', 'ORG1', 'Organization', alice.id); - - const cleared = await clearGitHubInstallationOwnerForUser(env.db, [], alice.id); - - expect(cleared).toBe(0); - // No install altered. - expect((await getGitHubInstallation(env.db, '100'))!.user_id).toBe(alice.id); - }); }); describe('github_installation_revocations — monotonic revocation tombstone', () => { diff --git a/platform/packages/api/test/integration/github-join-routes.test.ts b/platform/packages/api/test/integration/github-join-routes.test.ts index b7b86dec3..7f5b5df1e 100644 --- a/platform/packages/api/test/integration/github-join-routes.test.ts +++ b/platform/packages/api/test/integration/github-join-routes.test.ts @@ -18,6 +18,7 @@ import { getGitHubInstallationsByUser, recordInstallationRevocations, upsertGitHubInstallation, + upsertGitHubInstallationMember, } from '../../src/db.ts'; import type { ApiEnv } from '../../src/env.ts'; import { githubRoutes } from '../../src/routes/github.ts'; @@ -224,19 +225,17 @@ async function runJoinCallback(opts: { return { res, body, joinCode, target }; } -// Seed an installation Void tracks. `userId` is the owning Void user (or null for -// an unowned install). `accountType` defaults to 'Organization' (the only account -// type org-share admits) — pass 'User' to seed a personal install for the -// Organization-only guard regressions. +// Seed an installation Void tracks, with no owner. `accountType` defaults to +// 'Organization' (the only account type org-share admits) — pass 'User' to seed +// an unlinked personal install for the Organization-only guard regressions. async function seedInstall(opts: { installationId: string; - userId?: string | null; accountId?: string; accountType?: 'User' | 'Organization'; }): Promise { await upsertGitHubInstallation(env.db, { installationId: opts.installationId, - userId: opts.userId ?? null, + userId: null, accountLogin: `acct-${opts.installationId}`, accountId: opts.accountId ?? `500${opts.installationId}`, accountType: opts.accountType ?? 'Organization', @@ -625,11 +624,10 @@ describe('GET /github/join-callback', () => { describe('POST /github/join/complete', () => { it('upserts a membership keyed on the completing token-holder and returns joined', async () => { - // The install is owned by a DIFFERENT Void user; the joiner is a google-only - // account with no github identity. - const owner = await createTestUser(env.db, 'owner', 'github', '900000700'); + // The joiner is a google-only account with no github identity. + const other = await createTestUser(env.db, 'other', 'github', '900000700'); const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - await seedInstall({ installationId: '700', userId: owner.id }); + await seedInstall({ installationId: '700' }); const challenge = await createCodeChallenge(CODE_VERIFIER); const { joinCode } = await runJoinCallback({ @@ -651,18 +649,17 @@ describe('POST /github/join/complete', () => { expect(res.status).toBe(200); expect(await res.json()).toEqual({ status: 'joined', count: 1 }); expect(await countMemberRows(env.db, '700', joiner.id)).toBe(1); - // Never bound to the owner (who already has the install via ownership). - expect(await countMemberRows(env.db, '700', owner.id)).toBe(0); + // Never bound to any other user. + expect(await countMemberRows(env.db, '700', other.id)).toBe(0); }); // THREAT L1 (the crux). A join_code minted in a callback is completed by an // arbitrary authed user; the membership binds to the COMPLETING bearer token, // NEVER to anyone named in the state/join_code. it('binds the membership to the completing token-holder, not the flow initiator', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000701'); const attacker = await createTestUser(env.db, 'attacker', 'google', 'google-attacker'); const completer = await createTestUser(env.db, 'completer', 'google', 'google-completer'); - await seedInstall({ installationId: '700', userId: owner.id }); + await seedInstall({ installationId: '700' }); const challenge = await createCodeChallenge(CODE_VERIFIER); const { joinCode } = await runJoinCallback({ @@ -690,9 +687,8 @@ describe('POST /github/join/complete', () => { }); it('is idempotent — a re-run refreshes the single (install,user) row', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000702'); const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - await seedInstall({ installationId: '700', userId: owner.id }); + await seedInstall({ installationId: '700' }); const challenge = await createCodeChallenge(CODE_VERIFIER); @@ -735,9 +731,8 @@ describe('POST /github/join/complete', () => { }); it('rejects a PKCE mismatch with invalid_verifier and binds nothing', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000703'); const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - await seedInstall({ installationId: '700', userId: owner.id }); + await seedInstall({ installationId: '700' }); const challenge = await createCodeChallenge(CODE_VERIFIER); const { joinCode } = await runJoinCallback({ @@ -822,11 +817,19 @@ describe('POST /github/join/complete', () => { expect(await countAllMemberRows(env.db)).toBe(1); }); - it('skips installs the caller already owns (not counted, no error)', async () => { - // The joiner OWNS install 700 (github identity matches). Joining it is a - // redundant no-op — skipped, not counted, no membership row. - const joiner = await createTestUser(env.db, 'joiner', 'github', '900000704'); - await seedInstall({ installationId: '700', userId: joiner.id }); + // The person who installed the App on an organization has no special standing: + // once the membership recorded by the install callback lapses, they rejoin like + // any other member and the installation becomes visible again. + it('lets the organization installer rejoin after their membership expires', async () => { + const installer = await createTestUser(env.db, 'installer', 'github', '900000704'); + await seedInstall({ installationId: '700' }); + await upsertGitHubInstallationMember(env.db, { + installationId: '700', + userId: installer.id, + githubAccountId: '900000704', + ttlSeconds: -60, + }); + expect(await getGitHubInstallationsByUser(env.db, installer.id)).toHaveLength(0); const challenge = await createCodeChallenge(CODE_VERIFIER); const { joinCode } = await runJoinCallback({ @@ -839,52 +842,16 @@ describe('POST /github/join/complete', () => { const res = await app.fetch( new Request( 'http://localhost/github/join/complete', - authedPost(joiner.jwt, { join_code: joinCode, code_verifier: CODE_VERIFIER }), - ), - { ...env, ...GITHUB_APP_USER_OAUTH_ENV }, - ); - - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ status: 'joined', count: 0 }); - expect(await countMemberRows(env.db, '700', joiner.id)).toBe(0); - }); - - // Org-share is Organization-only (guard b, defense behind guard a). A join_code - // that carries a personal (account_type='User') install id — a stale code minted - // before the eligibility gate existed, or a forged one — is skipped fail-soft: - // never counted, never minted. A same-code Organization install IS still joined, - // proving the skip is selective (not an all-or-nothing reject). - it('fail-soft skips a personal (account_type=User) install but joins the org one', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000720'); - const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - // 700: Organization, owned by someone else → should be joined. - // 701: personal (User), owned by someone else → must be skipped. - await seedInstall({ installationId: '700', userId: owner.id, accountType: 'Organization' }); - await seedInstall({ installationId: '701', userId: owner.id, accountType: 'User' }); - - const challenge = await createCodeChallenge(CODE_VERIFIER); - // Forge a VALID join_code listing BOTH installs (bypassing the callback's - // eligibility gate) to exercise the /join/complete skip directly. - const joinCode = await mintJoinCode({ - installationIds: ['700', '701'], - codeChallenge: challenge, - iat: Date.now(), - }); - - const res = await app.fetch( - new Request( - 'http://localhost/github/join/complete', - authedPost(joiner.jwt, { join_code: joinCode, code_verifier: CODE_VERIFIER }), + authedPost(installer.jwt, { join_code: joinCode, code_verifier: CODE_VERIFIER }), ), { ...env, ...GITHUB_APP_USER_OAUTH_ENV }, ); expect(res.status).toBe(200); - // Only the Organization install is counted. expect(await res.json()).toEqual({ status: 'joined', count: 1 }); - expect(await countMemberRows(env.db, '700', joiner.id)).toBe(1); - expect(await countMemberRows(env.db, '701', joiner.id)).toBe(0); - expect(await countAllMemberRows(env.db)).toBe(1); + expect(await countMemberRows(env.db, '700', installer.id)).toBe(1); + const installs = await getGitHubInstallationsByUser(env.db, installer.id); + expect(installs.map((i) => i.installation_id)).toEqual(['700']); }); it('rejects a malformed body', async () => { @@ -914,9 +881,8 @@ describe('POST /github/join/complete', () => { // Task 3 integration: a successful join makes the install visible via the // owner-OR-member by-user lookup. it('makes the joined install visible via getGitHubInstallationsByUser', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000705'); const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - await seedInstall({ installationId: '700', userId: owner.id }); + await seedInstall({ installationId: '700' }); // Before joining, the joiner sees nothing. expect(await getGitHubInstallationsByUser(env.db, joiner.id)).toHaveLength(0); @@ -944,11 +910,10 @@ describe('POST /github/join/complete', () => { // Monotonic revocation (Task 14): a join_code minted BEFORE a recorded // revocation (iat <= revoked_at) is a stale artifact from a removed member — it // must NOT resurrect the membership. The install is silently skipped (not - // counted), exactly like an owner-skip. + // counted). it('skips an install whose join_code predates a recorded revocation (stale replay)', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000710'); const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - await seedInstall({ installationId: '700', userId: owner.id }); + await seedInstall({ installationId: '700' }); // The member was removed AFTER minting the join_code: record the tombstone // now (revoked_at = now()), and forge a join_code stamped a minute in the past. @@ -977,9 +942,8 @@ describe('POST /github/join/complete', () => { // The tombstone is a HIGH-WATER MARK, not a permanent ban: a legit re-join AFTER // re-add mints a FRESH join_code (iat > revoked_at) which must be honored. it('restores membership when the join_code post-dates the revocation (legit re-join)', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000711'); const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - await seedInstall({ installationId: '700', userId: owner.id }); + await seedInstall({ installationId: '700' }); // Revoke first, then the member is re-added and re-joins: the fresh join_code // is stamped in the future relative to the tombstone. @@ -1004,19 +968,13 @@ describe('POST /github/join/complete', () => { expect(await countMemberRows(env.db, '700', joiner.id)).toBe(1); }); - // Fail-closed hardening (Task 14): a LEGACY join_code minted before the `iat` - // field existed carries NO iat. The complete gate treats a missing iat as 0 - // (predating every tombstone), so ANY recorded revocation rejects it — the - // install is skipped, membership never resurrected. Mint inline so the property - // is truly ABSENT from the signed payload (mintJoinCode would inject one). If a - // missing iat leaked through (a NaN compare), the membership would be wrongly - // restored — this test would then fail. - it('skips an install whose legacy join_code carries no iat against a revocation (fail closed)', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000712'); + // A join_code without `iat` cannot be compared with revocation tombstones, so + // it is rejected outright. Mint inline so the property is truly ABSENT from the + // signed payload (mintJoinCode would inject one). + it('rejects a join_code without iat', async () => { const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - await seedInstall({ installationId: '700', userId: owner.id }); + await seedInstall({ installationId: '700' }); - await recordInstallationRevocations(env.db, ['700'], JOIN_ACCOUNT_ID); const challenge = await createCodeChallenge(CODE_VERIFIER); const encoded = btoa( JSON.stringify({ @@ -1025,24 +983,22 @@ describe('POST /github/join/complete', () => { githubAccountId: '5551234', codeChallenge: challenge, codeChallengeMethod: 'S256', - // NO `iat` field — a legacy artifact predating the monotonic gate. exp: Date.now() + 5 * 60 * 1000, }), ); const signature = await hmacSignState(encoded, JWT_SECRET); - const legacyJoinCode = `${encoded}.${signature}`; + const joinCode = `${encoded}.${signature}`; const res = await app.fetch( new Request( 'http://localhost/github/join/complete', - authedPost(joiner.jwt, { join_code: legacyJoinCode, code_verifier: CODE_VERIFIER }), + authedPost(joiner.jwt, { join_code: joinCode, code_verifier: CODE_VERIFIER }), ), { ...env, ...GITHUB_APP_USER_OAUTH_ENV }, ); - expect(res.status).toBe(200); - // Skipped, not counted — the legacy (no-iat) code cannot resurrect membership. - expect(await res.json()).toEqual({ status: 'joined', count: 0 }); + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ error: 'invalid join_code' }); expect(await countMemberRows(env.db, '700', joiner.id)).toBe(0); }); @@ -1053,10 +1009,9 @@ describe('POST /github/join/complete', () => { // unchanged. Over a multi-install join_code, the revoked install is skipped and // the fresh one created in a SINGLE atomic commit, and `count` excludes the skip. it('F5: under the tx-wrap, a multi-install join skips the revoked install and creates the fresh one', async () => { - const owner = await createTestUser(env.db, 'owner', 'github', '900000720'); const joiner = await createTestUser(env.db, 'joiner', 'google', 'google-joiner'); - await seedInstall({ installationId: '700', userId: owner.id }); - await seedInstall({ installationId: '701', userId: owner.id }); + await seedInstall({ installationId: '700' }); + await seedInstall({ installationId: '701' }); // 700 was revoked AFTER the join_code was minted (stale → skip); 701 has no // tombstone (fresh → create). One join_code covers both installs. diff --git a/platform/packages/api/test/unit/build-manager.test.ts b/platform/packages/api/test/unit/build-manager.test.ts index 0d26324c2..034aefec0 100644 --- a/platform/packages/api/test/unit/build-manager.test.ts +++ b/platform/packages/api/test/unit/build-manager.test.ts @@ -233,16 +233,17 @@ vi.mock('../../src/db.ts', () => ({ return true; }), // JIT App-installation coverage recheck (fresh, non-locking Postgres read). - // Fails closed on a null repository id, exactly like the real helper. + // Fails closed on a missing connection or repository id, exactly like the real + // helper. installationCoversRepo: vi.fn( async ( _db: unknown, - _connectionId: string | undefined, + connectionId: string | undefined, _projectId: string, _installationId: string, repositoryId: string | null, ) => { - if (repositoryId === null) { + if (!connectionId || !repositoryId) { return false; } return dbState.installationCovered; @@ -1580,9 +1581,8 @@ describe('BuildManager.startBuild', () => { // The container build agent uses SOURCE_TOKEN only as the Bearer to download // the ONE repo's tarball, but it is injected into the container env where a // malicious dependency `postinstall` could read it. To cap that blast radius, -// startBuild mints the source token REPO-SCOPED + read-only when the connection -// carries a numeric repository id; a null (legacy/partial) id can't be scoped, -// so it falls back to the unscoped installation-wide mint for compatibility. +// startBuild always mints the source token REPO-SCOPED + read-only; a build +// without a repository id is cancelled before any token is minted. describe('BuildManager.startBuild source-token scoping', () => { it('mints a repo-scoped, read-only source token when repositoryId is non-null', async () => { const ctx = makeStubCtx(); @@ -1616,20 +1616,15 @@ describe('BuildManager.startBuild source-token scoping', () => { }); }); - it('never mints a SCOPED source token when repositoryId is null (unscoped fallback path)', async () => { + it('mints no source token when repositoryId is null', async () => { const ctx = makeStubCtx(); const env = makeEnv(); const m = makeManager(ctx, env); - // A null repository id fails the coverage recheck closed BEFORE the mint, so - // the scoped source-token call must never happen. The fallback (unscoped) - // call carries no third `opts` arg — assert no call passed scoping opts. + // A null repository id fails the coverage recheck closed BEFORE any mint. await m.startBuild(makeConfig({ repositoryId: null })); - const scopedCall = vi - .mocked(getInstallationToken) - .mock.calls.find((call) => call[2] !== undefined); - expect(scopedCall).toBeUndefined(); + expect(vi.mocked(getInstallationToken)).not.toHaveBeenCalled(); expect(containerCalls.started).toBe(0); }); }); @@ -1786,8 +1781,8 @@ describe('BuildManager.startBuild installation coverage recheck (TOCTOU)', () => }); it('fails closed (cancels) when the connection carries a null repository id', async () => { - // A legacy/partial connection with no repository id can't prove membership. - // The helper fails closed on a null id regardless of dbState.installationCovered. + // A build without a repository id can't prove membership, regardless of + // dbState.installationCovered. dbState.installationCovered = true; const ctx = makeStubCtx(); const env = makeEnv(); @@ -1800,6 +1795,22 @@ describe('BuildManager.startBuild installation coverage recheck (TOCTOU)', () => expect(containerCalls.started).toBe(0); }); + it('fails closed (cancels) when a stored build config has no connection id', async () => { + // Durable Object state written before the connection id was recorded can + // still be replayed once; it must cancel rather than crash or start. + dbState.installationCovered = true; + const ctx = makeStubCtx(); + const env = makeEnv(); + const m = makeManager(ctx, env); + + await m.startBuild(makeConfig({ connectionId: undefined })); + + expect(dbState.status.get('b1')).toBe('cancelled'); + expect(lastWrite('cancelled')?.opts?.error).toMatch(/reconnect the repository/i); + expect(vi.mocked(signDeployToken)).not.toHaveBeenCalled(); + expect(containerCalls.started).toBe(0); + }); + it('proceeds to mint + start when the installation still covers the repo (happy path)', async () => { dbState.installationCovered = true; const ctx = makeStubCtx(); diff --git a/platform/packages/api/test/unit/build-scheduler.test.ts b/platform/packages/api/test/unit/build-scheduler.test.ts index d95bae29f..5be87e3af 100644 --- a/platform/packages/api/test/unit/build-scheduler.test.ts +++ b/platform/packages/api/test/unit/build-scheduler.test.ts @@ -388,7 +388,7 @@ describe('BuildScheduler.alarm', () => { expect(ctx.storage.setAlarm).not.toHaveBeenCalled(); }); - it('cancels an unproven legacy organization connection before claiming the build', async () => { + it('cancels a connection without current authority before claiming the build', async () => { db.users.set('u1', { plan: 'free', login: 'octocat' }); enqueue({ id: 'b1', user_id: 'u1', project_id: 'p1' }); db.unauthorizedConnectionIds.add('connection-p1'); @@ -402,7 +402,7 @@ describe('BuildScheduler.alarm', () => { expect(db.cancelled).toEqual([ { id: 'b1', - error: 'github organization repository must be reconnected to renew authorization', + error: 'github repository authorization is no longer valid; reconnect the repository', }, ]); }); diff --git a/platform/packages/api/test/unit/github-authority-migration.test.ts b/platform/packages/api/test/unit/github-authority-migration.test.ts new file mode 100644 index 000000000..02893675d --- /dev/null +++ b/platform/packages/api/test/unit/github-authority-migration.test.ts @@ -0,0 +1,152 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { PGlite } from '@electric-sql/pglite'; +import { platformDatabaseSchemaDigest } from '@void/platform/installer'; +import { expect, it } from 'vite-plus/test'; + +const root = resolve(import.meta.dirname, '../../drizzle'); +const MIGRATION = '0052_github_connection_authority'; + +type JournalEntry = { tag: string; idx: number; when: number }; + +function readJournal(): Array { + return ( + JSON.parse(readFileSync(resolve(root, 'meta/_journal.json'), 'utf8')) as { + entries: Array; + } + ).entries; +} + +it('allows upgrading the 0.21.9 schema to the GitHub connection authority migration', () => { + const compatibility = JSON.parse(readFileSync(resolve(root, 'compatibility.json'), 'utf8')) as { + lineage: string; + rollbackSafeFrom: Array<{ platformVersion: string; schemaDigest: string }>; + }; + const previous = readJournal().filter((entry) => entry.idx <= 51); + expect(previous.at(-1)?.tag).toBe('0051_icy_psylocke'); + const schemaDigest = platformDatabaseSchemaDigest( + compatibility.lineage, + previous.map((entry) => ({ + index: entry.idx, + tag: entry.tag, + timestampMillis: entry.when, + sha256: createHash('sha256') + .update(readFileSync(resolve(root, `${entry.tag}.sql`))) + .digest('hex'), + })), + ); + expect(schemaDigest).toBe('ac70deb5847c71ece9938edd27e5dbc50ce41e16771926c78e757850baf15bfa'); + expect(compatibility.rollbackSafeFrom).toContainEqual({ + platformVersion: '0.21.9', + schemaDigest, + }); +}); + +it('keeps only GitHub connections and memberships that current authority rules accept', async () => { + const journal = readJournal(); + const target = journal.find((entry) => entry.tag === MIGRATION); + expect(target?.idx).toBe(52); + const db = new PGlite(); + try { + for (const entry of journal.filter((candidate) => candidate.idx < 52)) { + await db.exec(readFileSync(resolve(root, `${entry.tag}.sql`), 'utf8')); + } + await db.exec(` + INSERT INTO users (id, provider_id, login) VALUES + ('owner', '1', 'owner'), + ('other', '2', 'other'), + ('admin', '3', 'admin'); + INSERT INTO projects (id, user_id, slug) VALUES + ('p-personal', 'owner', 'personal'), + ('p-personal-mismatch', 'owner', 'personal-mismatch'), + ('p-personal-no-repo', 'owner', 'personal-no-repo'), + ('p-org-legacy', 'owner', 'org-legacy'), + ('p-org-authorized', 'owner', 'org-authorized'), + ('p-personal-authorized', 'owner', 'personal-authorized'), + ('p-org-demoted', 'owner', 'org-demoted'), + ('p-org-non-member', 'owner', 'org-non-member'); + INSERT INTO project_members (project_id, user_id, role) VALUES + ('p-org-authorized', 'admin', 'admin'), + ('p-org-demoted', 'admin', 'collaborator'); + INSERT INTO github_installations (id, installation_id, user_id, account_login, account_id, account_type) VALUES + ('ghi-user', '100', 'owner', 'owner', '1', 'User'), + ('ghi-user-other', '101', 'other', 'other', '2', 'User'), + ('ghi-user-unlinked', '102', NULL, 'nobody', '9', 'User'), + ('ghi-org-owned', '200', 'owner', 'org', '50', 'Organization'), + ('ghi-org-null', '201', NULL, 'org2', '51', 'Organization'); + INSERT INTO github_connections (id, project_id, installation_id, repo_full_name, repository_id, authorized_by_user_id) VALUES + ('c-personal', 'p-personal', '100', 'owner/a', '1', NULL), + ('c-personal-mismatch', 'p-personal-mismatch', '101', 'other/b', '2', NULL), + ('c-personal-no-repo', 'p-personal-no-repo', '100', 'owner/c', NULL, NULL), + ('c-org-legacy', 'p-org-legacy', '200', 'org/d', '4', NULL), + ('c-org-authorized', 'p-org-authorized', '201', 'org2/e', '5', 'admin'), + ('c-personal-authorized', 'p-personal-authorized', '100', 'owner/f', NULL, 'owner'), + ('c-org-demoted', 'p-org-demoted', '201', 'org2/g', '7', 'admin'), + ('c-org-non-member', 'p-org-non-member', '201', 'org2/h', '8', 'other'); + INSERT INTO github_installation_members (id, installation_id, user_id, expires_at) VALUES + ('m-user', '100', 'other', now() + interval '1 day'), + ('m-org', '200', 'other', now() + interval '1 day'); + INSERT INTO builds (id, project_id, user_id, executor, status, completed_at) VALUES + ('b-removed-container', 'p-org-legacy', 'owner', 'container', 'building', NULL), + ('b-removed-actions', 'p-personal-no-repo', 'owner', 'github_actions', 'deploying', NULL), + ('b-removed-queued', 'p-personal-mismatch', 'owner', 'container', 'queued', NULL), + ('b-removed-finished', 'p-org-legacy', 'owner', 'container', 'complete', '2026-01-01 00:00:00'), + ('b-kept', 'p-org-authorized', 'admin', 'container', 'building', NULL), + ('b-backfilled', 'p-personal', 'owner', 'github_actions', 'starting', NULL), + ('b-demoted', 'p-org-demoted', 'admin', 'container', 'building', NULL), + ('b-non-member', 'p-org-non-member', 'other', 'github_actions', 'deploying', NULL); + `); + + for (const statement of readFileSync(resolve(root, `${MIGRATION}.sql`), 'utf8') + .split('--> statement-breakpoint') + .map((value) => value.trim()) + .filter(Boolean)) { + await db.query(statement); + } + + expect( + ( + await db.query( + 'select installation_id, user_id from github_installations order by installation_id', + ) + ).rows, + ).toEqual([ + { installation_id: '100', user_id: 'owner' }, + { installation_id: '101', user_id: 'other' }, + { installation_id: '102', user_id: null }, + { installation_id: '200', user_id: null }, + { installation_id: '201', user_id: null }, + ]); + expect( + (await db.query('select id, authorized_by_user_id from github_connections order by id')).rows, + ).toEqual([ + { id: 'c-org-authorized', authorized_by_user_id: 'admin' }, + { id: 'c-personal', authorized_by_user_id: 'owner' }, + ]); + // Builds of removed connections lose their build-bound deploy tokens. + const cancelled = + 'github repository authorization is no longer valid; reconnect the repository'; + expect( + ( + await db.query( + 'select id, status, error, completed_at is not null as completed from builds order by id', + ) + ).rows, + ).toEqual([ + { id: 'b-backfilled', status: 'starting', error: null, completed: false }, + { id: 'b-demoted', status: 'cancelled', error: cancelled, completed: true }, + { id: 'b-kept', status: 'building', error: null, completed: false }, + { id: 'b-non-member', status: 'cancelled', error: cancelled, completed: true }, + { id: 'b-removed-actions', status: 'cancelled', error: cancelled, completed: true }, + { id: 'b-removed-container', status: 'cancelled', error: cancelled, completed: true }, + { id: 'b-removed-finished', status: 'complete', error: null, completed: true }, + { id: 'b-removed-queued', status: 'cancelled', error: cancelled, completed: true }, + ]); + expect((await db.query('select id from github_installation_members order by id')).rows).toEqual( + [{ id: 'm-org' }], + ); + } finally { + await db.close(); + } +}, 30_000);