From 4be2bf22c9a59e7253bb8f9553241da5315afd7e Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Wed, 11 Nov 2026 16:13:50 +0000 Subject: [PATCH 1/3] feat(eve): add a testing entry backed by emulate An eval for an eve agent had three options: run against GitHub, write a fetch stub by hand, or use eve's tool stubs, which skip the tool's code. None of them says who is talking to the agent. @github-tools/eve-extension/testing runs evals against vercel-labs/emulate, a stateful GitHub emulator, pinned at 0.13.1. emulateGithub() starts it from an eval's setup with a Vercel Connect emulator, and points the agent at both. An eval creates an issue as one person, asks the agent as another, and reads the result back from the emulator. What the package adds to emulate, in testing/github: - A role guard. emulate checks a personal token's role for contents, refs and admin routes only, so a reader could label, close, merge and release. Where GitHub accepts a request and ignores fields, the guard removes them: the labels, assignees and milestone a person without Triage sends with an issue. An unknown token gets 401. - A supplement: the 26 REST routes and the 15 GraphQL documents the SDK sends that emulate doesn't answer, including gists, notifications, reactions, commit statuses, sub-issues and security alerts. It registers before emulate's routes, whose /commits/:ref{.+} would otherwise answer /commits/{ref}/status. - Request fixes, for routes emulate answers differently from GitHub: a write with no body, review comments placed by line, the tag a release creates, and the collaborator permission route, which now reports the roles the guard enforces. - Webhook payload fixes: issue.pull_request on a pull request's issue_comment, and the action some payloads lack. The rest of the entry: - A Connect emulator for the token, authorize, connector metadata and revoke routes. An App token is narrowed to the scopes the request asks for, and a sign-in registers its token with the GitHub emulator. - A fetch redirect that emulateGithub names in NODE_OPTIONS, so no agent file imports it. If a worker thread of the eval process starts without it, the run stops before the first eval. - @github-tools/eve-extension/testing/agent: evalIdentity(), which names the caller of an eval from a header on a local eve server only, and underEmulation(), which replaces the webhook verifier of connectGitHubCredentials. testing/coverage.test.ts runs all 97 tools against the emulator, through @github-tools/sdk/eve-runtime. It fails on a GraphQL document the emulator doesn't know, on a write GitHub refuses a reader that the emulator lets through, on a field GitHub ignores from a reader that the emulator applies, and with "delete this route" when emulate answers a supplement route itself. Adding a tool without a sample input there is a type error. tests/eve-emulate uses the entry end to end with mockModel: a call as a named person, a reader refused, a sign-in, a revoked token, and a comment that reaches the agent as a signed webhook and gets a reply. @emulators/core and @emulators/github are devDependencies of the extension and optional peers. The emulate package isn't needed: the entry calls createServer, since createEmulator refuses a plugin. The two packages are imported through a specifier a bundler can't follow, because eve bundles what an eval imports from a workspace-linked package and @emulators/core reads files next to itself at load. The in-repo eval agents still use their own stubs. Moving them is a separate change. --- .changeset/eve-testing-kit.md | 41 ++ .github/CONTRIBUTING.md | 5 +- AGENTS.md | 17 +- .../docs/content/docs/4.integrations/2.eve.md | 70 +++ apps/docs/content/docs/5.guides/1.index.md | 1 + .../content/docs/5.guides/8.test-an-agent.md | 260 +++++++++++ apps/docs/skills/github-tools-agents/SKILL.md | 2 + .../references/eve-extension.md | 56 +++ packages/github-tools-eve-extension/README.md | 61 ++- .../eslint.config.mjs | 2 +- .../github-tools-eve-extension/package.json | 29 +- .../testing/agent.ts | 45 ++ .../testing/client.ts | 251 +++++++++++ .../testing/connect/emulator.test.ts | 96 ++++ .../testing/connect/emulator.ts | 136 ++++++ .../testing/coverage.test.ts | 421 ++++++++++++++++++ .../testing/emulate.ts | 137 ++++++ .../testing/emulators.ts | 10 + .../github-tools-eve-extension/testing/env.ts | 12 + .../testing/github/access.ts | 136 ++++++ .../testing/github/emulator.test.ts | 210 +++++++++ .../testing/github/emulator.ts | 309 +++++++++++++ .../testing/github/fixes.ts | 71 +++ .../testing/github/role-guard.ts | 126 ++++++ .../testing/github/supplement/context.ts | 34 ++ .../testing/github/supplement/discussions.ts | 47 ++ .../testing/github/supplement/gists.ts | 143 ++++++ .../testing/github/supplement/graphql.ts | 394 ++++++++++++++++ .../testing/github/supplement/index.ts | 35 ++ .../github/supplement/notifications.ts | 97 ++++ .../testing/github/supplement/reactions.ts | 72 +++ .../testing/github/supplement/repository.ts | 53 +++ .../testing/github/supplement/security.ts | 168 +++++++ .../testing/github/supplement/statuses.ts | 75 ++++ .../testing/github/supplement/sub-issues.ts | 47 ++ .../testing/github/supplement/webhooks.ts | 41 ++ .../testing/index.ts | 22 + .../testing/redirect.test.ts | 70 +++ .../testing/redirect.ts | 38 ++ .../github-tools-eve-extension/tsconfig.json | 4 +- .../tsconfig.testing.json | 10 + .../vitest.config.ts | 8 + pnpm-lock.yaml | 48 ++ tests/eve-emulate/README.md | 21 + tests/eve-emulate/agent/agent.ts | 24 + tests/eve-emulate/agent/channels/eve.ts | 4 + tests/eve-emulate/agent/channels/github.ts | 9 + tests/eve-emulate/agent/extensions/github.ts | 11 + tests/eve-emulate/agent/instructions.md | 1 + tests/eve-emulate/evals/evals.config.ts | 20 + tests/eve-emulate/evals/identity.eval.ts | 36 ++ tests/eve-emulate/evals/sign-in.eval.ts | 30 ++ tests/eve-emulate/evals/webhook.eval.ts | 62 +++ tests/eve-emulate/package.json | 22 + tests/eve-emulate/scripts/probe.mjs | 21 + turbo.json | 2 +- 56 files changed, 4159 insertions(+), 14 deletions(-) create mode 100644 .changeset/eve-testing-kit.md create mode 100644 apps/docs/content/docs/5.guides/8.test-an-agent.md create mode 100644 packages/github-tools-eve-extension/testing/agent.ts create mode 100644 packages/github-tools-eve-extension/testing/client.ts create mode 100644 packages/github-tools-eve-extension/testing/connect/emulator.test.ts create mode 100644 packages/github-tools-eve-extension/testing/connect/emulator.ts create mode 100644 packages/github-tools-eve-extension/testing/coverage.test.ts create mode 100644 packages/github-tools-eve-extension/testing/emulate.ts create mode 100644 packages/github-tools-eve-extension/testing/emulators.ts create mode 100644 packages/github-tools-eve-extension/testing/env.ts create mode 100644 packages/github-tools-eve-extension/testing/github/access.ts create mode 100644 packages/github-tools-eve-extension/testing/github/emulator.test.ts create mode 100644 packages/github-tools-eve-extension/testing/github/emulator.ts create mode 100644 packages/github-tools-eve-extension/testing/github/fixes.ts create mode 100644 packages/github-tools-eve-extension/testing/github/role-guard.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/context.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/discussions.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/gists.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/graphql.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/index.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/notifications.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/reactions.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/repository.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/security.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/statuses.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/sub-issues.ts create mode 100644 packages/github-tools-eve-extension/testing/github/supplement/webhooks.ts create mode 100644 packages/github-tools-eve-extension/testing/index.ts create mode 100644 packages/github-tools-eve-extension/testing/redirect.test.ts create mode 100644 packages/github-tools-eve-extension/testing/redirect.ts create mode 100644 packages/github-tools-eve-extension/tsconfig.testing.json create mode 100644 packages/github-tools-eve-extension/vitest.config.ts create mode 100644 tests/eve-emulate/README.md create mode 100644 tests/eve-emulate/agent/agent.ts create mode 100644 tests/eve-emulate/agent/channels/eve.ts create mode 100644 tests/eve-emulate/agent/channels/github.ts create mode 100644 tests/eve-emulate/agent/extensions/github.ts create mode 100644 tests/eve-emulate/agent/instructions.md create mode 100644 tests/eve-emulate/evals/evals.config.ts create mode 100644 tests/eve-emulate/evals/identity.eval.ts create mode 100644 tests/eve-emulate/evals/sign-in.eval.ts create mode 100644 tests/eve-emulate/evals/webhook.eval.ts create mode 100644 tests/eve-emulate/package.json create mode 100644 tests/eve-emulate/scripts/probe.mjs diff --git a/.changeset/eve-testing-kit.md b/.changeset/eve-testing-kit.md new file mode 100644 index 0000000..dc625ff --- /dev/null +++ b/.changeset/eve-testing-kit.md @@ -0,0 +1,41 @@ +--- +'@github-tools/eve-extension': minor +--- + +Test an eve agent without GitHub. + +`@github-tools/eve-extension/testing` runs an agent's evals against a local GitHub emulator, [`vercel-labs/emulate`](https://github.com/vercel-labs/emulate), and a Vercel Connect emulator. An eval creates an issue as one person, asks the agent as another, and reads the result back. No request reaches `api.github.com` or `api.vercel.com`, so an eval needs no GitHub token and makes no real write. + +```ts +// evals/evals.config.ts +import { defineEvalConfig } from 'eve/evals' +import { emulateGithub } from '@github-tools/eve-extension/testing' + +export default defineEvalConfig({ + setup: () => emulateGithub({ + repositories: { 'acme/web': { labels: ['bug'] } }, + people: { alice: { role: 'write' }, bob: { role: 'read' } }, + }), + teardown: context => context?.close(), +}) +``` + +```ts +// evals/triage.eval.ts +const web = t.context.github.repo('acme/web') +const issue = await web.as('bob').createIssue({ title: 'Crash on save' }) + +const turn = await t.send(`Triage acme/web#${issue.number}`, as('alice')) + +turn.calledTool('github__addLabels') +t.check((await web.issue(issue.number)).labels, includes('bug')) +``` + +What it adds: + +- **All 97 tools run against the emulator.** The package adds what emulate 0.13.1 lacks: the REST routes and GraphQL queries the tools call, and the role checks GitHub makes for a personal token. A reader's label or merge is refused with `403`, and the labels a reader sends with a new issue are dropped, as on GitHub. +- **Named people.** Each person is a GitHub user with a role and the eve principal of the same name. `as('alice')` sends a message or answers an approval as her, and `evalIdentity()` from `@github-tools/eve-extension/testing/agent` names the caller in the eve channel's auth. It accepts nothing outside a local eve server. +- **Vercel Connect.** App tokens are narrowed to the scopes the mounted tools ask for, a person with `authorized: false` signs in first, and `t.context.connect.revoke(person)` invalidates their token. +- **The GitHub channel.** After `t.context.github.deliverWebhooksTo(t)`, a comment an eval creates reaches the agent as a signed webhook, and `waitForComment` reads the reply. `underEmulation()` adapts `connectGitHubCredentials` for the run. + +Install `@emulators/core@0.13.1` and `@emulators/github@0.13.1` as development dependencies to use it. Nothing changes for an agent that doesn't. See [Test an agent](https://github-tools.com/guides/test-an-agent). diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 297ed91..b90db94 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -67,8 +67,9 @@ Every tool splits into a **core** function (pure logic) and a **tool factory** ( - `apps/docs/content/docs/3.core/3.approval.md` if the write tool joins `AUTO_APPROVAL_TOOLS` - `apps/docs/content/docs/3.core/5.context.md` if the tool is a context tool or changes default payload behavior (`detail`, `includePatch`, ranges) - `packages/github-tools/README.md` (tool tables, preset tables, write tools list, token permissions) — the root `README.md` is a symlink to this file, no separate edit needed -6. **Changeset** — `pnpm changeset` (`minor`) -7. Run checks: +6. **Emulator** — add a sample input for the tool to `SAMPLES` in `packages/github-tools-eve-extension/testing/coverage.test.ts`, which runs every tool against the GitHub emulator in that folder (the file doesn't type-check without it, once the SDK is built). When the tool calls a route or sends a GraphQL document emulate doesn't answer, add it to `testing/github/supplement/`. For a write tool, either the test's reader case gets `403`, which may need a rule in `testing/github/role-guard.ts`, or the tool joins `READER_MAY` with the reason GitHub allows it, and a `holds` check of the result when GitHub accepts the call and ignores part of it +7. **Changeset** — `pnpm changeset` (`minor`) +8. Run checks: ```sh pnpm build && pnpm lint && pnpm typecheck && pnpm test diff --git a/AGENTS.md b/AGENTS.md index cc4f3f0..2971416 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ pnpm build # Build all packages (turbo) pnpm lint # Lint all packages pnpm typecheck # Type-check all packages -pnpm test # SDK vitest + eve extension evals (examples/eve-smoke, tests/eve-act-as, tests/eve-auto) + the eve-bench gh classifier test +pnpm test # SDK and eve extension vitest + eve extension evals (examples/eve-smoke, tests/eve-act-as, tests/eve-auto, tests/eve-emulate) + the eve-bench gh classifier test pnpm dev # Run the chat app in dev mode pnpm docs:dev # Run the docs site in dev mode @@ -24,7 +24,7 @@ pnpm version-packages # Apply changesets pnpm release # Build SDK + publish ``` -Verify changes with `pnpm build && pnpm lint && pnpm typecheck && pnpm test`. The SDK has vitest (`packages/github-tools/**/*.test.ts`). The eve extension is covered by `examples/eve-smoke`: `eve eval` mounts the built extension with a `mockModel`, a fixed routing model, and an in-process `api.github.com` stub, and checks routing, registration, execution, and approval gating. +Verify changes with `pnpm build && pnpm lint && pnpm typecheck && pnpm test`. The SDK has vitest (`packages/github-tools/**/*.test.ts`), and so does the extension's testing entry (`packages/github-tools-eve-extension/testing/**/*.test.ts`). The eve extension is covered by `examples/eve-smoke`: `eve eval` mounts the built extension with a `mockModel`, a fixed routing model, and an in-process `api.github.com` stub, and checks routing, registration, execution, and approval gating. ## Monorepo Structure @@ -34,7 +34,7 @@ pnpm workspaces + Turborepo, with published packages, apps, and examples: - **`packages/github-tools-eve-extension`** — the published eve extension (`@github-tools/eve-extension`). - **`examples/*`** — consumer integrations used for development, smoke tests (`examples/eve-smoke`), and canary checks. - **`examples/eve`** — the Slack and GitHub agent people clone or deploy on its own (Deploy button, `giget`), so it must work outside the monorepo: no `workspace:*`, no root config. It depends on `@github-tools/eve-extension` from npm as `latest`, because Changesets rewrites a semver range to the unreleased version in the Version PR, which breaks `pnpm install --frozen-lockfile`. Only use released options in it; to try unreleased extension code, use `examples/eve-smoke` or `tests/*`. After a release, move its lockfile entry to the new version so CI builds against it: set the dependency to that version, run `pnpm install`, set it back to `latest` and run `pnpm install` again. `pnpm update --filter` also refreshes unrelated transitive dependencies. -- **`tests/*`** — eval-only agents that are not usable examples: `tests/eve-act-as` covers the eve extension's `actAs`, `approvers` and `githubChannel`'s `respondTo`, and `tests/eve-auto` covers `preset: 'auto'` and `requireApproval: 'auto'`, both with stubbed Vercel Connect and GitHub. +- **`tests/*`** — eval-only agents that are not usable examples: `tests/eve-act-as` covers the eve extension's `actAs`, `approvers` and `githubChannel`'s `respondTo`, and `tests/eve-auto` covers `preset: 'auto'` and `requireApproval: 'auto'`, both with stubbed Vercel Connect and GitHub. `tests/eve-emulate` runs the extension's testing entry end to end, against the GitHub and Vercel Connect emulators. - **`apps/chat`** — Nuxt 4 demo app with NuxtHub (SQLite + blob), GitHub OAuth, dual-mode agent (standard `ToolLoopAgent` vs durable `WorkflowAgent`). - **`apps/docs`** — Nuxt 4 docs site built on Docus. Also publishes a consumer-facing Agent Skill at `apps/docs/skills/github-tools-agents/` (served via `/.well-known/skills/`, see `apps/docs/content/docs/1.start/4.agent-skills.md`). @@ -112,6 +112,17 @@ Ten presets (`code-review`, `issue-triage`, `repo-explorer`, `ci-ops`, `security `channels/index.ts` (`@github-tools/eve-extension/channels`, the `githubChannel` wrapper with `respondTo`) is not part of the mounted extension: `tsc -p tsconfig.channels.json` compiles it to `channels/dist`. Keep it out of `extension/` and `dist/`. eve binds every module under `dist/extension` to a mount, so an agent with two mounts of the package can't import one from a channel file, and building an agent that uses the workspace extension rebuilds `dist/` and deletes anything else in it. A scheduled canary (`.github/workflows/eve-canary.yml`) builds `examples/eve` and runs that smoke eval against a coherent `eve@latest` / `ai@latest` pair. +`testing/` (`@github-tools/eve-extension/testing` for eval files, `/testing/agent` for agent files) is compiled the same way, by `tsc -p tsconfig.testing.json` to `testing/dist`. It runs evals against [`vercel-labs/emulate`](https://github.com/vercel-labs/emulate), pinned exactly, plus what emulate lacks: + +- `testing/github/role-guard.ts`: the role a personal token needs on each write route, and the body fields GitHub ignores from a person below Triage instead of refusing the request. emulate checks a role for contents, refs and admin routes only. +- `testing/github/supplement/`: the REST routes and the GraphQL documents the SDK sends that emulate doesn't answer. They register before emulate's routes, because its router takes the first match. +- `testing/github/fixes.ts`: requests emulate has a route for and answers differently from GitHub. +- `testing/connect/`: the Vercel Connect routes `@vercel/connect` calls. + +`testing/coverage.test.ts` is the contract: it runs every tool against the emulator, fails on a GraphQL document the emulator doesn't know, checks that a reader is refused every write GitHub refuses and that the fields GitHub ignores from a reader stay unset, and fails with "delete this route" when emulate answers a supplement route itself. It reaches the tools through `@github-tools/sdk/eve-runtime` (`listEveToolDescriptors`, `executeGithubEveTool`), so it runs against the SDK's build, and the SDK has no dependency on the extension. A bump of the emulate pin is its own pull request. + +`testing/emulators.ts` imports `@emulators/*` through a specifier a bundler can't follow, and `emulateGithub` finds the redirect with `import.meta.resolve`. Keep both: eve bundles what an eval imports from a workspace-linked package, and a bundled `@emulators/core` can't find the files it reads at load. + ## Chat App Architecture (`apps/chat`) - **Frontend**: Vue 3 + `@nuxt/ui`. Chat pages at `app/pages/chat/[id].vue` with tool invocation rendering and approval UI. diff --git a/apps/docs/content/docs/4.integrations/2.eve.md b/apps/docs/content/docs/4.integrations/2.eve.md index 4cb2300..0e43a02 100644 --- a/apps/docs/content/docs/4.integrations/2.eve.md +++ b/apps/docs/content/docs/4.integrations/2.eve.md @@ -261,6 +261,76 @@ export default githubExtension({ Pair it with `guardrails`, and try the schedule with `dryRun: true` first. +## Test your agent + +`@github-tools/eve-extension/testing` runs your evals against a local GitHub emulator, [`vercel-labs/emulate`](https://github.com/vercel-labs/emulate), with the routes, GraphQL queries and role checks the tools need added to it, and a Vercel Connect emulator beside it. An eval creates an issue as one person, asks the agent as another, and reads the result back, with no GitHub token and no real write. + +Install the emulator as a development dependency: + +:::code-group +```bash [pnpm] +pnpm add -D @emulators/core@0.13.1 @emulators/github@0.13.1 +``` +```bash [npm] +npm install -D @emulators/core@0.13.1 @emulators/github@0.13.1 +``` +```bash [yarn] +yarn add -D @emulators/core@0.13.1 @emulators/github@0.13.1 +``` +```bash [bun] +bun add -d @emulators/core@0.13.1 @emulators/github@0.13.1 +``` +::: + +Start the emulators from the eval run's `setup`, with the repositories and the people your evals use: + +```ts [evals/evals.config.ts] +import { defineEvalConfig } from 'eve/evals' +import { emulateGithub } from '@github-tools/eve-extension/testing' + +export default defineEvalConfig({ + setup: () => emulateGithub({ + repositories: { 'acme/web': { labels: ['bug', 'docs'] } }, + people: { alice: { role: 'write' }, bob: { role: 'read' } }, + }), + teardown: context => context?.close(), +}) +``` + +Name the caller of an eval in the eve channel's auth. `evalIdentity()` accepts a request on a local development server only, as eve's `localDev()` does, so it accepts nothing in production: + +```ts [agent/channels/eve.ts] +import { eveChannel } from 'eve/channels/eve' +import { evalIdentity } from '@github-tools/eve-extension/testing/agent' + +export default eveChannel({ auth: [evalIdentity(), /* your production auth */] }) +``` + +An eval then arranges, sends and asserts: + +```ts [evals/triage.eval.ts] +import { defineEval } from 'eve/evals' +import { includes } from 'eve/evals/expect' +import { as } from '@github-tools/eve-extension/testing' +import type config from './evals.config' + +export default defineEval({ + async test(t) { + const web = t.context.github.repo('acme/web') + const issue = await web.as('bob').createIssue({ title: 'Crash on save' }) + + const turn = await t.send(`Triage acme/web#${issue.number}`, as('alice')) + + turn.calledTool('github__addLabels') + t.check((await web.issue(issue.number)).labels, includes('bug')) + }, +}) +``` + +Each person is a GitHub user with the role you gave them, and the emulator answers a call the way GitHub does: a label that bob adds with his own token fails with `github_tools.FORBIDDEN`, and the labels he sends with a new issue are dropped. With `actAs: 'user'` or `'caller'`, the Connect emulator issues each person's token, and a person with `authorized: false` is asked to sign in first. + +On the GitHub channel, wrap Connect's credentials in `underEmulation` from the same entry, and call `t.context.github.deliverWebhooksTo(t)`: a comment an eval creates then reaches the agent as a signed webhook. [Test an agent](/guides/test-an-agent) walks through the channel, sign-ins, what the emulators don't cover, and which checks belong in an eval and which in a [shadow run](/approval#shadow-mode). + ## Config | Field | Type | What it does | diff --git a/apps/docs/content/docs/5.guides/1.index.md b/apps/docs/content/docs/5.guides/1.index.md index aea0eff..94f3c0f 100644 --- a/apps/docs/content/docs/5.guides/1.index.md +++ b/apps/docs/content/docs/5.guides/1.index.md @@ -19,6 +19,7 @@ Each guide builds one working GitHub agent for one job, from install to the comm | [Release notes](/guides/release-notes) | [AI SDK](/integrations/ai-sdk) | `release-manager` | Beginner | | [Chat bot](/guides/chat-bot) | [Chat SDK](/integrations/chat-sdk), [Vercel Workflow](/integrations/workflow) | `issue-triage` | Beginner | | [Multi-agent](/guides/multi-agent) | [eve](/integrations/eve), [AI SDK](/integrations/ai-sdk) | `code-review`, `issue-triage`, `release-manager` | Advanced | +| [Test an agent](/guides/test-an-agent) | [eve](/integrations/eve) | Any | Intermediate | New to agents? Start with [Your first agent](/learn/first-agent), which builds an issue-triage agent in a terminal and explains each part. diff --git a/apps/docs/content/docs/5.guides/8.test-an-agent.md b/apps/docs/content/docs/5.guides/8.test-an-agent.md new file mode 100644 index 0000000..bbe3c5f --- /dev/null +++ b/apps/docs/content/docs/5.guides/8.test-an-agent.md @@ -0,0 +1,260 @@ +--- +title: Test an agent +description: Run an eve agent's evals against a local GitHub emulator, as named people with GitHub roles, with no GitHub token and no real write. +seo: + title: Test an eve GitHub agent without GitHub +navigation: + icon: i-nucleo-shield-check +level: intermediate +path: /guides/test-an-agent +--- + +To test an eve agent that uses the GitHub tools, start a GitHub emulator from the eval run's `setup`, create the issue or pull request the eval is about, send the agent a message as a named person, and assert on what the emulator holds afterward. No request reaches `api.github.com` or `api.vercel.com`, so an eval needs no token, comments on no real issue, and gives the same result on every run. This guide adds evals to an agent built on the [eve extension](/integrations/eve). + +The emulator is [`vercel-labs/emulate`](https://github.com/vercel-labs/emulate), a stateful GitHub emulator. `@github-tools/eve-extension/testing` starts it with what emulate doesn't have: the routes and GraphQL queries the tools call, the role checks GitHub makes for a personal token, and a Vercel Connect emulator that issues its tokens. All 97 tools run against it. + +## What you'll build + +An `evals/` folder for your agent with two kinds of eval: + +- A behavior eval: bob, who has Read, opens an issue. alice, who has Write, asks the agent to triage it. The eval reads the issue back from the emulator and checks its labels. +- A channel eval: a comment created in the emulator reaches the agent as a signed webhook, and the eval reads the agent's reply from the thread. + +## Before you start + +- An eve agent that mounts `@github-tools/eve-extension`, on eve 1.0.0-rc.6 or later and Node.js 24. +- eve's [evals](https://eve.dev/docs/evals) run from an `evals/` folder with `npx eve eval`. An eval that calls a real model needs the model's credentials. Nothing else needs one. + +## 1. Install the emulator + +The emulator is a development dependency of your agent: + +:::code-group +```bash [pnpm] +pnpm add -D @emulators/core@0.13.1 @emulators/github@0.13.1 +``` +```bash [npm] +npm install -D @emulators/core@0.13.1 @emulators/github@0.13.1 +``` +```bash [yarn] +yarn add -D @emulators/core@0.13.1 @emulators/github@0.13.1 +``` +```bash [bun] +bun add -d @emulators/core@0.13.1 @emulators/github@0.13.1 +``` +::: + +The extension is tested against this exact version, so keep the pin. + +## 2. Start the emulators + +`emulateGithub` starts a GitHub emulator and a Vercel Connect emulator on loopback ports. Call it from `setup`, which eve runs once, before it starts the agent: + +```ts [evals/evals.config.ts] +import { defineEvalConfig } from 'eve/evals' +import { emulateGithub } from '@github-tools/eve-extension/testing' + +export default defineEvalConfig({ + setup: () => emulateGithub({ + repositories: { 'acme/web': { labels: ['bug', 'docs'] } }, + people: { alice: { role: 'write' }, bob: { role: 'read' } }, + }), + teardown: context => context?.close(), +}) +``` + +- `repositories` are created with a README on `main`. An owner named in `people` is that user, and any other owner is an organization. +- `people` are GitHub users. `role` is their role on every repository: `'read'`, `'triage'`, `'write'`, `'maintain'`, or `'admin'`. A person with no `role` is a GitHub user with no access beyond what a public repository gives everyone. +- One GitHub App, `eve-agent`, is installed on every owner with the permissions the tools use. It is the agent's bot. + +The return value is `t.context` in every eval. `emulateGithub` also points the agent at the emulators: it sets `NODE_OPTIONS` so that Node loads a `fetch` redirect in the agent's thread, and it sets `GITHUB_TOKEN`, the GitHub App variables eve's GitHub channel reads, and a placeholder `VERCEL_OIDC_TOKEN`. Your agent files don't import the redirect, and nothing of it is in a production build. + +If the agent's thread starts without the redirect, the run stops before the first eval and the error names the cause. Without that check, the agent would send the emulators' tokens to the real hosts. + +## 3. Say who is asking + +Approval, `actAs`, and `respondTo` depend on who is talking to the agent. Add `evalIdentity()` to the eve channel's auth: + +```ts [agent/channels/eve.ts] +import { eveChannel } from 'eve/channels/eve' +import { evalIdentity } from '@github-tools/eve-extension/testing/agent' + +export default eveChannel({ auth: [evalIdentity(), /* your production auth */] }) +``` + +`evalIdentity()` accepts what eve's `localDev()` accepts: a request to a local development server, from a loopback host. It then names the caller from the `x-eval-user` header. In production it accepts nothing, and your own auth decides. + +In an eval, `as('alice')` returns the request options that send that header. Pass it to `t.send` and to `session.respond`: + +```ts +const turn = await t.send('Triage acme/web#12', as('alice')) +``` + +A person is two things with one name: the eve principal `alice`, and the GitHub user `alice`. With [`actAs: 'user'` or `'caller'`](/integrations/eve#per-user-tokens), the extension asks Vercel Connect for alice's token, and the Connect emulator answers with one the GitHub emulator knows as her. + +## 4. Write an eval + +An eval arranges state as one person, sends a message as another, and asserts on the emulator: + +```ts [evals/triage.eval.ts] +import { defineEval } from 'eve/evals' +import { includes } from 'eve/evals/expect' +import { as } from '@github-tools/eve-extension/testing' +import type config from './evals.config' + +export default defineEval({ + async test(t) { + const web = t.context.github.repo('acme/web') + const issue = await web.as('bob').createIssue({ title: 'Crash on save', body: 'TypeError: cannot read properties of undefined' }) + + const turn = await t.send(`Triage acme/web#${issue.number}`, as('alice')) + + turn.calledTool('github__addLabels') + t.check((await web.issue(issue.number)).labels, includes('bug')) + }, +}) +``` + +Run it: + +```bash +npx eve eval +``` + +Evals run eight at a time and share one emulator. Create the issue or pull request an eval works on inside that eval, and use the number you get back, so two evals never share an item. An eval that changes repository-level state, such as labels, creates its own repository with `await t.context.github.createRepo('acme')`. + +### Check who can do what + +The emulator refuses a call the way GitHub does, so an eval can assert the refusal. bob has Read, and labeling needs Triage: + +```ts [evals/reader.eval.ts] +const asked = await t.send(`label acme/web#${issue.number}`, as('bob')) +const answered = await asked.session.respond([{ interactionId: asked.interactions[0]!.interactionId, optionId: 'approve' }], as('bob')) + +answered.calledTool('github__addLabels', { status: 'failed', count: 1 }) +t.check(answered.reply, includes('github_tools.FORBIDDEN')) +``` + +Where GitHub accepts a request and ignores part of it, the emulator does the same. A person without Triage can open an issue or edit their own, and GitHub drops the labels, assignees, and milestone they send. It also answers their request to assign someone with success and assigns nobody. The tool call completes in both cases, so assert on the issue and not on the call: + +```ts +t.check((await web.issue(issue.number)).labels, equals([])) +``` + +`t.context.github.requests` lists every request the agent sent, with the person or bot behind its token and the status the emulator answered. Use it to check that a call ran as the right identity. Evals share the log, so find the request by the item the eval created: + +```ts +const path = `/repos/acme/web/issues/${issue.number}/labels` +const labeling = t.context.github.requests.find(request => request.path === path) +t.check(labeling, equals({ method: 'POST', path, status: 403, actor: 'bob' })) +``` + +## 5. Test the GitHub channel + +When the agent runs on [eve's GitHub channel](/integrations/eve#run-on-eves-github-channel) with credentials from Vercel Connect, wrap them in `underEmulation`: + +```ts [agent/channels/github.ts] +import { connectGitHubCredentials } from '@vercel/connect/eve' +import { githubChannel } from '@github-tools/eve-extension/channels' +import { underEmulation } from '@github-tools/eve-extension/testing/agent' + +export default githubChannel({ + credentials: underEmulation(connectGitHubCredentials('github/my-agent')), + respondTo: 'writers', +}) +``` + +Outside an emulated eval run, `underEmulation` returns its argument unchanged. In one, it replaces the webhook verifier and nothing else: Connect's verifier checks a Vercel OIDC signature that Connect adds when it forwards a webhook, and the emulator signs the way GitHub does, with the webhook secret. The channel still gets its token and its bot name from Connect's routes. A channel with no `credentials` needs no change, because it reads the variables `emulateGithub` sets. + +`deliverWebhooksTo(t)` registers the agent's GitHub route as a webhook of every repository. From then on, a comment an eval creates reaches the agent, signed, and the eval builds no payload: + +```ts [evals/mention.eval.ts] +import { defineEval } from 'eve/evals' +import { includes } from 'eve/evals/expect' +import type config from './evals.config' + +export default defineEval({ + async test(t) { + const { github } = t.context + const web = github.repo('acme/web') + await github.deliverWebhooksTo(t) + + const issue = await web.as('bob').createIssue({ title: 'Crash on save' }) + await web.as('alice').comment(issue.number, `@${github.app.slug} what does this repository do?`) + + const reply = await web.issue(issue.number).waitForComment({ by: 'app' }) + t.check(reply.body, includes('acme/web')) + }, +}) +``` + +The turn runs after the webhook is answered, so the eval waits for the reply with `waitForComment` and doesn't read it right away. No identity mapping is needed on this channel: the commenter is the emulator user who posted the comment. + +An approval on GitHub is a comment, and a reply that mentions the agent answers it: + +```ts +const prompt = await web.issue(issue.number).waitForComment({ by: 'app' }) +await web.as('alice').comment(issue.number, `@${github.app.slug} Approve`) +const result = await web.issue(issue.number).waitForComment({ by: 'app', after: prompt.id }) +``` + +## 6. Test a sign-in + +A person with `authorized: false` hasn't connected GitHub through Vercel Connect yet. Their first call asks them to sign in, and `completeSignIn` finishes the sign-in the way a browser does after they consent: + +```ts [evals/evals.config.ts] +people: { alice: { role: 'write' }, carol: { role: 'write', authorized: false } }, +``` + +```ts [evals/sign-in.eval.ts] +const asked = await t.send('Summarize acme/web', as('carol')) +t.check(asked.interactions.map(interaction => interaction.request.kind), equals(['sign-in'])) + +const resumed = await t.context.connect.completeSignIn(t, asked) +resumed.calledTool('github__getRepository') +``` + +`t.context.connect.revoke('alice')` invalidates the token Connect holds for alice at GitHub. Her next call gets `401`, eve drops the token it cached, and asks her to sign in again. `t.context.connect.requests` lists every token request with its subject and scopes, so an eval can assert the scopes an App token asked for. + +## Where each check belongs + +| Layer | Answers | Needs | Cost of a run | +| --- | --- | --- | --- | +| Wiring eval: [`mockModel`](https://eve.dev/docs/evals#deterministic-fixture-models) and the emulator | Do the tools register, do approvals prompt, does the channel answer? | A separate test agent, since the model is part of the agent | Seconds, no paid call | +| Behavior eval: your model and the emulator | Does the agent do the right thing for this request, as this person? | The agent as it ships | Model tokens | +| Shadow run: [`dryRun: true`](/approval#shadow-mode) on real repositories | Does it behave on real data? | A GitHub token | Model tokens and reads | + +Tag evals by layer, such as `tags: ['wiring']`, and run the first on every push with `npx eve eval --tag wiring`. Run behavior evals on a schedule or a label, since they spend model tokens. + +An emulator run doesn't replace a shadow run. An eval that passes shows the agent does the right thing against the emulator's model of GitHub. Before an agent gets write access to real repositories, run it with `dryRun: true` on them. + +## What `t.context.github` has + +| Member | What it does | +| --- | --- | +| `repo(name)` | A seeded repository, acting as its admin | +| `repo(name).as(person)` | The same repository, acting as a person | +| `createIssue({ title, body?, labels?, assignees? })` | Opens an issue | +| `createPullRequest({ title, body?, files?, base?, draft? })` | Opens a pull request from a new branch with the given files. The person needs Write | +| `comment(number, body)` | Comments in the conversation of an issue or a pull request | +| `createDiscussion({ title, body?, category? })` | Opens a discussion | +| `issue(number)`, `pull(number)` | `await` it for the current state. `.comments()` lists its comments, and `.waitForComment({ by, after?, timeoutMs? })` waits for one | +| `createRepo(owner)` | Creates a repository with a unique name, with every person's role | +| `octokit(person?)` | An Octokit bound to the emulator, for anything else | +| `deliverWebhooksTo(t)` | Sends the repositories' webhooks to the agent. Calling it again changes nothing | +| `requests`, `deliveries` | The requests the emulator answered, and the webhooks it delivered | +| `app.slug` | The agent's GitHub App. Its bot comments as `eve-agent[bot]` | + +A repository can also be seeded with `private: true`, with `workflows: ['ci.yml']` so the workflow tools have a workflow to run, and with `alerts` for the security tools. + +## What the emulators don't cover + +- **The repository checkout.** eve's GitHub channel clones the repository into the sandbox with `git`, from `github.com`, and the redirect covers `fetch` only. The local sandbox skips the checkout and logs that it did. +- **`eve dev` and deployed targets.** The emulators start in an eval's `setup`, which only `eve eval` runs, and a deployment can't reach your machine. For a deployed target, use eve's [tool stubs](https://eve.dev/docs/evals/tool-stubs). +- **URLs.** `html_url` and other URLs in results name the emulator's host. Assert on numbers and state. +- **Other GraphQL.** The emulator answers the GraphQL documents the SDK sends. A tool of your own that sends another gets an error that says so. +- **Rulesets, running workflows, and auto-merge.** A branch has no ruleset rules. A workflow run starts and never finishes, and its job log is a placeholder. Auto-merge is recorded on the pull request and never merges it. +- **Organization roles and teams.** Roles come from `people`. A member of an organization is an admin of its repositories, which is how emulate models it. +- **Vercel Connect's webhook forwarding.** The emulator delivers webhooks straight to the agent, so Connect's check of a forwarded webhook isn't exercised. + +The tools' GitHub client spaces writes at least one second apart, and three seconds for writes that notify people, such as an issue or a comment. It does the same in an eval, so an eval where the agent makes many writes takes that long. diff --git a/apps/docs/skills/github-tools-agents/SKILL.md b/apps/docs/skills/github-tools-agents/SKILL.md index d23cb1f..4c04b48 100644 --- a/apps/docs/skills/github-tools-agents/SKILL.md +++ b/apps/docs/skills/github-tools-agents/SKILL.md @@ -117,6 +117,8 @@ import githubExtension from '@github-tools/eve-extension' export default githubExtension({ preset: 'code-review' }) ``` +To test an eve agent without GitHub, `emulateGithub` from `@github-tools/eve-extension/testing` starts a local GitHub emulator and a Vercel Connect emulator from the eval run's `setup`, and `evalIdentity()` from `@github-tools/eve-extension/testing/agent` names the caller of each eval. See the testing section of `./references/eve-extension.md`. + See `./references/eve-extension.md` and `/integrations/eve`. ### eve agent, direct import (deprecated) diff --git a/apps/docs/skills/github-tools-agents/references/eve-extension.md b/apps/docs/skills/github-tools-agents/references/eve-extension.md index 4f3f118..1bfa0f3 100644 --- a/apps/docs/skills/github-tools-agents/references/eve-extension.md +++ b/apps/docs/skills/github-tools-agents/references/eve-extension.md @@ -116,7 +116,63 @@ export default githubChannel({ - A comment from someone below it starts no turn: no reaction, no session, no model call. - Pair it with `actAs: 'caller'` on an agent that people mention on GitHub. +## Test the agent without GitHub + +`@github-tools/eve-extension/testing` runs evals against a local GitHub emulator (`vercel-labs/emulate`, plus the routes, GraphQL queries and role checks the tools need) and a Vercel Connect emulator. No request reaches GitHub or Vercel, and no token is needed. + +```sh +pnpm add -D @emulators/core@0.13.1 @emulators/github@0.13.1 +``` + +```ts +// evals/evals.config.ts +import { defineEvalConfig } from 'eve/evals' +import { emulateGithub } from '@github-tools/eve-extension/testing' + +export default defineEvalConfig({ + setup: () => emulateGithub({ + repositories: { 'acme/web': { labels: ['bug'] } }, + people: { alice: { role: 'write' }, bob: { role: 'read' }, carol: { role: 'write', authorized: false } }, + }), + teardown: context => context?.close(), +}) +``` + +```ts +// agent/channels/eve.ts +import { eveChannel } from 'eve/channels/eve' +import { evalIdentity } from '@github-tools/eve-extension/testing/agent' + +export default eveChannel({ auth: [evalIdentity(), /* production auth */] }) +``` + +```ts +// evals/triage.eval.ts +import { defineEval } from 'eve/evals' +import { includes } from 'eve/evals/expect' +import { as } from '@github-tools/eve-extension/testing' +import type config from './evals.config' + +export default defineEval({ + async test(t) { + const web = t.context.github.repo('acme/web') + const issue = await web.as('bob').createIssue({ title: 'Crash on save' }) + const turn = await t.send(`Triage acme/web#${issue.number}`, as('alice')) + turn.calledTool('github__addLabels') + t.check((await web.issue(issue.number)).labels, includes('bug')) + }, +}) +``` + +- `people`: each is a GitHub user with `role` (`'read'`, `'triage'`, `'write'`, `'maintain'`, `'admin'`) on every repository, and the eve principal of the same name. `as('alice')` sends a message, or answers an approval, as her. `authorized: false` is a person who has to sign in first: finish it with `t.context.connect.completeSignIn(t, turn)`. +- The emulator refuses what GitHub refuses: a reader's own token can't label, merge or release, and the call settles as failed with `github_tools.FORBIDDEN`. It also drops what GitHub drops: the labels, assignees and milestone a reader sends when opening or editing their own issue, and a reader's `addAssignees`, complete without changing them. Assert on the issue's state. +- `t.context.github`: `repo(name)`, `.as(person)`, `createIssue`, `createPullRequest`, `comment`, `issue(n)`, `pull(n)`, `createRepo(owner)`, `octokit(person)`, `requests`, `deliveries`. Create the item an eval works on inside that eval: evals run concurrently on one emulator. +- GitHub channel: wrap Connect's credentials, `credentials: underEmulation(connectGitHubCredentials('github/my-connector'))`, call `await t.context.github.deliverWebhooksTo(t)`, create a comment that mentions `@${t.context.github.app.slug}`, then `await web.issue(n).waitForComment({ by: 'app' })`. +- Don't hardcode a GitHub token in the extension config, and don't import the redirect: `emulateGithub` sets `GITHUB_TOKEN` and loads the redirect through `NODE_OPTIONS`. +- Only `eve eval` on a local target is covered. Use eve's tool stubs for a deployed target, and a `dryRun: true` pass on real repositories before granting write access. + ## Docs - `/integrations/eve` +- `/guides/test-an-agent` - `examples/eve/`: `pnpm dev:eve` from monorepo root diff --git a/packages/github-tools-eve-extension/README.md b/packages/github-tools-eve-extension/README.md index f03a638..da4eb10 100644 --- a/packages/github-tools-eve-extension/README.md +++ b/packages/github-tools-eve-extension/README.md @@ -100,6 +100,56 @@ export default githubChannel({ Pair it with `actAs: 'caller'`, which limits what a turn does to the commenter's role on each repository a call targets. +## Test your agent + +`@github-tools/eve-extension/testing` runs an agent's evals against a local GitHub emulator, [`vercel-labs/emulate`](https://github.com/vercel-labs/emulate), with the routes, GraphQL queries and role checks the tools need, and a Vercel Connect emulator beside it. An eval creates an issue as one person, asks the agent as another, and reads the result back. No request reaches GitHub or Vercel. + +```sh +pnpm add -D @emulators/core@0.13.1 @emulators/github@0.13.1 +``` + +```ts +// evals/evals.config.ts +import { defineEvalConfig } from 'eve/evals' +import { emulateGithub } from '@github-tools/eve-extension/testing' + +export default defineEvalConfig({ + setup: () => emulateGithub({ + repositories: { 'acme/web': { labels: ['bug'] } }, + people: { alice: { role: 'write' }, bob: { role: 'read' } }, + }), + teardown: context => context?.close(), +}) +``` + +```ts +// agent/channels/eve.ts +import { eveChannel } from 'eve/channels/eve' +import { evalIdentity } from '@github-tools/eve-extension/testing/agent' + +export default eveChannel({ auth: [evalIdentity(), /* your production auth */] }) +``` + +```ts +// evals/triage.eval.ts +import { defineEval } from 'eve/evals' +import { includes } from 'eve/evals/expect' +import { as } from '@github-tools/eve-extension/testing' +import type config from './evals.config' + +export default defineEval({ + async test(t) { + const web = t.context.github.repo('acme/web') + const issue = await web.as('bob').createIssue({ title: 'Crash on save' }) + const turn = await t.send(`Triage acme/web#${issue.number}`, as('alice')) + turn.calledTool('github__addLabels') + t.check((await web.issue(issue.number)).labels, includes('bug')) + }, +}) +``` + +`emulateGithub` points the agent at the emulators through `NODE_OPTIONS`, so no agent file imports a redirect, and it stops the run before the first eval if the agent starts without it. `evalIdentity()` and `underEmulation()`, which adapts `connectGitHubCredentials` for eve's GitHub channel, do nothing outside a local eve server. See [Test an agent](https://github-tools.com/guides/test-an-agent) for the GitHub channel, sign-ins, and what the emulators don't cover. + ## Structure ``` @@ -109,6 +159,12 @@ extension/ github.ts # defineDynamic() resolving listEveToolDescriptors(...) into authored defineTool calls channels/ index.ts # githubChannel with respondTo, compiled apart from the extension to channels/dist +testing/ + index.ts # eval side: emulateGithub, as, and the client behind t.context, compiled to testing/dist + agent.ts # agent side: evalIdentity and underEmulation + redirect.ts # the fetch redirect emulateGithub names in NODE_OPTIONS + github/ # emulate's GitHub service with the role guard, the request fixes and the supplement + connect/ # the Vercel Connect emulator ``` ## Config schema (`extension/extension.ts`) @@ -132,9 +188,12 @@ channels/ ## Build (contributors) ```sh -pnpm --filter @github-tools/eve-extension build # runs `eve extension build`, then compiles `channels/` +pnpm --filter @github-tools/eve-extension build # runs `eve extension build`, then compiles `channels/` and `testing/` +pnpm --filter @github-tools/eve-extension test # vitest for the emulators, the redirect, and every tool against the emulator ``` +The supplement in `testing/github/` adds what `@github-tools/sdk` calls and emulate lacks. `testing/coverage.test.ts` runs every tool against it, through `@github-tools/sdk/eve-runtime`, and fails with "delete this route" when a new emulate release answers a supplement route itself. + ## License [MIT](../../LICENSE) diff --git a/packages/github-tools-eve-extension/eslint.config.mjs b/packages/github-tools-eve-extension/eslint.config.mjs index 6d17047..6243ce9 100644 --- a/packages/github-tools-eve-extension/eslint.config.mjs +++ b/packages/github-tools-eve-extension/eslint.config.mjs @@ -3,6 +3,6 @@ import tseslint from 'typescript-eslint' export default tseslint.config( tseslint.configs.recommended, { - ignores: ['dist', 'channels/dist'], + ignores: ['dist', 'channels/dist', 'testing/dist'], }, ) diff --git a/packages/github-tools-eve-extension/package.json b/packages/github-tools-eve-extension/package.json index 0a3d5ec..e26cc44 100644 --- a/packages/github-tools-eve-extension/package.json +++ b/packages/github-tools-eve-extension/package.json @@ -34,17 +34,27 @@ "./channels": { "types": "./channels/dist/index.d.ts", "default": "./channels/dist/index.js" + }, + "./testing": { + "types": "./testing/dist/index.d.ts", + "default": "./testing/dist/index.js" + }, + "./testing/agent": { + "types": "./testing/dist/agent.d.ts", + "default": "./testing/dist/agent.js" } }, "files": [ "dist", - "channels/dist" + "channels/dist", + "testing/dist" ], "scripts": { - "build": "eve extension build && tsc -p tsconfig.channels.json", + "build": "eve extension build && tsc -p tsconfig.channels.json && tsc -p tsconfig.testing.json", "lint": "eslint .", "lint:fix": "eslint . --fix", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "test": "vitest run" }, "keywords": [ "ai", @@ -60,21 +70,32 @@ "zod": "^4.6.7" }, "peerDependencies": { + "@emulators/core": "0.13.1", + "@emulators/github": "0.13.1", "@vercel/connect": ">=2.7.0", "eve": "*" }, "peerDependenciesMeta": { + "@emulators/core": { + "optional": true + }, + "@emulators/github": { + "optional": true + }, "@vercel/connect": { "optional": true } }, "devDependencies": { + "@emulators/core": "0.13.1", + "@emulators/github": "0.13.1", "@types/node": "^26.5.0", "@vercel/connect": "^2.7.0", "eslint": "^10.10.0", "eve": "1.0.0-rc.6", "typescript": "^6.0.3", - "typescript-eslint": "^8.70.0" + "typescript-eslint": "^8.70.0", + "vitest": "^5.0.0" }, "packageManager": "pnpm@11.1.3", "publishConfig": { diff --git a/packages/github-tools-eve-extension/testing/agent.ts b/packages/github-tools-eve-extension/testing/agent.ts new file mode 100644 index 0000000..1c9d168 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/agent.ts @@ -0,0 +1,45 @@ +import { localDev, type AuthFn } from 'eve/channels/auth' +import type { GitHubChannelCredentials } from 'eve/channels/github' +import { GITHUB_URL_ENV } from './env.js' + +// `emulateGithub` sets the emulator's URL before the agent starts, and eve sets `EVE_DEV` for `eve dev` and `eve eval` only. +const emulating = () => process.env.EVE_DEV === '1' && Boolean(process.env[GITHUB_URL_ENV]) + +/** + * Auth for the eve channel that names the caller of an eval. It accepts what eve's `localDev()` + * accepts, a request to a local development server from a loopback host, and then reads the + * person from the `x-eval-user` header that `as('alice')` sends. A request without the header is + * the `local-dev` caller, as with `localDev()`. In production it accepts nothing. + * + * ```ts + * // agent/channels/eve.ts + * export default eveChannel({ auth: [evalIdentity(), yourProductionAuth()] }) + * ``` + */ +export function evalIdentity(): AuthFn { + const local = localDev() + return async (request) => { + const accepted = await local(request) + const person = request.headers.get('x-eval-user') + if (!accepted || !person) return accepted + return { authenticator: 'eval', issuer: 'https://eval.local', principalId: person, principalType: 'user', subject: person, attributes: {} } + } +} + +/** + * Credentials for eve's GitHub channel that work against the emulator. Outside an emulated eval + * run it returns `credentials` unchanged. In one, it replaces the webhook verifier and nothing + * else: `connectGitHubCredentials` checks the Vercel OIDC signature Connect adds when it forwards + * a webhook, and the emulator signs with GitHub's HMAC and the secret `emulateGithub` set. + * + * ```ts + * // agent/channels/github.ts + * export default githubChannel({ + * credentials: underEmulation(connectGitHubCredentials('github/my-agent')), + * }) + * ``` + */ +export function underEmulation(credentials: GitHubChannelCredentials): GitHubChannelCredentials { + if (!emulating()) return credentials + return { ...credentials, webhookVerifier: undefined, webhookSecret: process.env.GITHUB_WEBHOOK_SECRET } +} diff --git a/packages/github-tools-eve-extension/testing/client.ts b/packages/github-tools-eve-extension/testing/client.ts new file mode 100644 index 0000000..e5ece32 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/client.ts @@ -0,0 +1,251 @@ +import { createOctokit, type Octokit } from '@github-tools/sdk' +import type { GithubEmulator, GithubRequest } from './github/emulator.js' + +export interface EmulatedIssue { + number: number + title: string + body: string | null + state: 'open' | 'closed' + author: string + labels: string[] + assignees: string[] +} + +export interface EmulatedPullRequest extends EmulatedIssue { + draft: boolean + merged: boolean + /** The head branch. */ + head: string + headSha: string + /** The base branch. */ + base: string +} + +export interface EmulatedComment { + id: number + body: string + author: string +} + +export interface WaitForCommentOptions { + /** Who wrote it: a person, or `'app'` for the agent's GitHub App. */ + by: string + /** Only a comment created after this comment ID. */ + after?: number + /** How long to wait. Defaults to 30 seconds. */ + timeoutMs?: number +} + +/** The part of eve's eval context that names the agent under test. */ +export interface EvalTarget { + readonly target: { readonly url: string } +} + +type RestItem = { number: number, title: string, body: string | null, state: 'open' | 'closed', user: { login: string }, labels: Array<{ name: string }>, assignees: Array<{ login: string }> } +type RestComment = { id: number, body: string, user: { login: string } } + +const issueOf = (item: RestItem): EmulatedIssue => ({ + number: item.number, + title: item.title, + body: item.body, + state: item.state, + author: item.user.login, + labels: item.labels.map(label => label.name), + assignees: item.assignees.map(assignee => assignee.login), +}) + +const commentOf = (comment: RestComment): EmulatedComment => ({ id: comment.id, body: comment.body, author: comment.user.login }) + +/** + * An issue or a pull request in the emulator. Awaiting it reads its current state, so + * `await web.issue(7)` is the issue and `web.issue(7).waitForComment(...)` waits on it. + */ +export class ThreadHandle implements PromiseLike { + constructor( + private readonly github: GithubEmulator, + private readonly repository: string, + private readonly actor: string, + readonly number: number, + private readonly read: () => Promise, + ) {} + + then(onfulfilled?: ((value: T) => A | PromiseLike) | null, onrejected?: ((reason: unknown) => B | PromiseLike) | null): Promise { + return this.read().then(onfulfilled, onrejected) + } + + /** The comments in its conversation, oldest first. Review comments on a diff aren't included. */ + async comments(): Promise { + const comments = await this.github.request(this.actor, 'GET', `/repos/${this.repository}/issues/${this.number}/comments?per_page=100`) + return comments.map(commentOf) + } + + /** + * Waits for a comment in its conversation. A turn that a webhook starts runs after the webhook + * is answered, so an eval waits on the agent's reply and doesn't read it right away. + */ + async waitForComment({ by, after = 0, timeoutMs = 30_000 }: WaitForCommentOptions): Promise { + const author = by === 'app' ? `${this.github.githubApp.slug}[bot]` : by + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + const comment = (await this.comments()).find(candidate => candidate.author === author && candidate.id > after) + if (comment) return comment + await new Promise(resolve => setTimeout(resolve, 100)) + } + const deliveries = this.github.webhooks.getDeliveries().slice(-5).map(delivery => `${delivery.event}.${delivery.action} -> ${delivery.status_code ?? 'no answer'}`) + const requests = this.github.requests.slice(-10).map(request => `${request.method} ${request.path} as ${request.actor} -> ${request.status}`) + throw new Error([ + `No comment by ${author} on ${this.repository}#${this.number} after ${timeoutMs} ms.`, + `Last webhook deliveries: ${deliveries.join(', ') || 'none. Call github.deliverWebhooksTo(t) before creating the comment.'}`, + `Last requests to the emulator: ${requests.join(', ') || 'none'}`, + ].join('\n')) + } +} + +/** One repository in the emulator, read and changed as one person. */ +export class RepositoryClient { + constructor( + private readonly github: GithubEmulator, + /** The full name, such as `acme/web`. */ + readonly name: string, + private readonly actor: string, + ) {} + + private request(method: string, path: string, body?: unknown): Promise { + return this.github.request(this.actor, method, `/repos/${this.name}${path}`, body) + } + + /** The same repository, acting as a seeded person. Without it, calls act as the repository's admin. */ + as(person: string): RepositoryClient { + this.github.tokenFor(person) + return new RepositoryClient(this.github, this.name, person) + } + + async createIssue(input: { title: string, body?: string, labels?: string[], assignees?: string[] }): Promise { + return issueOf(await this.request('POST', '/issues', input)) + } + + /** + * Opens a pull request from a new branch with the given files, which default to one new file. + * The person needs Write, since the branch is in this repository. + */ + async createPullRequest(input: { title: string, body?: string, files?: Record, base?: string, draft?: boolean }): Promise { + const base = input.base ?? (await this.request<{ default_branch: string }>('GET', '')).default_branch + const { object } = await this.request<{ object: { sha: string } }>('GET', `/git/ref/heads/${base}`) + const branch = `eval-${this.github.nextId()}` + await this.request('POST', '/git/refs', { ref: `refs/heads/${branch}`, sha: object.sha }) + for (const [path, content] of Object.entries(input.files ?? { [`${branch}.txt`]: `${input.title}\n` })) { + await this.request('PUT', `/contents/${path}`, { message: `Add ${path}`, content: Buffer.from(content).toString('base64'), branch }) + } + const created = await this.request<{ number: number }>('POST', '/pulls', { title: input.title, body: input.body, head: branch, base, draft: input.draft }) + return this.pull(created.number) + } + + /** Comments in the conversation of an issue or a pull request. */ + async comment(number: number, body: string): Promise { + return commentOf(await this.request('POST', `/issues/${number}/comments`, { body })) + } + + /** Opens a discussion. GitHub has no REST route for it, so the emulator creates it directly. */ + createDiscussion(input: { title: string, body?: string, category?: string }): { number: number } { + return { number: this.github.createDiscussion(this.name, this.actor, input).number } + } + + issue(number: number): ThreadHandle { + return new ThreadHandle(this.github, this.name, this.actor, number, async () => issueOf(await this.request('GET', `/issues/${number}`))) + } + + pull(number: number): ThreadHandle { + return new ThreadHandle(this.github, this.name, this.actor, number, async () => { + const pull = await this.request('GET', `/pulls/${number}`) + return { ...issueOf(pull), draft: pull.draft, merged: pull.merged, head: pull.head.ref, headSha: pull.head.sha, base: pull.base.ref } + }) + } +} + +/** + * What an eval arranges and asserts on, as `t.context.github`. It calls the emulator in process + * through its REST routes, so `requests` holds only what arrived over HTTP: the agent's calls, + * and those of an Octokit from `octokit()`. + */ +export class GithubClient { + private readonly hooks = new Map>() + private readonly repositories: Set + private webhookUrl: string | undefined + + constructor(private readonly github: GithubEmulator, repositories: string[]) { + this.repositories = new Set(repositories) + } + + /** The emulator's URL. URLs in what it returns, such as `html_url`, name this host and not github.com. */ + get url(): string { + return this.github.url + } + + /** The agent's GitHub App. Its bot comments as `[bot]`, and a comment reaches the agent by mentioning `@`. */ + get app(): { slug: string } { + return { slug: this.github.githubApp.slug } + } + + /** Every request the emulator answered over HTTP, in order. */ + get requests(): readonly GithubRequest[] { + return this.github.requests + } + + /** Every webhook the emulator delivered, with the status the agent answered. */ + get deliveries() { + return this.github.webhooks.getDeliveries() + } + + repo(name: string): RepositoryClient { + if (!this.repositories.has(name)) throw new Error(`No repository "${name}" in the emulator. Seeded repositories: ${[...this.repositories].join(', ')}.`) + return new RepositoryClient(this.github, name, this.github.adminOf(name)) + } + + /** + * Creates a repository with a unique name under a seeded owner, with every person's role. Evals + * share one emulator, so one that changes repository-level state, such as labels, works on its own. + */ + async createRepo(owner: string): Promise { + if (!this.github.owners.includes(owner)) throw new Error(`No owner "${owner}" in the emulator. Seeded owners: ${this.github.owners.join(', ')}.`) + const admin = this.github.adminOf(owner) + const { full_name: name } = await this.github.request<{ full_name: string }>(admin, 'POST', admin === owner ? '/user/repos' : `/orgs/${owner}/repos`, { name: `repo-${this.github.nextId()}`, auto_init: true }) + await this.github.applyRoles(name) + this.repositories.add(name) + if (this.webhookUrl) await this.hook(name) + return this.repo(name) + } + + /** An Octokit bound to the emulator, as a seeded person or as the first repository's admin, for anything this client has no method for. */ + octokit(person?: string): Octokit { + const octokit = createOctokit(this.github.tokenFor(person ?? this.github.admin)) + octokit.hook.before('request', (options: { baseUrl: string }) => { + options.baseUrl = this.github.url + }) + return octokit + } + + /** + * Registers the agent's GitHub channel as a webhook of every repository, signed with the secret + * the agent was given. From then on, a comment an eval creates reaches the agent. Calling it + * again changes nothing, so every eval that needs it can call it. + */ + async deliverWebhooksTo(t: EvalTarget): Promise { + const url = `${t.target.url.replace(/\/$/u, '')}/eve/v1/github` + if (this.webhookUrl && this.webhookUrl !== url) throw new Error(`Webhooks already go to ${this.webhookUrl}.`) + this.webhookUrl = url + await Promise.all([...this.repositories].map(name => this.hook(name))) + } + + // One hook per repository: evals run concurrently, and a second one would deliver every comment twice. + private hook(name: string): Promise { + let registration = this.hooks.get(name) + if (!registration) { + registration = this.github.request(this.github.adminOf(name), 'POST', `/repos/${name}/hooks`, { + config: { url: this.webhookUrl, content_type: 'json', secret: this.github.githubApp.webhookSecret }, + events: ['*'], + }) + this.hooks.set(name, registration) + } + return registration + } +} diff --git a/packages/github-tools-eve-extension/testing/connect/emulator.test.ts b/packages/github-tools-eve-extension/testing/connect/emulator.test.ts new file mode 100644 index 0000000..fe94125 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/connect/emulator.test.ts @@ -0,0 +1,96 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { startGithubEmulator, type GithubEmulator } from '../github/emulator' +import { startConnectEmulator, type ConnectEmulator } from './emulator' + +const people = { alice: { role: 'write' }, erin: { role: 'read', authorized: false } } as const +let github: GithubEmulator +let connect: ConnectEmulator + +const post = (path: string, body: unknown, method = 'POST') => fetch(`${connect.url}/v1/connect/${path}`, { + method, + headers: { 'authorization': 'Bearer oidc', 'content-type': 'application/json' }, + body: JSON.stringify(body), +}) +const user = (id: string) => ({ subject: { type: 'user', id, issuer: 'https://eval.local' }, scopes: ['*'] }) +const githubAs = (token: string, method: string, path: string, body?: unknown) => fetch(`${github.url}${path}`, { + method, + headers: { 'authorization': `Bearer ${token}`, 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), +}) + +beforeAll(async () => { + github = await startGithubEmulator({ repositories: { 'acme/web': { labels: ['bug'] } }, people }) + connect = await startConnectEmulator(github, people) +}) + +beforeEach(async () => { + await github.reset() + connect.reset() +}) + +afterAll(() => Promise.all([github.close(), connect.close()])) + +describe('the Vercel Connect emulator', () => { + it('mints an installation token narrowed to the scopes the request asks for', async () => { + const response = await post('token/github%2Fmy-agent', { + subject: { type: 'app' }, + authorizationDetails: [{ type: 'github_app_installation', org: 'acme', repositories: ['web'] }], + scopes: ['contents:read', 'metadata:read', 'issues:read'], + }) + const { token, expiresAt } = await response.json() as { token: string, expiresAt: number } + expect(response.status).toBe(200) + expect(expiresAt).toBeGreaterThan(Date.now()) + const { number } = await github.request<{ number: number }>('alice', 'POST', '/repos/acme/web/issues', { title: 'Crash on save' }) + expect((await githubAs(token, 'GET', `/repos/acme/web/issues/${number}`)).status).toBe(200) + // The scopes had no `issues:write`, so GitHub refuses a write with this token. + expect((await githubAs(token, 'POST', '/repos/acme/web/issues', { title: 'x' })).status).toBe(403) + expect((await githubAs(token, 'POST', `/repos/acme/web/issues/${number}/reactions`, { content: 'eyes' })).status).toBe(403) + }) + + it('refuses scopes the App does not have, and an owner it is not installed on', async () => { + const beyond = await post('token/github%2Fmy-agent', { subject: { type: 'app' }, scopes: ['secret_scanning_alerts:write'] }) + expect([beyond.status, (await beyond.json() as { error: { code: string } }).error.code]).toEqual([403, 'forbidden']) + const elsewhere = await post('token/github%2Fmy-agent', { subject: { type: 'app' }, authorizationDetails: [{ type: 'github_app_installation', org: 'other' }] }) + expect([elsewhere.status, (await elsewhere.json() as { error: { code: string } }).error.code]).toEqual([403, 'connector_installation_required']) + }) + + it('answers a connected person with a token GitHub knows as them', async () => { + const { token } = await (await post('token/github%2Fmy-agent', user('alice'))).json() as { token: string } + expect((await (await githubAs(token, 'GET', '/user')).json() as { login: string }).login).toBe('alice') + }) + + it('asks a person who has not authorized to sign in, then issues a token GitHub knows', async () => { + const before = await post('token/github%2Fmy-agent', user('erin')) + expect([before.status, await before.json()]).toEqual([403, { error: { code: 'user_authorization_required', message: 'User has not authorized the connector.' } }]) + + const authorize = await post('authorize/github%2Fmy-agent', { ...user('erin'), returnUrl: 'http://localhost:3000/callback', deviceCode: true }) + expect(await authorize.json()).toMatchObject({ url: 'http://localhost:3000/callback', connector: { uid: 'github/my-agent', serviceName: 'GitHub' } }) + + const { token } = await (await post('token/github%2Fmy-agent', user('erin'))).json() as { token: string } + expect((await (await githubAs(token, 'GET', '/user')).json() as { login: string }).login).toBe('erin') + expect(connect.requests.map(request => `${request.route} ${request.body?.subject?.id} ${request.status}`)).toEqual(['token erin 403', 'authorize erin 200', 'token erin 200']) + }) + + it('refuses a sign-in for someone who is not a seeded person', async () => { + expect((await post('authorize/github%2Fmy-agent', user('nobody'))).status).toBe(404) + }) + + it('revokes a person\'s token at GitHub, from the eval and from the route @vercel/connect calls', async () => { + const { token } = await (await post('token/github%2Fmy-agent', user('alice'))).json() as { token: string } + connect.revoke('alice') + expect([(await githubAs(token, 'GET', '/repos/acme/web')).status, (await post('token/github%2Fmy-agent', user('alice'))).status]).toEqual([401, 403]) + + await post('authorize/github%2Fmy-agent', { ...user('alice'), returnUrl: 'http://localhost:3000/callback' }) + const again = await (await post('token/github%2Fmy-agent', user('alice'))).json() as { token: string } + expect(again.token).not.toBe(token) + expect((await post('connectors/github%2Fmy-agent/tokens', { subject: { type: 'user', id: 'alice' } }, 'DELETE')).status).toBe(200) + expect((await githubAs(again.token, 'GET', '/repos/acme/web')).status).toBe(401) + }) + + it('names the App in the connector metadata, and answers 404 to any other route', async () => { + const metadata = await fetch(`${connect.url}/v1/connect/connectors/github%2Fmy-agent`, { headers: { authorization: 'Bearer oidc' } }) + expect(await metadata.json()).toMatchObject({ uid: 'github/my-agent', data: { appSlug: github.githubApp.slug } }) + const unknown = await post('install/github%2Fmy-agent', {}) + expect([unknown.status, (await unknown.json() as { error: { code: string } }).error.code]).toEqual([404, 'not_found']) + }) +}) diff --git a/packages/github-tools-eve-extension/testing/connect/emulator.ts b/packages/github-tools-eve-extension/testing/connect/emulator.ts new file mode 100644 index 0000000..c390c36 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/connect/emulator.ts @@ -0,0 +1,136 @@ +import { once } from 'node:events' +import type { AddressInfo } from 'node:net' +import type { Context } from '@emulators/core' +import { ApiError, Hono, serve } from '../emulators.js' +import type { GithubEmulator, PersonSeed } from '../github/emulator.js' + +/** One request the Connect emulator answered. */ +export interface ConnectRequest { + method: string + /** `token`, `authorize`, `connectors`, or the path for a request with no route. */ + route: string + connector?: string + body?: { + subject?: { type: string, id?: string, issuer?: string } + scopes?: string[] + authorizationDetails?: Array<{ type?: string, org?: string, repositories?: string[] }> + returnUrl?: string + } + status: number +} + +export type ConnectEmulator = Awaited> + +const error = (status: number, code: string, message: string) => Response.json({ error: { code, message } }, { status }) + +/** + * The Vercel Connect routes `@vercel/connect` calls for a GitHub connector, answered from the + * GitHub emulator. Every connector name is the emulator's one GitHub App. + */ +export async function startConnectEmulator(github: GithubEmulator, people: Record) { + const requests: ConnectRequest[] = [] + const tokens = new Map() + let issued = 0 + + // A sign-in has to produce a token GitHub knows: one it doesn't is anonymous to emulate and `401` to the role guard. + function issue(person: string): string { + const token = `ghu_${person}_${++issued}` + github.registerToken(token, person) + tokens.set(person, token) + return token + } + + function seed(): void { + for (const [person, { authorized = true }] of Object.entries(people)) { + if (authorized) issue(person) + } + } + seed() + + function revoke(person: string): void { + const token = tokens.get(person) + if (token) github.revokeToken(token) + tokens.delete(person) + } + + const app = new Hono() + const connector = (c: Context) => ({ id: 'scl_emulator', uid: decodeURIComponent(c.req.param('connector')), serviceName: 'GitHub' }) + + app.post('/v1/connect/token/:connector', async (c) => { + const { subject, scopes = ['*'], authorizationDetails } = await c.req.json>() + if (subject?.type === 'app') { + // The scopes the extension derives from the mounted tools narrow the installation token, so a missing one fails in the eval. + const permissions = scopes.includes('*') + ? undefined + : Object.fromEntries([...scopes].sort((a, b) => Number(a.endsWith(':write')) - Number(b.endsWith(':write'))).map(scope => scope.split(':'))) + const installation = authorizationDetails?.find(detail => detail.type === 'github_app_installation') + const minted = await github.mintInstallationToken({ owner: installation?.org, permissions, repositories: installation?.repositories }) + if (minted.status === 404) return error(403, 'connector_installation_required', minted.message!) + if (!minted.token) return error(403, 'forbidden', `GitHub refused the installation token: ${minted.message}`) + return c.json({ token: minted.token, expiresAt: Date.parse(minted.expiresAt!), connector: connector(c) }) + } + // People are keyed on the principal's ID. Its issuer is in the subject and isn't checked. + const token = subject?.id === undefined ? undefined : tokens.get(subject.id) + if (!token) return error(403, 'user_authorization_required', 'User has not authorized the connector.') + return c.json({ token, expiresAt: Date.now() + 3_600_000, connector: connector(c) }) + }) + + // Starting a sign-in stands in for the person consenting on GitHub. An eval finishes it by fetching `url` on the agent. + app.post('/v1/connect/authorize/:connector', async (c) => { + const { subject, returnUrl } = await c.req.json>() + if (subject?.id === undefined || !github.people.includes(subject.id)) { + return error(404, 'not_found', `No person "${subject?.id}" in the emulator. Seeded people: ${github.people.join(', ') || 'none'}.`) + } + revoke(subject.id) + issue(subject.id) + return c.json({ url: returnUrl, request: `req_${issued}`, verifier: `ver_${issued}`, connector: connector(c) }) + }) + + app.get('/v1/connect/connectors/:connector', c => c.json({ ...connector(c), data: { appSlug: github.githubApp.slug } })) + + app.delete('/v1/connect/connectors/:connector/tokens', async (c) => { + const { subject } = await c.req.json>() + if (subject?.id !== undefined) revoke(subject.id) + return c.json({}) + }) + + app.notFound(c => error(404, 'not_found', `The Connect emulator has no route for ${c.req.method} ${c.req.path}.`)) + app.onError((thrown, c) => { + if (thrown instanceof ApiError) return error(thrown.status, 'error', thrown.message) + return error(500, 'internal_error', `The Connect emulator failed on ${c.req.method} ${c.req.path}: ${thrown instanceof Error ? thrown.message : String(thrown)}`) + }) + + const server = serve({ + port: 0, + fetch: async (request) => { + const body = request.method === 'GET' ? undefined : await request.clone().json().catch(() => undefined) as ConnectRequest['body'] + const response = await app.fetch(request) + const [, , , route, name] = new URL(request.url).pathname.split('/') + requests.push({ method: request.method, route: route ?? new URL(request.url).pathname, connector: name && decodeURIComponent(name), body, status: response.status }) + return response + }, + }) + await once(server, 'listening') + + return { + url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + /** Every request answered, in order, with the subject and the scopes each token asked for. */ + requests, + /** + * Invalidates the token Connect holds for a person, at GitHub. `@vercel/connect` caches a token + * in the agent until shortly before it expires, so the person's next call gets `401` from + * GitHub, eve drops the cached token, and asks them to sign in. + */ + revoke, + /** Back to the seeded state. Call it after the GitHub emulator's `reset()`. */ + reset(): void { + tokens.clear() + requests.length = 0 + seed() + }, + close: () => new Promise((resolve, reject) => { + server.close(failure => failure ? reject(failure) : resolve()) + server.closeAllConnections() + }), + } +} diff --git a/packages/github-tools-eve-extension/testing/coverage.test.ts b/packages/github-tools-eve-extension/testing/coverage.test.ts new file mode 100644 index 0000000..a7029f2 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/coverage.test.ts @@ -0,0 +1,421 @@ +import { executeGithubEveTool, listEveToolDescriptors, withGithubCallerAccess, type GithubToolName, type GithubWriteToolName } from '@github-tools/sdk/eve-runtime' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { ROLE_REFUSAL } from './github/access' +import { startGithubEmulator, type GithubEmulator } from './github/emulator' + +// The SDK's Octokit spaces writes a second apart, which the emulator doesn't need. +vi.mock('octokit', async (original) => { + const module = await original<{ Octokit: { defaults(options: object): unknown } }>() + return { ...module, Octokit: module.Octokit.defaults({ throttle: { enabled: false } }) } +}) + +// Every tool the SDK has, with its input schema, as the extension mounts them. Listing them makes +// no request, and the SDK still needs a token to build the list. +const TOOLS = listEveToolDescriptors({ token: 'unused' }) + +const REPO = 'acme/web' +const web = { owner: 'acme', repo: 'web' } + +let github: GithubEmulator +let counter = 0 +const unique = (prefix: string) => `${prefix}-${++counter}` +const call = (login: string, method: string, path: string, body?: unknown) => github.request(login, method, `/repos/${REPO}${path}`, body) +const mainSha = async () => (await call<{ object: { sha: string } }>('alice', 'GET', '/git/ref/heads/main')).object.sha + +// Fixtures are alice's, who has Write, so neither the admin nor the reader acts on an item of their own. +async function issue() { + return call<{ number: number, id: number }>('alice', 'POST', '/issues', { title: unique('Issue'), body: 'Something is broken.' }) +} + +async function issueComment() { + const { number } = await issue() + const comment = await call<{ id: number }>('alice', 'POST', `/issues/${number}/comments`, { body: 'A comment.' }) + return { number, commentId: comment.id } +} + +async function branch() { + const name = unique('branch') + await call('alice', 'POST', '/git/refs', { ref: `refs/heads/${name}`, sha: await mainSha() }) + return name +} + +async function pull(options: { draft?: boolean, body?: string } = {}) { + const head = await branch() + const path = `${head}.txt` + const file = await call<{ commit: { sha: string } }>('alice', 'PUT', `/contents/${path}`, { message: `Add ${path}`, content: Buffer.from('one\ntwo\n').toString('base64'), branch: head }) + const created = await call<{ number: number, node_id: string }>('alice', 'POST', '/pulls', { title: unique('Pull request'), head, base: 'main', ...options }) + return { number: created.number, nodeId: created.node_id, head, path, sha: file.commit.sha } +} + +async function reviewThread() { + const created = await pull() + const comment = await call<{ id: number }>('alice', 'POST', `/pulls/${created.number}/comments`, { body: 'Why two lines?', path: created.path, line: 1, side: 'RIGHT' }) + return { ...created, commentId: comment.id, threadId: `PRRT_${comment.id}` } +} + +async function release() { + const tag = unique('v1.0') + const created = await call<{ id: number }>('alice', 'POST', '/releases', { tag_name: tag, name: tag, body: 'Notes.' }) + return { id: created.id, tag } +} + +async function workflowRun(conclusion?: 'failure') { + await call('alice', 'POST', '/actions/workflows/ci.yml/dispatches', { ref: 'main' }) + const { workflow_runs: runs } = await call<{ workflow_runs: Array<{ id: number, head_sha: string }> }>('alice', 'GET', '/actions/runs?per_page=100') + const run = runs.reduce((latest, candidate) => candidate.id > latest.id ? candidate : latest) + if (conclusion) github.finishWorkflowRun(run.id, conclusion) + const { jobs } = await call<{ jobs: Array<{ id: number }> }>('alice', 'GET', `/actions/runs/${run.id}/jobs`) + return { runId: run.id, jobId: jobs[0]!.id, sha: run.head_sha } +} + +async function label() { + const name = unique('label') + await call('alice', 'POST', '/labels', { name, color: 'ededed' }) + return name +} + +async function milestone() { + return (await call<{ number: number }>('alice', 'POST', '/milestones', { title: unique('milestone') })).number +} + +// What only a person with Triage can set on an issue. +async function triaged(number: unknown) { + const found = await call<{ labels: Array<{ name: string }>, assignees: Array<{ login: string }>, milestone: { number: number } | null }>('alice', 'GET', `/issues/${number}`) + return { labels: found.labels.map(entry => entry.name), assignees: found.assignees.map(user => user.login), milestone: found.milestone?.number ?? null } +} + +const UNTRIAGED = { labels: [], assignees: [], milestone: null } + +async function labeledIssue() { + const [{ number }, name] = await Promise.all([issue(), label()]) + await call('alice', 'POST', `/issues/${number}/labels`, { labels: [name] }) + return { number, label: name } +} + +async function gist(owner: string) { + const created = await github.request<{ id: string }>(owner, 'POST', '/gists', { description: 'A note', public: true, files: { 'note.md': { content: 'A note.' } } }) + return created.id +} + +// A mention is what gives a person a notification thread. +async function notification(login: string) { + const { number } = await issue() + await call('alice', 'POST', `/issues/${number}/comments`, { body: `@${login} can you look at this?` }) + const threads = await github.request>(login, 'GET', '/notifications') + return threads[0]!.id +} + +const discussion = () => github.createDiscussion(REPO, 'alice', { title: unique('Discussion'), body: 'What do you think?', category: 'Ideas' }).number + +type Sample = (login: string) => unknown + +/** + * An input for every tool, built on fresh fixtures. A tool with more than one code path returns + * several, and the reader case runs the first. Adding a tool to the catalog without a sample here + * is a type error, so a new tool lands with emulator support. + */ +const SAMPLES = { + getRepository: () => web, + listBranches: () => web, + getFileContent: () => ({ ...web, path: 'README.md' }), + getRepositoryTree: () => [web, { ...web, recursive: true }], + createBranch: () => ({ ...web, branch: unique('created') }), + deleteBranch: async () => ({ ...web, branch: await branch() }), + forkRepository: () => web, + createRepository: () => [{ name: unique('repository'), org: 'acme' }, { name: unique('repository'), autoInit: true }], + createOrUpdateFile: async () => [ + { ...web, path: `${unique('file')}.md`, message: 'Add a file', content: 'Hello.' }, + { ...web, path: `${unique('file')}.md`, message: 'Add a file on a branch', content: 'Hello.', branch: await branch() }, + ], + editFiles: () => ({ + ...web, + branch: unique('edit'), + message: 'Rewrite the README', + edits: [{ path: 'README.md', find: '# web', replace: '# Web' }, { path: `${unique('notes')}.md`, content: 'Notes.' }], + pullRequest: { title: 'Rewrite the README' }, + }), + getBranchRules: () => ({ ...web, branch: 'main' }), + getCollaboratorPermission: () => ({ ...web, username: 'alice' }), + listPullRequests: async () => (await pull(), web), + getPullRequest: async () => ({ ...web, pullNumber: (await pull()).number }), + createPullRequest: async () => { + const head = await branch() + await call('alice', 'PUT', `/contents/${head}.txt`, { message: 'Add a file', content: Buffer.from('one\n').toString('base64'), branch: head }) + return { ...web, title: unique('Pull request'), head, base: 'main' } + }, + mergePullRequest: async () => ({ ...web, pullNumber: (await pull()).number }), + enablePullRequestAutoMerge: async () => ({ ...web, pullNumber: (await pull()).number, mergeMethod: 'squash' }), + disablePullRequestAutoMerge: async () => ({ ...web, pullNumber: (await pull()).number }), + updatePullRequest: async () => [ + { ...web, pullNumber: (await pull()).number, title: 'A better title' }, + { ...web, pullNumber: (await pull()).number, draft: true }, + { ...web, pullNumber: (await pull({ draft: true })).number, draft: false }, + ], + updatePullRequestBranch: async () => { + const created = await pull() + await call('alice', 'PUT', `/contents/${unique('main')}.txt`, { message: 'Move main', content: Buffer.from('main\n').toString('base64') }) + return { ...web, pullNumber: created.number } + }, + addPullRequestComment: async () => ({ ...web, pullNumber: (await pull()).number, body: 'Looks good.' }), + updatePullRequestComment: async () => ({ ...web, commentId: (await issueComment()).commentId, body: 'Edited.' }), + deletePullRequestComment: async () => ({ ...web, commentId: (await issueComment()).commentId }), + listPullRequestFiles: async () => ({ ...web, pullNumber: (await pull()).number }), + listPullRequestReviews: async () => ({ ...web, pullNumber: (await pull()).number }), + createPullRequestReview: async () => { + const created = await pull() + return { ...web, pullNumber: created.number, event: 'COMMENT', body: 'One note.', comments: [{ path: created.path, line: 1, side: 'RIGHT', body: 'Why?' }] } + }, + listPullRequestReviewThreads: async () => ({ ...web, pullNumber: (await reviewThread()).number, status: 'all' }), + replyToReviewComment: async () => { + const thread = await reviewThread() + return { ...web, pullNumber: thread.number, commentId: thread.commentId, body: 'Because of the test.' } + }, + resolveReviewThread: async () => ({ threadId: (await reviewThread()).threadId }), + requestReviewers: async () => ({ ...web, pullNumber: (await pull()).number, reviewers: ['alice'] }), + getPullRequestContext: async () => { + const closes = await issue() + const created = await pull({ body: `Fixes #${closes.number}` }) + return [{ ...web, pullNumber: created.number }, { ...web, pullNumber: created.number, includeChecks: true, includeLinkedIssues: true }] + }, + getIssueContext: async () => ({ ...web, issueNumber: (await issueComment()).number }), + listIssues: async () => (await issue(), web), + getIssue: async () => ({ ...web, issueNumber: (await issue()).number }), + listIssueComments: async () => ({ ...web, issueNumber: (await issueComment()).number }), + createIssue: async () => ({ ...web, title: unique('Issue'), body: 'Something is broken.', labels: ['bug'], assignees: ['alice'], milestone: await milestone() }), + addIssueComment: async () => ({ ...web, issueNumber: (await issue()).number, body: 'Thanks for the report.' }), + updateIssueComment: async () => ({ ...web, commentId: (await issueComment()).commentId, body: 'Edited.' }), + deleteIssueComment: async () => ({ ...web, commentId: (await issueComment()).commentId }), + closeIssue: async () => ({ ...web, issueNumber: (await issue()).number }), + updateIssue: async () => ({ ...web, issueNumber: (await issue()).number, title: 'A better title', labels: ['bug'] }), + listLabels: () => web, + addLabels: async () => ({ ...web, issueNumber: (await issue()).number, labels: ['bug'] }), + removeLabel: async () => { + const labeled = await labeledIssue() + return { ...web, issueNumber: labeled.number, label: labeled.label } + }, + createLabel: () => ({ ...web, name: unique('created-label'), color: 'ff0000' }), + updateLabel: async () => ({ ...web, name: await label(), color: '00ff00' }), + deleteLabel: async () => ({ ...web, name: await label() }), + addAssignees: async () => ({ ...web, issueNumber: (await issue()).number, assignees: ['alice'] }), + removeAssignees: async () => { + const { number } = await issue() + await call('alice', 'POST', `/issues/${number}/assignees`, { assignees: ['alice'] }) + return { ...web, issueNumber: number, assignees: ['alice'] } + }, + listMilestones: () => web, + listSubIssues: async () => { + const [parent, child] = await Promise.all([issue(), issue()]) + await call('alice', 'POST', `/issues/${parent.number}/sub_issues`, { sub_issue_id: child.id }) + return { ...web, issueNumber: parent.number } + }, + addSubIssue: async () => { + const [parent, child] = await Promise.all([issue(), issue()]) + return { ...web, issueNumber: parent.number, subIssueNumber: child.number } + }, + listIssueReactions: async () => { + const { number } = await issue() + await call('alice', 'POST', `/issues/${number}/reactions`, { content: 'eyes' }) + return { ...web, issueNumber: number } + }, + addIssueReaction: async () => ({ ...web, issueNumber: (await issue()).number, content: 'rocket' }), + listCommentReactions: async () => { + const { commentId } = await issueComment() + await call('alice', 'POST', `/issues/comments/${commentId}/reactions`, { content: 'heart' }) + return { ...web, commentId } + }, + addCommentReaction: async () => ({ ...web, commentId: (await issueComment()).commentId, content: '+1' }), + listDiscussions: () => (discussion(), [web, { ...web, category: 'Ideas' }]), + getDiscussion: () => ({ ...web, discussionNumber: discussion() }), + addDiscussionComment: () => ({ ...web, discussionNumber: discussion(), body: 'I agree.' }), + listNotifications: async login => (await notification(login), [{}, { all: true }]), + markNotificationRead: async login => ({ threadId: await notification(login) }), + searchCode: () => ({ query: 'repo:acme/web web' }), + searchRepositories: () => ({ query: 'web org:acme' }), + searchIssues: async () => (await issue(), { query: 'repo:acme/web is:issue Issue' }), + listCommits: () => [web, { ...web, path: 'README.md' }], + getCommit: () => ({ ...web, ref: 'main' }), + getBlame: () => [{ ...web, path: 'README.md' }, { ...web, path: 'README.md', ref: 'main', line: 1 }], + compareCommits: async () => ({ ...web, base: 'main', head: (await pull()).head }), + listGists: async login => (await gist(login), [{}, { username: 'alice' }]), + getGist: async login => ({ gistId: await gist(login) }), + listGistComments: async login => ({ gistId: await gist(login) }), + createGist: () => ({ description: 'A note', files: { 'note.md': { content: 'A note.' } } }), + updateGist: async login => ({ gistId: await gist(login), files: { 'more.md': { content: 'More.' } }, filesToDelete: ['note.md'] }), + deleteGist: async login => ({ gistId: await gist(login) }), + createGistComment: async login => ({ gistId: await gist(login), body: 'Useful.' }), + listWorkflows: () => web, + listWorkflowRuns: async () => (await workflowRun(), [web, { ...web, workflowId: 'ci.yml' }]), + getWorkflowRun: async () => ({ ...web, runId: (await workflowRun()).runId }), + listWorkflowJobs: async () => ({ ...web, runId: (await workflowRun()).runId }), + getWorkflowJobLogs: async () => ({ ...web, jobId: (await workflowRun()).jobId }), + triggerWorkflow: () => ({ ...web, workflowId: 'ci.yml', ref: 'main' }), + cancelWorkflowRun: async () => ({ ...web, runId: (await workflowRun()).runId }), + rerunWorkflowRun: async () => [ + { ...web, runId: (await workflowRun('failure')).runId }, + { ...web, runId: (await workflowRun('failure')).runId, onlyFailedJobs: true }, + ], + listCheckRuns: () => ({ ...web, ref: 'main' }), + getCombinedStatus: async () => { + const sha = await mainSha() + await call('alice', 'POST', `/statuses/${sha}`, { state: 'success', context: 'ci/build' }) + return [{ ...web, ref: 'main' }, { ...web, ref: sha }] + }, + createCommitStatus: async () => ({ ...web, sha: await mainSha(), state: 'pending', context: 'bot/review' }), + getCiFailureContext: async () => { + const failed = await workflowRun('failure') + return [{ ...web, runId: failed.runId }, { ...web, ref: 'main' }] + }, + listReleases: async () => (await release(), web), + getLatestRelease: async () => (await release(), web), + getRelease: async () => { + const created = await release() + return [{ ...web, releaseId: created.id }, { ...web, tag: created.tag }] + }, + getReleaseContext: async () => { + await release() + return [web, { ...web, tag: (await release()).tag }] + }, + createRelease: () => ({ ...web, tagName: unique('v2.0'), name: 'Two', body: 'Notes.' }), + updateRelease: async () => ({ ...web, releaseId: (await release()).id, name: 'Renamed' }), + deleteRelease: async () => ({ ...web, releaseId: (await release()).id }), + listCodeScanningAlerts: () => [web, { ...web, severity: 'high' }], + listDependabotAlerts: () => [web, { ...web, perPage: 1 }], + listSecretScanningAlerts: () => web, +} satisfies Record + +interface ReaderCase { + /** Why GitHub answers a person with Read with success. */ + why: string + /** What the emulator has to hold afterward, where GitHub accepts the call and ignores part of it. */ + holds?: (input: Record, result: unknown) => Promise +} + +/** + * The writes GitHub accepts from a person with Read, each with the reason. Every other write tool + * has to be refused for a reader: without that, a route missing from the role guard would go + * unnoticed. Where GitHub accepts a call and ignores what the person may not set, the status isn't + * enough, so `holds` reads the issue back. + */ +const READER_MAY: Partial> = { + createIssue: { + why: 'anyone who can read a repository can open an issue, and GitHub drops the labels, assignees, and milestone they send', + holds: async (_input, result) => expect(await triaged((result as { number: number }).number)).toEqual(UNTRIAGED), + }, + addAssignees: { + why: 'GitHub ignores the assignees a person without Triage adds, and answers with success', + holds: async input => expect((await triaged(input.issueNumber)).assignees).toEqual([]), + }, + removeAssignees: { + why: 'GitHub ignores the assignees a person without Triage removes, and answers with success', + holds: async input => expect((await triaged(input.issueNumber)).assignees).toEqual(['alice']), + }, + addIssueComment: { why: 'anyone who can read a repository can comment' }, + addPullRequestComment: { why: 'anyone who can read a repository can comment' }, + createPullRequest: { why: 'anyone who can read a repository can open a pull request between its branches' }, + createPullRequestReview: { why: 'anyone who can read a repository can leave a review comment' }, + replyToReviewComment: { why: 'anyone who can read a repository can reply in a review thread' }, + addIssueReaction: { why: 'anyone who can read a repository can react' }, + addCommentReaction: { why: 'anyone who can read a repository can react' }, + addDiscussionComment: { why: 'anyone who can read a repository can comment on a discussion' }, + forkRepository: { why: 'anyone who can read a repository can fork it' }, + createGist: { why: 'a gist belongs to its user' }, + updateGist: { why: 'a gist belongs to its user' }, + deleteGist: { why: 'a gist belongs to its user' }, + createGistComment: { why: 'anyone can comment on a gist' }, + markNotificationRead: { why: 'a notification thread belongs to its user' }, +} + +// Runs a tool the way the extension does. A failed call throws: a catalog error with its `{ code, status }` as the cause. +async function run(name: GithubToolName, login: string, input: unknown) { + const { inputSchema } = TOOLS.find(tool => tool.name === name)! + return executeGithubEveTool(name, inputSchema.parse(input) as Record, { token: github.tokenFor(login) }) +} + +const inputs = async (name: GithubToolName, login: string) => [await SAMPLES[name](login)].flat() + +// A REST refusal is a catalog error with status 403. A GraphQL one is Octokit's error, whose message quotes the guard's. +function isForbidden(error: unknown): boolean { + if (!(error instanceof Error)) return false + return (error.cause as { status?: number } | undefined)?.status === 403 || error.message.includes(ROLE_REFUSAL) +} + +beforeAll(async () => { + github = await startGithubEmulator({ + repositories: { + [REPO]: { + labels: ['bug'], + workflows: ['ci.yml'], + alerts: { + codeScanning: [{ rule: 'js/sql-injection', severity: 'high', path: 'src/db.ts', line: 12 }], + dependabot: [ + { package: 'lodash', ecosystem: 'npm', severity: 'high', summary: 'Prototype pollution', firstPatchedVersion: '4.17.21' }, + { package: 'minimist', ecosystem: 'npm', severity: 'medium', summary: 'Prototype pollution' }, + ], + secretScanning: [{ secretType: 'github_personal_access_token' }], + }, + }, + }, + people: { alice: { role: 'write' }, bob: { role: 'read' } }, + }) + Object.assign(process.env, { EVE_DEV: '1', GITHUB_TOOLS_EMULATE_GITHUB: github.url, GITHUB_TOOLS_EMULATE_CONNECT: 'http://127.0.0.1:9' }) + await import('./redirect') +}) + +afterAll(() => github.close()) + +describe('every tool against the GitHub emulator', () => { + it.each(TOOLS.map(tool => tool.name))('%s is answered', async (name) => { + for (const input of await inputs(name, github.admin)) { + await expect(run(name, github.admin, input), `${name}(${JSON.stringify(input)})`).resolves.toBeDefined() + } + }) + + // `createOrUpdateFile` and `editFiles` fall back to REST when their GraphQL call fails, so a missing handler would hide behind a success. + it('was sent no GraphQL document it doesn\'t answer', () => { + expect(github.unknownDocuments).toEqual([]) + }) + + it.each(TOOLS.filter(tool => tool.writeTool).map(tool => tool.name))('%s as a reader', async (name) => { + const [input] = await inputs(name, 'bob') + const allowed = READER_MAY[name as GithubWriteToolName] + if (allowed) { + const result = await run(name, 'bob', input).catch((error: unknown) => { + throw new Error(`${name} should succeed for a person with Read: ${allowed.why}`, { cause: error }) + }) + await allowed.holds?.(input as Record, result) + return + } + const outcome = await run(name, 'bob', input).then(result => ({ result, error: undefined }), (error: unknown) => ({ result: undefined, error })) + expect(isForbidden(outcome.error), `${name} should be refused for a person with Read, and got ${JSON.stringify(outcome)}`).toBe(true) + }) + + // The reader cases above update alice's issue, which GitHub refuses. On their own issue, GitHub applies what an author may change. + it('updateIssue as the author keeps their edit and drops the labels, assignees, and milestone', async () => { + const own = await call<{ number: number }>('bob', 'POST', '/issues', { title: unique('Issue') }) + await run('updateIssue', 'bob', { ...web, issueNumber: own.number, title: 'A better title', labels: ['bug'], assignees: ['alice'], milestone: await milestone() }) + expect((await call<{ title: string }>('alice', 'GET', `/issues/${own.number}`)).title).toBe('A better title') + expect(await triaged(own.number)).toEqual(UNTRIAGED) + }) + + it('answers the review thread lookup of the caller-access check', async () => { + const { threadId } = await reviewThread() + const installation = await github.mintInstallationToken() + // A GitHub commenter is the caller, and the tool runs with the App's token once their role on the thread's repository allows it. + const as = (login: string) => executeGithubEveTool('resolveReviewThread', { threadId }, { token: withGithubCallerAccess(installation.token, { login, repository: web }) }) + await expect(as('bob')).rejects.toMatchObject({ cause: { code: 'github_tools.CALLER_FORBIDDEN' } }) + await expect(as('alice')).resolves.toMatchObject({ threadId, isResolved: true }) + expect(github.unknownDocuments).toEqual([]) + }) + + it('has no supplement route that emulate answers itself', async () => { + const plain = await startGithubEmulator({ repositories: { [REPO]: {} }, supplement: false }) + // Param names differ between two definitions of one route, so they are compared without them. + const shape = (route: { method: string, path: string }) => `${route.method} ${route.path.replace(/:\w+(?:\{[^}]*\})?/gu, ':param')}` + const emulated = new Set(plain.app.routeTable.map(shape)) + await plain.close() + expect(github.supplementRoutes.length).toBeGreaterThan(0) + for (const route of github.supplementRoutes) { + expect(emulated.has(shape(route)), `emulate now answers ${route.method} ${route.path}: delete this route from the supplement`).toBe(false) + } + }) +}) diff --git a/packages/github-tools-eve-extension/testing/emulate.ts b/packages/github-tools-eve-extension/testing/emulate.ts new file mode 100644 index 0000000..76265c7 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/emulate.ts @@ -0,0 +1,137 @@ +import { setEnvironmentData, type Worker } from 'node:worker_threads' +import type { EveEvalSession, EveEvalTurn } from 'eve/evals' +import { GithubClient, type EvalTarget } from './client.js' +import { startConnectEmulator, type ConnectEmulator, type ConnectRequest } from './connect/emulator.js' +import { CONNECT_URL_ENV, GITHUB_URL_ENV, PROBE_KEY } from './env.js' +import { startGithubEmulator, type GithubEmulator, type PersonSeed, type RepositorySeed } from './github/emulator.js' + +export interface EmulateGithubOptions { + /** Repositories by full name, such as `acme/web`. An owner named in `people` is that user, and any other is an organization. */ + repositories: Record + /** + * The people evals act as. Each is a GitHub user with a role on every repository, and the + * GitHub account of the eve principal with the same name: `as('alice')` sends a message as her. + */ + people?: Record +} + +/** What an eval reads from Vercel Connect, as `t.context.connect`. */ +export class ConnectClient { + constructor(private readonly connect: ConnectEmulator) {} + + /** Every request the Connect emulator answered, in order, with the subject and the scopes each token asked for. */ + get requests(): readonly ConnectRequest[] { + return this.connect.requests + } + + /** + * Invalidates the token Vercel Connect holds for a person, at GitHub. Their next call gets + * `401`, eve drops the token it cached, and asks them to sign in. + */ + revoke(person: string): void { + this.connect.revoke(person) + } + + /** + * Finishes the sign-in a turn asked for, the way a browser does after the person consents on + * GitHub, and returns the turn that resumes. + */ + async completeSignIn(t: { readonly target: { fetch(path: string): Promise } }, turn: Pick & { readonly session: Pick }): Promise { + const url = turn.interactions.find(interaction => interaction.request.kind === 'sign-in')?.request.signIn?.url + if (!url) throw new Error('The turn asked for no sign-in.') + const { pathname, search } = new URL(url) + const callback = await t.target.fetch(`${pathname}${search}`) + if (!callback.ok) throw new Error(`The sign-in callback answered ${callback.status}.`) + return turn.session.nextTurn() + } +} + +/** The running emulators, returned by `emulateGithub` from an eval's `setup`. */ +export interface GithubEmulation { + readonly github: GithubClient + readonly connect: ConnectClient + /** Stops both emulators. Call it from `teardown`. */ + close(): Promise +} + +const PROBE_SLOTS = 64 + +/** + * Starts a GitHub emulator and a Vercel Connect emulator, and points the agent at them. Call it + * from `setup` in `evals/evals.config.ts`: everything the agent needs is in `process.env` when it + * returns, which is before eve starts the agent. If the agent's thread then starts without the + * redirect to the emulators, the run fails before the first eval. + * + * ```ts + * export default defineEvalConfig({ + * setup: () => emulateGithub({ + * repositories: { 'acme/web': { labels: ['bug'] } }, + * people: { alice: { role: 'write' }, bob: { role: 'read' } }, + * }), + * teardown: context => context?.close(), + * }) + * ``` + */ +export async function emulateGithub({ repositories, people = {} }: EmulateGithubOptions): Promise { + const github = await startGithubEmulator({ repositories, people }) + const connect = await startConnectEmulator(github, people) + const installation = await github.mintInstallationToken() + // The redirect writes the ID of each thread it loads in to this buffer, which every worker of this process shares. + const probe = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * PROBE_SLOTS)) + setEnvironmentData(PROBE_KEY, probe.buffer) + + // eve runs the agent in a worker thread of this process. A worker's first message comes after + // Node ran the preload there, and the agent's is its address, which eve waits for before the first eval. + const probeWorker = (worker: Worker) => { + worker.once('message', () => { + if (probe.subarray(1, 1 + Atomics.load(probe, 0)).includes(worker.threadId)) return + throw new Error([ + `GitHub is emulated for this eval run, and thread ${worker.threadId} started without the redirect to the emulators.`, + 'The agent would send the emulators\' tokens to api.github.com and api.vercel.com, so the run stops here.', + '`emulateGithub` names the redirect in NODE_OPTIONS, and eve gives the agent\'s thread that environment.', + 'Check that nothing clears NODE_OPTIONS after `setup`, and that this version of eve still starts the agent in a worker thread of the `eve eval` process.', + ].join(' ')) + }) + } + process.on('worker', probeWorker) + + // Resolved through the package's name: eve can bundle this file into a cache directory, away from its neighbors. + const redirect = new URL('./redirect.js', import.meta.resolve('@github-tools/eve-extension/testing')).href + + const environment: Record = { + [GITHUB_URL_ENV]: github.url, + [CONNECT_URL_ENV]: connect.url, + // eve gives the agent's thread this environment, and Node loads the redirect there before any agent file. + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=${redirect}`.trim(), + // `@vercel/connect` refuses to send a request without an unexpired OIDC token. + VERCEL_OIDC_TOKEN: `e30.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 86_400 })).toString('base64url')}.emulator`, + // A mount with a static token would send the real one to the emulator. + GITHUB_TOKEN: installation.token!, + // What eve's GitHub channel reads when it has no `credentials`. + GITHUB_APP_ID: String(github.githubApp.id), + GITHUB_APP_PRIVATE_KEY: github.githubApp.privateKey, + GITHUB_APP_SLUG: github.githubApp.slug, + GITHUB_WEBHOOK_SECRET: github.githubApp.webhookSecret, + } + const previous = Object.fromEntries(Object.keys(environment).map(name => [name, process.env[name]])) + Object.assign(process.env, environment) + + return { + github: new GithubClient(github, Object.keys(repositories)), + connect: new ConnectClient(connect), + async close() { + for (const [name, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[name] + else process.env[name] = value + } + process.off('worker', probeWorker) + setEnvironmentData(PROBE_KEY, undefined) + await Promise.all([github.close(), connect.close()]) + }, + } +} + +/** Request options that send a message, or answer an approval, as a seeded person. */ +export const as = (person: string) => ({ headers: { 'x-eval-user': person } }) + +export type { EvalTarget, GithubEmulator } diff --git a/packages/github-tools-eve-extension/testing/emulators.ts b/packages/github-tools-eve-extension/testing/emulators.ts new file mode 100644 index 0000000..0764d25 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/emulators.ts @@ -0,0 +1,10 @@ +// `@emulators/core` reads files next to itself when it loads. eve bundles what an eval imports +// from a package linked in a workspace, and a bundled copy would look for those files beside the +// bundle. A specifier the bundler can't follow leaves both packages for Node to load. +const load = (name: string): Promise => import(name) + +const core = await load('@emulators/core') +const github = await load('@emulators/github') + +export const { ApiError, Hono, createServer, serve } = core +export const { createAppKeyResolver, getGitHubStore, githubPlugin, prepareSeed, seedFromConfig } = github diff --git a/packages/github-tools-eve-extension/testing/env.ts b/packages/github-tools-eve-extension/testing/env.ts new file mode 100644 index 0000000..dea161c --- /dev/null +++ b/packages/github-tools-eve-extension/testing/env.ts @@ -0,0 +1,12 @@ +/** Set by `emulateGithub` before the agent starts, and read by the redirect and the agent-side helpers. */ +export const GITHUB_URL_ENV = 'GITHUB_TOOLS_EMULATE_GITHUB' +export const CONNECT_URL_ENV = 'GITHUB_TOOLS_EMULATE_CONNECT' + +/** Set on `globalThis` by the redirect once it wraps `fetch`. */ +export const REDIRECT_MARKER = Symbol.for('github-tools.emulate.redirect') + +/** + * `worker_threads` environment data key for a shared buffer. Slot 0 counts the threads of the + * `eve eval` process the redirect loaded in, and the slots after it hold their thread IDs. + */ +export const PROBE_KEY = 'github-tools.emulate.probe' diff --git a/packages/github-tools-eve-extension/testing/github/access.ts b/packages/github-tools-eve-extension/testing/github/access.ts new file mode 100644 index 0000000..1292fef --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/access.ts @@ -0,0 +1,136 @@ +import type { AppEnv, Context } from '@emulators/core' +import type { GitHubRepo, GitHubStore, GitHubUser } from '@emulators/github' +import { ApiError } from '../emulators.js' + +export type Ctx = Context + +/** GitHub's repository roles, lowest first. */ +export type Role = 'read' | 'triage' | 'write' | 'maintain' | 'admin' + +export const ROLE_RANK: Record = { read: 1, triage: 2, write: 3, maintain: 4, admin: 5 } + +/** emulate stores a collaborator's role under GitHub's legacy permission names. */ +export const ROLE_PERMISSION = { read: 'pull', triage: 'triage', write: 'push', maintain: 'maintain', admin: 'admin' } as const satisfies Record + +const PERMISSION_ROLE: Record = { pull: 'read', triage: 'triage', push: 'write', maintain: 'maintain', admin: 'admin' } + +export function findRepo(gh: GitHubStore, owner: string, name: string): GitHubRepo { + const repo = gh.repos.findOneBy('full_name', `${owner}/${name}`) + if (!repo) throw new ApiError(404, 'Not Found') + return repo +} + +function isOrgMember(gh: GitHubStore, userId: number, orgId: number): boolean { + return gh.teams.findBy('org_id', orgId).some(team => gh.teamMembers.findBy('team_id', team.id).some(member => member.user_id === userId)) +} + +/** + * Rank of a person's role on a repository, 0 when they can't see it. Follows emulate's own + * `computeRepoPermissions`, so it agrees with what `GET .../collaborators/{user}/permission` reports. + */ +export function roleRank(gh: GitHubStore, user: GitHubUser, repo: GitHubRepo): number { + if (repo.owner_type === 'User' && repo.owner_id === user.id) return ROLE_RANK.admin + if (repo.owner_type === 'Organization' && isOrgMember(gh, user.id, repo.owner_id)) return ROLE_RANK.admin + const collaborator = gh.collaborators.findBy('repo_id', repo.id).find(entry => entry.user_id === user.id) + if (collaborator) return ROLE_RANK[PERMISSION_ROLE[collaborator.permission]!] + return repo.private ? 0 : ROLE_RANK.read +} + +/** What the emulator answers a personal token below the role a request needs. */ +export const ROLE_REFUSAL = 'Resource not accessible by personal access token' + +export const forbiddenForRole = () => new ApiError(403, ROLE_REFUSAL) + +// emulate's `installationActor`, which it doesn't export: the App's bot user, created on first use. +function installationBot(gh: GitHubStore, appId: number): GitHubUser { + const app = gh.apps.all().find(entry => entry.app_id === appId) + const login = `${app?.slug ?? `app-${appId}`}[bot]` + const existing = gh.users.findOneBy('login', login) + if (existing) return existing + const bot = gh.users.insert({ + login, + node_id: '', + avatar_url: '', + gravatar_id: '', + type: 'Bot', + site_admin: false, + name: app?.name ?? 'GitHub App', + company: null, + blog: '', + location: null, + email: `${appId}+${login}@users.noreply.github.com`, + hireable: null, + bio: null, + twitter_username: null, + public_repos: 0, + public_gists: 0, + followers: 0, + following: 0, + }) + return gh.users.update(bot.id, { node_id: Buffer.from(`0:Bot${bot.id}`).toString('base64').replace(/=+$/u, '') })! +} + +export interface Requirement { + /** The GitHub App permission an installation token needs, such as `issues`. Any one of several is enough. */ + permission: string | string[] + access: 'read' | 'write' + /** The lowest repository role a personal token needs. */ + role: Role +} + +/** + * Who is calling, once they are allowed to. Repeats emulate's `assertRepoPermission` for an + * installation token and adds the role check emulate skips for a personal token. + */ +export function requireActor(c: Ctx, gh: GitHubStore, repo: GitHubRepo, { permission, access, role }: Requirement): GitHubUser { + const auth = c.get('authUser') + if (!auth) throw new ApiError(401, 'Requires authentication') + if (auth.installation) { + const { installation } = auth + const reaches = repo.owner_id === installation.accountId && repo.owner_type === installation.accountType + && (installation.repositorySelection === 'all' || installation.repositoryIds.includes(repo.id)) + const granted = [permission].flat().some((name) => { + const level = installation.permissions[name] + return access === 'write' ? level === 'write' : level === 'read' || level === 'write' + }) + if (!reaches || !granted) throw new ApiError(403, 'Resource not accessible by integration') + return installationBot(gh, installation.appId) + } + const user = gh.users.findOneBy('login', auth.login) + if (!user) throw new ApiError(401, 'Bad credentials') + const rank = roleRank(gh, user, repo) + if (rank === 0) throw new ApiError(404, 'Not Found') + if (rank < ROLE_RANK[role]) throw forbiddenForRole() + return user +} + +/** A read anyone may make on a public repository, and only someone with access on a private one. */ +export function requireRead(c: Ctx, gh: GitHubStore, repo: GitHubRepo, permission: string): void { + if (!repo.private && !c.get('authUser')?.installation) return + requireActor(c, gh, repo, { permission, access: 'read', role: 'read' }) +} + +/** A personal token's user. Gists and notifications belong to a user, so an installation token can't use them. */ +export function requireUser(c: Ctx, gh: GitHubStore): GitHubUser { + const auth = c.get('authUser') + if (!auth) throw new ApiError(401, 'Requires authentication') + if (auth.installation) throw new ApiError(403, 'Resource not accessible by integration') + const user = gh.users.findOneBy('login', auth.login) + if (!user) throw new ApiError(401, 'Bad credentials') + return user +} + +/** Replaces a request's JSON body. emulate reads the body from `c.req.raw`, so the route receives the new one. */ +export function replaceBody(c: Ctx, body: unknown): void { + const headers = new Headers(c.req.raw.headers) + headers.set('content-type', 'application/json') + ;(c.req as { raw: Request }).raw = new Request(c.req.raw.url, { method: c.req.method, headers, body: JSON.stringify(body) }) +} + +export const briefUser = (user: GitHubUser | undefined) => user ? { login: user.login, id: user.id, node_id: user.node_id, type: user.type, site_admin: user.site_admin } : null + +export function paginate(c: Ctx, items: T[]): T[] { + const perPage = Math.min(Number(c.req.query('per_page') ?? 30) || 30, 100) + const page = Math.max(Number(c.req.query('page') ?? 1) || 1, 1) + return items.slice((page - 1) * perPage, page * perPage) +} diff --git a/packages/github-tools-eve-extension/testing/github/emulator.test.ts b/packages/github-tools-eve-extension/testing/github/emulator.test.ts new file mode 100644 index 0000000..94a1cd8 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/emulator.test.ts @@ -0,0 +1,210 @@ +import { createHmac } from 'node:crypto' +import { once } from 'node:events' +import { createServer, type IncomingMessage } from 'node:http' +import type { AddressInfo } from 'node:net' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { startGithubEmulator, type GithubEmulator } from './emulator' +import { documentKey } from './supplement/graphql' + +let github: GithubEmulator + +// Over HTTP, as the agent calls the emulator, so the request log sees it. +async function api(login: string | undefined, method: string, path: string, body?: unknown, token = login && github.tokenFor(login)) { + const response = await fetch(`${github.url}${path}`, { + method, + headers: { ...token ? { authorization: `Bearer ${token}` } : {}, 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }) + const text = await response.text() + return { status: response.status, body: text ? JSON.parse(text) : undefined } +} + +const graphql = (login: string, query: string, variables: Record) => api(login, 'POST', '/graphql', { query, variables }) +const issue = (login: string) => github.request<{ number: number }>(login, 'POST', '/repos/acme/web/issues', { title: 'Crash on save' }) + +beforeAll(async () => { + github = await startGithubEmulator({ + repositories: { 'acme/web': { labels: ['bug'] }, 'acme/secret': { private: true }, 'erin/dotfiles': {} }, + people: { alice: { role: 'write' }, tara: { role: 'triage' }, bob: { role: 'read' }, mallory: {}, erin: {} }, + }) +}) + +beforeEach(() => github.reset()) + +afterAll(() => github.close()) + +describe('the role guard', () => { + it('answers 401 to a token GitHub doesn\'t know, and to one that was revoked', async () => { + expect((await api(undefined, 'GET', '/repos/acme/web', undefined, 'ghp_unknown')).status).toBe(401) + github.registerToken('ghu_alice_1', 'alice') + expect((await api(undefined, 'GET', '/repos/acme/web', undefined, 'ghu_alice_1')).status).toBe(200) + github.revokeToken('ghu_alice_1') + expect((await api(undefined, 'GET', '/repos/acme/web', undefined, 'ghu_alice_1')).status).toBe(401) + expect((await api(undefined, 'GET', '/repos/acme/web')).status).toBe(200) + }) + + it('lets anyone who can read open an issue and comment, and needs Triage to label', async () => { + const { number } = await issue('mallory') + const label = (login: string) => api(login, 'POST', `/repos/acme/web/issues/${number}/labels`, { labels: ['bug'] }) + expect((await api('bob', 'POST', `/repos/acme/web/issues/${number}/comments`, { body: 'Same here.' })).status).toBe(201) + expect([(await label('mallory')).status, (await label('bob')).status, (await label('tara')).status, (await label('alice')).status]).toEqual([403, 403, 200, 200]) + }) + + it('needs Write to merge and to manage labels, which Triage doesn\'t give', async () => { + const create = (login: string) => api(login, 'POST', '/repos/acme/web/labels', { name: `label-${login}`, color: 'ededed' }) + expect([(await create('bob')).status, (await create('tara')).status, (await create('alice')).status]).toEqual([403, 403, 201]) + }) + + // What GitHub ignores from a person without Triage: its labels, assignees, and milestone. + const triaged = async (number: number) => { + const { body } = await api('alice', 'GET', `/repos/acme/web/issues/${number}`) + return { labels: body.labels.map((label: { name: string }) => label.name), assignees: body.assignees.map((user: { login: string }) => user.login), milestone: body.milestone?.number ?? null } + } + + it('lets an author edit and close their own issue, and refuses someone else below Triage', async () => { + const { number } = await issue('bob') + const patch = (login: string, body: unknown) => api(login, 'PATCH', `/repos/acme/web/issues/${number}`, body) + expect((await patch('bob', { title: 'Crash on save, with a trace' })).status).toBe(200) + expect((await patch('mallory', { state: 'closed' })).status).toBe(403) + expect((await patch('mallory', { labels: ['bug'] })).status).toBe(403) + expect((await patch('bob', { state: 'closed' })).body.state).toBe('closed') + }) + + it('accepts an issue from a person without Triage and drops its labels, assignees, and milestone, as GitHub does', async () => { + const { number: milestone } = await github.request<{ number: number }>('alice', 'POST', '/repos/acme/web/milestones', { title: 'v1' }) + const fields = { labels: ['bug'], assignees: ['alice'], milestone } + const create = (login: string) => api(login, 'POST', '/repos/acme/web/issues', { title: 'Crash on save', ...fields }) + + const byReader = await create('bob') + expect([byReader.status, byReader.body.title, await triaged(byReader.body.number)]).toEqual([201, 'Crash on save', { labels: [], assignees: [], milestone: null }]) + const byTriager = await create('tara') + expect([byTriager.status, await triaged(byTriager.body.number)]).toEqual([201, fields]) + + // An author's update goes through, without the fields they may not set. + const updated = await api('bob', 'PATCH', `/repos/acme/web/issues/${byReader.body.number}`, { title: 'Crash on save, with a trace', ...fields }) + expect([updated.status, updated.body.title, await triaged(byReader.body.number)]).toEqual([200, 'Crash on save, with a trace', { labels: [], assignees: [], milestone: null }]) + const cleared = await api('bob', 'PATCH', `/repos/acme/web/issues/${byTriager.body.number}`, { labels: [], assignees: [], milestone: null }) + expect([cleared.status, await triaged(byTriager.body.number)]).toEqual([403, fields]) + }) + + it('answers a person without Triage who assigns with success, and assigns nobody', async () => { + const { number } = await issue('bob') + const assign = (login: string, method: string) => api(login, method, `/repos/acme/web/issues/${number}/assignees`, { assignees: ['alice'] }) + // emulate answers 200 to everyone here, where GitHub answers 201. + expect([(await assign('bob', 'POST')).status, (await triaged(number)).assignees]).toEqual([200, []]) + expect([(await assign('tara', 'POST')).status, (await triaged(number)).assignees]).toEqual([200, ['alice']]) + expect([(await assign('bob', 'DELETE')).status, (await triaged(number)).assignees]).toEqual([200, ['alice']]) + expect([(await assign('tara', 'DELETE')).status, (await triaged(number)).assignees]).toEqual([200, []]) + }) + + it('lets an author edit their own comment, and needs Write for someone else\'s', async () => { + const { number } = await issue('bob') + const { id } = await github.request<{ id: number }>('bob', 'POST', `/repos/acme/web/issues/${number}/comments`, { body: 'First.' }) + const edit = (login: string) => api(login, 'PATCH', `/repos/acme/web/issues/comments/${id}`, { body: 'Edited.' }) + expect([(await edit('bob')).status, (await edit('tara')).status, (await edit('alice')).status]).toEqual([200, 403, 200]) + }) + + it('reports the same roles it enforces, as GitHub names them', async () => { + const role = async (repo: string, login: string) => { + const { body } = await api('alice', 'GET', `/repos/${repo}/collaborators/${login}/permission`) + return `${body.permission}/${body.role_name}` + } + expect(await Promise.all(['alice', 'tara', 'bob', 'mallory'].map(login => role('acme/web', login)))).toEqual(['write/write', 'read/triage', 'read/read', 'read/read']) + expect(await role('acme/secret', 'mallory')).toBe('none/none') + // A user's own repository: erin is its admin, and the people with a role keep it there. + expect([await role('erin/dotfiles', 'erin'), await role('erin/dotfiles', 'alice')]).toEqual(['admin/admin', 'write/write']) + }) + + it('checks an installation token\'s permissions on a route the supplement adds', async () => { + const { number } = await issue('bob') + const narrowed = await github.mintInstallationToken({ permissions: { issues: 'read', metadata: 'read' } }) + const full = await github.mintInstallationToken() + const react = (token: string) => api(undefined, 'POST', `/repos/acme/web/issues/${number}/reactions`, { content: 'eyes' }, token) + expect((await react(narrowed.token!)).status).toBe(403) + const reaction = await react(full.token!) + expect([reaction.status, reaction.body.user.login]).toEqual([201, `${github.githubApp.slug}[bot]`]) + }) +}) + +describe('the emulator', () => { + it('logs each request over HTTP with who made it, and none of its own', async () => { + const { number } = await issue('bob') + await api('bob', 'POST', `/repos/acme/web/issues/${number}/labels`, { labels: ['bug'] }) + await api(undefined, 'GET', '/repos/acme/web') + expect(github.requests).toEqual([ + { method: 'POST', path: `/repos/acme/web/issues/${number}/labels`, status: 403, actor: 'bob' }, + { method: 'GET', path: '/repos/acme/web', status: 200, actor: 'anonymous' }, + ]) + }) + + it('goes back to the seeded state on reset', async () => { + await issue('bob') + await github.reset() + expect((await api('alice', 'GET', '/repos/acme/web/issues')).body).toEqual([]) + expect((await api('alice', 'GET', '/repos/acme/web/labels')).body.map((label: { name: string }) => label.name)).toEqual(['bug']) + expect((await api('bob', 'POST', '/repos/acme/web/labels', { name: 'docs' })).status).toBe(403) + }) + + it('signs a webhook and names the pull request in an issue_comment payload', async () => { + const received: Array<{ event: string, signature: string, body: string }> = [] + const read = (request: IncomingMessage) => new Promise((resolve) => { + let body = '' + request.on('data', chunk => body += chunk).on('end', () => resolve(body)) + }) + const receiver = createServer(async (request, response) => { + received.push({ event: String(request.headers['x-github-event']), signature: String(request.headers['x-hub-signature-256']), body: await read(request) }) + response.end() + }).listen(0, '127.0.0.1') + await once(receiver, 'listening') + const url = `http://127.0.0.1:${(receiver.address() as AddressInfo).port}` + await github.request(github.admin, 'POST', '/repos/acme/web/hooks', { config: { url, content_type: 'json', secret: github.githubApp.webhookSecret }, events: ['issue_comment'] }) + + const { object } = await github.request<{ object: { sha: string } }>('alice', 'GET', '/repos/acme/web/git/ref/heads/main') + await github.request('alice', 'POST', '/repos/acme/web/git/refs', { ref: 'refs/heads/fix', sha: object.sha }) + await github.request('alice', 'PUT', '/repos/acme/web/contents/fix.txt', { message: 'Fix', content: Buffer.from('fix\n').toString('base64'), branch: 'fix' }) + const pull = await github.request<{ number: number }>('alice', 'POST', '/repos/acme/web/pulls', { title: 'Fix', head: 'fix', base: 'main' }) + await github.request('alice', 'POST', `/repos/acme/web/issues/${pull.number}/comments`, { body: 'Ready.' }) + await expect.poll(() => received.length).toBe(1) + receiver.close() + + const [{ event, signature, body }] = received as [typeof received[number]] + const payload = JSON.parse(body) + expect(event).toBe('issue_comment') + expect(signature).toBe(`sha256=${createHmac('sha256', github.githubApp.webhookSecret).update(body).digest('hex')}`) + expect(payload.issue.pull_request.url).toBe(`${github.url}/repos/acme/web/pulls/${pull.number}`) + expect(payload.installation.id).toBe(github.githubApp.installations.acme) + }) +}) + +describe('the GraphQL handler', () => { + it('names a document by its root field, with or without an operation name', () => { + expect(documentKey('mutation($pullRequestId: ID!) { convertPullRequestToDraft(input: { pullRequestId: $pullRequestId }) { pullRequest { id } } }')).toBe('convertPullRequestToDraft') + expect(documentKey('query ReviewThreads($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviewThreads(first: 1) { totalCount } } } }')).toBe('repository.pullRequest.reviewThreads') + expect(documentKey('query ($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { discussionCategories(first: 100) { nodes { id } } } }')).toBe('repository.discussionCategories') + }) + + it('answers a document it doesn\'t know with an error that says so, and records it', async () => { + const { status, body } = await graphql('alice', 'query { viewer { login } }', {}) + expect(status).toBe(200) + expect(body.errors[0]).toMatchObject({ type: 'EMULATOR_UNSUPPORTED', message: expect.stringContaining('query { viewer { login } }') }) + expect(github.unknownDocuments).toEqual(['query { viewer { login } }']) + }) + + it('blames each line on the commit that introduced it', async () => { + const put = async (content: string, message: string, sha?: string) => { + const { content: file, commit } = await github.request<{ content: { sha: string }, commit: { sha: string } }>('alice', 'PUT', '/repos/acme/web/contents/notes.md', { message, content: Buffer.from(content).toString('base64'), sha }) + return { blob: file.sha, commit: commit.sha } + } + const first = await put('one\ntwo\nthree\n', 'Add notes') + const second = await put('one\nTWO\nthree\nfour\n', 'Change two, add four', first.blob) + const { body } = await graphql('bob', 'query ($owner: String!, $name: String!, $expression: String!, $path: String!) { repository(owner: $owner, name: $name) { object(expression: $expression) { ... on Commit { oid blame(path: $path) { ranges { startingLine } } } } } }', { owner: 'acme', name: 'web', expression: 'main', path: 'notes.md' }) + const { oid, blame } = body.data.repository.object + expect(oid).toBe(second.commit) + expect(blame.ranges.map((range: { startingLine: number, endingLine: number, commit: { oid: string, messageHeadline: string } }) => [range.startingLine, range.endingLine, range.commit.messageHeadline])).toEqual([ + [1, 1, 'Add notes'], + [2, 2, 'Change two, add four'], + [3, 3, 'Add notes'], + [4, 4, 'Change two, add four'], + ]) + }) +}) diff --git a/packages/github-tools-eve-extension/testing/github/emulator.ts b/packages/github-tools-eve-extension/testing/github/emulator.ts new file mode 100644 index 0000000..6b1e621 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/emulator.ts @@ -0,0 +1,309 @@ +import { once } from 'node:events' +import type { Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { createSign, randomBytes } from 'node:crypto' +import type { AppEnv, Hono, ServicePlugin, Store, TokenMap, WebhookDispatcher } from '@emulators/core' +import type { GitHubSeedConfig, GitHubStore } from '@emulators/github' +import { createAppKeyResolver, createServer, getGitHubStore, githubPlugin, prepareSeed, seedFromConfig, serve } from '../emulators.js' +import { ROLE_PERMISSION, type Role } from './access.js' +import { registerRequestFixes } from './fixes.js' +import { registerRoleGuard } from './role-guard.js' +import { fixWebhookPayloads, registerSupplementRoutes, type SecurityAlertSeeds } from './supplement/index.js' + +export type { Role } from './access.js' +export type { CodeScanningAlertSeed, DependabotAlertSeed, SecretScanningAlertSeed, SecurityAlertSeeds } from './supplement/security.js' + +/** A repository to create before the first eval, with a README on its default branch. */ +export interface RepositorySeed { + private?: boolean + /** Names of the labels the repository starts with. */ + labels?: string[] + /** Workflow file names under `.github/workflows`, such as `ci.yml`. emulate has no route that creates a workflow. */ + workflows?: string[] + /** Security alerts the repository lists. */ + alerts?: SecurityAlertSeeds +} + +/** A person, who is a GitHub user and, once they sign in, the user behind an eve principal with the same name. */ +export interface PersonSeed { + /** Their role on every seeded repository. Without one they are a GitHub user with no role. */ + role?: Role + /** `false` for a person who hasn't connected GitHub through Vercel Connect yet. */ + authorized?: boolean +} + +export interface GithubEmulatorOptions { + /** Repositories by full name, such as `acme/web`. An owner named in `people` is that user, and any other is an organization. */ + repositories: Record + people?: Record + /** Registers the routes emulate lacks. Only the coverage test turns it off, to ask emulate what it answers alone. */ + supplement?: boolean +} + +/** One request the emulator answered over HTTP. */ +export interface GithubRequest { + method: string + path: string + status: number + /** The login behind the token, the App's bot for an installation token, `app` for an App JWT, `unknown` for a token the emulator doesn't know, or `anonymous`. */ + actor: string +} + +/** The seeded GitHub App, which is installed on every seeded owner with every permission. */ +export interface GithubEmulatorApp { + id: number + slug: string + privateKey: string + webhookSecret: string + /** Installation IDs by owner. */ + installations: Record +} + +const ADMIN = 'emulator-admin' +const APP_ID = 1 +const APP_SLUG = 'eve-agent' +const APP_PERMISSIONS = { + actions: 'write', + administration: 'write', + checks: 'write', + contents: 'write', + discussions: 'write', + issues: 'write', + metadata: 'read', + pull_requests: 'write', + secret_scanning_alerts: 'read', + security_events: 'read', + statuses: 'write', + vulnerability_alerts: 'read', + workflows: 'write', +} + +export type GithubEmulator = Awaited> + +/** + * Starts emulate's GitHub service on a loopback port with the role guard and the supplement. + * `createEmulator` from `emulate` only takes a built-in service, so this owns what it does around + * `createServer`: preparing the seed, resolving App keys, `reset()`, and listening. + */ +export async function startGithubEmulator({ repositories, people = {}, supplement = true }: GithubEmulatorOptions) { + const requests: GithubRequest[] = [] + const unknownDocuments: string[] = [] + const supplementRoutes: Array<{ method: string, path: string }> = [] + const tokenLogins = new Map() + const personalTokens = new Map() + const webhookSecret = randomBytes(24).toString('hex') + const owners = [...new Set(Object.keys(repositories).map(name => name.split('/')[0]!))] + const installations = Object.fromEntries(owners.map((owner, index) => [owner, 1000 + index])) + let parts: ReturnType | undefined + let ids = 0 + + const plugin: ServicePlugin = { + name: 'github', + register(app, store, webhooks, baseUrl, tokenMap) { + const context = { app, store, gh: getGitHubStore(store), webhooks, baseUrl } + registerRoleGuard(app, store) + registerRequestFixes(app, store) + if (supplement) { + const before = app.routeTable.length + parts = registerSupplementRoutes(context, unknownDocuments) + supplementRoutes.push(...app.routeTable.slice(before).map(({ method, path }) => ({ method, path }))) + } + githubPlugin.register(app, store, webhooks, baseUrl, tokenMap) + if (parts) fixWebhookPayloads(context, parts.notify) + }, + seed: githubPlugin.seed, + } + + function actorOf(request: Request): string { + const token = request.headers.get('authorization')?.replace(/^(?:bearer|token)\s+/iu, '').trim() + if (!token) return 'anonymous' + if (token.startsWith('eyJ')) return 'app' + const installation = tokenMap.get(token)?.installation + if (installation) return `${gh.apps.all().find(app => app.app_id === installation.appId)?.slug}[bot]` + return tokenLogins.get(token) ?? 'unknown' + } + + // The routes need the server's URL, so it listens first and answers once they exist. + const server: Server = serve({ + port: 0, + fetch: async (request) => { + const response = await app.fetch(request) + requests.push({ method: request.method, path: new URL(request.url).pathname, status: response.status, actor: actorOf(request) }) + return response + }, + }) + await once(server, 'listening') + const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + + const users = [ADMIN, ...Object.keys(people)] + const prepared = await prepareSeed({ + users: users.map(login => ({ login })), + orgs: owners.filter(owner => !(owner in people)).map(login => ({ login, members: [{ login: ADMIN, role: 'admin' }] })), + repos: Object.entries(repositories).map(([fullName, repository]) => { + const [owner, name] = fullName.split('/') + return { owner: owner!, name: name!, private: repository.private ?? false, auto_init: true } + }), + apps: [{ + app_id: APP_ID, + slug: APP_SLUG, + name: 'eve agent', + permissions: APP_PERMISSIONS, + // Every event: emulate adds `installation` to a repository webhook's payload only for the events the App subscribes to. + events: ['*'], + installations: owners.map(owner => ({ installation_id: installations[owner]!, account: owner, repository_selection: 'all' })), + }], + } satisfies GitHubSeedConfig) + const privateKey = (prepared.config as GitHubSeedConfig).apps![0]!.private_key! + + const { app, store, webhooks, tokenMap }: { app: Hono, store: Store, webhooks: WebhookDispatcher, tokenMap: TokenMap } = createServer(plugin, { + baseUrl: url, + appKeyResolver: appId => createAppKeyResolver(store)(appId), + }) + const gh: GitHubStore = getGitHubStore(store) + + /** Calls the emulator in process, as a person. Nothing is added to `requests`. */ + async function request(login: string, method: string, path: string, body?: unknown): Promise { + const response = await app.request(path, { + method, + headers: { 'authorization': `Bearer ${tokenFor(login)}`, 'accept': 'application/vnd.github+json', 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }) + const text = await response.text() + if (!response.ok) throw new Error(`GitHub emulator: ${method} ${path} as ${login} answered ${response.status}: ${text}`) + return (text ? JSON.parse(text) : undefined) as T + } + + function registerToken(token: string, login: string): void { + const user = gh.users.findOneBy('login', login) + if (!user) throw new Error(`GitHub emulator: no user "${login}". Seeded people: ${Object.keys(people).join(', ') || 'none'}.`) + tokenMap.set(token, { login, id: user.id, scopes: ['repo', 'user', 'gist', 'notifications', 'workflow'] }) + tokenLogins.set(token, login) + } + + function tokenFor(login: string): string { + const token = personalTokens.get(login) + if (!token) throw new Error(`GitHub emulator: no person "${login}". Seeded people: ${Object.keys(people).join(', ') || 'none'}.`) + return token + } + + /** The admin of a repository or of its owner: the owner for a user's repository, the emulator's own admin for an organization's. */ + const adminOf = (name: string) => { + const owner = name.split('/')[0]! + return owner in people ? owner : ADMIN + } + + async function applyRoles(fullName: string): Promise { + for (const [login, person] of Object.entries(people)) { + if (person.role && login !== adminOf(fullName)) { + await request(adminOf(fullName), 'PUT', `/repos/${fullName}/collaborators/${login}`, { permission: ROLE_PERMISSION[person.role] }) + } + } + } + + // emulate's seed has no collaborators or labels, so both are set through its REST routes afterward. + async function seed(): Promise { + plugin.seed!(store, url) + seedFromConfig(store, url, prepared.config as GitHubSeedConfig) + for (const login of users) { + personalTokens.set(login, `ghp_${login}`) + registerToken(`ghp_${login}`, login) + } + for (const [fullName, repository] of Object.entries(repositories)) { + await applyRoles(fullName) + for (const name of repository.labels ?? []) { + await request(adminOf(fullName), 'POST', `/repos/${fullName}/labels`, { name }) + } + const repo = gh.repos.findOneBy('full_name', fullName)! + for (const file of repository.workflows ?? []) { + const name = file.replace(/\.ya?ml$/u, '') + const workflow = gh.workflows.insert({ node_id: '', repo_id: repo.id, name, path: `.github/workflows/${file}`, state: 'active', badge_url: `${url}/${fullName}/workflows/${name}/badge.svg` }) + gh.workflows.update(workflow.id, { node_id: `W_${workflow.id}` }) + } + if (repository.alerts) parts?.seedAlerts(repo, repository.alerts) + } + } + + function appJwt(): string { + const now = Math.floor(Date.now() / 1000) + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url') + const unsigned = `${encode({ alg: 'RS256', typ: 'JWT' })}.${encode({ iat: now - 60, exp: now + 540, iss: String(APP_ID) })}` + return `${unsigned}.${createSign('RSA-SHA256').update(unsigned).sign(privateKey, 'base64url')}` + } + await seed() + + return { + url, + app, + store, + webhooks, + /** Every request answered over HTTP, in order. In-process calls, such as seeding, aren't recorded. */ + requests, + /** GraphQL documents the emulator was sent and doesn't answer. */ + unknownDocuments, + /** The routes this package adds to emulate's. */ + supplementRoutes, + admin: ADMIN, + owners, + people: Object.keys(people), + /** A number no earlier call returned, for names that have to be unique in a run. */ + nextId: () => ++ids, + githubApp: { id: APP_ID, slug: APP_SLUG, privateKey, webhookSecret, installations } satisfies GithubEmulatorApp, + request, + adminOf, + applyRoles, + /** A person's own token, which the emulator knows from the seed. It isn't the one Vercel Connect issues for them. */ + tokenFor, + /** Makes the emulator accept `token` as `login`. */ + registerToken, + /** Makes the emulator answer `401` to `token`. */ + revokeToken(token: string): void { + tokenMap.delete(token) + }, + /** + * An installation token from emulate's own App flow: a JWT signed with the App's key, exchanged + * at `POST /app/installations/{id}/access_tokens`. emulate refuses permissions the installation lacks. + */ + async mintInstallationToken(options: { owner?: string, permissions?: Record, repositories?: string[] } = {}): Promise<{ status: number, token?: string, expiresAt?: string, message?: string }> { + const installation = installations[options.owner ?? owners[0]!] + if (installation === undefined) return { status: 404, message: `The App isn't installed on "${options.owner}".` } + const response = await app.request(`/app/installations/${installation}/access_tokens`, { + method: 'POST', + headers: { 'authorization': `Bearer ${appJwt()}`, 'content-type': 'application/json' }, + body: JSON.stringify({ permissions: options.permissions, repositories: options.repositories }), + }) + const body = await response.json() as { token?: string, expires_at?: string, message?: string } + return { status: response.status, token: body.token, expiresAt: body.expires_at, message: body.message } + }, + /** Ends a workflow run and its jobs with a conclusion. emulate starts a run and never finishes one. */ + finishWorkflowRun(runId: number, conclusion: 'success' | 'failure' | 'cancelled'): void { + const run = gh.workflowRuns.get(runId) + if (!run) throw new Error(`GitHub emulator: no workflow run ${runId}.`) + const now = new Date().toISOString() + gh.workflowRuns.update(run.id, { status: 'completed', conclusion }) + for (const job of gh.jobs.findBy('run_id', run.id)) { + gh.jobs.update(job.id, { status: 'completed', conclusion, completed_at: now, steps: job.steps.map(step => ({ ...step, status: 'completed', conclusion, completed_at: now })) }) + } + }, + createDiscussion(fullName: string, author: string, input: { title: string, body?: string, category?: string }) { + if (!parts) throw new Error('GitHub emulator: discussions need the supplement.') + const repo = gh.repos.findOneBy('full_name', fullName) + const user = gh.users.findOneBy('login', author) + if (!repo || !user) throw new Error(`GitHub emulator: no repository "${fullName}" or no user "${author}".`) + return parts.discussions.create(repo, user, input) + }, + /** Back to the seeded state: the store, the webhooks, the tokens, and the logs. */ + async reset(): Promise { + store.reset() + webhooks.clear() + tokenMap.clear() + tokenLogins.clear() + requests.length = 0 + unknownDocuments.length = 0 + await seed() + }, + close: () => new Promise((resolve, reject) => { + server.close(error => error ? reject(error) : resolve()) + server.closeAllConnections() + }), + } +} diff --git a/packages/github-tools-eve-extension/testing/github/fixes.ts b/packages/github-tools-eve-extension/testing/github/fixes.ts new file mode 100644 index 0000000..7fa1eff --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/fixes.ts @@ -0,0 +1,71 @@ +import type { AppEnv, Hono, Store } from '@emulators/core' +import { ApiError, getGitHubStore } from '../emulators.js' +import { briefUser, findRepo, replaceBody, requireRead, roleRank, type Ctx } from './access.js' +import { callAsCaller } from './supplement/context.js' + +interface ReviewComment { + path?: string + body?: string + position?: number + line?: number + side?: 'LEFT' | 'RIGHT' +} + +/** + * Requests emulate 0.13.1 has a route for and answers differently from GitHub. Registered before + * emulate's routes, each fix changes the request on its way in or the store on its way out. + */ +export function registerRequestFixes(app: Hono, store: Store): void { + const gh = getGitHubStore(store) + + // GitHub reads a write with no body as an empty object. emulate answers 400, which breaks + // `forkRepository` and `updatePullRequestBranch` when they send no option. + app.use('*', async (c: Ctx, next) => { + if (['POST', 'PUT', 'PATCH'].includes(c.req.method) && await c.req.raw.clone().text() === '') replaceBody(c, {}) + await next() + }) + + // emulate places a review's comments by `position`, which GitHub deprecated, and stores no line. + // The SDK sends `line` and `side`, so the line stands in for the position and is stored afterward. + app.use('/repos/:owner/:repo/pulls/:pull_number/reviews', async (c: Ctx, next) => { + if (c.req.method !== 'POST') return next() + const body = await c.req.raw.clone().json() as { comments?: ReviewComment[] } + const byLine = (body.comments ?? []).filter(comment => comment.position === undefined && comment.line !== undefined) + if (byLine.length === 0) return next() + replaceBody(c, { ...body, comments: body.comments!.map(comment => byLine.includes(comment) ? { ...comment, position: comment.line } : comment) }) + const before = Math.max(0, ...gh.comments.all().map(comment => comment.id)) + await next() + const repo = gh.repos.findOneBy('full_name', `${c.req.param('owner')}/${c.req.param('repo')}`) + const created = gh.comments.all().filter(comment => comment.id > before && comment.repo_id === repo?.id && comment.review_id !== null && comment.pull_number === Number(c.req.param('pull_number'))) + for (const sent of byLine) { + const comment = created.find(candidate => candidate.line === null && candidate.path === sent.path && candidate.body === sent.body) + if (comment) gh.comments.update(comment.id, { line: sent.line, side: sent.side ?? 'RIGHT' }) + } + }) + + // GitHub answers 200 for a user with no role, with `none` on a private repository and `read` + // on a public one, and names roles `read` and `write`. emulate answers 404, and names them + // `pull` and `push`. This route is registered first, so it replaces emulate's. + app.get('/repos/:owner/:repo/collaborators/:username/permission', (c: Ctx) => { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + requireRead(c, gh, repo, 'metadata') + const user = gh.users.findOneBy('login', c.req.param('username')) + if (!user) throw new ApiError(404, 'Not Found') + const role = (['none', 'read', 'triage', 'write', 'maintain', 'admin'] as const)[roleRank(gh, user, repo)]! + const permission = role === 'maintain' ? 'write' : role === 'triage' ? 'read' : role + return c.json({ permission, role_name: role, user: briefUser(user) }) + }) + + // Publishing a release on GitHub creates its tag. emulate stores the tag's name only, so a + // compare between two releases, which `getReleaseContext` makes, finds no ref. + app.use('/repos/:owner/:repo/releases', async (c: Ctx, next) => { + if (c.req.method !== 'POST') return next() + const { tag_name: tag, target_commitish: target, draft } = await c.req.raw.clone().json() as { tag_name?: string, target_commitish?: string, draft?: boolean } + await next() + const repo = gh.repos.findOneBy('full_name', `${c.req.param('owner')}/${c.req.param('repo')}`) + if (!repo || !tag || draft || !gh.releases.findBy('repo_id', repo.id).some(release => release.tag_name === tag)) return + if (gh.refs.findBy('repo_id', repo.id).some(ref => ref.ref === `refs/tags/${tag}`)) return + const commit = await callAsCaller<{ sha: string }>(app, c, 'GET', `/repos/${repo.full_name}/commits/${encodeURIComponent(target ?? repo.default_branch)}`) + await callAsCaller(app, c, 'POST', `/repos/${repo.full_name}/git/refs`, { ref: `refs/tags/${tag}`, sha: commit.sha }) + }) +} diff --git a/packages/github-tools-eve-extension/testing/github/role-guard.ts b/packages/github-tools-eve-extension/testing/github/role-guard.ts new file mode 100644 index 0000000..69915c9 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/role-guard.ts @@ -0,0 +1,126 @@ +import type { AppEnv, Hono, Store } from '@emulators/core' +import type { GitHubRepo, GitHubStore, GitHubUser } from '@emulators/github' +import { getGitHubStore } from '../emulators.js' +import { forbiddenForRole, replaceBody, ROLE_RANK, roleRank, type Ctx, type Role } from './access.js' + +interface RuleInput { + gh: GitHubStore + repo: GitHubRepo + user: GitHubUser + /** The capture groups of the rule's path. */ + match: RegExpExecArray + /** The request's JSON object, or an empty one when it has no JSON body. */ + body: () => Promise> +} + +interface Rule { + methods: string[] + /** Matched against the path after `/repos/{owner}/{repo}`. */ + path: RegExp + /** The role a personal token needs, or a function for routes where the author may act on their own item. */ + needs?: Role | ((input: RuleInput) => Role | undefined | Promise) + /** + * Body fields GitHub ignores from a person below Triage. It answers the request with its + * success status and leaves these as they were, so the guard removes them and lets it through. + */ + drop?: string[] +} + +const authored = (items: Array<{ repo_id: number, number: number, user_id: number }>, { repo, user, match }: RuleInput) => + items.some(item => item.repo_id === repo.id && item.number === Number(match[1]) && item.user_id === user.id) + +const ownComment = ({ gh, repo, user, match }: RuleInput) => { + const comment = gh.comments.get(Number(match[1])) + return comment?.repo_id === repo.id && comment.user_id === user.id ? undefined : 'write' as const +} + +// "Only users with push access can set labels for new issues. Labels are silently dropped otherwise", and the +// same for assignees and the milestone, on creating and on updating an issue. Triage is the lowest role with that access. +const TRIAGE_FIELDS = ['labels', 'assignees', 'milestone'] +const AUTHOR_PULL_FIELDS = new Set(['title', 'body', 'state', 'base', 'maintainer_can_modify']) + +/** + * The role a personal token needs on each write route. emulate 0.13.1 checks it for contents, + * refs, and admin routes only, so a reader could label, close, merge, and release. Routes absent + * here are either checked by emulate or open to anyone who can read the repository, as on GitHub: + * opening a pull request, commenting, reviewing, reacting, and forking. + * + * GitHub refuses most of these with `403`. On the issue routes with `drop`, it accepts the request + * and ignores what the person may not set, and the guard does the same. + */ +const RULES: Rule[] = [ + { methods: ['POST', 'PUT', 'DELETE'], path: /^\/issues\/\d+\/labels(?:\/.+)?$/u, needs: 'triage' }, + // "Only users with push access can add assignees to an issue. Assignees are silently ignored otherwise." + { methods: ['POST', 'DELETE'], path: /^\/issues\/\d+\/assignees$/u, drop: ['assignees'] }, + { methods: ['POST'], path: /^\/issues$/u, drop: TRIAGE_FIELDS }, + { methods: ['PUT', 'DELETE'], path: /^\/issues\/\d+\/lock$/u, needs: 'triage' }, + { methods: ['POST', 'DELETE'], path: /^\/pulls\/\d+\/requested_reviewers$/u, needs: 'triage' }, + { + methods: ['PATCH'], + path: /^\/issues\/(\d+)$/u, + // "Issue owners and users with push access or Triage role can edit an issue." + needs: input => authored(input.gh.issues.findBy('repo_id', input.repo.id), input) ? undefined : 'triage', + drop: TRIAGE_FIELDS, + }, + { + methods: ['PATCH'], + path: /^\/pulls\/(\d+)$/u, + needs: async (input) => { + const fields = Object.keys(await input.body()) + if (authored(input.gh.pullRequests.findBy('repo_id', input.repo.id), input) && fields.every(field => AUTHOR_PULL_FIELDS.has(field))) return undefined + return fields.every(field => field === 'state') ? 'triage' : 'write' + }, + }, + { methods: ['PATCH', 'DELETE'], path: /^\/issues\/comments\/(\d+)$/u, needs: ownComment }, + { methods: ['PATCH', 'DELETE'], path: /^\/pulls\/comments\/(\d+)$/u, needs: ownComment }, + { methods: ['POST'], path: /^\/labels$/u, needs: 'write' }, + { methods: ['PATCH', 'DELETE'], path: /^\/labels\/.+$/u, needs: 'write' }, + { methods: ['POST'], path: /^\/milestones$/u, needs: 'write' }, + { methods: ['PATCH', 'DELETE'], path: /^\/milestones\/\d+$/u, needs: 'write' }, + { methods: ['PUT'], path: /^\/pulls\/\d+\/(?:merge|update-branch)$/u, needs: 'write' }, + { methods: ['PUT'], path: /^\/pulls\/\d+\/reviews\/\d+\/dismissals$/u, needs: 'write' }, + { methods: ['POST'], path: /^\/releases(?:\/generate-notes|\/\d+\/assets)?$/u, needs: 'write' }, + { methods: ['PATCH', 'DELETE'], path: /^\/releases\/(?:assets\/)?\d+$/u, needs: 'write' }, + { methods: ['POST'], path: /^\/actions\/workflows\/[^/]+\/dispatches$/u, needs: 'write' }, + { methods: ['PUT'], path: /^\/actions\/workflows\/[^/]+\/(?:enable|disable)$/u, needs: 'write' }, + { methods: ['POST'], path: /^\/actions\/runs\/\d+\/(?:cancel|rerun)$/u, needs: 'write' }, + { methods: ['DELETE'], path: /^\/actions\/(?:runs|artifacts)\/\d+$/u, needs: 'write' }, + { methods: ['POST'], path: /^\/check-(?:runs|suites)(?:\/\d+\/rerequest)?$/u, needs: 'write' }, + { methods: ['PATCH'], path: /^\/check-(?:runs\/\d+|suites\/preferences)$/u, needs: 'write' }, +] + +/** + * Registered before emulate's routes. Answers `401` to a token that resolves to no user and no + * App, which `createServer` would treat as anonymous, and `403` to a personal token below the + * role a write route needs. Where GitHub ignores fields instead of refusing, it removes them. + */ +export function registerRoleGuard(app: Hono, store: Store): void { + const gh = getGitHubStore(store) + app.use('*', async (c: Ctx, next) => { + if (c.req.header('authorization') && !c.get('authUser') && !c.get('authApp')) return c.json({ message: 'Bad credentials' }, 401) + await next() + }) + // emulate's router has no trailing wildcard: a param with a regex is how a pattern takes the rest of a path. + app.use('/repos/:owner/:repo/:rest{.+}', async (c: Ctx, next) => { + const auth = c.get('authUser') + if (!auth || auth.installation || c.req.method === 'GET') return next() + const repo = gh.repos.findOneBy('full_name', `${c.req.param('owner')}/${c.req.param('repo')}`) + const user = gh.users.findOneBy('login', auth.login) + if (!repo || !user) return next() + const path = c.req.path.slice(`/repos/${c.req.param('owner')}/${c.req.param('repo')}`.length) + const rank = roleRank(gh, user, repo) + const body = () => c.req.raw.clone().json().catch(() => ({})) as Promise> + for (const rule of RULES) { + const match = rule.methods.includes(c.req.method) ? rule.path.exec(path) : null + if (!match) continue + const needs = typeof rule.needs === 'function' ? await rule.needs({ gh, repo, user, match, body }) : rule.needs + if (needs && rank < ROLE_RANK[needs]) throw forbiddenForRole() + if (rule.drop && rank < ROLE_RANK.triage) { + const sent = await body() + if (rule.drop.some(field => field in sent)) replaceBody(c, Object.fromEntries(Object.entries(sent).filter(([field]) => !rule.drop!.includes(field)))) + } + break + } + return next() + }) +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/context.ts b/packages/github-tools-eve-extension/testing/github/supplement/context.ts new file mode 100644 index 0000000..e35fb81 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/context.ts @@ -0,0 +1,34 @@ +import type { AppEnv, Hono, Store, WebhookDispatcher } from '@emulators/core' +import type { GitHubStore } from '@emulators/github' +import { ApiError } from '../../emulators.js' +import type { Ctx } from '../access.js' + +export interface SupplementContext { + app: Hono + store: Store + gh: GitHubStore + webhooks: WebhookDispatcher + baseUrl: string +} + +/** + * Calls one of emulate's own routes as the current caller, so its permission checks, its bot + * user, and its webhook dispatch apply to what a supplement route builds on top of it. An error + * status is rethrown as the caller's error. + */ +export async function callAsCaller(app: Hono, c: Ctx, method: string, path: string, body?: unknown): Promise { + const authorization = c.req.header('authorization') + const response = await app.request(path, { + method, + headers: { + accept: 'application/vnd.github+json', + ...authorization ? { authorization } : {}, + ...body === undefined ? {} : { 'content-type': 'application/json' }, + }, + body: body === undefined ? undefined : JSON.stringify(body), + }) + const text = await response.text() + const parsed = text ? JSON.parse(text) : undefined + if (response.status >= 400) throw new ApiError(response.status, parsed?.message ?? 'Request failed', parsed?.errors) + return parsed as T +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/discussions.ts b/packages/github-tools-eve-extension/testing/github/supplement/discussions.ts new file mode 100644 index 0000000..ff0062c --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/discussions.ts @@ -0,0 +1,47 @@ +import type { Entity, Store } from '@emulators/core' +import type { GitHubRepo, GitHubUser } from '@emulators/github' + +export interface Discussion extends Entity { + repo_id: number + number: number + title: string + body: string + category: string + user_id: number + answered: boolean +} + +export interface DiscussionComment extends Entity { + discussion_id: number + user_id: number + body: string +} + +/** The categories GitHub gives a repository when discussions are turned on. */ +export const DISCUSSION_CATEGORIES = ['Announcements', 'General', 'Ideas', 'Polls', 'Q&A', 'Show and tell'] + +export const categoryId = (name: string) => `DIC_${Buffer.from(name).toString('base64url')}` +export const discussionId = (discussion: Discussion) => `D_${discussion.id}` + +/** Discussions and their comments. GitHub has no REST API for them, so they are created here and read through GraphQL. */ +export function discussionStore(store: Store) { + const discussions = store.collection('supplement.discussions', ['repo_id']) + const comments = store.collection('supplement.discussion_comments', ['discussion_id']) + return { + discussions, + comments, + create(repo: GitHubRepo, author: GitHubUser, input: { title: string, body?: string, category?: string }): Discussion { + const category = input.category ?? 'General' + if (!DISCUSSION_CATEGORIES.includes(category)) throw new Error(`Unknown discussion category "${category}". Use one of: ${DISCUSSION_CATEGORIES.join(', ')}.`) + return discussions.insert({ + repo_id: repo.id, + number: discussions.findBy('repo_id', repo.id).length + 1, + title: input.title, + body: input.body ?? '', + category, + user_id: author.id, + answered: false, + }) + }, + } +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/gists.ts b/packages/github-tools-eve-extension/testing/github/supplement/gists.ts new file mode 100644 index 0000000..cc1136d --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/gists.ts @@ -0,0 +1,143 @@ +import { randomBytes } from 'node:crypto' +import type { Entity } from '@emulators/core' +import { ApiError } from '../../emulators.js' +import { briefUser, paginate, requireUser, type Ctx } from '../access.js' +import type { SupplementContext } from './context.js' + +interface Gist extends Entity { + gist_id: string + user_id: number + description: string | null + public: boolean + files: Record +} + +interface GistComment extends Entity { + gist_id: string + user_id: number + body: string +} + +type FileChanges = Record + +/** Gists belong to a user, so every route needs a personal token. A secret gist is unlisted, not private. */ +export function registerGists({ app, store, gh, baseUrl }: SupplementContext): void { + const gists = store.collection('supplement.gists', ['gist_id', 'user_id']) + const comments = store.collection('supplement.gist_comments', ['gist_id']) + + const format = (gist: Gist, withContent: boolean) => ({ + id: gist.gist_id, + node_id: `G_${gist.gist_id}`, + url: `${baseUrl}/gists/${gist.gist_id}`, + html_url: `${baseUrl}/gist/${gist.gist_id}`, + description: gist.description, + public: gist.public, + owner: briefUser(gh.users.get(gist.user_id)), + comments: comments.findBy('gist_id', gist.gist_id).length, + files: Object.fromEntries(Object.entries(gist.files).map(([filename, content]) => [filename, { + filename, + type: 'text/plain', + language: null, + raw_url: `${baseUrl}/gist/${gist.gist_id}/raw/${encodeURIComponent(filename)}`, + size: Buffer.byteLength(content), + ...withContent ? { content, truncated: false } : {}, + }])), + created_at: gist.created_at, + updated_at: gist.updated_at, + }) + + const formatComment = (comment: GistComment) => ({ + id: comment.id, + node_id: `GC_${comment.id}`, + url: `${baseUrl}/gists/${comment.gist_id}/comments/${comment.id}`, + body: comment.body, + user: briefUser(gh.users.get(comment.user_id)), + created_at: comment.created_at, + updated_at: comment.updated_at, + }) + + function find(c: Ctx): Gist { + const gist = gists.findOneBy('gist_id', c.req.param('gist_id')) + if (!gist) throw new ApiError(404, 'Not Found') + return gist + } + + // GitHub answers 404, not 403, to a change on someone else's gist. + function findOwn(c: Ctx): Gist { + const user = requireUser(c, gh) + const gist = find(c) + if (gist.user_id !== user.id) throw new ApiError(404, 'Not Found') + return gist + } + + function applyFiles(current: Record, changes: FileChanges): Record { + const files = { ...current } + for (const [filename, change] of Object.entries(changes)) { + if (change === null) { + delete files[filename] + continue + } + const content = change.content ?? files[filename] + if (content === undefined || content === '') throw new ApiError(422, 'Validation Failed') + delete files[filename] + files[change.filename ?? filename] = content + } + if (Object.keys(files).length === 0) throw new ApiError(422, 'Validation Failed') + return files + } + + app.get('/gists', (c: Ctx) => { + const user = requireUser(c, gh) + return c.json(paginate(c, gists.findBy('user_id', user.id)).map(gist => format(gist, false))) + }) + + app.get('/users/:username/gists', (c: Ctx) => { + const owner = gh.users.findOneBy('login', c.req.param('username')) + if (!owner) throw new ApiError(404, 'Not Found') + const viewer = c.get('authUser') + const own = viewer && !viewer.installation && viewer.login === owner.login + return c.json(paginate(c, gists.findBy('user_id', owner.id).filter(gist => own || gist.public)).map(gist => format(gist, false))) + }) + + app.post('/gists', async (c: Ctx) => { + const user = requireUser(c, gh) + const body = await c.req.json<{ description?: string, public?: boolean, files?: FileChanges }>() + const gist = gists.insert({ + gist_id: randomBytes(16).toString('hex'), + user_id: user.id, + description: body.description ?? null, + public: body.public ?? false, + files: applyFiles({}, body.files ?? {}), + }) + return c.json(format(gist, true), 201) + }) + + app.get('/gists/:gist_id', (c: Ctx) => c.json(format(find(c), true))) + + app.patch('/gists/:gist_id', async (c: Ctx) => { + const gist = findOwn(c) + const body = await c.req.json<{ description?: string, files?: FileChanges }>() + const updated = gists.update(gist.id, { + description: body.description ?? gist.description, + files: body.files ? applyFiles(gist.files, body.files) : gist.files, + })! + return c.json(format(updated, true)) + }) + + app.delete('/gists/:gist_id', (c: Ctx) => { + const gist = findOwn(c) + for (const comment of comments.findBy('gist_id', gist.gist_id)) comments.delete(comment.id) + gists.delete(gist.id) + return c.body(null, 204) + }) + + app.get('/gists/:gist_id/comments', (c: Ctx) => c.json(paginate(c, comments.findBy('gist_id', find(c).gist_id)).map(formatComment))) + + app.post('/gists/:gist_id/comments', async (c: Ctx) => { + const user = requireUser(c, gh) + const gist = find(c) + const { body } = await c.req.json<{ body?: string }>() + if (!body?.trim()) throw new ApiError(422, 'Validation Failed') + return c.json(formatComment(comments.insert({ gist_id: gist.gist_id, user_id: user.id, body })), 201) + }) +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/graphql.ts b/packages/github-tools-eve-extension/testing/github/supplement/graphql.ts new file mode 100644 index 0000000..7f5204f --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/graphql.ts @@ -0,0 +1,394 @@ +import type { Entity } from '@emulators/core' +import type { GitHubComment, GitHubPullRequest, GitHubRepo } from '@emulators/github' +import { ApiError } from '../../emulators.js' +import { requireActor, requireRead, ROLE_RANK, roleRank, type Ctx, type Role } from '../access.js' +import { callAsCaller, type SupplementContext } from './context.js' +import { categoryId, DISCUSSION_CATEGORIES, discussionId, discussionStore, type Discussion } from './discussions.js' + +interface ResolvedThread extends Entity { + root_comment_id: number + resolved_by_id: number +} + +/** The variables of the documents the SDK sends. */ +interface Variables { + owner?: string + name?: string + number?: number + first?: number + after?: string | null + categoryId?: string | null + expression?: string + path?: string + threadId?: string + pullRequestId?: string + mergeMethod?: string + commitHeadline?: string + commitBody?: string + discussionId?: string + body?: string + input?: { + branch: { repositoryNameWithOwner: string, branchName: string } + expectedHeadOid: string + message: { headline: string, body?: string } + fileChanges?: { additions?: Array<{ path: string, contents: string }>, deletions?: Array<{ path: string }> } + } +} + +/** An entry of a GraphQL response's `errors`, with the `data` GitHub sends beside it. */ +class GraphqlError extends Error { + constructor(readonly type: string, message: string, readonly data: unknown = null) { + super(message) + } +} + +const THREAD_PREFIX = 'PRRT_' +const CLOSING_REFERENCE = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\s+(?:([\w.-]+\/[\w.-]+))?#(\d+)/giu +const UNSUPPORTED = 'EMULATOR_UNSUPPORTED' + +/** + * Names a document by its root field, and for `repository` by the fields under it. Nine of the + * SDK's documents have no operation name, and several share a first line. + */ +export function documentKey(query: string): string | undefined { + const root = /^\s*(\w+)/u.exec(query.slice(query.indexOf('{') + 1))?.[1] + if (root !== 'repository') return root + const field = /\brepository\s*\([^)]*\)\s*\{\s*(\w+)/u.exec(query)?.[1] + if (field !== 'pullRequest') return `repository.${field}` + return `repository.pullRequest.${/\bpullRequest\s*\([^)]*\)\s*\{\s*(\w+)/u.exec(query)?.[1]}` +} + +// The longest common subsequence of two files' lines: for each line of `next`, its index in `previous`, or -1 for a new line. +function carriedLines(previous: string[], next: string[]): number[] { + const lengths = Array.from({ length: previous.length + 1 }, () => new Uint32Array(next.length + 1)) + for (let i = previous.length - 1; i >= 0; i--) { + for (let j = next.length - 1; j >= 0; j--) { + lengths[i]![j] = previous[i] === next[j] ? lengths[i + 1]![j + 1]! + 1 : Math.max(lengths[i + 1]![j]!, lengths[i]![j + 1]!) + } + } + const origin = new Array(next.length).fill(-1) + for (let i = 0, j = 0; i < previous.length && j < next.length;) { + if (previous[i] === next[j]) origin[j++] = i++ + else if (lengths[i + 1]![j]! >= lengths[i]![j + 1]!) i++ + else j++ + } + return origin +} + +/** + * `POST /graphql` for the documents `@github-tools/sdk` sends. It isn't a GraphQL engine: it + * recognizes each document and answers from the store. Any other document gets an error, and + * its text is added to `unknownDocuments`. + */ +export function registerGraphql({ app, store, gh, baseUrl }: SupplementContext, unknownDocuments: string[]) { + const resolved = store.collection('supplement.resolved_threads', ['root_comment_id']) + const discussions = discussionStore(store) + + const lines = (text: string) => text.replace(/\n$/u, '').split('\n') + const login = (userId: number) => gh.users.get(userId)?.login + + function repository(variables: Variables): GitHubRepo { + const repo = gh.repos.findOneBy('full_name', `${variables.owner}/${variables.name}`) + if (!repo) throw new GraphqlError('NOT_FOUND', `Could not resolve to a Repository with the name '${variables.owner}/${variables.name}'.`, { repository: null }) + return repo + } + + function pullRequestNode(id: string | undefined): { pull: GitHubPullRequest, repo: GitHubRepo } { + const pull = gh.pullRequests.all().find(candidate => candidate.node_id === id) + const repo = pull && gh.repos.get(pull.repo_id) + if (!pull || !repo) throw new GraphqlError('NOT_FOUND', `Could not resolve to a node with the global id of '${id}'`) + return { pull, repo } + } + + // The author of a pull request may resolve its threads and change its draft state without Write. + function requireWriterOrAuthor(c: Ctx, repo: GitHubRepo, authorId: number) { + const auth = c.get('authUser') + const user = auth && !auth.installation ? gh.users.findOneBy('login', auth.login) : undefined + const role: Role = user?.id === authorId && roleRank(gh, user, repo) >= ROLE_RANK.read ? 'read' : 'write' + return requireActor(c, gh, repo, { permission: 'pull_requests', access: 'write', role }) + } + + function threadOf(id: unknown): { root: GitHubComment, repo: GitHubRepo } { + const root = typeof id === 'string' && id.startsWith(THREAD_PREFIX) ? gh.comments.get(Number(id.slice(THREAD_PREFIX.length))) : undefined + const repo = root && gh.repos.get(root.repo_id) + if (!root || !repo || root.comment_type !== 'review' || root.in_reply_to_id !== null) throw new GraphqlError('NOT_FOUND', `Could not resolve to a node with the global id of '${id}'`) + return { root, repo } + } + + const discussionNode = (discussion: Discussion, repo: GitHubRepo) => ({ + id: discussionId(discussion), + number: discussion.number, + title: discussion.title, + body: discussion.body, + url: `${baseUrl}/${repo.full_name}/discussions/${discussion.number}`, + createdAt: discussion.created_at, + updatedAt: discussion.updated_at, + isAnswered: discussion.answered, + author: { login: login(discussion.user_id) }, + category: { name: discussion.category }, + comments: { totalCount: discussions.comments.findBy('discussion_id', discussion.id).length }, + }) + + function discussion(c: Ctx, variables: Variables) { + const repo = repository(variables) + requireRead(c, gh, repo, 'discussions') + const found = discussions.discussions.findBy('repo_id', repo.id).find(candidate => candidate.number === variables.number) + if (!found) throw new GraphqlError('NOT_FOUND', `Could not resolve to a Discussion with the number of ${variables.number}.`, { repository: { discussion: null } }) + return { repository: { discussion: discussionNode(found, repo) } } + } + + async function setDraft(c: Ctx, variables: Variables, draft: boolean) { + const { pull, repo } = pullRequestNode(variables.pullRequestId) + // emulate's own route changes the draft state, with the role guard in front of it. + await callAsCaller(app, c, 'PATCH', `/repos/${repo.full_name}/pulls/${pull.number}`, { draft }) + return { pullRequest: { id: pull.node_id } } + } + + function setAutoMerge(c: Ctx, variables: Variables, enable: boolean) { + const { pull, repo } = pullRequestNode(variables.pullRequestId) + const actor = requireActor(c, gh, repo, { permission: 'pull_requests', access: 'write', role: 'write' }) + if (enable && pull.state !== 'open') throw new GraphqlError('UNPROCESSABLE', 'Pull request is not open') + const mergeMethod = String(variables.mergeMethod ?? 'MERGE') + // emulate types `auto_merge` as always null and returns whatever the pull request holds. The request is recorded and never carried out. + const autoMerge = enable + ? { enabled_by: { login: actor.login, id: actor.id }, merge_method: mergeMethod.toLowerCase(), commit_title: variables.commitHeadline ?? null, commit_message: variables.commitBody ?? null } + : null + const updated = gh.pullRequests.update(pull.id, { auto_merge: autoMerge as null })! + return { + pullRequest: { + number: pull.number, + url: `${baseUrl}/${repo.full_name}/pull/${pull.number}`, + autoMergeRequest: enable ? { enabledAt: updated.updated_at, mergeMethod } : null, + }, + } + } + + const documents: Record unknown> = { + 'repository.pullRequest.reviewThreads'(c, variables) { + const repo = repository(variables) + requireRead(c, gh, repo, 'pull_requests') + if (!gh.pullRequests.findBy('repo_id', repo.id).some(pull => pull.number === variables.number)) { + throw new GraphqlError('NOT_FOUND', `Could not resolve to a PullRequest with the number of ${variables.number}.`, { repository: { pullRequest: null } }) + } + const comments = gh.comments.findBy('repo_id', repo.id).filter(comment => comment.comment_type === 'review' && comment.pull_number === variables.number) + const roots = comments.filter(comment => comment.in_reply_to_id === null) + const start = variables.after ? Number(variables.after) : 0 + const page = roots.slice(start, start + (variables.first ?? roots.length)) + const end = start + page.length + return { + repository: { + pullRequest: { + reviewThreads: { + totalCount: roots.length, + pageInfo: { hasNextPage: end < roots.length, endCursor: page.length > 0 ? String(end) : null }, + nodes: page.map((root) => { + const thread = [root, ...comments.filter(comment => comment.in_reply_to_id === root.id)] + const resolution = resolved.findOneBy('root_comment_id', root.id) + return { + id: `${THREAD_PREFIX}${root.id}`, + isResolved: Boolean(resolution), + isOutdated: false, + path: root.path, + line: root.line, + startLine: null, + resolvedBy: resolution ? { login: login(resolution.resolved_by_id) } : null, + comments: { + totalCount: thread.length, + nodes: thread.slice(0, 30).map(comment => ({ databaseId: comment.id, body: comment.body, createdAt: comment.created_at, author: { login: login(comment.user_id) } })), + }, + } + }), + }, + }, + }, + } + }, + + async 'repository.pullRequest.closingIssuesReferences'(c, variables) { + const repo = repository(variables) + const pull = await callAsCaller<{ body: string | null }>(app, c, 'GET', `/repos/${repo.full_name}/pulls/${variables.number}`) + const nodes = [...(pull.body ?? '').matchAll(CLOSING_REFERENCE)].flatMap(([, fullName, number]) => { + const target = fullName ? gh.repos.findOneBy('full_name', fullName) : repo + const issue = target && gh.issues.findBy('repo_id', target.id).find(candidate => candidate.number === Number(number) && !candidate.is_pull_request) + if (!target || !issue) return [] + return [{ number: issue.number, title: issue.title, state: issue.state.toUpperCase(), url: `${baseUrl}/${target.full_name}/issues/${issue.number}`, repository: { nameWithOwner: target.full_name } }] + }) + return { repository: { pullRequest: { closingIssuesReferences: { nodes: nodes.slice(0, 10) } } } } + }, + + async 'repository.object'(c, variables) { + const repo = repository(variables) + const path = `/repos/${repo.full_name}` + const { expression = repo.default_branch, path: file = '' } = variables + // emulate resolves the expression and lists the commits that changed the file, newest first. + const history = await callAsCaller>( + app, c, 'GET', `${path}/commits?sha=${encodeURIComponent(expression)}&path=${encodeURIComponent(file)}&per_page=100`, + ).catch((error) => { + if (error instanceof ApiError && error.status === 404) return undefined + throw error + }) + if (!history) return { repository: { object: null } } + const head = await callAsCaller<{ sha: string }>(app, c, 'GET', `${path}/commits/${encodeURIComponent(expression)}`) + const versions = await Promise.all(history.map(async (commit) => { + const version = await callAsCaller<{ content: string }>(app, c, 'GET', `${path}/contents/${file}?ref=${commit.sha}`).catch((error) => { + if (error instanceof ApiError && error.status === 404) return undefined + throw error + }) + return version ? lines(Buffer.from(version.content, 'base64').toString()) : [] + })) + // Follows each line of the newest version back through the file's history, to the commit that introduced it. + const blamed = new Array(versions[0]?.length ?? 0).fill(history.length - 1) + let positions = blamed.map((_, index) => index) + for (let index = 0; index < history.length; index++) { + const origin = carriedLines(versions[index + 1] ?? [], versions[index]!) + positions = positions.map((position, line) => { + if (position === -1) return -1 + if (origin[position] === -1) blamed[line] = index + return origin[position]! + }) + } + const ranges: Array<{ startingLine: number, endingLine: number, commit: number }> = [] + blamed.forEach((commit, index) => { + const last = ranges.at(-1) + if (last?.commit === commit) last.endingLine = index + 1 + else ranges.push({ startingLine: index + 1, endingLine: index + 1, commit }) + }) + return { + repository: { + object: { + oid: head.sha, + blame: { + ranges: ranges.map(({ commit, ...range }) => { + const entry = history[commit]! + return { + ...range, + age: 1, + commit: { + oid: entry.sha, + abbreviatedOid: entry.sha.slice(0, 7), + messageHeadline: entry.commit.message.split('\n')[0], + authoredDate: entry.commit.author.date, + url: `${baseUrl}/${repo.full_name}/commit/${entry.sha}`, + author: { name: entry.commit.author.name, email: entry.commit.author.email, user: entry.author ? { login: entry.author.login } : null }, + }, + } + }), + }, + }, + }, + } + }, + + 'repository.discussionCategories'(c, variables) { + requireRead(c, gh, repository(variables), 'discussions') + return { repository: { discussionCategories: { nodes: DISCUSSION_CATEGORIES.map(name => ({ id: categoryId(name), name })) } } } + }, + + 'repository.discussions'(c, variables) { + const repo = repository(variables) + requireRead(c, gh, repo, 'discussions') + const matching = discussions.discussions.findBy('repo_id', repo.id) + .filter(candidate => !variables.categoryId || categoryId(candidate.category) === variables.categoryId) + .sort((a, b) => b.updated_at.localeCompare(a.updated_at) || b.number - a.number) + const start = variables.after ? Number(variables.after) : 0 + const page = matching.slice(start, start + (variables.first ?? matching.length)) + const end = start + page.length + return { + repository: { + discussions: { + pageInfo: { hasNextPage: end < matching.length, endCursor: page.length > 0 ? String(end) : null }, + nodes: page.map(candidate => discussionNode(candidate, repo)), + }, + }, + } + }, + + 'repository.discussion': discussion, + + node(c, variables) { + const { repo } = threadOf(variables.threadId) + requireRead(c, gh, repo, 'pull_requests') + const [owner, name] = repo.full_name.split('/') + return { node: { repository: { name, owner: { login: owner } } } } + }, + + resolveReviewThread(c, variables) { + const { root, repo } = threadOf(variables.threadId) + const pull = gh.pullRequests.findBy('repo_id', repo.id).find(candidate => candidate.number === root.pull_number) + const actor = requireWriterOrAuthor(c, repo, pull?.user_id ?? -1) + if (!resolved.findOneBy('root_comment_id', root.id)) resolved.insert({ root_comment_id: root.id, resolved_by_id: actor.id }) + return { resolveReviewThread: { thread: { id: variables.threadId, isResolved: true } } } + }, + + markPullRequestReadyForReview: async (c, variables) => ({ markPullRequestReadyForReview: await setDraft(c, variables, false) }), + convertPullRequestToDraft: async (c, variables) => ({ convertPullRequestToDraft: await setDraft(c, variables, true) }), + enablePullRequestAutoMerge: (c, variables) => ({ enablePullRequestAutoMerge: setAutoMerge(c, variables, true) }), + disablePullRequestAutoMerge: (c, variables) => ({ disablePullRequestAutoMerge: setAutoMerge(c, variables, false) }), + + addDiscussionComment(c, variables) { + const found = discussions.discussions.all().find(candidate => discussionId(candidate) === variables.discussionId) + const repo = found && gh.repos.get(found.repo_id) + if (!found || !repo) throw new GraphqlError('NOT_FOUND', `Could not resolve to a node with the global id of '${variables.discussionId}'`) + const actor = requireActor(c, gh, repo, { permission: 'discussions', access: 'write', role: 'read' }) + const comment = discussions.comments.insert({ discussion_id: found.id, user_id: actor.id, body: variables.body ?? '' }) + discussions.discussions.update(found.id, {}) + return { + addDiscussionComment: { + comment: { + id: `DC_${comment.id}`, + url: `${baseUrl}/${repo.full_name}/discussions/${found.number}#discussioncomment-${comment.id}`, + body: comment.body, + createdAt: comment.created_at, + author: { login: actor.login }, + }, + }, + } + }, + + // One commit from several file changes, built with emulate's Git database routes as the caller. + async createCommitOnBranch(c, { input }) { + if (!input) throw new GraphqlError('UNPROCESSABLE', 'createCommitOnBranch needs an input') + const path = `/repos/${input.branch.repositoryNameWithOwner}` + const ref = await callAsCaller<{ object: { sha: string } }>(app, c, 'GET', `${path}/git/ref/heads/${input.branch.branchName}`) + if (ref.object.sha !== input.expectedHeadOid) { + throw new GraphqlError('STALE_DATA', `Expected branch to point to "${input.expectedHeadOid}" but it did not. Pull and try again.`) + } + const head = await callAsCaller<{ tree: { sha: string } }>(app, c, 'GET', `${path}/git/commits/${ref.object.sha}`) + const { additions = [], deletions = [] } = input.fileChanges ?? {} + const blobs = await Promise.all(additions.map(addition => callAsCaller<{ sha: string }>(app, c, 'POST', `${path}/git/blobs`, { content: addition.contents, encoding: 'base64' }))) + const tree = await callAsCaller<{ sha: string }>(app, c, 'POST', `${path}/git/trees`, { + base_tree: head.tree.sha, + tree: [ + ...additions.map((addition, index) => ({ path: addition.path, mode: '100644', type: 'blob', sha: blobs[index]!.sha })), + ...deletions.map(deletion => ({ path: deletion.path, mode: '100644', type: 'blob', sha: null })), + ], + }) + const message = input.message.body ? `${input.message.headline}\n\n${input.message.body}` : input.message.headline + const commit = await callAsCaller<{ sha: string }>(app, c, 'POST', `${path}/git/commits`, { message, tree: tree.sha, parents: [ref.object.sha] }) + await callAsCaller(app, c, 'PATCH', `${path}/git/refs/heads/${input.branch.branchName}`, { sha: commit.sha }) + return { createCommitOnBranch: { commit: { oid: commit.sha, url: `${baseUrl}/${input.branch.repositoryNameWithOwner}/commit/${commit.sha}` } } } + }, + } + + app.post('/graphql', async (c: Ctx) => { + if (!c.get('authUser')) throw new ApiError(401, 'This endpoint requires you to be authenticated.') + const { query, variables = {} } = await c.req.json<{ query: string, variables?: Variables }>() + const key = documentKey(query) + const answer = key === undefined ? undefined : documents[key] + if (!answer) { + unknownDocuments.push(query) + return c.json({ errors: [{ type: UNSUPPORTED, message: `The GitHub emulator answers the GraphQL documents @github-tools/sdk sends, and this isn't one of them: ${query.replace(/\s+/gu, ' ').trim().slice(0, 200)}` }] }) + } + try { + return c.json({ data: await answer(c, variables) }) + } catch (error) { + // GitHub answers a GraphQL request it refuses with 200 and the reason under `errors`. + if (error instanceof GraphqlError) return c.json({ data: error.data, errors: [{ type: error.type, message: error.message }] }) + if (error instanceof ApiError && error.status === 403) return c.json({ data: null, errors: [{ type: 'FORBIDDEN', message: error.message }] }) + if (error instanceof ApiError && error.status === 404) return c.json({ data: null, errors: [{ type: 'NOT_FOUND', message: error.message }] }) + throw error + } + }) + + return discussions +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/index.ts b/packages/github-tools-eve-extension/testing/github/supplement/index.ts new file mode 100644 index 0000000..7d3cd7b --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/index.ts @@ -0,0 +1,35 @@ +import type { SupplementContext } from './context.js' +import { registerGists } from './gists.js' +import { registerGraphql } from './graphql.js' +import { registerNotifications } from './notifications.js' +import { registerReactions } from './reactions.js' +import { registerRepositoryRoutes } from './repository.js' +import { registerSecurityAlerts } from './security.js' +import { registerStatuses } from './statuses.js' +import { registerSubIssues } from './sub-issues.js' +import { fixWebhookPayloads } from './webhooks.js' + +export type { SupplementContext } from './context.js' +export type { SecurityAlertSeeds } from './security.js' + +/** + * What `@github-tools/sdk` calls and emulate 0.13.1 doesn't answer. Each part can move to + * emulate, and `testing/coverage.test.ts` fails with "delete this route" once emulate has it. + * + * The routes are registered before emulate's, because its router takes the first route that + * matches and its `/commits/:ref{.+}` would answer `/commits/{ref}/status`. + */ +export function registerSupplementRoutes(context: SupplementContext, unknownDocuments: string[]) { + registerReactions(context) + registerStatuses(context) + registerRepositoryRoutes(context) + registerSubIssues(context) + registerGists(context) + return { + seedAlerts: registerSecurityAlerts(context), + notify: registerNotifications(context), + discussions: registerGraphql(context, unknownDocuments), + } +} + +export { fixWebhookPayloads } diff --git a/packages/github-tools-eve-extension/testing/github/supplement/notifications.ts b/packages/github-tools-eve-extension/testing/github/supplement/notifications.ts new file mode 100644 index 0000000..2873b25 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/notifications.ts @@ -0,0 +1,97 @@ +import type { Entity } from '@emulators/core' +import type { GitHubRepo } from '@emulators/github' +import { ApiError } from '../../emulators.js' +import { paginate, requireUser, type Ctx } from '../access.js' +import type { SupplementContext } from './context.js' + +interface NotificationThread extends Entity { + user_id: number + repo_id: number + /** The issue or pull request the thread is about. A person has one thread for each. */ + subject_number: number + subject: { title: string, type: 'Issue' | 'PullRequest', url: string } + reason: 'mention' | 'assign' | 'review_requested' + unread: boolean + last_read_at: string | null +} + +export interface NotifyingPayload { + action?: string + sender?: { login?: string } + issue?: { number: number, title: string, body?: string | null, pull_request?: unknown } + pull_request?: { number: number, title: string, body?: string | null } + comment?: { body?: string } + assignee?: { login?: string } + requested_reviewer?: { login?: string } +} + +const MENTION = /(?:^|[^\w/-])@([a-z\d](?:[a-z\d-]{0,38}))(?![\w-])/giu + +/** + * Notifications belong to a user, so both routes need a personal token. A thread appears for a + * person who is mentioned, assigned, or asked for a review, which are the events emulate dispatches. + */ +export function registerNotifications({ app, store, gh, baseUrl }: SupplementContext) { + const threads = store.collection('supplement.notifications', ['user_id']) + + const format = (thread: NotificationThread) => { + const repo = gh.repos.get(thread.repo_id) + return { + id: String(thread.id), + unread: thread.unread, + reason: thread.reason, + updated_at: thread.updated_at, + last_read_at: thread.last_read_at, + subject: { ...thread.subject, latest_comment_url: null }, + repository: { id: thread.repo_id, name: repo?.name, full_name: repo?.full_name, private: repo?.private }, + url: `${baseUrl}/notifications/threads/${thread.id}`, + subscription_url: `${baseUrl}/notifications/threads/${thread.id}/subscription`, + } + } + + app.get('/notifications', (c: Ctx) => { + const user = requireUser(c, gh) + // Every reason the emulator records is a direct one, so `participating` narrows nothing. + const matching = threads.findBy('user_id', user.id) + .filter(thread => c.req.query('all') === 'true' || thread.unread) + .sort((a, b) => b.updated_at.localeCompare(a.updated_at)) + return c.json(paginate(c, matching).map(format)) + }) + + app.patch('/notifications/threads/:thread_id', (c: Ctx) => { + const user = requireUser(c, gh) + const thread = threads.get(Number(c.req.param('thread_id'))) + if (!thread || thread.user_id !== user.id) throw new ApiError(404, 'Not Found') + threads.update(thread.id, { unread: false, last_read_at: new Date().toISOString() }) + return c.body(null, 205) + }) + + return function notify(event: string, payload: NotifyingPayload, repo: GitHubRepo): void { + const subject = payload.pull_request ?? payload.issue + if (!subject) return + const type = payload.pull_request || payload.issue?.pull_request ? 'PullRequest' : 'Issue' + const add = (login: string | undefined, reason: NotificationThread['reason']) => { + const user = login === undefined ? undefined : gh.users.findOneBy('login', login) + if (!user || user.type !== 'User' || user.login === payload.sender?.login) return + const existing = threads.findBy('user_id', user.id).find(thread => thread.repo_id === repo.id && thread.subject_number === subject.number) + if (existing) { + threads.update(existing.id, { unread: true, reason }) + return + } + threads.insert({ + user_id: user.id, + repo_id: repo.id, + subject_number: subject.number, + subject: { title: subject.title, type, url: `${baseUrl}/repos/${repo.full_name}/${type === 'Issue' ? 'issues' : 'pulls'}/${subject.number}` }, + reason, + unread: true, + last_read_at: null, + }) + } + if (payload.action === 'assigned') add(payload.assignee?.login, 'assign') + if (payload.action === 'review_requested') add(payload.requested_reviewer?.login, 'review_requested') + const text = payload.action === 'created' ? payload.comment?.body : payload.action === 'opened' ? subject.body : undefined + if (!text || !['issues', 'pull_request', 'issue_comment', 'pull_request_review_comment'].includes(event)) return + for (const [, login] of text.matchAll(MENTION)) add(login, 'mention') + } +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/reactions.ts b/packages/github-tools-eve-extension/testing/github/supplement/reactions.ts new file mode 100644 index 0000000..775903a --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/reactions.ts @@ -0,0 +1,72 @@ +import type { Entity } from '@emulators/core' +import { ApiError } from '../../emulators.js' +import { briefUser, findRepo, paginate, requireActor, requireRead, type Ctx } from '../access.js' +import type { SupplementContext } from './context.js' + +type Subject = 'issue' | 'issue_comment' | 'review_comment' + +interface Reaction extends Entity { + repo_id: number + subject: Subject + /** The issue number for an issue, the comment ID otherwise. */ + subject_id: number + user_id: number + content: string +} + +const CONTENTS = ['+1', '-1', 'laugh', 'confused', 'heart', 'hooray', 'rocket', 'eyes'] + +// GitHub accepts either permission for a reaction on an issue or its comments, because pull requests share them. +const PERMISSIONS: Record = { + issue: ['issues', 'pull_requests'], + issue_comment: ['issues', 'pull_requests'], + review_comment: ['pull_requests'], +} + +export function registerReactions({ app, store, gh }: SupplementContext): void { + const reactions = store.collection('supplement.reactions', ['repo_id']) + + function target(c: Ctx, subject: Subject) { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + const id = Number(c.req.param(subject === 'issue' ? 'issue_number' : 'comment_id')) + const comment = subject === 'issue' ? undefined : gh.comments.get(id) + const exists = subject === 'issue' + ? [...gh.issues.findBy('repo_id', repo.id), ...gh.pullRequests.findBy('repo_id', repo.id)].some(item => item.number === id) + : comment?.repo_id === repo.id && comment.comment_type === (subject === 'issue_comment' ? 'issue' : 'review') + if (!exists) throw new ApiError(404, 'Not Found') + return { repo, id } + } + + const format = (reaction: Reaction) => ({ + id: reaction.id, + node_id: `REA_${reaction.id}`, + user: briefUser(gh.users.get(reaction.user_id)), + content: reaction.content, + created_at: reaction.created_at, + }) + + const create = (subject: Subject) => async (c: Ctx) => { + const { repo, id } = target(c, subject) + const actor = requireActor(c, gh, repo, { permission: PERMISSIONS[subject], access: 'write', role: 'read' }) + const { content } = await c.req.json<{ content?: string }>() + if (!content || !CONTENTS.includes(content)) throw new ApiError(422, 'Validation Failed') + const existing = reactions.findBy('repo_id', repo.id).find(reaction => reaction.subject === subject && reaction.subject_id === id && reaction.user_id === actor.id && reaction.content === content) + if (existing) return c.json(format(existing), 200) + return c.json(format(reactions.insert({ repo_id: repo.id, subject, subject_id: id, user_id: actor.id, content })), 201) + } + + const list = (subject: Subject) => (c: Ctx) => { + const { repo, id } = target(c, subject) + requireRead(c, gh, repo, PERMISSIONS[subject][0]!) + const content = c.req.query('content') + const matching = reactions.findBy('repo_id', repo.id).filter(reaction => reaction.subject === subject && reaction.subject_id === id && (!content || reaction.content === content)) + return c.json(paginate(c, matching).map(format)) + } + + app.get('/repos/:owner/:repo/issues/:issue_number/reactions', list('issue')) + app.post('/repos/:owner/:repo/issues/:issue_number/reactions', create('issue')) + app.get('/repos/:owner/:repo/issues/comments/:comment_id/reactions', list('issue_comment')) + app.post('/repos/:owner/:repo/issues/comments/:comment_id/reactions', create('issue_comment')) + // eve's GitHub channel reacts to a review comment before it replies. No tool lists these. + app.post('/repos/:owner/:repo/pulls/comments/:comment_id/reactions', create('review_comment')) +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/repository.ts b/packages/github-tools-eve-extension/testing/github/supplement/repository.ts new file mode 100644 index 0000000..eb0a6ff --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/repository.ts @@ -0,0 +1,53 @@ +import { ApiError } from '../../emulators.js' +import { findRepo, requireRead, type Ctx } from '../access.js' +import { callAsCaller, type SupplementContext } from './context.js' + +export function registerRepositoryRoutes({ app, gh }: SupplementContext): void { + // Rules come from rulesets, which the emulator doesn't model, so a branch has none. Classic + // branch protection is emulate's, and `getBranchRules` reads it from the branch. + app.get('/repos/:owner/:repo/rules/branches/:branch{.+}', (c: Ctx) => { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + requireRead(c, gh, repo, 'metadata') + if (!gh.branches.findBy('repo_id', repo.id).some(branch => branch.name === c.req.param('branch'))) throw new ApiError(404, 'Not Found') + return c.json([]) + }) + + // The repositories an installation token reaches, which the SDK's caller-access check lists before a search. + app.get('/installation/repositories', (c: Ctx) => { + const installation = c.get('authUser')?.installation + if (!installation) throw new ApiError(403, 'You must authenticate with an installation access token in order to list repositories for an installation.') + const reached = gh.repos.all().filter(repo => repo.owner_id === installation.accountId && repo.owner_type === installation.accountType + && (installation.repositorySelection === 'all' || installation.repositoryIds.includes(repo.id))) + return c.json({ + total_count: reached.length, + repository_selection: installation.repositorySelection, + repositories: reached.map(repo => ({ id: repo.id, node_id: repo.node_id, name: repo.name, full_name: repo.full_name, private: repo.private })), + }) + }) + + // emulate models a rerun as a new run with stub jobs, so rerunning the failed jobs is the same rerun. + app.post('/repos/:owner/:repo/actions/runs/:run_id/rerun-failed-jobs', async (c: Ctx) => { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + await callAsCaller(app, c, 'POST', `/repos/${repo.full_name}/actions/runs/${c.req.param('run_id')}/rerun`) + return c.json({}, 201) + }) + + // A reply joins its parent's thread: same file, line, and commit. emulate's own route creates it. + app.post('/repos/:owner/:repo/pulls/:pull_number/comments/:comment_id/replies', async (c: Ctx) => { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + const pullNumber = Number(c.req.param('pull_number')) + const parent = gh.comments.get(Number(c.req.param('comment_id'))) + if (!parent || parent.repo_id !== repo.id || parent.comment_type !== 'review' || parent.pull_number !== pullNumber) throw new ApiError(404, 'Not Found') + const { body } = await c.req.json<{ body?: string }>() + const reply = await callAsCaller(app, c, 'POST', `/repos/${repo.full_name}/pulls/${pullNumber}/comments`, { + body, + in_reply_to_id: parent.in_reply_to_id ?? parent.id, + commit_id: parent.commit_sha, + path: parent.path, + line: parent.line, + side: parent.side, + subject_type: parent.subject_type, + }) + return c.json(reply, 201) + }) +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/security.ts b/packages/github-tools-eve-extension/testing/github/supplement/security.ts new file mode 100644 index 0000000..e096812 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/security.ts @@ -0,0 +1,168 @@ +import type { Entity } from '@emulators/core' +import type { GitHubRepo } from '@emulators/github' +import { findRepo, paginate, requireActor, type Ctx, type Role } from '../access.js' +import type { SupplementContext } from './context.js' + +/** A code scanning alert to seed. */ +export interface CodeScanningAlertSeed { + rule: string + description?: string + severity?: 'critical' | 'high' | 'medium' | 'low' | 'warning' | 'note' | 'error' + tool?: string + path?: string + line?: number + ref?: string + state?: 'open' | 'dismissed' | 'fixed' +} + +/** A Dependabot alert to seed. */ +export interface DependabotAlertSeed { + package: string + ecosystem: string + severity: 'critical' | 'high' | 'medium' | 'low' + summary: string + manifestPath?: string + ghsaId?: string + cveId?: string + vulnerableVersionRange?: string + firstPatchedVersion?: string + state?: 'open' | 'fixed' | 'dismissed' | 'auto_dismissed' +} + +/** A secret scanning alert to seed. The secret itself is never stored. */ +export interface SecretScanningAlertSeed { + secretType: string + displayName?: string + validity?: 'active' | 'inactive' | 'unknown' + state?: 'open' | 'resolved' + resolution?: string +} + +/** Security alerts to seed on a repository. The emulator lists them and never changes them. */ +export interface SecurityAlertSeeds { + codeScanning?: CodeScanningAlertSeed[] + dependabot?: DependabotAlertSeed[] + secretScanning?: SecretScanningAlertSeed[] +} + +type Kind = 'code_scanning' | 'dependabot' | 'secret_scanning' + +interface Alert extends Entity { + repo_id: number + kind: Kind + number: number + state: string + /** GitHub's alert object, without the fields added when it is listed. */ + alert: Record + filters: Record +} + +// GitHub shows code scanning and Dependabot alerts to people who can write, and secret scanning alerts to admins. +const ACCESS: Record = { + code_scanning: { segment: 'code-scanning', permission: 'security_events', role: 'write' }, + dependabot: { segment: 'dependabot', permission: 'vulnerability_alerts', role: 'write' }, + secret_scanning: { segment: 'secret-scanning', permission: 'secret_scanning_alerts', role: 'admin' }, +} + +export function registerSecurityAlerts({ app, store, gh, baseUrl }: SupplementContext) { + const alerts = store.collection('supplement.security_alerts', ['repo_id']) + + function list(c: Ctx, kind: Kind, filters: string[]) { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + requireActor(c, gh, repo, { permission: ACCESS[kind].permission, access: 'read', role: ACCESS[kind].role }) + const state = c.req.query('state') + const matching = alerts.findBy('repo_id', repo.id) + .filter(entry => entry.kind === kind && (!state || entry.state === state)) + .filter(entry => filters.every(name => !c.req.query(name) || entry.filters[name] === c.req.query(name))) + .sort((a, b) => b.number - a.number) + return { repo, matching } + } + + const format = (repo: GitHubRepo, entry: Alert) => ({ + number: entry.number, + state: entry.state, + created_at: entry.created_at, + updated_at: entry.updated_at, + url: `${baseUrl}/repos/${repo.full_name}/${ACCESS[entry.kind].segment}/alerts/${entry.number}`, + html_url: `${baseUrl}/${repo.full_name}/security/${ACCESS[entry.kind].segment}/${entry.number}`, + ...entry.alert, + }) + + app.get('/repos/:owner/:repo/code-scanning/alerts', (c: Ctx) => { + const { repo, matching } = list(c, 'code_scanning', ['severity', 'ref']) + return c.json(paginate(c, matching).map(entry => format(repo, entry))) + }) + + app.get('/repos/:owner/:repo/secret-scanning/alerts', (c: Ctx) => { + const { repo, matching } = list(c, 'secret_scanning', ['secret_type']) + return c.json(paginate(c, matching).map(entry => format(repo, entry))) + }) + + // Dependabot alerts page with a cursor: the next one is the `after` parameter of the Link header. + app.get('/repos/:owner/:repo/dependabot/alerts', (c: Ctx) => { + const { repo, matching } = list(c, 'dependabot', ['severity', 'ecosystem']) + const perPage = Math.min(Number(c.req.query('per_page') ?? 30) || 30, 100) + const after = c.req.query('after') + const rest = after ? matching.filter(entry => entry.number < Number(after)) : matching + const page = rest.slice(0, perPage) + if (rest.length > perPage) { + const next = new URL(c.req.url) + next.searchParams.set('after', String(page.at(-1)!.number)) + c.header('Link', `<${next.href}>; rel="next"`) + } + return c.json(page.map(entry => format(repo, entry))) + }) + + return function seed(repo: GitHubRepo, seeds: SecurityAlertSeeds): void { + const insert = (kind: Kind, state: string, alert: Record, filters: Alert['filters']) => { + const number = alerts.findBy('repo_id', repo.id).filter(entry => entry.kind === kind).length + 1 + alerts.insert({ repo_id: repo.id, kind, number, state, alert, filters }) + } + for (const seeded of seeds.codeScanning ?? []) { + const state = seeded.state ?? 'open' + const severity = seeded.severity ?? 'warning' + const security = ['critical', 'high', 'medium', 'low'].includes(severity) + insert('code_scanning', state, { + dismissed_reason: state === 'dismissed' ? 'won\'t fix' : null, + rule: { + id: seeded.rule, + description: seeded.description ?? seeded.rule, + severity: security ? 'error' : severity, + security_severity_level: security ? severity : null, + }, + tool: { name: seeded.tool ?? 'CodeQL', version: null }, + most_recent_instance: { + ref: seeded.ref ?? `refs/heads/${repo.default_branch}`, + state, + location: seeded.path ? { path: seeded.path, start_line: seeded.line ?? 1, end_line: seeded.line ?? 1 } : undefined, + }, + }, { severity, ref: seeded.ref ?? `refs/heads/${repo.default_branch}` }) + } + for (const seeded of seeds.dependabot ?? []) { + insert('dependabot', seeded.state ?? 'open', { + dependency: { + package: { name: seeded.package, ecosystem: seeded.ecosystem }, + manifest_path: seeded.manifestPath ?? 'package.json', + scope: 'runtime', + }, + security_advisory: { ghsa_id: seeded.ghsaId ?? null, cve_id: seeded.cveId ?? null, summary: seeded.summary, severity: seeded.severity }, + security_vulnerability: { + package: { name: seeded.package, ecosystem: seeded.ecosystem }, + severity: seeded.severity, + vulnerable_version_range: seeded.vulnerableVersionRange ?? '>= 0', + first_patched_version: seeded.firstPatchedVersion ? { identifier: seeded.firstPatchedVersion } : null, + }, + }, { severity: seeded.severity, ecosystem: seeded.ecosystem }) + } + for (const seeded of seeds.secretScanning ?? []) { + const state = seeded.state ?? 'open' + insert('secret_scanning', state, { + secret_type: seeded.secretType, + secret_type_display_name: seeded.displayName ?? seeded.secretType, + validity: seeded.validity ?? 'unknown', + push_protection_bypassed: false, + resolution: state === 'resolved' ? seeded.resolution ?? 'revoked' : null, + }, { secret_type: seeded.secretType }) + } + } +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/statuses.ts b/packages/github-tools-eve-extension/testing/github/supplement/statuses.ts new file mode 100644 index 0000000..4e69bc3 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/statuses.ts @@ -0,0 +1,75 @@ +import type { Entity } from '@emulators/core' +import { ApiError } from '../../emulators.js' +import { briefUser, findRepo, requireActor, type Ctx } from '../access.js' +import { callAsCaller, type SupplementContext } from './context.js' + +interface CommitStatus extends Entity { + repo_id: number + sha: string + state: string + context: string + description: string | null + target_url: string | null + creator_id: number +} + +const STATES = ['error', 'failure', 'pending', 'success'] + +export function registerStatuses({ app, store, gh, baseUrl }: SupplementContext): void { + const statuses = store.collection('supplement.statuses', ['repo_id']) + + const format = (status: CommitStatus, fullName: string) => ({ + id: status.id, + node_id: `SC_${status.id}`, + url: `${baseUrl}/repos/${fullName}/statuses/${status.sha}`, + state: status.state, + context: status.context, + description: status.description, + target_url: status.target_url, + creator: briefUser(gh.users.get(status.creator_id)), + created_at: status.created_at, + updated_at: status.updated_at, + }) + + app.post('/repos/:owner/:repo/statuses/:sha', async (c: Ctx) => { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + const actor = requireActor(c, gh, repo, { permission: 'statuses', access: 'write', role: 'write' }) + const sha = c.req.param('sha') + if (!gh.commits.findBy('repo_id', repo.id).some(commit => commit.sha === sha)) throw new ApiError(422, `No commit found for SHA: ${sha}`) + const body = await c.req.json<{ state?: string, context?: string, description?: string, target_url?: string }>() + if (!body.state || !STATES.includes(body.state)) throw new ApiError(422, 'Validation Failed') + const status = statuses.insert({ + repo_id: repo.id, + sha, + state: body.state, + context: body.context ?? 'default', + description: body.description ?? null, + target_url: body.target_url ?? null, + creator_id: actor.id, + }) + return c.json(format(status, repo.full_name), 201) + }) + + // Registered before emulate's routes: its `/commits/:ref{.+}` would take this path as a ref. + app.get('/repos/:owner/:repo/commits/:ref{.+}/status', async (c: Ctx) => { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + // emulate resolves the ref and checks the caller can read the repository's contents. + const commit = await callAsCaller<{ sha: string }>(app, c, 'GET', `/repos/${repo.full_name}/commits/${c.req.param('ref')}`) + const latest = new Map() + for (const status of statuses.findBy('repo_id', repo.id)) { + if (status.sha === commit.sha) latest.set(status.context, status) + } + const states = [...latest.values()].map(status => status.state) + const state = states.some(value => value === 'failure' || value === 'error') + ? 'failure' + : states.length > 0 && states.every(value => value === 'success') ? 'success' : 'pending' + return c.json({ + state, + sha: commit.sha, + total_count: latest.size, + statuses: [...latest.values()].map(status => format(status, repo.full_name)), + commit_url: `${baseUrl}/repos/${repo.full_name}/commits/${commit.sha}`, + url: `${baseUrl}/repos/${repo.full_name}/commits/${commit.sha}/status`, + }) + }) +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/sub-issues.ts b/packages/github-tools-eve-extension/testing/github/supplement/sub-issues.ts new file mode 100644 index 0000000..e23ea4a --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/sub-issues.ts @@ -0,0 +1,47 @@ +import type { Entity } from '@emulators/core' +import type { GitHubIssue, GitHubRepo } from '@emulators/github' +import { ApiError } from '../../emulators.js' +import { findRepo, paginate, requireActor, requireRead, type Ctx } from '../access.js' +import { callAsCaller, type SupplementContext } from './context.js' + +interface SubIssue extends Entity { + parent_id: number + /** The sub-issue's issue ID. An issue has one parent at most. */ + issue_id: number +} + +export function registerSubIssues({ app, store, gh }: SupplementContext): void { + const links = store.collection('supplement.sub_issues', ['parent_id', 'issue_id']) + + function parentOf(c: Ctx): { repo: GitHubRepo, parent: GitHubIssue } { + const repo = findRepo(gh, c.req.param('owner'), c.req.param('repo')) + const parent = gh.issues.findBy('repo_id', repo.id).find(issue => issue.number === Number(c.req.param('issue_number'))) + if (!parent) throw new ApiError(404, 'Not Found') + return { repo, parent } + } + + const formatted = (c: Ctx, issue: GitHubIssue) => callAsCaller(app, c, 'GET', `/repos/${gh.repos.get(issue.repo_id)!.full_name}/issues/${issue.number}`) + + app.get('/repos/:owner/:repo/issues/:issue_number/sub_issues', async (c: Ctx) => { + const { repo, parent } = parentOf(c) + requireRead(c, gh, repo, 'issues') + const children = links.findBy('parent_id', parent.id).map(link => gh.issues.get(link.issue_id)).filter(issue => issue !== undefined) + return c.json(await Promise.all(paginate(c, children).map(issue => formatted(c, issue)))) + }) + + app.post('/repos/:owner/:repo/issues/:issue_number/sub_issues', async (c: Ctx) => { + const { repo, parent } = parentOf(c) + requireActor(c, gh, repo, { permission: 'issues', access: 'write', role: 'triage' }) + const body = await c.req.json<{ sub_issue_id?: number, replace_parent?: boolean }>() + const child = body.sub_issue_id === undefined ? undefined : gh.issues.get(body.sub_issue_id) + const childRepo = child && gh.repos.get(child.repo_id) + if (!child || !childRepo || child.id === parent.id) throw new ApiError(422, 'Validation Failed') + // A sub-issue can live in another repository of the same owner. + if (childRepo.owner_id !== repo.owner_id || childRepo.owner_type !== repo.owner_type) throw new ApiError(422, 'Sub-issue must belong to the same owner as the parent issue') + const existing = links.findOneBy('issue_id', child.id) + if (existing && !body.replace_parent) throw new ApiError(422, 'Issue may only have one parent') + if (existing) links.delete(existing.id) + links.insert({ parent_id: parent.id, issue_id: child.id }) + return c.json(await formatted(c, parent), 201) + }) +} diff --git a/packages/github-tools-eve-extension/testing/github/supplement/webhooks.ts b/packages/github-tools-eve-extension/testing/github/supplement/webhooks.ts new file mode 100644 index 0000000..6926a2c --- /dev/null +++ b/packages/github-tools-eve-extension/testing/github/supplement/webhooks.ts @@ -0,0 +1,41 @@ +import type { GitHubRepo } from '@emulators/github' +import type { SupplementContext } from './context.js' +import type { NotifyingPayload } from './notifications.js' + +type Dispatch = SupplementContext['webhooks']['dispatch'] + +/** + * Wraps the dispatcher after emulate has wrapped it, the way emulate adds `installation`, to fix + * two payloads. emulate's `issue_comment` payload for a comment on a pull request has no + * `issue.pull_request`, and without it eve's GitHub channel takes the thread for an issue and + * loads no pull request context. Some payloads also lack their `action`. + */ +export function fixWebhookPayloads({ gh, webhooks, baseUrl }: SupplementContext, observe: (event: string, payload: NotifyingPayload, repo: GitHubRepo) => void): void { + const dispatch: Dispatch = webhooks.dispatch.bind(webhooks) + webhooks.dispatch = async (event, action, payload, owner, repo) => { + const repository = repo === undefined ? undefined : gh.repos.findOneBy('full_name', `${owner}/${repo}`) + const issue = (payload as { issue?: { number: number, pull_request?: unknown } } | null)?.issue + const pull = event === 'issue_comment' && repository && issue && !issue.pull_request + ? gh.pullRequests.findBy('repo_id', repository.id).find(candidate => candidate.number === issue.number) + : undefined + const amended = pull && repository + ? { + ...payload as object, + issue: { + ...issue, + pull_request: { + url: `${baseUrl}/repos/${repository.full_name}/pulls/${pull.number}`, + html_url: `${baseUrl}/${repository.full_name}/pull/${pull.number}`, + diff_url: `${baseUrl}/${repository.full_name}/pull/${pull.number}.diff`, + patch_url: `${baseUrl}/${repository.full_name}/pull/${pull.number}.patch`, + merged_at: pull.merged_at, + }, + }, + } + : payload + // emulate passes the action beside some payloads, such as `workflow_run`, and GitHub puts it in every one. + const complete = action && amended && typeof amended === 'object' && !('action' in amended) ? { ...amended, action } : amended + if (repository && complete && typeof complete === 'object') observe(event, complete, repository) + await dispatch(event, action, complete, owner, repo) + } +} diff --git a/packages/github-tools-eve-extension/testing/index.ts b/packages/github-tools-eve-extension/testing/index.ts new file mode 100644 index 0000000..0c38eec --- /dev/null +++ b/packages/github-tools-eve-extension/testing/index.ts @@ -0,0 +1,22 @@ +export { as, ConnectClient, emulateGithub, type EmulateGithubOptions, type GithubEmulation } from './emulate.js' +export { + GithubClient, + RepositoryClient, + ThreadHandle, + type EmulatedComment, + type EmulatedIssue, + type EmulatedPullRequest, + type EvalTarget, + type WaitForCommentOptions, +} from './client.js' +export type { ConnectRequest } from './connect/emulator.js' +export type { + CodeScanningAlertSeed, + DependabotAlertSeed, + GithubRequest, + PersonSeed, + RepositorySeed, + Role, + SecretScanningAlertSeed, + SecurityAlertSeeds, +} from './github/emulator.js' diff --git a/packages/github-tools-eve-extension/testing/redirect.test.ts b/packages/github-tools-eve-extension/testing/redirect.test.ts new file mode 100644 index 0000000..cbec59c --- /dev/null +++ b/packages/github-tools-eve-extension/testing/redirect.test.ts @@ -0,0 +1,70 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { CONNECT_URL_ENV, GITHUB_URL_ENV, REDIRECT_MARKER } from './env' + +const realFetch = globalThis.fetch + +// Loads the preload as Node would, with a fetch that records where each request went. +async function load(env: Record) { + const seen: string[] = [] + globalThis.fetch = async (input) => { + seen.push(input instanceof Request ? input.url : String(input)) + return new Response('{}') + } + vi.stubEnv('EVE_DEV', env.EVE_DEV) + vi.stubEnv(GITHUB_URL_ENV, 'http://127.0.0.1:1111') + vi.stubEnv(CONNECT_URL_ENV, 'http://127.0.0.1:2222') + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.resetModules() + await import('./redirect') + return seen +} + +afterEach(() => { + globalThis.fetch = realFetch + delete (globalThis as { [REDIRECT_MARKER]?: true })[REDIRECT_MARKER] + vi.unstubAllEnvs() + vi.restoreAllMocks() +}) + +describe('the fetch redirect', () => { + it('sends api.github.com and Vercel Connect to the emulators', async () => { + const seen = await load({ EVE_DEV: '1' }) + await fetch('https://api.github.com/repos/acme/web/issues?state=open') + await fetch(new Request('https://api.github.com/graphql', { method: 'POST', body: '{}' })) + await fetch('https://api.vercel.com/v1/connect/token/github%2Fmy-agent', { method: 'POST' }) + await fetch(new URL('https://api-iad1.vercel.com/v1/connect/connectors/github%2Fmy-agent')) + expect(seen).toEqual([ + 'http://127.0.0.1:1111/repos/acme/web/issues?state=open', + 'http://127.0.0.1:1111/graphql', + 'http://127.0.0.1:2222/v1/connect/token/github%2Fmy-agent', + 'http://127.0.0.1:2222/v1/connect/connectors/github%2Fmy-agent', + ]) + }) + + it('keeps the method, the headers, and the body of a redirected request', async () => { + await load({ EVE_DEV: '1' }) + const sent = vi.fn(async () => new Response('{}')) + delete (globalThis as { [REDIRECT_MARKER]?: true })[REDIRECT_MARKER] + globalThis.fetch = sent + vi.resetModules() + await import('./redirect') + await fetch(new Request('https://api.github.com/repos/acme/web/issues', { method: 'POST', headers: { authorization: 'token abc' }, body: '{"title":"x"}' })) + const request = sent.mock.calls[0]![0] as Request + expect([request.method, request.headers.get('authorization'), await request.text()]).toEqual(['POST', 'token abc', '{"title":"x"}']) + }) + + it('leaves other hosts and other api.vercel.com paths alone', async () => { + const seen = await load({ EVE_DEV: '1' }) + await fetch('https://github.com/acme/web.git') + await fetch('https://api.vercel.com/v2/user') + await fetch('https://uploads.github.com/repos/acme/web/releases/1/assets') + expect(seen).toEqual(['https://github.com/acme/web.git', 'https://api.vercel.com/v2/user', 'https://uploads.github.com/repos/acme/web/releases/1/assets']) + }) + + it('does nothing outside eve dev and eve eval', async () => { + const seen = await load({ EVE_DEV: undefined }) + await fetch('https://api.github.com/repos/acme/web') + expect(seen).toEqual(['https://api.github.com/repos/acme/web']) + expect((globalThis as { [REDIRECT_MARKER]?: true })[REDIRECT_MARKER]).toBeUndefined() + }) +}) diff --git a/packages/github-tools-eve-extension/testing/redirect.ts b/packages/github-tools-eve-extension/testing/redirect.ts new file mode 100644 index 0000000..62ec5f0 --- /dev/null +++ b/packages/github-tools-eve-extension/testing/redirect.ts @@ -0,0 +1,38 @@ +import { getEnvironmentData, threadId } from 'node:worker_threads' +import { CONNECT_URL_ENV, GITHUB_URL_ENV, PROBE_KEY, REDIRECT_MARKER } from './env.js' + +// Loaded with `NODE_OPTIONS=--import`, which `emulateGithub` sets before the agent starts. It +// sends the agent's requests to api.github.com and to Vercel Connect to the local emulators, and +// holds no state. It does nothing outside `eve dev` and `eve eval`, which set `EVE_DEV=1`. +const github = process.env[GITHUB_URL_ENV] +const connect = process.env[CONNECT_URL_ENV] +const state = globalThis as typeof globalThis & { [REDIRECT_MARKER]?: true } + +function emulatorFor(url: URL): string | undefined { + if (url.hostname === 'api.github.com') return github + // `@vercel/connect` calls api.vercel.com, or api-.vercel.com when it knows the region. + if (/^api(?:-[a-z0-9]+)?\.vercel\.com$/u.test(url.hostname) && url.pathname.startsWith('/v1/connect/')) return connect + return undefined +} + +if (process.env.EVE_DEV === '1' && github && connect && !state[REDIRECT_MARKER]) { + const original = globalThis.fetch + state[REDIRECT_MARKER] = true + globalThis.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + const emulator = emulatorFor(url) + if (!emulator) return original(input, init) + const target = `${emulator}${url.pathname}${url.search}` + return original(input instanceof Request ? new Request(target, input) : target, init) + } + + // Tells `emulateGithub`, in the same process, that this thread has the redirect. + const probe = getEnvironmentData(PROBE_KEY) + if (probe instanceof SharedArrayBuffer) { + const slots = new Int32Array(probe) + const slot = Atomics.add(slots, 0, 1) + 1 + if (slot < slots.length) Atomics.store(slots, slot, threadId) + } + + console.error(`[github-tools] emulating GitHub in process ${process.pid}, thread ${threadId}: api.github.com -> ${github}, Vercel Connect -> ${connect}`) +} diff --git a/packages/github-tools-eve-extension/tsconfig.json b/packages/github-tools-eve-extension/tsconfig.json index af9ad28..ef6dc07 100644 --- a/packages/github-tools-eve-extension/tsconfig.json +++ b/packages/github-tools-eve-extension/tsconfig.json @@ -14,6 +14,6 @@ "lib": ["ESNext"], "types": ["node"] }, - "include": ["extension", "channels"], - "exclude": ["dist", "channels/dist", "node_modules"] + "include": ["extension", "channels", "testing"], + "exclude": ["dist", "channels/dist", "testing/dist", "node_modules"] } diff --git a/packages/github-tools-eve-extension/tsconfig.testing.json b/packages/github-tools-eve-extension/tsconfig.testing.json new file mode 100644 index 0000000..fde7c34 --- /dev/null +++ b/packages/github-tools-eve-extension/tsconfig.testing.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "testing", + "outDir": "testing/dist", + "declarationMap": false + }, + "include": ["testing"], + "exclude": ["testing/dist", "testing/**/*.test.ts"] +} diff --git a/packages/github-tools-eve-extension/vitest.config.ts b/packages/github-tools-eve-extension/vitest.config.ts new file mode 100644 index 0000000..427063a --- /dev/null +++ b/packages/github-tools-eve-extension/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + include: ['testing/**/*.test.ts'], + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 96644f8..502e48c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -383,6 +383,12 @@ importers: specifier: ^4.6.7 version: 4.6.7 devDependencies: + '@emulators/core': + specifier: 0.13.1 + version: 0.13.1 + '@emulators/github': + specifier: 0.13.1 + version: 0.13.1 '@types/node': specifier: ^26.5.0 version: 26.5.0 @@ -401,6 +407,9 @@ importers: typescript-eslint: specifier: ^8.70.0 version: 8.70.0(eslint@10.10.0(jiti@2.7.0))(typescript@6.0.3) + vitest: + specifier: ^5.0.0 + version: 5.0.0(@types/node@26.5.0)(vite@8.3.6(@types/node@26.5.0)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.13)(yaml@2.9.1)) tests/eve-act-as: dependencies: @@ -438,6 +447,31 @@ importers: specifier: ^4.6.7 version: 4.6.7 + tests/eve-emulate: + dependencies: + '@github-tools/eve-extension': + specifier: workspace:* + version: link:../../packages/github-tools-eve-extension + '@vercel/connect': + specifier: ^2.7.0 + version: 2.7.0(@ai-sdk/mcp@2.0.93(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.2(zod@4.6.7))(ai@7.0.148(zod@4.6.7))(eve@1.0.0-rc.6) + ai: + specifier: ^7.0.148 + version: 7.0.148(zod@4.6.7) + eve: + specifier: ^1.0.0-rc.6 + version: 1.0.0-rc.6(f8168b37b4887d4feb9da8853275c7e5) + zod: + specifier: ^4.6.7 + version: 4.6.7 + devDependencies: + '@emulators/core': + specifier: 0.13.1 + version: 0.13.1 + '@emulators/github': + specifier: 0.13.1 + version: 0.13.1 + packages: '@adonisjs/hash@9.1.1': @@ -971,6 +1005,12 @@ packages: '@emotion/weak-memoize@0.4.0': resolution: {integrity: sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==} + '@emulators/core@0.13.1': + resolution: {integrity: sha512-otPAqo7b1Me+Ak84Yw+oyvpSnPKu+X7XDgbscFrkwXmZ3lb5HjlN4wbMeQ01a6f5p562DtlKhpIUU+Q2mvfDRQ==} + + '@emulators/github@0.13.1': + resolution: {integrity: sha512-5QxGs+8BGBA0cbrLYWDNhrqMwgwo1praPwqWMoQ0sS06NwzkzSUHVkrPfRoZSIjGotvRhF+wE/pvsInyHVXrwQ==} + '@es-joy/jsdoccomment@0.91.0': resolution: {integrity: sha512-vgqlMGNNhZxwDYbUNIHj3Hskb4R28iqdXx90ufHyt/NeuTQkeqjTDslAs9I0/GCAfbxP5BpH5WsL1R1fht5Lxg==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} @@ -12539,6 +12579,14 @@ snapshots: '@emotion/weak-memoize@0.4.0': {} + '@emulators/core@0.13.1': + dependencies: + jose: 6.2.12 + + '@emulators/github@0.13.1': + dependencies: + '@emulators/core': 0.13.1 + '@es-joy/jsdoccomment@0.91.0': dependencies: '@types/estree': 1.0.10 diff --git a/tests/eve-emulate/README.md b/tests/eve-emulate/README.md new file mode 100644 index 0000000..3414e61 --- /dev/null +++ b/tests/eve-emulate/README.md @@ -0,0 +1,21 @@ +# eve testing entry eval + +Runs `@github-tools/eve-extension/testing` end to end: `evals/evals.config.ts` starts the GitHub and Vercel Connect emulators with `emulateGithub`, and a `mockModel` agent mounts the built extension, eve's channel with `evalIdentity()`, and `githubChannel` on `underEmulation(connectGitHubCredentials(...))`. No agent file imports a stub or a redirect. The run needs no token, network, or AI Gateway credentials. + +The evals check that: + +- a write that a person with Write approves runs with their GitHub token and changes the issue in the emulator +- the same write, approved by a person with Read, is refused by the role guard with `403`, settles as failed, and leaves the issue as it was +- a person who never authorized the App gets a sign-in prompt, and the call resumes with the token the sign-in issued +- a person whose token is revoked gets `401` from the emulator, signs in again, and the call resumes +- a request the emulator didn't sign is refused by the GitHub channel +- with `respondTo: 'writers'`, a reader's mention starts no turn, and a writer's comment, created in the emulator, starts one whose reply is read back from the thread +- an approval on the GitHub channel is answered by a comment +- a comment on a pull request's conversation loads the pull request, and a review comment gets a reply in its thread + +`scripts/probe.mjs` then runs the evals with the redirect taken out of `NODE_OPTIONS`, and checks that the run stops before the first eval with the probe's message. + +```bash +pnpm --filter @github-tools/sdk --filter @github-tools/eve-extension build +pnpm --filter @github-tools/eve-emulate-test test +``` diff --git a/tests/eve-emulate/agent/agent.ts b/tests/eve-emulate/agent/agent.ts new file mode 100644 index 0000000..3a00376 --- /dev/null +++ b/tests/eve-emulate/agent/agent.ts @@ -0,0 +1,24 @@ +import { defineAgent } from 'eve' +import { mockModel } from 'eve/evals' + +// A fixed model: each message names the tool call to make, and the reply after a tool result +// carries that result, so an eval can read what the emulator answered. +export default defineAgent({ + defaultTools: false, + model: mockModel(({ messages, lastUserMessage, toolResults }) => { + if (messages.at(-1)?.role === 'tool') { + const last = toolResults.at(-1)! + return `result ${last.name} ${last.isError ? 'error' : 'ok'} ${JSON.stringify(last.output)}` + } + const message = lastUserMessage ?? '' + // A comment from the GitHub channel arrives with its context block, and names no repository. + if (message.includes('read this repository')) return { toolCalls: [{ name: 'github__getRepository', input: {} }] } + // The channel's context names the issue the comment is on. + if (message.includes('label this issue')) return { toolCalls: [{ name: 'github__addLabels', input: { labels: ['bug'] } }] } + const read = /^read ([\w-]+)\/([\w-]+)$/u.exec(message) + if (read) return { toolCalls: [{ name: 'github__getRepository', input: { owner: read[1], repo: read[2] } }] } + const label = /^label ([\w-]+)\/([\w-]+)#(\d+)$/u.exec(message) + if (label) return { toolCalls: [{ name: 'github__addLabels', input: { owner: label[1], repo: label[2], issueNumber: Number(label[3]), labels: ['bug'] } }] } + return `unexpected message: ${message}` + }), +}) diff --git a/tests/eve-emulate/agent/channels/eve.ts b/tests/eve-emulate/agent/channels/eve.ts new file mode 100644 index 0000000..591dc23 --- /dev/null +++ b/tests/eve-emulate/agent/channels/eve.ts @@ -0,0 +1,4 @@ +import { eveChannel } from 'eve/channels/eve' +import { evalIdentity } from '@github-tools/eve-extension/testing/agent' + +export default eveChannel({ auth: [evalIdentity()] }) diff --git a/tests/eve-emulate/agent/channels/github.ts b/tests/eve-emulate/agent/channels/github.ts new file mode 100644 index 0000000..a7a7338 --- /dev/null +++ b/tests/eve-emulate/agent/channels/github.ts @@ -0,0 +1,9 @@ +import { connectGitHubCredentials } from '@vercel/connect/eve' +import { githubChannel } from '@github-tools/eve-extension/channels' +import { underEmulation } from '@github-tools/eve-extension/testing/agent' + +// The channel as a deployed agent mounts it: the token and the bot name come from Vercel Connect. +export default githubChannel({ + credentials: underEmulation(connectGitHubCredentials('github/eval')), + respondTo: 'writers', +}) diff --git a/tests/eve-emulate/agent/extensions/github.ts b/tests/eve-emulate/agent/extensions/github.ts new file mode 100644 index 0000000..76a83d5 --- /dev/null +++ b/tests/eve-emulate/agent/extensions/github.ts @@ -0,0 +1,11 @@ +import githubExtension from '@github-tools/eve-extension' + +// A signed-in person's turn runs with their own GitHub token, and a turn with no person runs as +// the App. Both tokens come from Vercel Connect, which the eval run emulates. +export default githubExtension({ + connector: 'github/eval', + actAs: 'caller', + approvers: 'anyone', + include: ['getRepository', 'addLabels'], + requireApproval: { addLabels: 'always' }, +}) diff --git a/tests/eve-emulate/agent/instructions.md b/tests/eve-emulate/agent/instructions.md new file mode 100644 index 0000000..0cf33e8 --- /dev/null +++ b/tests/eve-emulate/agent/instructions.md @@ -0,0 +1 @@ +Test agent for the eve testing kit. A mock model answers. diff --git a/tests/eve-emulate/evals/evals.config.ts b/tests/eve-emulate/evals/evals.config.ts new file mode 100644 index 0000000..71e62fd --- /dev/null +++ b/tests/eve-emulate/evals/evals.config.ts @@ -0,0 +1,20 @@ +import { defineEvalConfig } from 'eve/evals' +import { emulateGithub } from '@github-tools/eve-extension/testing' + +export default defineEvalConfig({ + async setup() { + const emulation = await emulateGithub({ + repositories: { 'acme/web': { labels: ['bug'] } }, + people: { + alice: { role: 'write' }, + bob: { role: 'read' }, + carol: { role: 'write', authorized: false }, + dave: { role: 'write' }, + }, + }) + // `scripts/probe.mjs` sets this to check that a run whose agent has no redirect stops before the first eval. + if (process.env.EVAL_WITHOUT_REDIRECT) process.env.NODE_OPTIONS = '' + return emulation + }, + teardown: context => context?.close(), +}) diff --git a/tests/eve-emulate/evals/identity.eval.ts b/tests/eve-emulate/evals/identity.eval.ts new file mode 100644 index 0000000..0aa59a6 --- /dev/null +++ b/tests/eve-emulate/evals/identity.eval.ts @@ -0,0 +1,36 @@ +import { defineEval } from 'eve/evals' +import { equals, includes } from 'eve/evals/expect' +import { as } from '@github-tools/eve-extension/testing' +import type config from './evals.config' + +export default defineEval({ + description: 'a tool call runs with the GitHub token of the person who asked, and a reader is refused', + async test(t) { + const { github } = t.context + const web = github.repo('acme/web') + const issue = await web.as('bob').createIssue({ title: 'Crash on save' }) + + // alice has Write: the call she approves runs with her token and labels the issue. + const asked = await t.send(`label acme/web#${issue.number}`, as('alice')) + await t.require(asked.interactions.map(interaction => interaction.request.kind), equals(['approval'])) + const approved = await asked.session.respond([{ interactionId: asked.interactions[0]!.interactionId, optionId: 'approve' }], as('alice')) + t.check(approved.requireToolCall('github__addLabels').status, equals('completed')) + t.check((await web.issue(issue.number)).labels, equals(['bug'])) + + // bob has Read: GitHub refuses the same call with his token, and the issue stays as it was. + const other = await web.as('alice').createIssue({ title: 'Typo in the docs' }) + const refused = await t.send(`label acme/web#${other.number}`, as('bob')) + const answered = await refused.session.respond([{ interactionId: refused.interactions[0]!.interactionId, optionId: 'approve' }], as('bob')) + answered.calledTool('github__addLabels', { status: 'failed', count: 1 }) + t.check(answered.reply, includes('github_tools.FORBIDDEN')) + t.check((await web.issue(other.number)).labels, equals([])) + + // Evals share the emulator's log, so only this eval's two issues are read from it. + const paths = [issue.number, other.number].map(number => `/repos/acme/web/issues/${number}/labels`) + const labeling = github.requests.filter(request => request.method === 'POST' && paths.includes(request.path)) + t.check(labeling.map(request => `${request.path} ${request.actor} ${request.status}`), equals([ + `/repos/acme/web/issues/${issue.number}/labels alice 200`, + `/repos/acme/web/issues/${other.number}/labels bob 403`, + ])) + }, +}) diff --git a/tests/eve-emulate/evals/sign-in.eval.ts b/tests/eve-emulate/evals/sign-in.eval.ts new file mode 100644 index 0000000..5081b86 --- /dev/null +++ b/tests/eve-emulate/evals/sign-in.eval.ts @@ -0,0 +1,30 @@ +import { defineEval } from 'eve/evals' +import { equals } from 'eve/evals/expect' +import { as } from '@github-tools/eve-extension/testing' +import type config from './evals.config' + +export default defineEval({ + description: 'a person who has not connected GitHub signs in, and one whose token GitHub rejects signs in again', + async test(t) { + const { connect } = t.context + const kinds = (turn: { interactions: readonly { request: { kind: string } }[] }) => turn.interactions.map(interaction => interaction.request.kind) + + // carol never authorized the App: the read waits for her sign-in, then runs with the token it issued. + const asked = await t.send('read acme/web', as('carol')) + await t.require(kinds(asked), equals(['sign-in'])) + const signedIn = await connect.completeSignIn(t, asked) + t.check(signedIn.requireToolCall('github__getRepository').status, equals('completed')) + const carol = connect.requests.filter(request => request.body?.subject?.id === 'carol') + t.check(carol.map(request => `${request.route} ${request.status}`), equals(['token 403', 'authorize 200', 'token 200'])) + t.check(carol[0]?.body?.scopes, equals(['*'])) + + // dave is connected, and the agent caches his token. Once it is revoked, GitHub answers 401 and eve asks him to sign in. + const first = await t.send('read acme/web', as('dave')) + t.check(first.requireToolCall('github__getRepository').status, equals('completed')) + connect.revoke('dave') + const revoked = await t.send('read acme/web', as('dave')) + await t.require(kinds(revoked), equals(['sign-in'])) + const reconnected = await connect.completeSignIn(t, revoked) + t.check(reconnected.requireToolCall('github__getRepository').status, equals('completed')) + }, +}) diff --git a/tests/eve-emulate/evals/webhook.eval.ts b/tests/eve-emulate/evals/webhook.eval.ts new file mode 100644 index 0000000..1e95c64 --- /dev/null +++ b/tests/eve-emulate/evals/webhook.eval.ts @@ -0,0 +1,62 @@ +import { defineEval } from 'eve/evals' +import { equals, includes, satisfies } from 'eve/evals/expect' +import type config from './evals.config' + +export default defineEval({ + description: 'a comment created in the emulator reaches the agent as a signed webhook, and the reply is read back', + async test(t) { + const { github } = t.context + const web = github.repo('acme/web') + const mention = `@${github.app.slug} read this repository` + await github.deliverWebhooksTo(t) + + // The channel checks the emulator's signature, so a request it didn't sign is refused. + const forged = await t.target.fetch('/eve/v1/github', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-github-event': 'issue_comment', 'x-github-delivery': 'forged', 'x-hub-signature-256': 'sha256=00' }, + body: JSON.stringify({ action: 'created' }), + }) + t.check(forged.status, equals(401)) + + // An issue: bob has Read, so his mention starts nothing, and alice's starts a turn that replies. + const issue = await web.as('bob').createIssue({ title: 'Crash on save' }) + await web.as('bob').comment(issue.number, mention) + const asked = await web.as('alice').comment(issue.number, mention) + const reply = await web.issue(issue.number).waitForComment({ by: 'app' }) + t.check(reply.body, includes('result github__getRepository ok')) + t.check(reply.body, includes('acme/web')) + t.check((await web.issue(issue.number).comments()).filter(comment => comment.author === `${github.app.slug}[bot]`).length, equals(1)) + t.check(github.requests.some(request => request.path === `/repos/acme/web/issues/comments/${asked.id}/reactions` && request.status === 201), equals(true)) + + // An approval on GitHub is a comment, and a reply that mentions the agent answers it. + const unlabeled = await web.as('bob').createIssue({ title: 'Needs a label' }) + await web.as('alice').comment(unlabeled.number, `@${github.app.slug} label this issue`) + const prompt = await web.issue(unlabeled.number).waitForComment({ by: 'app' }) + t.check(prompt.body, includes('Add labels on acme/web')) + await web.as('alice').comment(unlabeled.number, `@${github.app.slug} Approve`) + const labeled = await web.issue(unlabeled.number).waitForComment({ by: 'app', after: prompt.id }) + t.check(labeled.body, includes('result github__addLabels ok')) + t.check((await web.issue(unlabeled.number)).labels, equals(['bug'])) + + // A pull request's conversation: the payload names the pull request, so the channel loads it. + const pull = await web.as('alice').createPullRequest({ title: 'Fix the crash' }) + await web.as('alice').comment(pull.number, mention) + await web.pull(pull.number).waitForComment({ by: 'app' }) + t.check(github.requests.some(request => request.path === `/repos/acme/web/pulls/${pull.number}` && request.actor === `${github.app.slug}[bot]`), equals(true)) + + // A review comment on the diff: the agent reacts to it and replies in its thread. + const octokit = github.octokit('alice') + const { data: review } = await octokit.rest.pulls.createReviewComment({ owner: 'acme', repo: 'web', pull_number: pull.number, body: mention, commit_id: pull.headSha, path: `${pull.head}.txt`, line: 1, side: 'RIGHT' }) + await t.require(review.id, satisfies(id => typeof id === 'number', 'the review comment was created')) + let threadReply: { in_reply_to_id?: number } | undefined + for (let attempt = 0; attempt < 300 && !threadReply; attempt++) { + const { data: comments } = await octokit.rest.pulls.listReviewComments({ owner: 'acme', repo: 'web', pull_number: pull.number }) + threadReply = comments.find(comment => comment.user?.login === `${github.app.slug}[bot]`) + if (!threadReply) await t.sleep(100) + } + t.check(threadReply?.in_reply_to_id, equals(review.id)) + + const fromPeople = github.deliveries.filter(delivery => (delivery.payload as { sender?: { type?: string } }).sender?.type === 'User') + t.check(fromPeople.every(delivery => delivery.status_code === 200), equals(true)) + }, +}) diff --git a/tests/eve-emulate/package.json b/tests/eve-emulate/package.json new file mode 100644 index 0000000..e3e16eb --- /dev/null +++ b/tests/eve-emulate/package.json @@ -0,0 +1,22 @@ +{ + "name": "@github-tools/eve-emulate-test", + "private": true, + "type": "module", + "engines": { + "node": "24.x" + }, + "scripts": { + "test": "eve eval --skip-report && node scripts/probe.mjs" + }, + "dependencies": { + "@github-tools/eve-extension": "workspace:*", + "@vercel/connect": "^2.7.0", + "ai": "^7.0.148", + "eve": "^1.0.0-rc.6", + "zod": "^4.6.7" + }, + "devDependencies": { + "@emulators/core": "0.13.1", + "@emulators/github": "0.13.1" + } +} diff --git a/tests/eve-emulate/scripts/probe.mjs b/tests/eve-emulate/scripts/probe.mjs new file mode 100644 index 0000000..c68fbb3 --- /dev/null +++ b/tests/eve-emulate/scripts/probe.mjs @@ -0,0 +1,21 @@ +import { spawnSync } from 'node:child_process' + +// Runs the evals with the redirect taken out of NODE_OPTIONS after `setup`. `emulateGithub` has +// to stop the run before the first eval, with a message that names the cause. +const run = spawnSync('pnpm', ['exec', 'eve', 'eval', '--skip-report'], { + cwd: new URL('..', import.meta.url), + env: { ...process.env, EVAL_WITHOUT_REDIRECT: '1' }, + encoding: 'utf8', +}) +const output = `${run.stdout}${run.stderr}` +const failures = [ + run.status === 0 && 'the run passed', + !output.includes('started without the redirect to the emulators') && 'the output has no probe message', + /^[✓✗] /mu.test(output) && 'an eval ran', +].filter(Boolean) + +if (failures.length > 0) { + console.error(`A run without the redirect should fail before the first eval, and ${failures.join(', ')}.\n${output}`) + process.exit(1) +} +console.log('✓ a run without the redirect stops before the first eval') diff --git a/turbo.json b/turbo.json index b3f1cdf..c6f0e35 100644 --- a/turbo.json +++ b/turbo.json @@ -12,7 +12,7 @@ "tasks": { "build": { "dependsOn": ["^build"], - "outputs": [".vercel/output/**", "dist/**", "channels/dist/**", ".nuxt/**", ".output/**"], + "outputs": [".vercel/output/**", "dist/**", "channels/dist/**", "testing/dist/**", ".nuxt/**", ".output/**"], "inputs": ["$TURBO_DEFAULT$", ".env", ".env.*"], "env": [ "NUXT_STUDIO_SSO_URL", From 7e6a3c038edbc5d2c085ea1b84ab83a802c7e6fe Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Wed, 11 Nov 2026 16:32:02 +0000 Subject: [PATCH 2/3] fix(eve): close the testing emulators to web pages and fix pull request emulation Four fixes to the testing entry, from the reviews of the pull request. Security review (low): a web page open during an eval run could call the emulators. emulate allows every origin, and the seeded tokens were ghp_, the admin's included. - Both emulators refuse a request with an Origin header, which only a browser sends. The GitHub emulator still accepts its own origin. A preflight gets 403 with no CORS header. - Each person's token, the admin's, and the tokens the Connect emulator issues are random on every run. A person's token is the same after reset(), since the agent may hold it. Vercel Agent review: - createPullRequest({ files }) failed with 422 for a path that exists on the base branch, because the contents route needs the file's SHA. It now writes its files in one commit through the Git database routes. - A pull request's author with Read got FORBIDDEN when changing its draft state. The GraphQL handler delegates to PATCH /pulls/{n}, and the role guard didn't count draft among the fields an author may send. Found while writing the regression tests: - emulate lists a pull request's files from a stub, one fake name for each of a counter that stays at 0, so listPullRequestFiles and getPullRequestContext always saw no file. The files route now answers with the diff emulate's compare route computes, read from the head branch, since emulate keeps the head SHA the pull request was opened with. changed_files, additions and deletions on the pull request follow the same diff. --- .../content/docs/5.guides/8.test-an-agent.md | 2 + .../testing/client.test.ts | 39 +++++++++++++++++ .../testing/client.ts | 17 +++++--- .../testing/connect/emulator.test.ts | 17 ++++++++ .../testing/connect/emulator.ts | 10 +++-- .../testing/github/emulator.test.ts | 39 +++++++++++++++++ .../testing/github/emulator.ts | 26 ++++++++---- .../testing/github/fixes.ts | 42 ++++++++++++++++++- .../testing/github/role-guard.ts | 3 +- 9 files changed, 175 insertions(+), 20 deletions(-) create mode 100644 packages/github-tools-eve-extension/testing/client.test.ts diff --git a/apps/docs/content/docs/5.guides/8.test-an-agent.md b/apps/docs/content/docs/5.guides/8.test-an-agent.md index bbe3c5f..bbca7d3 100644 --- a/apps/docs/content/docs/5.guides/8.test-an-agent.md +++ b/apps/docs/content/docs/5.guides/8.test-an-agent.md @@ -69,6 +69,8 @@ export default defineEvalConfig({ The return value is `t.context` in every eval. `emulateGithub` also points the agent at the emulators: it sets `NODE_OPTIONS` so that Node loads a `fetch` redirect in the agent's thread, and it sets `GITHUB_TOKEN`, the GitHub App variables eve's GitHub channel reads, and a placeholder `VERCEL_OIDC_TOKEN`. Your agent files don't import the redirect, and nothing of it is in a production build. +Both emulators listen on loopback only, answer no request a web page sends, and give each person a token that differs on every run. + If the agent's thread starts without the redirect, the run stops before the first eval and the error names the cause. Without that check, the agent would send the emulators' tokens to the real hosts. ## 3. Say who is asking diff --git a/packages/github-tools-eve-extension/testing/client.test.ts b/packages/github-tools-eve-extension/testing/client.test.ts new file mode 100644 index 0000000..15ee16a --- /dev/null +++ b/packages/github-tools-eve-extension/testing/client.test.ts @@ -0,0 +1,39 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { GithubClient } from './client' +import { startGithubEmulator, type GithubEmulator } from './github/emulator' + +let github: GithubEmulator +let client: GithubClient + +beforeAll(async () => { + github = await startGithubEmulator({ repositories: { 'acme/web': {} }, people: { alice: { role: 'write' } } }) + client = new GithubClient(github, ['acme/web']) +}) + +afterAll(() => github.close()) + +describe('createPullRequest', () => { + it('changes a file that is on the base branch, and adds a new one', async () => { + const pull = await client.repo('acme/web').as('alice').createPullRequest({ title: 'Rewrite the README', files: { 'README.md': '# Web\n', 'docs/guide.md': 'A guide.\n' } }) + const files = await github.request>('alice', 'GET', `/repos/acme/web/pulls/${pull.number}/files`) + expect(files.map(file => `${file.status} ${file.filename}`).sort()).toEqual(['added docs/guide.md', 'modified README.md']) + const counters = await github.request<{ changed_files: number, additions: number, deletions: number }>('alice', 'GET', `/repos/acme/web/pulls/${pull.number}`) + expect([counters.changed_files, counters.additions, counters.deletions]).toEqual([2, 2, 1]) + }) + + it('lists the files of commits pushed after the pull request was opened', async () => { + const pull = await client.repo('acme/web').as('alice').createPullRequest({ title: 'Add the changelog' }) + await github.request('alice', 'PUT', '/repos/acme/web/contents/CHANGELOG.md', { message: 'Add the changelog', content: Buffer.from('# Changelog\n').toString('base64'), branch: pull.head }) + const files = await github.request>('alice', 'GET', `/repos/acme/web/pulls/${pull.number}/files`) + expect(files.map(file => file.filename).sort()).toEqual(['CHANGELOG.md', `${pull.head}.txt`]) + const after = await github.request<{ head: { sha: string } }>('alice', 'GET', `/repos/acme/web/pulls/${pull.number}`) + // The reason the diff is read from the branch: emulate keeps the head SHA the pull request was opened with. + expect(after.head.sha).toBe(pull.headSha) + }) + + it('opens a pull request with one new file when given none', async () => { + const pull = await client.repo('acme/web').as('alice').createPullRequest({ title: 'Fix the crash' }) + const files = await github.request>('alice', 'GET', `/repos/acme/web/pulls/${pull.number}/files`) + expect(files.map(file => `${file.status} ${file.filename}`)).toEqual([`added ${pull.head}.txt`]) + }) +}) diff --git a/packages/github-tools-eve-extension/testing/client.ts b/packages/github-tools-eve-extension/testing/client.ts index e5ece32..1883f92 100644 --- a/packages/github-tools-eve-extension/testing/client.ts +++ b/packages/github-tools-eve-extension/testing/client.ts @@ -125,17 +125,22 @@ export class RepositoryClient { } /** - * Opens a pull request from a new branch with the given files, which default to one new file. - * The person needs Write, since the branch is in this repository. + * Opens a pull request from a new branch with one commit that writes the given files, by path. + * They default to one new file. The person needs Write, since the branch is in this repository. */ async createPullRequest(input: { title: string, body?: string, files?: Record, base?: string, draft?: boolean }): Promise { const base = input.base ?? (await this.request<{ default_branch: string }>('GET', '')).default_branch const { object } = await this.request<{ object: { sha: string } }>('GET', `/git/ref/heads/${base}`) + const { tree: baseTree } = await this.request<{ tree: { sha: string } }>('GET', `/git/commits/${object.sha}`) const branch = `eval-${this.github.nextId()}` - await this.request('POST', '/git/refs', { ref: `refs/heads/${branch}`, sha: object.sha }) - for (const [path, content] of Object.entries(input.files ?? { [`${branch}.txt`]: `${input.title}\n` })) { - await this.request('PUT', `/contents/${path}`, { message: `Add ${path}`, content: Buffer.from(content).toString('base64'), branch }) - } + // One commit through the Git database routes, which take a file whether or not the base branch has it. + const files = input.files ?? { [`${branch}.txt`]: `${input.title}\n` } + const tree = await this.request<{ sha: string }>('POST', '/git/trees', { + base_tree: baseTree.sha, + tree: Object.entries(files).map(([path, content]) => ({ path, mode: '100644', type: 'blob', content })), + }) + const commit = await this.request<{ sha: string }>('POST', '/git/commits', { message: input.title, tree: tree.sha, parents: [object.sha] }) + await this.request('POST', '/git/refs', { ref: `refs/heads/${branch}`, sha: commit.sha }) const created = await this.request<{ number: number }>('POST', '/pulls', { title: input.title, body: input.body, head: branch, base, draft: input.draft }) return this.pull(created.number) } diff --git a/packages/github-tools-eve-extension/testing/connect/emulator.test.ts b/packages/github-tools-eve-extension/testing/connect/emulator.test.ts index fe94125..3f9ba73 100644 --- a/packages/github-tools-eve-extension/testing/connect/emulator.test.ts +++ b/packages/github-tools-eve-extension/testing/connect/emulator.test.ts @@ -87,6 +87,23 @@ describe('the Vercel Connect emulator', () => { expect((await githubAs(again.token, 'GET', '/repos/acme/web')).status).toBe(401) }) + it('answers no request a web page sends, and issues tokens that differ on every sign-in', async () => { + // A form or a `text/plain` fetch needs no preflight, so a page could otherwise sign a person in. + const fromPage = await fetch(`${connect.url}/v1/connect/authorize/github%2Fmy-agent`, { + method: 'POST', + headers: { 'origin': 'https://evil.example', 'content-type': 'text/plain' }, + body: JSON.stringify({ ...user('erin'), returnUrl: 'http://localhost:3000/callback' }), + }) + expect(fromPage.status).toBe(403) + expect((await post('token/github%2Fmy-agent', user('erin'))).status).toBe(403) + + const first = await (await post('token/github%2Fmy-agent', user('alice'))).json() as { token: string } + await post('authorize/github%2Fmy-agent', { ...user('alice'), returnUrl: 'http://localhost:3000/callback' }) + const second = await (await post('token/github%2Fmy-agent', user('alice'))).json() as { token: string } + expect([first.token, second.token].some(token => /^ghu_alice_\d+$/u.test(token))).toBe(false) + expect(second.token).not.toBe(first.token) + }) + it('names the App in the connector metadata, and answers 404 to any other route', async () => { const metadata = await fetch(`${connect.url}/v1/connect/connectors/github%2Fmy-agent`, { headers: { authorization: 'Bearer oidc' } }) expect(await metadata.json()).toMatchObject({ uid: 'github/my-agent', data: { appSlug: github.githubApp.slug } }) diff --git a/packages/github-tools-eve-extension/testing/connect/emulator.ts b/packages/github-tools-eve-extension/testing/connect/emulator.ts index c390c36..d352d3a 100644 --- a/packages/github-tools-eve-extension/testing/connect/emulator.ts +++ b/packages/github-tools-eve-extension/testing/connect/emulator.ts @@ -1,3 +1,4 @@ +import { randomBytes } from 'node:crypto' import { once } from 'node:events' import type { AddressInfo } from 'node:net' import type { Context } from '@emulators/core' @@ -30,11 +31,11 @@ const error = (status: number, code: string, message: string) => Response.json({ export async function startConnectEmulator(github: GithubEmulator, people: Record) { const requests: ConnectRequest[] = [] const tokens = new Map() - let issued = 0 + let authorizations = 0 // A sign-in has to produce a token GitHub knows: one it doesn't is anonymous to emulate and `401` to the role guard. function issue(person: string): string { - const token = `ghu_${person}_${++issued}` + const token = `ghu_${randomBytes(20).toString('hex')}` github.registerToken(token, person) tokens.set(person, token) return token @@ -83,7 +84,8 @@ export async function startConnectEmulator(github: GithubEmulator, people: Recor } revoke(subject.id) issue(subject.id) - return c.json({ url: returnUrl, request: `req_${issued}`, verifier: `ver_${issued}`, connector: connector(c) }) + authorizations++ + return c.json({ url: returnUrl, request: `req_${authorizations}`, verifier: `ver_${authorizations}`, connector: connector(c) }) }) app.get('/v1/connect/connectors/:connector', c => c.json({ ...connector(c), data: { appSlug: github.githubApp.slug } })) @@ -103,6 +105,8 @@ export async function startConnectEmulator(github: GithubEmulator, people: Recor const server = serve({ port: 0, fetch: async (request) => { + // Only a browser sends an `Origin` header, and a web page has no business with these routes. + if (request.headers.get('origin') !== null) return error(403, 'forbidden', 'The Connect emulator answers no request from a web page.') const body = request.method === 'GET' ? undefined : await request.clone().json().catch(() => undefined) as ConnectRequest['body'] const response = await app.fetch(request) const [, , , route, name] = new URL(request.url).pathname.split('/') diff --git a/packages/github-tools-eve-extension/testing/github/emulator.test.ts b/packages/github-tools-eve-extension/testing/github/emulator.test.ts index 94a1cd8..977341f 100644 --- a/packages/github-tools-eve-extension/testing/github/emulator.test.ts +++ b/packages/github-tools-eve-extension/testing/github/emulator.test.ts @@ -137,6 +137,28 @@ describe('the emulator', () => { ]) }) + it('answers no request a web page sends from another origin', async () => { + const from = (origin: string, init: RequestInit = {}) => fetch(`${github.url}/repos/acme/web`, { ...init, headers: { ...init.headers, origin } }) + expect((await from('https://evil.example')).status).toBe(403) + expect((await from('null')).status).toBe(403) + // A browser asks before a request with an Authorization header, and reads the answer's CORS headers. + const preflight = await from('https://evil.example', { method: 'OPTIONS', headers: { 'access-control-request-method': 'POST', 'access-control-request-headers': 'authorization' } }) + expect([preflight.status, preflight.headers.get('access-control-allow-origin')]).toEqual([403, null]) + expect((await from(github.url)).status).toBe(200) + }) + + it('gives each person a token that differs on every run', async () => { + expect((await api(undefined, 'GET', '/repos/acme/web', undefined, 'ghp_alice')).status).toBe(401) + expect((await api(undefined, 'GET', '/repos/acme/web', undefined, `ghp_${github.admin}`)).status).toBe(401) + const other = await startGithubEmulator({ repositories: { 'acme/web': {} }, people: { alice: {} } }) + const tokens = [github.tokenFor('alice'), other.tokenFor('alice'), github.tokenFor(github.admin)] + await other.close() + expect(new Set(tokens).size).toBe(3) + // The same token after a reset, since the agent may hold it. + await github.reset() + expect(github.tokenFor('alice')).toBe(tokens[0]) + }) + it('goes back to the seeded state on reset', async () => { await issue('bob') await github.reset() @@ -190,6 +212,23 @@ describe('the GraphQL handler', () => { expect(github.unknownDocuments).toEqual(['query { viewer { login } }']) }) + it('lets the author of a pull request change its draft state, and needs Write from anyone else', async () => { + // alice pushes the branch, and bob, who has Read, opens the pull request from it. + const { object } = await github.request<{ object: { sha: string } }>('alice', 'GET', '/repos/acme/web/git/ref/heads/main') + await github.request('alice', 'POST', '/repos/acme/web/git/refs', { ref: 'refs/heads/draft', sha: object.sha }) + await github.request('alice', 'PUT', '/repos/acme/web/contents/draft.txt', { message: 'Draft', content: Buffer.from('draft\n').toString('base64'), branch: 'draft' }) + const pull = await github.request<{ number: number, node_id: string }>('bob', 'POST', '/repos/acme/web/pulls', { title: 'Draft', head: 'draft', base: 'main' }) + const setDraft = (login: string, mutation: string) => graphql(login, `mutation($pullRequestId: ID!) { ${mutation}(input: { pullRequestId: $pullRequestId }) { pullRequest { id } } }`, { pullRequestId: pull.node_id }) + const draft = async () => (await api('alice', 'GET', `/repos/acme/web/pulls/${pull.number}`)).body.draft + + expect((await setDraft('tara', 'convertPullRequestToDraft')).body.errors[0].type).toBe('FORBIDDEN') + expect(await draft()).toBe(false) + expect((await setDraft('bob', 'convertPullRequestToDraft')).body.data.convertPullRequestToDraft.pullRequest.id).toBe(pull.node_id) + expect(await draft()).toBe(true) + expect((await setDraft('alice', 'markPullRequestReadyForReview')).body.errors).toBeUndefined() + expect(await draft()).toBe(false) + }) + it('blames each line on the commit that introduced it', async () => { const put = async (content: string, message: string, sha?: string) => { const { content: file, commit } = await github.request<{ content: { sha: string }, commit: { sha: string } }>('alice', 'PUT', '/repos/acme/web/contents/notes.md', { message, content: Buffer.from(content).toString('base64'), sha }) diff --git a/packages/github-tools-eve-extension/testing/github/emulator.ts b/packages/github-tools-eve-extension/testing/github/emulator.ts index 6b1e621..b3b1075 100644 --- a/packages/github-tools-eve-extension/testing/github/emulator.ts +++ b/packages/github-tools-eve-extension/testing/github/emulator.ts @@ -3,10 +3,10 @@ import type { Server } from 'node:http' import type { AddressInfo } from 'node:net' import { createSign, randomBytes } from 'node:crypto' import type { AppEnv, Hono, ServicePlugin, Store, TokenMap, WebhookDispatcher } from '@emulators/core' -import type { GitHubSeedConfig, GitHubStore } from '@emulators/github' +import type { GitHubPullRequest, GitHubRepo, GitHubSeedConfig, GitHubStore } from '@emulators/github' import { createAppKeyResolver, createServer, getGitHubStore, githubPlugin, prepareSeed, seedFromConfig, serve } from '../emulators.js' import { ROLE_PERMISSION, type Role } from './access.js' -import { registerRequestFixes } from './fixes.js' +import { registerRequestFixes, type ChangedFile } from './fixes.js' import { registerRoleGuard } from './role-guard.js' import { fixWebhookPayloads, registerSupplementRoutes, type SecurityAlertSeeds } from './supplement/index.js' @@ -90,7 +90,6 @@ export async function startGithubEmulator({ repositories, people = {}, supplemen const unknownDocuments: string[] = [] const supplementRoutes: Array<{ method: string, path: string }> = [] const tokenLogins = new Map() - const personalTokens = new Map() const webhookSecret = randomBytes(24).toString('hex') const owners = [...new Set(Object.keys(repositories).map(name => name.split('/')[0]!))] const installations = Object.fromEntries(owners.map((owner, index) => [owner, 1000 + index])) @@ -102,7 +101,7 @@ export async function startGithubEmulator({ repositories, people = {}, supplemen register(app, store, webhooks, baseUrl, tokenMap) { const context = { app, store, gh: getGitHubStore(store), webhooks, baseUrl } registerRoleGuard(app, store) - registerRequestFixes(app, store) + registerRequestFixes(app, store, changedFiles) if (supplement) { const before = app.routeTable.length parts = registerSupplementRoutes(context, unknownDocuments) @@ -127,6 +126,10 @@ export async function startGithubEmulator({ repositories, people = {}, supplemen const server: Server = serve({ port: 0, fetch: async (request) => { + // emulate allows every origin, so a web page open during a run could call the emulator. Nothing the + // kit starts sends an `Origin` header: only a browser does. + const origin = request.headers.get('origin') + if (origin !== null && origin !== url) return Response.json({ message: 'The GitHub emulator answers no request from another origin.' }, { status: 403 }) const response = await app.fetch(request) requests.push({ method: request.method, path: new URL(request.url).pathname, status: response.status, actor: actorOf(request) }) return response @@ -136,6 +139,8 @@ export async function startGithubEmulator({ repositories, people = {}, supplemen const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}` const users = [ADMIN, ...Object.keys(people)] + // Random on every run, the admin's included, so nothing outside the run can act as a seeded person. + const personalTokens = new Map(users.map(login => [login, `ghp_${randomBytes(20).toString('hex')}`])) const prepared = await prepareSeed({ users: users.map(login => ({ login })), orgs: owners.filter(owner => !(owner in people)).map(login => ({ login, members: [{ login: ADMIN, role: 'admin' }] })), @@ -186,6 +191,14 @@ export async function startGithubEmulator({ repositories, people = {}, supplemen return token } + // A pull request's diff, which emulate computes on its compare route. The head branch moves when + // commits are pushed, and emulate keeps the head SHA the pull request was opened with. + async function changedFiles(repo: GitHubRepo, pull: GitHubPullRequest): Promise { + const pushed = pull.head_repo_id === repo.id && gh.branches.findBy('repo_id', repo.id).some(branch => branch.name === pull.head_ref) + const { files } = await request<{ files: ChangedFile[] }>(adminOf(repo.full_name), 'GET', `/repos/${repo.full_name}/compare/${pull.base_sha}...${pushed ? encodeURIComponent(pull.head_ref) : pull.head_sha}`) + return files + } + /** The admin of a repository or of its owner: the owner for a user's repository, the emulator's own admin for an organization's. */ const adminOf = (name: string) => { const owner = name.split('/')[0]! @@ -204,10 +217,7 @@ export async function startGithubEmulator({ repositories, people = {}, supplemen async function seed(): Promise { plugin.seed!(store, url) seedFromConfig(store, url, prepared.config as GitHubSeedConfig) - for (const login of users) { - personalTokens.set(login, `ghp_${login}`) - registerToken(`ghp_${login}`, login) - } + for (const [login, token] of personalTokens) registerToken(token, login) for (const [fullName, repository] of Object.entries(repositories)) { await applyRoles(fullName) for (const name of repository.labels ?? []) { diff --git a/packages/github-tools-eve-extension/testing/github/fixes.ts b/packages/github-tools-eve-extension/testing/github/fixes.ts index 7fa1eff..4f551c3 100644 --- a/packages/github-tools-eve-extension/testing/github/fixes.ts +++ b/packages/github-tools-eve-extension/testing/github/fixes.ts @@ -1,8 +1,17 @@ import type { AppEnv, Hono, Store } from '@emulators/core' +import type { GitHubPullRequest, GitHubRepo } from '@emulators/github' import { ApiError, getGitHubStore } from '../emulators.js' -import { briefUser, findRepo, replaceBody, requireRead, roleRank, type Ctx } from './access.js' +import { briefUser, findRepo, paginate, replaceBody, requireRead, roleRank, type Ctx } from './access.js' import { callAsCaller } from './supplement/context.js' +/** A file of a pull request, as emulate's compare route describes it. */ +export interface ChangedFile { + filename: string + status: string + additions: number + deletions: number +} + interface ReviewComment { path?: string body?: string @@ -15,9 +24,38 @@ interface ReviewComment { * Requests emulate 0.13.1 has a route for and answers differently from GitHub. Registered before * emulate's routes, each fix changes the request on its way in or the store on its way out. */ -export function registerRequestFixes(app: Hono, store: Store): void { +export function registerRequestFixes(app: Hono, store: Store, changedFiles: (repo: GitHubRepo, pull: GitHubPullRequest) => Promise): void { const gh = getGitHubStore(store) + function findPull(c: Ctx): { repo: GitHubRepo, pull: GitHubPullRequest } | undefined { + const repo = gh.repos.findOneBy('full_name', `${c.req.param('owner')}/${c.req.param('repo')}`) + const pull = repo && gh.pullRequests.findBy('repo_id', repo.id).find(candidate => candidate.number === Number(c.req.param('pull_number'))) + return repo && pull ? { repo, pull } : undefined + } + + // emulate lists a pull request's files as `file1.ts`, `file2.ts`, and so on, one for each of a + // counter that stays at 0, so the list is empty. This route is registered first and answers with the real diff. + app.get('/repos/:owner/:repo/pulls/:pull_number/files', async (c: Ctx) => { + const found = findPull(c) + if (!found) throw new ApiError(404, 'Not Found') + requireRead(c, gh, found.repo, 'pull_requests') + return c.json(paginate(c, await changedFiles(found.repo, found.pull))) + }) + + // The same counters are on the pull request itself, so they follow the diff before emulate reads them. + app.use('/repos/:owner/:repo/pulls/:pull_number', async (c: Ctx, next) => { + const found = c.req.method === 'GET' ? findPull(c) : undefined + if (found) { + const files = await changedFiles(found.repo, found.pull) + gh.pullRequests.update(found.pull.id, { + changed_files: files.length, + additions: files.reduce((total, file) => total + file.additions, 0), + deletions: files.reduce((total, file) => total + file.deletions, 0), + }) + } + await next() + }) + // GitHub reads a write with no body as an empty object. emulate answers 400, which breaks // `forkRepository` and `updatePullRequestBranch` when they send no option. app.use('*', async (c: Ctx, next) => { diff --git a/packages/github-tools-eve-extension/testing/github/role-guard.ts b/packages/github-tools-eve-extension/testing/github/role-guard.ts index 69915c9..e1ba3f8 100644 --- a/packages/github-tools-eve-extension/testing/github/role-guard.ts +++ b/packages/github-tools-eve-extension/testing/github/role-guard.ts @@ -37,7 +37,8 @@ const ownComment = ({ gh, repo, user, match }: RuleInput) => { // "Only users with push access can set labels for new issues. Labels are silently dropped otherwise", and the // same for assignees and the milestone, on creating and on updating an issue. Triage is the lowest role with that access. const TRIAGE_FIELDS = ['labels', 'assignees', 'milestone'] -const AUTHOR_PULL_FIELDS = new Set(['title', 'body', 'state', 'base', 'maintainer_can_modify']) +// `draft` is how the GraphQL handler changes a pull request's stage, which its author may do on GitHub. +const AUTHOR_PULL_FIELDS = new Set(['title', 'body', 'state', 'base', 'maintainer_can_modify', 'draft']) /** * The role a personal token needs on each write route. emulate 0.13.1 checks it for contents, From 19bdcc9653140cf8d3a6c5a5eb643a6acdf63536 Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Mon, 16 Nov 2026 09:12:19 +0000 Subject: [PATCH 3/3] docs: add the testing guide to the sidebar The docs sidebar is the list in docs-sidebar.ts, and only the paths in it are rendered. "Test an agent" was never added, so the page had no sidebar entry and no "Guides" breadcrumb. It was reachable from the guides table and the eve page only. Its file is renumbered from 8 to 9, since main now has 8.self-improving-agent.md. The page's URL comes from its frontmatter and doesn't change. --- apps/docs/app/utils/docs-sidebar.ts | 3 ++- .../docs/5.guides/{8.test-an-agent.md => 9.test-an-agent.md} | 0 2 files changed, 2 insertions(+), 1 deletion(-) rename apps/docs/content/docs/5.guides/{8.test-an-agent.md => 9.test-an-agent.md} (100%) diff --git a/apps/docs/app/utils/docs-sidebar.ts b/apps/docs/app/utils/docs-sidebar.ts index b6b4013..0353859 100644 --- a/apps/docs/app/utils/docs-sidebar.ts +++ b/apps/docs/app/utils/docs-sidebar.ts @@ -61,7 +61,8 @@ export const docsSidebar: DocsSidebarGroup[] = [ { path: '/guides/release-notes' }, { path: '/guides/chat-bot' }, { path: '/guides/multi-agent' }, - { path: '/guides/self-improving-agent' } + { path: '/guides/self-improving-agent' }, + { path: '/guides/test-an-agent' } ] }, { diff --git a/apps/docs/content/docs/5.guides/8.test-an-agent.md b/apps/docs/content/docs/5.guides/9.test-an-agent.md similarity index 100% rename from apps/docs/content/docs/5.guides/8.test-an-agent.md rename to apps/docs/content/docs/5.guides/9.test-an-agent.md