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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/open-pull-requests-as-approver.md
Original file line number Diff line number Diff line change
@@ -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.
65 changes: 64 additions & 1 deletion apps/worker/src/github/user-token.test.ts
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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()
})
})
48 changes: 48 additions & 0 deletions apps/worker/src/github/user-token.ts
Original file line number Diff line number Diff line change
@@ -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: {
Expand Down Expand Up @@ -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<string | null> {
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'
24 changes: 22 additions & 2 deletions apps/worker/src/host.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand Down Expand Up @@ -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 {
Expand All @@ -46,6 +65,7 @@ export function workerHost(env: ShuttleEnv): ShuttleHost {
ports: {
identity: workerIdentity(env),
people: workerPeople(env),
githubPeople: workerGithubPeople(env),
previews: workerPreviews(env),
},
}
Expand Down
37 changes: 35 additions & 2 deletions docs/hosting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. |
Expand All @@ -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
}
Expand Down Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions packages/api/src/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ export const SessionAccess = z.object({
})
export type SessionAccess = z.infer<typeof SessionAccess>

/** 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<typeof PullRequestOpener>

/** 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<typeof PullRequestOpeners>

export const INTERJECTION_KINDS = [
'question',
'idea',
Expand Down Expand Up @@ -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) }))
Expand Down
86 changes: 85 additions & 1 deletion packages/engine/src/api/serve.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, test } from 'bun:test'
import { afterEach, describe, expect, test } from 'bun:test'

import { z } from 'zod'

Expand Down Expand Up @@ -229,3 +229,87 @@ describe('serveShuttle', () => {
})
})
})

function hostWithPeople(tokens: Readonly<Record<string, string>>): 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<Record<string, string>>): 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)
})
})
Loading
Loading