diff --git a/.changeset/open-pull-requests-as-approver.md b/.changeset/open-pull-requests-as-approver.md new file mode 100644 index 0000000..31d35c8 --- /dev/null +++ b/.changeset/open-pull-requests-as-approver.md @@ -0,0 +1,7 @@ +--- +'@swirls/shuttle': minor +--- + +A pull request can be opened by the person who approves it. The publish card has an "Open as" choice between them and Shuttle, starting on them when their GitHub account is connected; `GET /sessions/{id}/pull-request/opener` (`api.sessions.pullRequestOpener`) says who they are on GitHub, and the approval's payload carries `openAs: 'you' | 'shuttle'`. A host lets its people open pull requests by supplying the new `githubPeople` port (`GithubPeople`, `tokenOf(userId)`); without it the App opens every pull request, as before. An approval decided by the host's policy is always opened by the App. + +Published commits are the App's again: Shuttle no longer sets the approver as a commit's author and committer, so GitHub credits and signs them as the App, and a squash merge of a pull request someone opened is theirs with the App as `Co-authored-by`. `GitEnv.AUTH_DB` is gone with it. `GitAccess.userToken()` and `GITHUB_TOKEN` are no longer tried when the App is refused opening a pull request; they remain a fallback for reading pull requests only. diff --git a/apps/worker/src/github/user-token.test.ts b/apps/worker/src/github/user-token.test.ts index c00b330..e635fab 100644 --- a/apps/worker/src/github/user-token.test.ts +++ b/apps/worker/src/github/user-token.test.ts @@ -1,6 +1,9 @@ import { describe, expect, test } from 'bun:test' -import { githubTokenOf, type GithubTokenSource } from './user-token' +import { createAuth } from '../auth/auth' +import { signUp, TEST_AUTH_ENV } from '../testing/auth' +import { migratedD1 } from '../testing/fake-d1' +import { githubTokenOf, githubTokenOfUser, type GithubTokenSource } from './user-token' /** An auth instance that knows these accounts and hands out `token` for the GitHub one. */ function authWith( @@ -56,3 +59,63 @@ describe('githubTokenOf', () => { expect(await githubTokenOf(auth, headers)).toBeNull() }) }) + +async function linkGithub(database: D1Database, userId: string, accessToken: string) { + await database + .prepare( + `insert into "account" ("id", "accountId", "providerId", "userId", "accessToken", "accessTokenExpiresAt", "createdAt", "updatedAt") + values (?, '583231', 'github', ?, ?, ?, ?, ?)`, + ) + .bind( + `acct_${userId}`, + userId, + accessToken, + new Date(Date.now() + 3_600_000).toISOString(), + new Date().toISOString(), + new Date().toISOString(), + ) + .run() +} + +describe('githubTokenOfUser', () => { + const GITHUB_ENV = { + ...TEST_AUTH_ENV, + GITHUB_CLIENT_ID: 'client', + GITHUB_CLIENT_SECRET: 'secret', + } + + /** A real auth instance, with one person signed up and their id. */ + async function person(name: string) { + const database = await migratedD1() + const auth = createAuth(GITHUB_ENV, database) + const session = await auth.api.getSession({ headers: await signUp(auth, name) }) + + if (session === null) { + throw new Error('sign-up left no session') + } + + return { auth, database, userId: session.user.id } + } + + test('is the token of their linked GitHub account, with no request of theirs to go by', async () => { + const { auth, database, userId } = await person('Ada') + + await linkGithub(database, userId, 'ghu_ada') + + expect(await githubTokenOfUser(auth, database, userId)).toBe('ghu_ada') + }) + + test('is null for someone who has not linked GitHub', async () => { + const { auth, database, userId } = await person('Grace') + + expect(await githubTokenOfUser(auth, database, userId)).toBeNull() + }) + + test("is never another person's token", async () => { + const { auth, database, userId } = await person('Ada') + + await linkGithub(database, userId, 'ghu_ada') + + expect(await githubTokenOfUser(auth, database, 'someone-else')).toBeNull() + }) +}) diff --git a/apps/worker/src/github/user-token.ts b/apps/worker/src/github/user-token.ts index def1ee7..f07caab 100644 --- a/apps/worker/src/github/user-token.ts +++ b/apps/worker/src/github/user-token.ts @@ -1,3 +1,5 @@ +import { z } from 'zod' + /** The part of the auth instance that holds a person's linked accounts and their tokens. */ export interface GithubTokenSource { readonly api: { @@ -39,5 +41,51 @@ export async function githubTokenOf( } } +/** The part of the auth instance that reads a person's token with no request of theirs. */ +export interface GithubTokenStore { + readonly api: { + getAccessToken(input: { + body: { accountId: string; userId: string } + }): Promise<{ readonly accessToken: string }> + } +} + +const AccountRowSchema = z.object({ id: z.string() }) + +/** + * The GitHub token that acts as the Shuttle user `userId`, read where there is no request of + * theirs to go by: in a run, publishing a pull request they approved. Better Auth renews it when + * it has expired. + * + * Null when they have no GitHub account connected, or GitHub will no longer renew the one they + * had. + */ +export async function githubTokenOfUser( + auth: GithubTokenStore, + db: D1Database, + userId: string, +): Promise { + try { + const row = AccountRowSchema.safeParse( + await db + .prepare( + `select "id" from "account" where "userId" = ? and "providerId" = 'github' limit 1`, + ) + .bind(userId) + .first(), + ) + + if (!row.success) { + return null + } + + const tokens = await auth.api.getAccessToken({ body: { accountId: row.data.id, userId } }) + + return tokens.accessToken === '' ? null : tokens.accessToken + } catch { + return null + } +} + /** What a route answers when someone has to connect GitHub before it can act as them. */ export const GITHUB_NOT_CONNECTED = 'github_not_connected' diff --git a/apps/worker/src/host.ts b/apps/worker/src/host.ts index 4f3c4f6..10e433f 100644 --- a/apps/worker/src/host.ts +++ b/apps/worker/src/host.ts @@ -1,10 +1,16 @@ -import { personIdentity, type IdentityPort, type ShuttleHost } from '@shuttle/engine' +import { + personIdentity, + type GithubPeople, + type IdentityPort, + type ShuttleHost, +} from '@shuttle/engine' import type { PeoplePort } from '@shuttle/engine/ports/people' import type { PreviewKeys } from '@shuttle/engine/ports/previews' import { resolveActor } from './auth/actor' import { getAuth } from './auth/auth' import type { ShuttleEnv } from './env' +import { githubTokenOfUser } from './github/user-token' import { previewKeyFor, runOfPreviewKey } from './tenancy/previews' /** Shuttle's own Worker acts for the person signed in to the request. */ @@ -35,9 +41,22 @@ export function workerPreviews(env: ShuttleEnv): PreviewKeys | null { : { keyFor: (runId) => previewKeyFor(db, runId), runOf: (key) => runOfPreviewKey(db, key) } } +/** + * The GitHub token of each person who signed in with GitHub or linked it, so a pull request they + * approve can be opened in their name. Null without the sign-in database. + */ +export function workerGithubPeople(env: ShuttleEnv): GithubPeople | null { + const db = env.AUTH_DB + + return db === undefined + ? null + : { tokenOf: (userId) => githubTokenOfUser(getAuth(env), db, userId) } +} + /** * Shuttle's own Worker as a host of the engine: its environment, the signed-in person as the one - * it acts for, and its sign-in database for who is in an organization and for preview keys. + * it acts for, and its sign-in database for who is in an organization, for their GitHub tokens + * and for preview keys. * Every other port is left to the engine's standalone behaviour. */ export function workerHost(env: ShuttleEnv): ShuttleHost { @@ -46,6 +65,7 @@ export function workerHost(env: ShuttleEnv): ShuttleHost { ports: { identity: workerIdentity(env), people: workerPeople(env), + githubPeople: workerGithubPeople(env), previews: workerPreviews(env), }, } diff --git a/docs/hosting.md b/docs/hosting.md index 3c07a17..97a985d 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -168,7 +168,10 @@ front of routes of its own. A host whose own routes share Shuttle's paths (a `/r `/sessions` of its own) mounts Shuttle under a path with `basePath`: ```ts -const shuttle = serveShuttle(host(env), { modules: shuttleApiModules, basePath: '/shuttle' }) +const shuttle = serveShuttle(host(env), { + modules: shuttleApiModules, + basePath: '/shuttle', +}) ``` It then answers every path under `/shuttle` and `null` for the rest. It takes `/shuttle` off before @@ -251,6 +254,7 @@ A port is a small interface. Leave it out and Shuttle does what it does standalo | `credentials` | Whose credential a vendor agent turn runs on, and the API keys the host holds. | The person it works for, on their own sign-in. | | `approvals` | How long an approval waits before a decision is refused, and whether the host decides it. | A person decides, whenever they do. | | `git` | A token for one GitHub repository at one access, and the user token. | Shuttle's own GitHub App, narrowed per repository. | +| `githubPeople` | A GitHub token that acts as one of the host's people, to open a pull request as them. | None: the App opens every pull request. | | `codeStorage` | A token for a repository's Code Storage repository (`store`) and one purpose. | Signed with `PIERRE_ORG` and `PIERRE_PRIVATE_KEY`. | | `snapshots` | A repository's files at a commit, for a sandbox with no machine. | GitHub through `git`, a store through `codeStorage`. | | `environment` | The values of a session's environment variable names, when a process of it starts. | None: the names get no values. | @@ -268,7 +272,13 @@ const repo: RepoRef = { label: 'acme/shop', // what people read defaultBranch: 'main', private: true, - origin: { kind: 'github', owner: 'acme', name: 'shop', repositoryId: '42', installationId: 7 }, + origin: { + kind: 'github', + owner: 'acme', + name: 'shop', + repositoryId: '42', + installationId: 7, + }, store: { repoName: 'acme/shop' }, // where session work is kept, or null hostRef: null, // opaque to Shuttle, handed back to the host's ports } @@ -303,6 +313,29 @@ repository by `changeHostFor(env, repo)`: - `githubChangeHost(env)` for `origin.kind === 'github'`: one commit per layer through the Git Data API and a pull request per layer, based on the layer below's, with a native GitHub stack when a stack has two or more. Its tokens come from `git.repoToken(write)`. + +### Who a pull request is by + +Shuttle makes a pull request's commits itself, with the token from `git.repoToken(write)` and no +author, so GitHub credits them to whoever that token belongs to: the App, which GitHub also signs +them as. The person behind a pull request is whoever opens it, and GitHub credits a squash merge +to the opener, adding the commits' author as `Co-authored-by`. + +- **Opened by the person who approved it.** The publish card offers "Open as" to someone the host + can act as on GitHub, and it starts on them. The pull request is then opened with + `githubPeople.tokenOf(userId)`, their own token, and a squash merge is theirs with the App as + co-author. Someone who chose this and cannot be acted as, or whom GitHub refuses, gets an error + naming the reason: the App never opens it in their place. +- **Opened by the App.** When they choose Shuttle, when they have no GitHub account connected, + when the host supplies no `githubPeople`, and whenever the host's approval policy decided the + gate (no person approved it). A squash merge is then the App's alone. +- **An existing pull request keeps its opener.** GitHub fixes it when the pull request is opened, + so a later push to it, by anyone, changes nothing. + +`git.userToken()` is only a fallback for reading pull requests where the App lacks a scope. It +never opens one. Shuttle's own app supplies `githubPeople` from the GitHub tokens its sign-in +keeps; `GET /sessions/{id}/pull-request/opener` tells the card who the person asking is on GitHub. + - `storeChangeHost(env)` for `origin.kind === 'store'`: one commit per layer on its branch in the repository's store, on a `codeStorage` token of purpose `publish` for that one branch. The branch is started at the layer's base commit first, a re-published layer moves only its own branch back diff --git a/packages/api/src/sessions.ts b/packages/api/src/sessions.ts index 7521e0a..39d5108 100644 --- a/packages/api/src/sessions.ts +++ b/packages/api/src/sessions.ts @@ -26,6 +26,19 @@ export const SessionAccess = z.object({ }) export type SessionAccess = z.infer +/** Who opens a pull request: the person who approves it, or Shuttle (the host's GitHub App). */ +export const PullRequestOpener = z.enum(['you', 'shuttle']) +export type PullRequestOpener = z.infer + +/** Who someone can open a session's pull requests as. */ +export const PullRequestOpeners = z.object({ + /** Their GitHub account, when the host can open a pull request as them. */ + you: z.object({ login: z.string() }).nullable(), + /** Whether the host can act as a person at all, so connecting GitHub would let them. */ + connectable: z.boolean(), +}) +export type PullRequestOpeners = z.infer + export const INTERJECTION_KINDS = [ 'question', 'idea', @@ -158,6 +171,16 @@ export const sessionsContract = { ) .output(z.object({ approvalId: z.string() })), + /** + * Who the person asking can open this session's pull requests as. `you` is their GitHub + * account, when the host can act as them there; without it Shuttle opens them. `connectable` + * says whether connecting a GitHub account would change that. + */ + pullRequestOpener: oc + .route({ method: 'GET', path: '/sessions/{id}/pull-request/opener' }) + .input(SessionParams) + .output(PullRequestOpeners), + rename: oc .route({ method: 'POST', path: '/sessions/{id}/rename' }) .input(SessionParams.extend({ title: z.string().trim().min(1).max(120) })) diff --git a/packages/engine/src/api/serve.test.ts b/packages/engine/src/api/serve.test.ts index 8613941..37ba50c 100644 --- a/packages/engine/src/api/serve.test.ts +++ b/packages/engine/src/api/serve.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from 'bun:test' +import { afterEach, describe, expect, test } from 'bun:test' import { z } from 'zod' @@ -229,3 +229,87 @@ describe('serveShuttle', () => { }) }) }) + +function hostWithPeople(tokens: Readonly>): ShuttleHost { + const host = hostWith() + + return { + ...host, + ports: { + ...host.ports, + githubPeople: { tokenOf: async (userId) => tokens[userId] ?? null }, + }, + } +} + +function opener(init: RequestInit, host: ShuttleHost) { + return ask(`/sessions/${RUN}/pull-request/opener`, init, {}, host) +} + +describe('who someone can open a session’s pull requests as', () => { + const realFetch = globalThis.fetch + + afterEach(() => { + globalThis.fetch = realFetch + }) + + /** GitHub answering `GET /user` for each token it knows, and recording the tokens it was asked with. */ + function github(logins: Readonly>): string[] { + const tokens: string[] = [] + + globalThis.fetch = Object.assign( + async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + const token = (request.headers.get('authorization') ?? '').replace('Bearer ', '') + const login = logins[token] + + tokens.push(token) + + return new URL(request.url).pathname === '/user' && login !== undefined + ? Response.json({ login }) + : new Response('{}', { status: 401 }) + }, + { preconnect: realFetch.preconnect }, + ) + + return tokens + } + + test('themselves, by their GitHub login, when the host has a token GitHub accepts', async () => { + const asked = github({ ghu_ada: 'ada-on-github' }) + const response = await opener(asAda, hostWithPeople({ ada: 'ghu_ada' })) + + expect(Body.parse(await response?.json())).toEqual({ + you: { login: 'ada-on-github' }, + connectable: true, + }) + + expect(asked).toEqual(['ghu_ada']) + }) + + test('only Shuttle, when they have no GitHub account connected', async () => { + github({}) + + const response = await opener(asAda, hostWithPeople({ grace: 'ghu_grace' })) + + expect(Body.parse(await response?.json())).toEqual({ you: null, connectable: true }) + }) + + test('only Shuttle, when GitHub no longer accepts their token', async () => { + github({}) + + const response = await opener(asAda, hostWithPeople({ ada: 'ghu_revoked' })) + + expect(Body.parse(await response?.json())).toEqual({ you: null, connectable: true }) + }) + + test('only Shuttle, and nothing to connect, on a host that cannot act as its people', async () => { + const response = await opener(asAda, hostWith()) + + expect(Body.parse(await response?.json())).toEqual({ you: null, connectable: false }) + }) + + test('nobody is told anything without being signed in', async () => { + expect((await opener({}, hostWithPeople({ ada: 'ghu_ada' })))?.status).toBe(401) + }) +}) diff --git a/packages/engine/src/api/sessions.ts b/packages/engine/src/api/sessions.ts index d0f784e..8e27647 100644 --- a/packages/engine/src/api/sessions.ts +++ b/packages/engine/src/api/sessions.ts @@ -4,6 +4,7 @@ import { PlaybookState } from '@shuttle/api' import { scopedRunId } from '@shuttle/api' import { deleteScratchRepo } from '@shuttle/git/codestorage/client' import { scratchPlace } from '@shuttle/git/codestorage/scratch' +import { githubLoginOf } from '@shuttle/git/github/person' import { ACTOR_HEADER } from '@swirls/looms/runtime' import { headAsset, type AssetRef } from '../assets/store' @@ -198,6 +199,25 @@ export const sessionsRouter = { return { approvalId: `pr_publish_${requestId}` } }), + /** + * Who the person asking can open a pull request as: themselves, when the host has a GitHub + * token for them that GitHub still accepts, or only Shuttle. + */ + pullRequestOpener: sessions.pullRequestOpener.handler( + async ({ context: { env, actor, ports } }) => { + const people = ports?.githubPeople ?? env.GITHUB_PEOPLE ?? null + + if (people === null) { + return { you: null, connectable: false } + } + + const token = await people.tokenOf(actor.userId).catch(() => null) + const login = token === null ? null : await githubLoginOf(env, token).catch(() => null) + + return { you: login === null ? null : { login }, connectable: true } + }, + ), + /** Renames a session wherever it is listed. Anyone who can open the session may. */ rename: sessions.rename.handler(async ({ input, context: { env, actor } }) => { const access = await loomsStub(env.LOOMS_RUN, input.id).getAccess() diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index d4c5bed..c65ba3a 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -14,6 +14,7 @@ export type { Actor, SessionAccess } from './tenancy/access' export { fixedGitAccess, type GitAccess, + type GithubPeople, type RepoAccessLevel, type RepoTokenRequest, } from '@shuttle/git/access' diff --git a/packages/engine/src/ports/host.test.ts b/packages/engine/src/ports/host.test.ts index 28fbd7f..9971ee9 100644 --- a/packages/engine/src/ports/host.test.ts +++ b/packages/engine/src/ports/host.test.ts @@ -44,6 +44,7 @@ describe('a host that replaces nothing', () => { credentials: sponsorCredentials, approvals: neverExpire, git: null, + githubPeople: null, codeStorage: null, environment: null, people: noPeople, diff --git a/packages/engine/src/ports/host.ts b/packages/engine/src/ports/host.ts index 9e6bb00..8b8a434 100644 --- a/packages/engine/src/ports/host.ts +++ b/packages/engine/src/ports/host.ts @@ -1,4 +1,4 @@ -import type { GitAccess } from '@shuttle/git/access' +import type { GitAccess, GithubPeople } from '@shuttle/git/access' import { keyCodeStorageAccess, type CodeStorageAccess } from '@shuttle/git/codestorage/access' import type { EnvironmentPort } from '@shuttle/sandbox/environment' import { defaultSnapshotSource, type RepoSnapshotSource } from '@shuttle/sandbox/snapshot-source' @@ -34,6 +34,12 @@ export interface HostPorts { * narrowed to the repository. */ readonly git: GitAccess | null + /** + * GitHub tokens of the host's own people, so someone who approves a pull request can open it + * in their own name. Standalone: none, so the App opens every pull request (Shuttle's own app + * supplies the tokens its sign-in keeps). + */ + readonly githubPeople?: GithubPeople | null /** * Code Storage tokens for a repository's `store`, by purpose. Standalone: signed with * `PIERRE_ORG` and `PIERRE_PRIVATE_KEY` when both are set (`keyCodeStorageAccess`). @@ -89,9 +95,9 @@ export function projectorsFor( export interface ResolvedHost { /** - * `host.env`, with the host's Git access, Code Storage access, snapshot source and environment - * in place (`GIT_ACCESS`, `CODE_STORAGE`, `SNAPSHOT_SOURCE`, `ENVIRONMENT`) when it supplied - * them. + * `host.env`, with the host's Git access, its people's GitHub tokens, Code Storage access, + * snapshot source and environment in place (`GIT_ACCESS`, `GITHUB_PEOPLE`, `CODE_STORAGE`, + * `SNAPSHOT_SOURCE`, `ENVIRONMENT`) when it supplied them. */ readonly env: EngineEnv readonly ports: HostPorts @@ -112,6 +118,10 @@ export function resolveHost(host: ShuttleHost): ResolvedHost { env = { ...env, GIT_ACCESS: git } } + if (supplied.githubPeople !== undefined && supplied.githubPeople !== null) { + env = { ...env, GITHUB_PEOPLE: supplied.githubPeople } + } + if (supplied.codeStorage !== undefined && supplied.codeStorage !== null) { env = { ...env, CODE_STORAGE: supplied.codeStorage } } @@ -135,6 +145,7 @@ export function resolveHost(host: ShuttleHost): ResolvedHost { credentials: supplied.credentials ?? sponsorCredentials, approvals: supplied.approvals ?? neverExpire, git, + githubPeople: supplied.githubPeople ?? null, codeStorage, snapshots, environment: supplied.environment ?? null, diff --git a/packages/engine/src/session/change-host.ts b/packages/engine/src/session/change-host.ts index f8c2dd4..da1ca16 100644 --- a/packages/engine/src/session/change-host.ts +++ b/packages/engine/src/session/change-host.ts @@ -60,8 +60,6 @@ export interface ChangeCommitInput { readonly branch: string readonly files: readonly ChangesetFile[] readonly message: string - /** The host's user to credit the commit to, where the change host can. */ - readonly authorUserId?: string | null } export interface ChangeOpenInput { @@ -75,6 +73,11 @@ export interface ChangeOpenInput { readonly draft: boolean /** The review the branch had before this publish. */ readonly existing: ChangeReview | null + /** + * The host's user who opens a new review in their own name, where the change host can. Null: + * the host's own identity opens it. An existing review keeps whoever opened it. + */ + readonly openAsUserId?: string | null } /** A host's native stack of reviews. */ @@ -105,7 +108,10 @@ function pullNumbers(reviews: readonly ChangeReview[]): number[] { return reviews.flatMap((review) => (review.kind === 'pull_request' ? [review.number] : [])) } -/** GitHub: commits through the Git Data API and pull requests, on tokens from `repoToken(write)`. */ +/** + * GitHub: commits through the Git Data API and pull requests, on tokens from `repoToken(write)`. + * A pull request someone opens in their own name is opened with their token (`GithubPeople`). + */ export function githubChangeHost(env: GitEnv): ChangeHost { return { async commit(input) { @@ -116,7 +122,6 @@ export function githubChangeHost(env: GitEnv): ChangeHost { branch: input.branch, files: input.files, message: input.message, - authorUserId: input.authorUserId ?? null, }) return { sha: committed.commitSha, treeSha: committed.treeSha } @@ -141,6 +146,7 @@ export function githubChangeHost(env: GitEnv): ChangeHost { head: input.branch, base: input.base, draft: input.draft, + openAsUserId: input.openAsUserId ?? null, }) return { diff --git a/packages/engine/src/session/mirror-stack.test.ts b/packages/engine/src/session/mirror-stack.test.ts index 642a57d..0cdf604 100644 --- a/packages/engine/src/session/mirror-stack.test.ts +++ b/packages/engine/src/session/mirror-stack.test.ts @@ -24,11 +24,7 @@ function fakeGitHub(baseSha: string, baseTree: Tree) { const github: ChangeHost = { commit: async (input) => { - calls.push( - input.authorUserId === undefined || input.authorUserId === null - ? `commit ${input.branch}` - : `commit ${input.branch} as ${input.authorUserId}`, - ) + calls.push(`commit ${input.branch}`) const parent = commits.get(input.baseSha) @@ -62,7 +58,13 @@ function fakeGitHub(baseSha: string, baseTree: Tree) { } const number = pulls.size + 1 - calls.push(`create #${number} ${input.branch} -> ${input.base}`) + + calls.push( + input.openAsUserId === undefined || input.openAsUserId === null + ? `create #${number} ${input.branch} -> ${input.base}` + : `create #${number} ${input.branch} -> ${input.base} as ${input.openAsUserId}`, + ) + pulls.set(number, { head: input.branch, base: input.base, title: input.title ?? '' }) return { @@ -259,17 +261,27 @@ describe('mirrorRepoStack', () => { expect(calls).toEqual([]) }) - test('commits are credited to the person who approved the publish', async () => { + test('a pull request is opened as the person who chose to open it, and its commit is not theirs', async () => { const { write, publish, calls } = setup() write('a.txt', 'a\n') - await publish({ authorUserId: 'user_1' }) + await publish({ openAsUserId: 'user_1' }) - expect(calls.filter((call) => call.startsWith('commit '))).toEqual([ - 'commit shuttle/session_1/glue as user_1', + expect(calls.filter((call) => !call.startsWith('stack '))).toEqual([ + 'commit shuttle/session_1/glue', + 'create #1 shuttle/session_1/glue -> main as user_1', ]) }) + test('with nobody to open it as, the pull request is opened by the host itself', async () => { + const { write, publish, calls } = setup() + + write('a.txt', 'a\n') + await publish() + + expect(calls).toContain('create #1 shuttle/session_1/glue -> main') + }) + test('publishing a stack that does not exist fails clearly', async () => { const { publish } = setup() diff --git a/packages/engine/src/session/mirror-stack.ts b/packages/engine/src/session/mirror-stack.ts index 154a769..21340eb 100644 --- a/packages/engine/src/session/mirror-stack.ts +++ b/packages/engine/src/session/mirror-stack.ts @@ -57,8 +57,11 @@ export interface MirrorInput { readonly stackId: number | null /** Layer the title and body describe; null means the current (or top) layer. */ readonly layer: number | null - /** Shuttle user who approved the publish; the commits are credited to them. */ - readonly authorUserId?: string | null + /** + * The host's user who opens the new pull requests in their own name. Null: the host's own + * identity (the App) opens them. The commits are the App's either way. + */ + readonly openAsUserId?: string | null /** * The host's prefix for published branches: layer n of the first stack is `-` and of * stack s after it `--`. Absent: each layer is published on its local branch. @@ -193,7 +196,6 @@ export async function mirrorRepoStack( branch, files, message: isTarget ? input.title : `Shuttle layer ${planned.layer}`, - authorUserId: input.authorUserId ?? null, }) remoteByLayer.set(planned.layer, { sha: committed.sha, branch }) @@ -211,6 +213,7 @@ export async function mirrorRepoStack( body: existing === null || isTarget ? input.body : null, draft: input.draft, existing, + openAsUserId: input.openAsUserId ?? null, }) const { github, ...review } = opened diff --git a/packages/engine/src/session/publish-effects.test.ts b/packages/engine/src/session/publish-effects.test.ts index 76dd830..e59a101 100644 --- a/packages/engine/src/session/publish-effects.test.ts +++ b/packages/engine/src/session/publish-effects.test.ts @@ -116,11 +116,39 @@ describe("a decision by the host's approval policy", () => { expect(decidedByPolicy({ origin: { type: 'external', actorId: 'user_1' } })).toBe(false) }) - test('has no person behind it to author the commits', () => { + test('has no person behind it to open the pull request as', () => { expect(actorOfEvent(decided)).toBeNull() }) }) +function choosing(openAs: string) { + return withPrApprovalDecision( + awaiting(), + { ...approve, payload: { openAs } }, + { approvedBy: 'user_1' }, + ) +} + +describe('who the approver chose to open the pull request as', () => { + test('their choice is kept and passed to the publish effect', () => { + for (const openAs of ['you', 'shuttle'] as const) { + const next = choosing(openAs) + const effects: RuntimeEffect[] = [] + + expect(next?.pendingPrPublish?.openAs).toBe(openAs) + + appendPrPublishEffects(next ?? awaiting(), effects) + + expect(JSON.stringify(effects[0])).toContain(`"openAs":"${openAs}"`) + } + }) + + test('no choice, or one that is not a choice, is left for the publish to settle', () => { + expect(withPrApprovalDecision(awaiting(), approve)?.pendingPrPublish?.openAs).toBeNull() + expect(choosing('someone-else')?.pendingPrPublish?.openAs).toBeNull() + }) +}) + describe('publishing as the person who approved it', () => { test('the approver is passed to the publish effect', () => { const next = withPrApprovalDecision(awaiting(), approve, { approvedBy: 'user_1' }) diff --git a/packages/engine/src/session/publish-effects.ts b/packages/engine/src/session/publish-effects.ts index 0ebb6cc..a46aa17 100644 --- a/packages/engine/src/session/publish-effects.ts +++ b/packages/engine/src/session/publish-effects.ts @@ -4,7 +4,7 @@ import { emit, invoke, isJsonObject, type JsonValue, type RuntimeEffect } from ' import { hasExpired, POLICY_DECIDER } from '../ports/approvals' import { shuttleModule } from './scope' -import { stacksAsJson, type PendingPrPublish } from './stack-state' +import { pullRequestOpenerOf, stacksAsJson, type PendingPrPublish } from './stack-state' function asObject(value: JsonValue | undefined): { [key: string]: JsonValue } { return isJsonObject(value) ? value : {} @@ -79,8 +79,8 @@ export function withPrApprovalDecision( state: S, payload: ApprovalDecision, /** - * When the decision was recorded, to hold it against the approval's expiry, and the Shuttle user - * who made it, whose GitHub account then authors the commits. + * When the decision was recorded, to hold it against the approval's expiry, and the host's user + * who made it, who may open the pull request in their own name. */ { at = Date.now(), approvedBy = null, byPolicy = false }: ApprovalContext = {}, ): S | null { @@ -142,6 +142,7 @@ export function withPrApprovalDecision( restacks: pending.restacks, status: 'publishing', approvedBy, + openAs: pullRequestOpenerOf(fields.openAs), }, } } @@ -174,6 +175,7 @@ export function appendPrPublishEffects(state: PublishSessionSlice, effects: Runt layer: pending.layer, stacks: stacksAsJson(state.stacks), approvedBy: pending.approvedBy ?? null, + openAs: pending.openAs ?? null, }, `publish_pr_${pending.approvalId}`, ), diff --git a/packages/engine/src/session/publish-opener.test.ts b/packages/engine/src/session/publish-opener.test.ts new file mode 100644 index 0000000..8d0e969 --- /dev/null +++ b/packages/engine/src/session/publish-opener.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, test } from 'bun:test' + +import type { GithubPeople } from '@shuttle/git/access' +import { GITHUB_NOT_CONNECTED_TO_OPEN } from '@shuttle/git/github/pulls' + +import { pullRequestOpener } from './publish-pr' + +/** People with a GitHub token each, recording who was asked for. */ +function people(tokens: Readonly>) { + const asked: string[] = [] + + const port: GithubPeople = { + tokenOf: async (userId) => { + asked.push(userId) + return tokens[userId] ?? null + }, + } + + return { env: { GITHUB_PEOPLE: port }, asked } +} + +describe('who opens the pull requests of a publish', () => { + test('the approver, when they chose themselves and GitHub is connected', async () => { + const { env } = people({ user_1: 'ghu_1' }) + + expect(await pullRequestOpener(env, 'you', 'user_1')).toEqual({ userId: 'user_1' }) + }) + + test('the approver by default, when GitHub is connected', async () => { + const { env } = people({ user_1: 'ghu_1' }) + + expect(await pullRequestOpener(env, null, 'user_1')).toEqual({ userId: 'user_1' }) + }) + + test('Shuttle by default, when the approver has no GitHub account connected', async () => { + const { env } = people({}) + + expect(await pullRequestOpener(env, null, 'user_1')).toEqual({ userId: null }) + }) + + test('Shuttle when the approver chose it, without asking for their token', async () => { + const { env, asked } = people({ user_1: 'ghu_1' }) + + expect(await pullRequestOpener(env, 'shuttle', 'user_1')).toEqual({ userId: null }) + expect(asked).toEqual([]) + }) + + test("Shuttle when the host's policy approved: there is no person to open it as", async () => { + const { env, asked } = people({ user_1: 'ghu_1' }) + + expect(await pullRequestOpener(env, null, null)).toEqual({ userId: null }) + expect(await pullRequestOpener(env, 'you', null)).toEqual({ userId: null }) + expect(asked).toEqual([]) + }) + + test('an approver who chose themselves with no GitHub connected is told, not replaced by Shuttle', async () => { + const { env } = people({}) + + expect(await pullRequestOpener(env, 'you', 'user_1')).toEqual({ + error: GITHUB_NOT_CONNECTED_TO_OPEN, + }) + }) + + test('a host that cannot act as its people opens every pull request itself by default', async () => { + expect(await pullRequestOpener({}, null, 'user_1')).toEqual({ userId: null }) + + expect(await pullRequestOpener({}, 'you', 'user_1')).toEqual({ + error: GITHUB_NOT_CONNECTED_TO_OPEN, + }) + }) + + test('a token lookup that fails counts as not connected', async () => { + const env = { + GITHUB_PEOPLE: { + tokenOf: async (): Promise => { + throw new Error('the sign-in store is down') + }, + }, + } + + expect(await pullRequestOpener(env, null, 'user_1')).toEqual({ userId: null }) + }) +}) diff --git a/packages/engine/src/session/publish-pr.ts b/packages/engine/src/session/publish-pr.ts index eb912bc..e83bced 100644 --- a/packages/engine/src/session/publish-pr.ts +++ b/packages/engine/src/session/publish-pr.ts @@ -2,6 +2,7 @@ import { Schema } from 'effect' import { orgOfRun } from '@shuttle/api' import { findRepo, githubFullName, type RepoRef } from '@shuttle/core/repo-ref' +import { GITHUB_NOT_CONNECTED_TO_OPEN } from '@shuttle/git/github/pulls' import { asJson } from '@swirls/looms/core' import { pullsRunId } from '../config' @@ -15,7 +16,12 @@ import { prepareSessionSandbox } from './handoff' import { mirrorRepoStack, type MirroredStack } from './mirror-stack' import { ChangeReviewSchema, shuttleModule } from './scope' import { writeSessionStacks } from './session-stacks' -import { sessionStacksOf, stackKey, type SessionStacks } from './stack-state' +import { + sessionStacksOf, + stackKey, + type PullRequestOpener, + type SessionStacks, +} from './stack-state' /** A published layer as the session's state holds it: this release's `review`, or an earlier one's `pull`. */ const StackLayerSchema = Schema.Struct({ @@ -48,6 +54,9 @@ const PublishPullSchema = Schema.Struct({ stackId: Schema.optional(Schema.NullOr(Schema.Finite)), layer: Schema.optional(Schema.NullOr(Schema.Finite)), approvedBy: Schema.optional(Schema.NullOr(Schema.String)), + openAs: Schema.optional( + Schema.NullOr(Schema.Union([Schema.Literal('you'), Schema.Literal('shuttle')])), + ), stacks: Schema.optional( Schema.Record( Schema.String, @@ -69,6 +78,34 @@ function isPresent(value: string | undefined | null): value is string { return value !== undefined && value !== null && value !== '' } +/** + * Who opens the new pull requests of a publish: the host's user `approvedBy`, with their own + * GitHub token, or the App (`userId: null`). + * + * The App opens them when the approver chose `shuttle`, or when no person approved (the host's + * policy did). An approver who chose `you` and has no GitHub account connected gets an error + * rather than a pull request in the App's name. With no choice made, the approver opens them + * when the host can act as them, and the App otherwise. + */ +export async function pullRequestOpener( + env: Pick, + openAs: PullRequestOpener | null, + approvedBy: string | null, +): Promise<{ readonly userId: string | null } | { readonly error: string }> { + if (openAs === 'shuttle' || !isPresent(approvedBy)) { + return { userId: null } + } + + const token = await env.GITHUB_PEOPLE?.tokenOf(approvedBy).catch(() => null) + const connected = isPresent(token?.trim()) + + if (connected) { + return { userId: approvedBy } + } + + return openAs === 'you' ? { error: GITHUB_NOT_CONNECTED_TO_OPEN } : { userId: null } +} + export function createPublishPullRequestEffect(env: EngineEnv, storage?: DurableObjectStorage) { return shuttleModule.effect({ type: 'shuttle.publishPullRequest', @@ -104,6 +141,16 @@ export function createPublishPullRequestEffect(env: EngineEnv, storage?: Durable return publishFailed(input.approvalId, 'No matching linked repositories to publish') } + // Settled before anything is pushed: someone who asked to open the pull request themselves + // and cannot is told so, with no branch left behind. + const opener = selected.some((repo) => repo.origin.kind === 'github') + ? await pullRequestOpener(env, input.openAs ?? null, input.approvedBy ?? null) + : { userId: null } + + if ('error' in opener) { + return publishFailed(input.approvalId, opener.error) + } + try { await prepareSessionSandbox(env, storage, ctx.runId, binding) @@ -126,7 +173,7 @@ export function createPublishPullRequestEffect(env: EngineEnv, storage?: Durable draft: input.draft, stackId: stamped ? (input.stackId ?? null) : null, layer: stamped ? (input.layer ?? null) : null, - authorUserId: input.approvedBy ?? null, + openAsUserId: opener.userId, changePrefix: binding.changeBranches?.prefix ?? null, }, priorStacks, diff --git a/packages/engine/src/session/stack-state.ts b/packages/engine/src/session/stack-state.ts index 538952e..7faa02e 100644 --- a/packages/engine/src/session/stack-state.ts +++ b/packages/engine/src/session/stack-state.ts @@ -1,5 +1,6 @@ import { Predicate } from 'effect' +import type { PullRequestOpener } from '@shuttle/api' import { findRepo, githubFullName, type RepoRef } from '@shuttle/core/repo-ref' import { asJson, isJsonObject, type JsonObject, type JsonValue } from '@swirls/looms/core' @@ -154,8 +155,20 @@ export interface PendingPrPublish { readonly status: 'awaiting_approval' | 'publishing' /** When a decision stops being accepted. Absent or null: never. */ readonly expiresAt?: number | null - /** Shuttle user who approved the publish; their GitHub account authors the commits. */ + /** The host's user who approved the publish. Null when the host's policy did. */ readonly approvedBy?: string | null + /** + * Who the approver chose to open new pull requests as: themselves, or Shuttle (the App). + * Absent or null: themselves when the host can act as them on GitHub, else Shuttle. + */ + readonly openAs?: PullRequestOpener | null +} + +export type { PullRequestOpener } + +/** Reads a {@link PullRequestOpener} from an approval's payload. Anything else is no choice. */ +export function pullRequestOpenerOf(value: JsonValue | undefined): PullRequestOpener | null { + return value === 'you' || value === 'shuttle' ? value : null } export interface StackSessionSlice { diff --git a/packages/git/src/access.ts b/packages/git/src/access.ts index 3d4c4bf..af83c74 100644 --- a/packages/git/src/access.ts +++ b/packages/git/src/access.ts @@ -35,12 +35,29 @@ export interface GitAccess { */ installationToken?(installationId: number): Promise /** - * A person's own token, tried when the repository token is refused: pull request sync and - * creation where the App lacks scopes. Null when there is none. + * A person's own token, tried when the repository token is refused: reading pull requests + * where the App lacks scopes. Null when there is none. Never used to open a pull request: + * that is the App, or the person who approved it (`GithubPeople`). */ userToken?(): string | null } +/** + * The GitHub tokens of the host's own people: the host port for acting on GitHub as one of them. + * + * Shuttle makes a pull request's commits itself, with a repository token, so they are the App's. + * The pull request is opened by whoever approved it, when they chose to and the host can act as + * them here; GitHub then credits a squash merge to that person, with the App as co-author. + * Without this port, or for someone it has no token for, the App opens the pull request. + */ +export interface GithubPeople { + /** + * A token that acts on GitHub as the host's user `userId`, or null when they have no GitHub + * account connected. Asked for when it is needed and never kept by Shuttle. + */ + tokenOf(userId: string): Promise +} + /** A `GitAccess` that answers every repository with `token`. For tests and single-token hosts. */ export function fixedGitAccess(token: string): GitAccess { return { diff --git a/packages/git/src/env.ts b/packages/git/src/env.ts index 33931b4..1b11e3f 100644 --- a/packages/git/src/env.ts +++ b/packages/git/src/env.ts @@ -1,4 +1,4 @@ -import type { GitAccess } from './access' +import type { GitAccess, GithubPeople } from './access' import type { CodeStorageAccess } from './codestorage/access' /** @@ -12,8 +12,8 @@ export interface GitEnv { readonly GITHUB_STATE_SECRET?: string readonly GITHUB_WEBHOOK_SECRET?: string /** - * Optional user/PAT token. Used when the GitHub App lacks `pull_requests` - * (and related) scopes so local inbox sync and PR create still work. + * Optional user/PAT token. Used when the GitHub App lacks `pull_requests` (and related) scopes + * so local inbox sync still works. Reads only: a pull request is never opened with it. */ readonly GITHUB_TOKEN?: string /** @@ -34,8 +34,8 @@ export interface GitEnv { */ readonly CODE_STORAGE?: CodeStorageAccess /** - * Shuttle's sign-in database, where a person's linked GitHub account is found so the commits - * they approve are credited to them. Without it commits are credited to the GitHub App. + * The GitHub tokens of the host's own people, for a pull request someone opens in their own + * name. Unset: every pull request is opened by the App. See `access.ts`. */ - readonly AUTH_DB?: D1Database + readonly GITHUB_PEOPLE?: GithubPeople } diff --git a/packages/git/src/github/commit-identity.test.ts b/packages/git/src/github/commit-identity.test.ts deleted file mode 100644 index a476c38..0000000 --- a/packages/git/src/github/commit-identity.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test' - -import type { GitEnv } from '../env' -import { fakeEnv } from '../testing/fake-env' -import { commitIdentityOf } from './commit-identity' - -const realFetch = globalThis.fetch - -afterEach(() => { - globalThis.fetch = realFetch -}) - -/** An auth database whose `account` table holds these GitHub account ids, by user. */ -function envWith(githubAccounts: Readonly>): GitEnv { - const db = { - prepare: () => ({ - bind: (userId: string) => ({ - first: async () => { - const accountId = githubAccounts[userId] - - return accountId === undefined ? null : { accountId } - }, - }), - }), - } - - // SAFETY: the lookup calls only `prepare().bind().first()`, which this fake implements. - return fakeEnv({ AUTH_DB: db as never }) -} - -/** What GitHub says about an account: a profile, or an error message. */ -type GithubAnswer = - | { readonly id: number; readonly login: string; readonly name: string | null } - | { readonly message: string } - -/** GitHub answers `/user/:id` with this, and records what was asked. */ -function githubAnswers(status: number, profile: GithubAnswer): string[] { - const asked: string[] = [] - - globalThis.fetch = Object.assign( - async (input: string | URL | Request) => { - asked.push(input instanceof Request ? input.url : input.toString()) - - return Response.json(profile, { status }) - }, - { preconnect: realFetch.preconnect }, - ) - - return asked -} - -describe('commitIdentityOf', () => { - test("is the person's GitHub name and no-reply address", async () => { - const asked = githubAnswers(200, { id: 42, login: 'electric-gizzard', name: 'J. Eric' }) - - expect(await commitIdentityOf(envWith({ user_1: '42' }), 'user_1', 'token')).toEqual({ - name: 'J. Eric', - email: '42+electric-gizzard@users.noreply.github.com', - }) - - expect(asked).toEqual(['https://api.github.com/user/42']) - }) - - test('falls back to the login when the profile has no name', async () => { - githubAnswers(200, { id: 42, login: 'electric-gizzard', name: null }) - - const identity = await commitIdentityOf(envWith({ user_1: '42' }), 'user_1', 'token') - - expect(identity?.name).toBe('electric-gizzard') - }) - - test('is null for someone with no GitHub account linked', async () => { - const asked = githubAnswers(200, { message: 'unused' }) - - expect(await commitIdentityOf(envWith({}), 'user_1', 'token')).toBeNull() - expect(asked).toEqual([]) - }) - - test('is null when GitHub cannot say who the account is', async () => { - githubAnswers(404, { message: 'Not Found' }) - - expect(await commitIdentityOf(envWith({ user_1: '42' }), 'user_1', 'token')).toBeNull() - }) -}) diff --git a/packages/git/src/github/commit-identity.ts b/packages/git/src/github/commit-identity.ts deleted file mode 100644 index 9896fd6..0000000 --- a/packages/git/src/github/commit-identity.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { z } from 'zod' - -import type { GitEnv } from '../env' -import { githubFetch } from './client' - -/** The name and email a commit is credited to. */ -export interface CommitIdentity { - readonly name: string - readonly email: string -} - -const GithubUserSchema = z.object({ - id: z.number(), - login: z.string(), - name: z.string().nullable().optional(), -}) - -const AccountRowSchema = z.object({ accountId: z.string() }) - -/** - * The commit identity of a Shuttle user's linked GitHub account: their profile name (or login), - * and the no-reply address GitHub gives every account. That address always leads back to the - * account, so GitHub shows the commit as theirs whichever emails they have verified. - * - * Null when the person has no GitHub account linked, or GitHub cannot say who it is. The commit - * is then credited to the App, as it was before. - */ -export async function commitIdentityOf( - env: GitEnv, - userId: string, - token: string, -): Promise { - const db = env.AUTH_DB - - if (db === undefined) { - return null - } - - const row = AccountRowSchema.safeParse( - await db - .prepare( - `select "accountId" from "account" where "userId" = ? and "providerId" = 'github' limit 1`, - ) - .bind(userId) - .first(), - ) - - if (!row.success || !/^\d+$/.test(row.data.accountId)) { - return null - } - - const response = await githubFetch(env, `/user/${row.data.accountId}`, { token }) - - if (!response.ok) { - return null - } - - const user = GithubUserSchema.safeParse(await response.json().catch(() => null)) - - if (!user.success) { - return null - } - - const { id, login, name } = user.data - - return { - name: name !== undefined && name !== null && name.trim() !== '' ? name : login, - email: `${id}+${login}@users.noreply.github.com`, - } -} diff --git a/packages/git/src/github/git-data.ts b/packages/git/src/github/git-data.ts index 1739e82..86176c0 100644 --- a/packages/git/src/github/git-data.ts +++ b/packages/git/src/github/git-data.ts @@ -10,7 +10,6 @@ import { ShaBodySchema, type GithubCoordinates, } from './client' -import { commitIdentityOf, type CommitIdentity } from './commit-identity' export type ChangesetFileStatus = 'added' | 'modified' | 'deleted' @@ -31,8 +30,6 @@ export interface CommitChangesetInput { readonly branch: string readonly files: readonly ChangesetFile[] readonly message: string - /** Shuttle user to credit the commit to, through their linked GitHub account. */ - readonly authorUserId?: string | null } export interface CommitChangesetResult { @@ -82,20 +79,17 @@ async function createCommit( message: string, treeSha: string, parentSha: string, - author: CommitIdentity | null, ): Promise { - // Without an author GitHub credits the commit to the App the token belongs to. - const credit = author === null ? {} : { author, committer: author } - const response = await githubFetch(env, `/repos/${repo.owner}/${repo.name}/git/commits`, { method: 'POST', token, headers: { 'Content-Type': 'application/json' }, + // No author is sent: GitHub credits the commit to whoever the token belongs to (the App, + // on Shuttle's own tokens) and signs it. The person behind a pull request is its opener. body: JSON.stringify({ message, tree: treeSha, parents: [parentSha], - ...credit, }), }) @@ -262,20 +256,7 @@ export async function commitChangeset( const treeSha = treeBody.sha - const author = - input.authorUserId === undefined || input.authorUserId === null || input.authorUserId === '' - ? null - : await commitIdentityOf(env, input.authorUserId, token) - - const commitSha = await createCommit( - env, - repo, - token, - input.message, - treeSha, - input.baseSha, - author, - ) + const commitSha = await createCommit(env, repo, token, input.message, treeSha, input.baseSha) await upsertBranchRef(env, repo, token, input.branch, commitSha) diff --git a/packages/git/src/github/open-pull-request.test.ts b/packages/git/src/github/open-pull-request.test.ts new file mode 100644 index 0000000..575161a --- /dev/null +++ b/packages/git/src/github/open-pull-request.test.ts @@ -0,0 +1,207 @@ +import { afterEach, describe, expect, test } from 'bun:test' + +import type { RepoRef } from '@shuttle/core/repo-ref' + +import { fixedGitAccess, type GithubPeople } from '../access' +import { fakeEnv } from '../testing/fake-env' +import { commitChangeset } from './git-data' +import { createPullRequest, GITHUB_NOT_CONNECTED_TO_OPEN } from './pulls' + +const shop: RepoRef = { + id: 'r1', + dir: 'shop', + label: 'acme/shop', + defaultBranch: 'main', + private: true, + origin: { kind: 'github', owner: 'acme', name: 'shop', repositoryId: '42', installationId: 42 }, + store: null, + hostRef: null, +} + +const target = { runId: 'run-1', repo: shop } +const pull = { target, title: 'feat: a change', body: '', head: 'shuttle/run-1/shop', base: 'main' } + +const people: GithubPeople = { + tokenOf: async (userId) => (userId === 'user_1' ? 'person-token' : null), +} + +const realFetch = globalThis.fetch + +afterEach(() => { + globalThis.fetch = realFetch +}) + +interface Seen { + readonly method: string + readonly path: string + readonly token: string + readonly body: string +} + +/** Answers GitHub's REST calls from `answer`, recording who each was made as. */ +function fakeGithub(answer: (seen: Seen) => Response): Seen[] { + const calls: Seen[] = [] + + globalThis.fetch = Object.assign( + async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + + const seen = { + method: request.method, + path: new URL(request.url).pathname, + token: (request.headers.get('authorization') ?? '').replace('Bearer ', ''), + body: await request.text(), + } + + calls.push(seen) + return answer(seen) + }, + { preconnect: realFetch.preconnect }, + ) + + return calls +} + +function opened(login: string): Response { + return Response.json({ + number: 7, + title: 'feat: a change', + html_url: 'https://github.com/acme/shop/pull/7', + state: 'open', + draft: true, + user: { login }, + head: { ref: 'shuttle/run-1/shop', sha: 'abc' }, + base: { ref: 'main', sha: 'def' }, + updated_at: '2026-12-04T00:00:00Z', + }) +} + +/** What a call rejects with; fails the test when the call succeeds. */ +async function rejection(call: Promise): Promise { + try { + await call + } catch (error) { + if (error instanceof Error) { + return error + } + + throw error + } + + throw new Error('expected the call to fail') +} + +describe('who a pull request is opened by', () => { + test('the App, when nobody is named', async () => { + const env = fakeEnv({ GIT_ACCESS: fixedGitAccess('app-token'), GITHUB_PEOPLE: people }) + const calls = fakeGithub(() => opened('shuttle-codes[bot]')) + + const summary = await createPullRequest(env, pull) + + expect(calls.map((call) => `${call.method} ${call.path} as ${call.token}`)).toEqual([ + 'POST /repos/acme/shop/pulls as app-token', + ]) + + expect(summary.authorLogin).toBe('shuttle-codes[bot]') + }) + + test('the person named, with their own token and never the App’s', async () => { + const env = fakeEnv({ GIT_ACCESS: fixedGitAccess('app-token'), GITHUB_PEOPLE: people }) + const calls = fakeGithub(() => opened('octocat')) + + const summary = await createPullRequest(env, { ...pull, openAsUserId: 'user_1' }) + + expect(calls.map((call) => `${call.method} ${call.path} as ${call.token}`)).toEqual([ + 'POST /repos/acme/shop/pulls as person-token', + ]) + + expect(summary.authorLogin).toBe('octocat') + }) + + test('nobody, when the person named has no GitHub account connected: nothing is sent', async () => { + const env = fakeEnv({ GIT_ACCESS: fixedGitAccess('app-token'), GITHUB_PEOPLE: people }) + const calls = fakeGithub(() => opened('shuttle-codes[bot]')) + + const error = await rejection(createPullRequest(env, { ...pull, openAsUserId: 'user_2' })) + + expect(error.message).toBe(GITHUB_NOT_CONNECTED_TO_OPEN) + expect(calls).toEqual([]) + }) + + test('nobody, when GitHub refuses the person: the App does not open it in their place', async () => { + const env = fakeEnv({ GIT_ACCESS: fixedGitAccess('app-token'), GITHUB_PEOPLE: people }) + const calls = fakeGithub(() => new Response('{}', { status: 403 })) + + const error = await rejection(createPullRequest(env, { ...pull, openAsUserId: 'user_1' })) + + expect(error.message).toContain('would not open the pull request as you (403)') + expect(error.message).toContain('acme/shop') + expect(calls.map((call) => call.token)).toEqual(['person-token']) + }) + + test('a refusal of the App is not retried with the host’s own token', async () => { + const env = fakeEnv({ + GIT_ACCESS: { ...fixedGitAccess('app-token'), userToken: () => 'host-wide-token' }, + }) + + const calls = fakeGithub(() => new Response('{}', { status: 403 })) + + await rejection(createPullRequest(env, pull)) + + expect(calls.map((call) => call.token)).toEqual(['app-token']) + }) + + test('a pull request the branch already has is found as the person who asked', async () => { + const env = fakeEnv({ GIT_ACCESS: fixedGitAccess('app-token'), GITHUB_PEOPLE: people }) + + const calls = fakeGithub((seen) => + seen.method === 'POST' ? new Response('{}', { status: 422 }) : Response.json([]), + ) + + await rejection(createPullRequest(env, { ...pull, openAsUserId: 'user_1' })) + + expect(calls.map((call) => `${call.method} as ${call.token}`)).toEqual([ + 'POST as person-token', + 'GET as person-token', + ]) + }) +}) + +describe('who a published commit is by', () => { + test('no author or committer is sent, so GitHub credits and signs it as the App', async () => { + const env = fakeEnv({ GIT_ACCESS: fixedGitAccess('app-token'), GITHUB_PEOPLE: people }) + + const calls = fakeGithub((seen) => { + if (seen.path.endsWith('/git/commits/base')) { + return Response.json({ tree: { sha: 'base-tree' } }) + } + + if (seen.path.includes('/git/ref/heads/')) { + return new Response('missing', { status: 404 }) + } + + return Response.json({ sha: 'made' }) + }) + + await commitChangeset(env, { + runId: 'run-1', + repo: shop, + baseSha: 'base', + branch: 'shuttle/run-1/shop', + files: [{ path: 'a.txt', status: 'added', content: 'a\n', mode: '100644' }], + message: 'feat: a change', + }) + + const commit = calls.find( + (call) => call.method === 'POST' && call.path === '/repos/acme/shop/git/commits', + ) + + expect(JSON.parse(commit?.body ?? '{}')).toEqual({ + message: 'feat: a change', + tree: 'made', + parents: ['base'], + }) + + expect(calls.every((call) => call.token === 'app-token')).toBe(true) + }) +}) diff --git a/packages/git/src/github/person.ts b/packages/git/src/github/person.ts new file mode 100644 index 0000000..9013f96 --- /dev/null +++ b/packages/git/src/github/person.ts @@ -0,0 +1,26 @@ +import { z } from 'zod' + +import type { GitEnv } from '../env' +import { githubFetch } from './client' + +const PersonSchema = z.object({ login: z.string() }) + +/** + * The GitHub login a person's token acts as: who a pull request opened with it is by. Null when + * the token is empty or GitHub no longer accepts it. + */ +export async function githubLoginOf(env: GitEnv, token: string): Promise { + if (token.trim() === '') { + return null + } + + const response = await githubFetch(env, '/user', { token }) + + if (!response.ok) { + return null + } + + const person = PersonSchema.safeParse(await response.json().catch(() => null)) + + return person.success ? person.data.login : null +} diff --git a/packages/git/src/github/pulls.ts b/packages/git/src/github/pulls.ts index a05c508..ff4b3a6 100644 --- a/packages/git/src/github/pulls.ts +++ b/packages/git/src/github/pulls.ts @@ -7,7 +7,6 @@ import { githubFetch, githubGraphql, githubGraphqlWithToken, - githubUserToken, GithubGraphqlError, type GithubCoordinates, type GithubTarget, @@ -47,6 +46,11 @@ export interface CreatePullRequestInput { readonly head: string readonly base: string readonly draft?: boolean + /** + * The host's user who opens it, with their own GitHub token (`GithubPeople`). Absent or null: + * the App opens it. A person the host cannot act as fails the call. + */ + readonly openAsUserId?: string | null } export interface PullReviewComment { @@ -138,6 +142,29 @@ export interface GithubStack { const STACKS_API_VERSION = '2026-03-10' +/** What a pull request that was to be opened as a person says when Shuttle cannot act as them. */ +export const GITHUB_NOT_CONNECTED_TO_OPEN = + 'Your GitHub account is not connected, so the pull request cannot be opened as you. Connect it, or open the pull request as Shuttle.' + +/** True for a string that is neither missing nor empty. */ +function isPresent(value: string | undefined | null): value is string { + return value !== undefined && value !== null && value !== '' +} + +/** + * The GitHub token of the host's user `userId`, to open a pull request as them. Throws when the + * host cannot act as them: they asked to open it themselves, so the App does not stand in. + */ +async function personTokenOf(env: GitEnv, userId: string): Promise { + const token = (await env.GITHUB_PEOPLE?.tokenOf(userId))?.trim() ?? '' + + if (token === '') { + throw new Error(GITHUB_NOT_CONNECTED_TO_OPEN) + } + + return token +} + export async function createPullRequest( env: GitEnv, input: CreatePullRequestInput, @@ -160,18 +187,12 @@ export async function createPullRequest( body: payload, }) - const appToken = await getRepoToken(env, input.target, 'write') - let token = appToken - let response = await postPull(token) + const person = isPresent(input.openAsUserId) ? await personTokenOf(env, input.openAsUserId) : null - if (response.status === 403) { - const user = githubUserToken(env) - - if (user !== null) { - token = user - response = await postPull(user) - } - } + // Opened by the App, or by the person who asked to open it themselves. One is never swapped + // for the other here: whoever opens a pull request is who a squash merge of it is credited to. + const token = person ?? (await getRepoToken(env, input.target, 'write')) + const response = await postPull(token) if (response.status === 422) { const existing = await findOpenPullByHead(env, repo, input.head, token) @@ -182,6 +203,12 @@ export async function createPullRequest( } if (!response.ok) { + if (person !== null) { + throw new Error( + `GitHub would not open the pull request as you (${response.status}). Check that your GitHub account can open pull requests in ${repo.owner}/${repo.name}, or open it as Shuttle.`, + ) + } + const detail = response.status === 403 ? ' — grant the GitHub App Pull requests (read/write) permission and approve the install update' diff --git a/packages/react/src/features/sessions/pull-publish-card.test.tsx b/packages/react/src/features/sessions/pull-publish-card.test.tsx new file mode 100644 index 0000000..42930a6 --- /dev/null +++ b/packages/react/src/features/sessions/pull-publish-card.test.tsx @@ -0,0 +1,128 @@ +import { describe, expect, test } from 'bun:test' + +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { renderToStaticMarkup } from 'react-dom/server' + +import type { PullRequestOpeners } from '@shuttle/api' + +import { createShuttleHost, ShuttleProvider, type ShuttleIdentity } from '../../shuttle' +import type { ShuttleRouter } from '../../shuttle/router' +import { PullPublishCard } from './pull-publish-card' +import type { FeedItem } from './session-feed' + +const RUN_ID = 'session_1' + +const host = createShuttleHost({ baseUrl: 'https://shuttle.example' }) + +const router: ShuttleRouter = { + Link: () => null, + navigate: () => {}, + location: { page: 'session', sessionId: RUN_ID }, +} + +const identity: ShuttleIdentity = { + tenant: { + user: { id: 'user_1', name: 'Ada', email: 'ada@example.com' }, + org: { id: 'org_1', role: 'owner' }, + runs: { workspace: 'w', personal: 'm', pulls: 'p', playbook: 'b' }, + }, + listPeople: async () => [], +} + +type Question = Extract + +function card(overrides: Partial = {}): Question { + return { + kind: 'question', + id: 'q1', + seq: 1, + ts: 0, + threadId: 'thr_1', + approvalId: 'pr_publish_1', + title: 'Publish pull requests?', + defaults: { title: 'feat: a change', body: '' }, + ...overrides, + } +} + +/** The card as it first draws, knowing `openers` (or not yet, when undefined). */ +function draw(item: Question, openers: PullRequestOpeners | undefined, readOnly = false): string { + const queryClient = new QueryClient() + + if (openers !== undefined) { + queryClient.setQueryData( + host.api.sessions.pullRequestOpener.queryOptions({ input: { id: RUN_ID } }).queryKey, + openers, + ) + } + + return renderToStaticMarkup( + + + {} }} + /> + + , + ) +} + +/** The label of the option that is checked in the "Open as" choice, if it is drawn. */ +function checked(html: string): string | null { + return /role="radio" aria-checked="true"[^>]*>([^<]*) { + test('starts on the person approving it, named by their GitHub login', () => { + const html = draw(card(), linked) + + expect(html).toContain('Open as') + expect(checked(html)).toBe('@octocat') + expect(html).toContain('>Shuttle') + expect(html).toContain('credited to you, with Shuttle as co-author') + }) + + test('is not offered to someone with no GitHub account connected, who is told why', () => { + const html = draw(card(), { you: null, connectable: true }) + + expect(html).not.toContain('role="radio"') + expect(html).toContain('Shuttle will open this pull request') + expect(html).toContain('Connect your GitHub account') + }) + + test('says nothing where the host cannot act as its people at all', () => { + const html = draw(card(), { you: null, connectable: false }) + + expect(html).not.toContain('role="radio"') + expect(html).not.toContain('Connect your GitHub account') + }) + + test('is not drawn before who they are on GitHub is known', () => { + expect(draw(card(), undefined)).not.toContain('Open as') + }) + + test('is not offered for a pull request that already exists: it keeps who opened it', () => { + const html = draw( + card({ defaults: { title: 't', body: '', existingPullLabel: 'acme/shop#7' } }), + linked, + ) + + expect(html).toContain('Push update') + expect(html).not.toContain('Open as') + }) + + test('is not offered for a publish that opens no pull request', () => { + const html = draw(card({ defaults: { title: 't', body: '', branchOnly: true } }), linked) + + expect(html).not.toContain('Open as') + }) + + test('is gone once the card is decided', () => { + const html = draw(card({ decision: { answer: 'publish', ts: 0 } }), linked) + + expect(html).not.toContain('Open as') + }) +}) diff --git a/packages/react/src/features/sessions/pull-publish-card.tsx b/packages/react/src/features/sessions/pull-publish-card.tsx index bc6b7e9..1cdc02c 100644 --- a/packages/react/src/features/sessions/pull-publish-card.tsx +++ b/packages/react/src/features/sessions/pull-publish-card.tsx @@ -1,16 +1,19 @@ -import { useMutation } from '@tanstack/react-query' +import { useMutation, useQuery } from '@tanstack/react-query' import { ExternalLink, GitBranch, GitPullRequest, LoaderCircle } from 'lucide-react' import { useState } from 'react' +import type { JsonObject } from '@swirls/looms/core' + import { Button } from '../../components/ui/button' import { Textarea } from '../../components/ui/textarea' import { cn } from '../../lib/cn' import { jsonText } from '../../lib/json' import { clockTime } from '../../lib/time' import { useNow } from '../../lib/use-now' -import { useShuttleHost } from '../../shuttle' +import { useApi, useShuttleHost } from '../../shuttle' import type { AgentIdentity } from './agents' import { agentRole } from './agents' +import { openAsChoice, type OpenAs, type PullRequestOpeners } from './pull-request-opener' import type { FeedItem, PublishedBranch, PublishedPull } from './session-feed' import { decideStructuredApproval } from './signals' @@ -40,22 +43,46 @@ export function PullPublishCard({ const existingBranchName = existingBranch(item) const branchOnly = isBranchOnly(item) + // Who opens it is only a question for a pull request that does not exist yet: GitHub keeps + // whoever opened one, and a store branch has no opener. + const opensPull = existing === null && existingBranchName === null && !branchOnly + const api = useApi() + + const openers = useQuery({ + ...api.sessions.pullRequestOpener.queryOptions({ input: { id: context.runId } }), + enabled: opensPull && item.decision === undefined && !context.readOnly, + staleTime: 60_000, + retry: false, + }).data + + const [picked, setPicked] = useState(null) + const openAs = opensPull ? openAsChoice(openers, picked) : null + const decide = useMutation({ - mutationFn: (actionId: 'draft' | 'publish' | 'update' | 'discard') => - actionId === 'discard' - ? decideStructuredApproval(host, context.runId, item.approvalId, { - actionId: 'discard', - outcome: 'reject', - }) - : decideStructuredApproval(host, context.runId, item.approvalId, { - actionId, - outcome: 'approve', - payload: { - title: title.trim() === '' ? 'Shuttle changes' : title.trim(), - body, - draft: actionId === 'update' ? (existing?.draft ?? true) : actionId === 'draft', - }, - }), + mutationFn: (actionId: 'draft' | 'publish' | 'update' | 'discard') => { + if (actionId === 'discard') { + return decideStructuredApproval(host, context.runId, item.approvalId, { + actionId: 'discard', + outcome: 'reject', + }) + } + + const fields = { + title: title.trim() === '' ? 'Shuttle changes' : title.trim(), + body, + draft: actionId === 'update' ? (existing?.draft ?? true) : actionId === 'draft', + } + + // The choice is left out when there is none to make: the session then opens it as the + // approver if it can, and as Shuttle if not. + const payload: JsonObject = openAs === null ? fields : { ...fields, openAs } + + return decideStructuredApproval(host, context.runId, item.approvalId, { + actionId, + outcome: 'approve', + payload, + }) + }, }) // Once the session has the decision the card stays locked: the feed replaces it with the outcome. @@ -161,6 +188,14 @@ export function PullPublishCard({ placeholder="Summary, testing, risks…" className="min-h-24 resize-none text-[13px]" /> + {opensPull ? ( + + ) : null}
{error !== undefined && error !== '' ? ( @@ -226,6 +261,77 @@ export function PullPublishCard({ ) } +/** + * Who the pull request is opened by: the person approving it, or Shuttle. Whoever opens it is + * who GitHub credits a squash merge to; the commits are Shuttle's either way. + */ +function OpenAsChoice({ + openers, + value, + disabled, + onChange, +}: { + openers: PullRequestOpeners | undefined + value: OpenAs | null + disabled: boolean + onChange: (value: OpenAs) => void +}) { + if (openers === undefined) { + return null + } + + if (openers.you === null) { + return openers.connectable ? ( +

+ Shuttle will open this pull request. Connect your GitHub account to open pull requests as + yourself. +

+ ) : null + } + + const options: readonly { value: OpenAs; label: string }[] = [ + { value: 'you', label: `@${openers.you.login}` }, + { value: 'shuttle', label: 'Shuttle' }, + ] + + return ( +
+ + Open as + +
+ {options.map((option) => ( + + ))} +
+ + {value === 'you' + ? 'A squash merge is credited to you, with Shuttle as co-author.' + : 'A squash merge is credited to Shuttle.'} + +
+ ) +} + /** The pull request this card would push to, when the layer already has one. */ function existingPull( item: Extract, diff --git a/packages/react/src/features/sessions/pull-request-opener.test.ts b/packages/react/src/features/sessions/pull-request-opener.test.ts new file mode 100644 index 0000000..96540dd --- /dev/null +++ b/packages/react/src/features/sessions/pull-request-opener.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, test } from 'bun:test' + +import { openAsChoice } from './pull-request-opener' + +const linked = { you: { login: 'octocat' }, connectable: true } + +describe('who the publish card opens a pull request as', () => { + test('the person approving it, when GitHub is connected', () => { + expect(openAsChoice(linked, null)).toBe('you') + }) + + test('Shuttle, once they pick it, and themselves again if they change their mind', () => { + expect(openAsChoice(linked, 'shuttle')).toBe('shuttle') + expect(openAsChoice(linked, 'you')).toBe('you') + }) + + test('no choice is sent while who they are on GitHub is not known', () => { + expect(openAsChoice(undefined, null)).toBeNull() + }) + + test('no choice is sent by someone with no GitHub account connected', () => { + expect(openAsChoice({ you: null, connectable: true }, null)).toBeNull() + expect(openAsChoice({ you: null, connectable: false }, 'you')).toBeNull() + }) +}) diff --git a/packages/react/src/features/sessions/pull-request-opener.ts b/packages/react/src/features/sessions/pull-request-opener.ts new file mode 100644 index 0000000..5c013fa --- /dev/null +++ b/packages/react/src/features/sessions/pull-request-opener.ts @@ -0,0 +1,24 @@ +import type { PullRequestOpener, PullRequestOpeners } from '@shuttle/api' + +export type { PullRequestOpeners } + +/** Who a pull request is opened by: the person approving it, or Shuttle. */ +export type OpenAs = PullRequestOpener + +/** + * Who the publish card says opens the pull request. The person approving it, unless they picked + * Shuttle; Shuttle is not offered as a choice to someone the host cannot act as on GitHub. + * + * Null when there is no choice to send: who they can open it as is not known yet, or it can + * only be Shuttle. The session then settles it the same way. + */ +export function openAsChoice( + openers: PullRequestOpeners | undefined, + picked: OpenAs | null, +): OpenAs | null { + if (openers === undefined || openers.you === null) { + return null + } + + return picked ?? 'you' +}