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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ github-agent-contracts gives Hermes, Claude Code, GitHub Copilot, OpenClaw, Curs

## Give agents their own identity in 3 steps

1. **Create your own GitHub App** from [docs/app-manifest.json](docs/app-manifest.json). Your user or organization owns the App and its key; install it on selected repositories only. Follow [ONBOARDING](docs/ONBOARDING.md) for registration and the two publisher environment variables.
1. **Create your own GitHub App** from [docs/app-manifest.json](docs/app-manifest.json). Your user or organization owns the App and its key; install it on selected repositories only. Follow [ONBOARDING](docs/ONBOARDING.md) for registration and the two publisher environment variables. Keep the manifest scoped to the repository and task: if project management or environment orchestration is required, review the optional `repository_projects`, `organization_projects`, `actions`, `deployments`, `environments`, and `variables` scopes before installation.
2. **Define repository permissions** in root `agent-policy.yml`. A human reviews and publishes the [default-deny example](examples/agent-policy.yml). Coder can commit feature branches, open draft PRs, comment, and label; merge and deploy remain denied by default. See [POLICY](docs/POLICY.md).
3. **Publish as the App bot** with `node scripts/agent-pr.mjs`. Copy the required files from the onboarding guide, review and stage the changes, pass tests and policy gates, then run the authorized publication command:

Expand Down
2 changes: 1 addition & 1 deletion docs/ONBOARDING.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Browser entry point: **[Register App from manifest](app-manifest.json)**. Use a

This link is a **static template, not a working registration service**. Replace its placeholder callback with an operator-controlled receiver before submitting it through [GitHub's manifest flow](https://docs.github.com/en/apps/sharing-github-apps/registering-a-github-app-from-a-manifest). Callback hosting is a follow-on, not part of this change. Until your receiver exists, use GitHub's manual App registration form with the same settings; do not submit secrets or a conversion code to this project's maintainer.

The manifest sets `public: false`, disables webhooks and user OAuth, and requests repository permissions **Metadata: read**, **Checks: read-only**, and **Contents, Issues, Pull requests: read-write**. Omit Issues write if you do not need comment or label outputs. It requests no Administration, Secrets, Workflows, Actions, or Deployments permissions. GitHub has **no manifest field to default repository selection**; selecting repositories during installation is a required human step, not something the JSON enforces. Existing App installations must have the Checks permission change accepted by a human before opt-in merge can use it.
The manifest sets `public: false`, disables webhooks and user OAuth, and requests repository permissions **Metadata: read**, **Checks: read-only**, **Contents: write**, **Issues: write**, **Pull requests: write**, **Repository projects: write**, **Actions: read**, **Deployments: read**, **Environments: read**, and **Variables: read**, plus the organization permission **Organization projects: write**. GitHub names the two project permissions `repository_projects` and `organization_projects`; `projects` is not a valid manifest or installation-token permission. Remove any scope you do not need and keep the App on a least-privilege path for the repository and task. Organization project access is installation-wide and is not narrowed by selecting repositories, so omit it unless the agent must manage organization projects. GitHub has **no manifest field to default repository selection**; selecting repositories during installation is a required human step, not something the JSON enforces. Existing App installations must have permission changes accepted by a human before the new access is available.

Do not install `r4yharris-agent-coder` on private or production repositories. A maintainer demo App is optional for public playgrounds only; see [the threat model](THREAT_MODEL.md).

Expand Down
2 changes: 1 addition & 1 deletion docs/ROLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The optional [merge-when-green flow](POLICY.md#opt-in-merge) requires coder `com

## Permissions by role

The manifest specifies Metadata read, Checks read-only, and Contents, Issues, Pull requests read-write. Issues write is optional for approved comment/label handlers. Normal publishing requests only contents and pull requests write; the opt-in merge flag also requests Checks read-only. A human must accept the permission change on existing installations. Keep repositories explicitly selected and retain required human reviews and merge controls. Staged or selected `.github/workflows/**` paths are refused before token minting and published by humans; the coder App needs no Workflows permission.
The manifest specifies Metadata read, Checks read-only, and the repository scopes used for branch publication and review: Contents write, Issues write, and Pull requests write. If a broader agent workflow needs project or environment orchestration, add `repository_projects: write`, `organization_projects: write`, `actions: read`, `deployments: read`, `environments: read`, and `variables: read` only after the owner reviews the use case; these are not implicit requirements for every installation. Repository and organization projects are separate GitHub App permissions, and organization project access is not narrowed by the installation's selected repositories. Normal publishing requests only its core permissions; an approved orchestration token may request the reviewed subset, while the opt-in merge flag also requests Checks read-only. A human must accept permission changes on existing installations. Keep repositories explicitly selected and retain required human reviews and merge controls. Staged or selected `.github/workflows/**` paths are refused before token minting and published by humans; the coder App needs no Workflows permission.

GitHub does not expose a separate draft-only or merge-only version of pull requests write. A coder token may technically call broader endpoints than the helper permits. Do not put the coder App on branch-rule bypass lists; restrict protected-branch updates and merges to authorized humans. Separate Apps reduce shared-key exposure but do not replace these controls.

Expand Down
8 changes: 7 additions & 1 deletion docs/app-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,16 @@
"request_oauth_on_install": false,
"default_permissions": {
"metadata": "read",
"actions": "read",
"checks": "read",
"contents": "write",
"deployments": "read",
"environments": "read",
"issues": "write",
"pull_requests": "write"
"organization_projects": "write",
"pull_requests": "write",
"repository_projects": "write",
"variables": "read"
},
"default_events": []
}
4 changes: 3 additions & 1 deletion docs/github-app-agent-identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Git author/committer fields that copy a human hide provenance. GitHub Apps creat

Start with [ONBOARDING.md](ONBOARDING.md) and [app-manifest.json](app-manifest.json), using a unique account-specific name ending in `-agent-coder`. Register under the user or organization that owns the repositories. The template is private (`public: false`, Only on this account), with webhooks inactive, no events, and no user OAuth.

The manifest requests repository permissions Metadata read, Checks read-only, and Contents, Issues, and Pull requests read-write for feature-branch publication, optional merge checks, and approved outputs. Omit Issues write when unused. It grants no Administration, Secrets, Workflows, Actions, or Deployments permissions. A human must accept the Checks permission change for an existing installation before using opt-in merge. Keep read-only agent/MCP tokens separate from publication credentials.
The manifest requests repository permissions Metadata read, Checks read-only, Contents write, Issues write, and Pull requests write for feature-branch publication, optional merge checks, and approved outputs. For broader project and environment orchestration, it also includes Repository projects write, Organization projects write, Actions read, Deployments read, Environments read, and Variables read. The project permission keys are `repository_projects` and `organization_projects`, not `projects`. Keep each scope aligned to the exact task and remove unused permissions before installation; in particular, organization project access is installation-wide rather than limited by selected repositories. A human must accept permission changes for an existing installation before using them. Keep read-only agent/MCP tokens separate from publication credentials.

Choose **Only select repositories** at installation. GitHub does not support a manifest field for that selection. Start with one repository and separate unrelated trust boundaries.

Expand Down Expand Up @@ -50,6 +50,8 @@ An approved publisher or credential service signs a short-lived App JWT, discove

Installation tokens normally expire after one hour. Request a fresh token when needed, and revoke it when a session is finished if it is no longer needed. Do not reuse the App JWT as a repository token.

Request only the permissions needed for the operation. The publisher keeps its core publication token narrow. An approved orchestration broker can use `mintInstallationToken` with `additionalPermissions` limited to Actions read, Deployments read, Environments read, Variables read, Issues read/write, and repository or organization Projects read/write. The helper rejects unknown permission names, access above those limits, and the invalid generic `projects` key.

Inject the installation token through the environment of the local MCP server or an approved credential helper. The official local MCP server calls its token variable `GITHUB_PERSONAL_ACCESS_TOKEN`; in this pack its value must still be an **installation token**, not a PAT. Never echo it, store it in a remote URL, or persist it in config or a tracked file.

The caller must enforce the approved owner and repository on every tool call. An installation token does not turn a broad tool allowlist into a safe one.
Expand Down
37 changes: 34 additions & 3 deletions scripts/agent-pr.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,40 @@ async function githubRequest(path, token, { method = "GET", body, fetchImpl = gl
}
}

const OPTIONAL_ORCHESTRATION_PERMISSIONS = new Map([
["actions", new Set(["read"])],
["deployments", new Set(["read"])],
["environments", new Set(["read"])],
["issues", new Set(["read", "write"])],
["organization_projects", new Set(["read", "write"])],
["repository_projects", new Set(["read", "write"])],
["variables", new Set(["read"])],
]);

export function buildInstallationPermissions({ readChecks = false, additionalPermissions = {} } = {}) {
if (
additionalPermissions === null ||
typeof additionalPermissions !== "object" ||
Array.isArray(additionalPermissions)
) {
throw new AgentPrError("Additional installation permissions must be an object.");
}
for (const [permission, access] of Object.entries(additionalPermissions)) {
if (!OPTIONAL_ORCHESTRATION_PERMISSIONS.get(permission)?.has(access)) {
throw new AgentPrError(`Unsupported additional installation permission: ${permission}.`);
}
}
const permissions = {
contents: "write",
pull_requests: "write",
...additionalPermissions,
};
if (readChecks) permissions.checks = "read";
return permissions;
}

export async function mintInstallationToken(
{ appId, privateKey, owner, repository, readChecks = false },
{ appId, privateKey, owner, repository, readChecks = false, additionalPermissions = {} },
{ fetchImpl = globalThis.fetch, now = Date.now() } = {},
) {
const jwt = createAppJwt(appId, privateKey, now);
Expand All @@ -81,8 +113,7 @@ export async function mintInstallationToken(
) {
throw new AgentPrError("The repository needs an active installation matching GITHUB_APP_ID.");
}
const permissions = { contents: "write", pull_requests: "write" };
if (readChecks) permissions.checks = "read";
const permissions = buildInstallationPermissions({ readChecks, additionalPermissions });
const access = await githubRequest(`/app/installations/${installation.id}/access_tokens`, jwt, {
method: "POST",
body: { repositories: [repository], permissions },
Expand Down
74 changes: 70 additions & 4 deletions tests/agent-pr.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import {
buildCommitMessage, createAppJwt, main,
buildCommitMessage, buildInstallationPermissions, createAppJwt, main,
mintInstallationToken, parseArgs, parseOrigin, publishAgentPr as publishAgentPrRaw, upsertAgentRun,
} from "../scripts/agent-pr.mjs";
import { AgentPolicyError, loadAgentPolicy, parseAgentPolicy } from "../scripts/load-agent-policy.mjs";
Expand Down Expand Up @@ -78,6 +78,58 @@ test("installation token is scoped to the origin repository and required write p
assert.ok(github.calls[0].headers.Authorization.startsWith("Bearer "));
});

test("GitHub App installation tokens can opt into orchestration scopes while keeping core publication permissions", async () => {
const github = mockGitHub([installation, access]);
const token = await mintInstallationToken({
...credentials,
additionalPermissions: {
actions: "read",
deployments: "read",
environments: "read",
issues: "write",
organization_projects: "write",
repository_projects: "write",
variables: "read",
},
}, github);
assert.deepEqual(token, { token: access.token, appSlug: AGENT });
assert.deepEqual(JSON.parse(github.calls[1].body), {
repositories: ["example-repo"],
permissions: {
contents: "write",
issues: "write",
pull_requests: "write",
actions: "read",
deployments: "read",
environments: "read",
issues: "write",
organization_projects: "write",
repository_projects: "write",
variables: "read",
},
});
});

test("additional installation permissions reject invalid names and excessive access", () => {
for (const additionalPermissions of [
{ projects: "write" },
{ actions: "write" },
{ deployments: "write" },
{ environments: "write" },
{ variables: "write" },
{ administration: "write" },
]) {
assert.throws(
() => buildInstallationPermissions({ additionalPermissions }),
/Unsupported additional installation permission/,
);
}
assert.throws(
() => buildInstallationPermissions({ additionalPermissions: null }),
/must be an object/,
);
});

test("a different or suspended App installation is rejected before minting a token", async () => {
for (const invalid of [
{ ...installation, app_slug: "invalid slug" },
Expand Down Expand Up @@ -462,7 +514,11 @@ test("--merge-when-green merges a ready or draft PR by exact SHA and only then d
assert.equal(merge.method, "PUT");
assert.deepEqual(JSON.parse(merge.body), { sha: commitSha, merge_method: "merge", commit_message: buildCommitMessage("feat: helper", "test-model", AGENT) });
const tokenRequest = mock.requests.find((call) => call.url.endsWith("/access_tokens"));
assert.deepEqual(JSON.parse(tokenRequest.body).permissions, { contents: "write", pull_requests: "write", checks: "read" });
assert.deepEqual(JSON.parse(tokenRequest.body).permissions, {
contents: "write",
pull_requests: "write",
checks: "read",
});
const deletion = mock.requests.find((call) => call.url.includes("/git/refs/heads/"));
assert.equal(deletion.method, "DELETE");
assert.ok(deletion.url.endsWith("/git/refs/heads/feat%2Fbot-helper"));
Expand Down Expand Up @@ -787,14 +843,24 @@ test("an invalid or human account cannot stand in for the configured App bot", a
}
});

test("the onboarding manifest is owner-only with explicit minimal permissions and placeholder callbacks", () => {
test("the onboarding manifest is owner-only with explicit scoped permissions and placeholder callbacks", () => {
const manifest = JSON.parse(readFileSync(new URL("../docs/app-manifest.json", import.meta.url), "utf8"));
assert.equal(manifest.name, "YOUR-ACCOUNT-agent-coder");
assert.equal(manifest.url, "https://github.com/R4yHarris/github-agent-contracts");
assert.equal(manifest.public, false);
assert.equal(manifest.request_oauth_on_install, false);
assert.deepEqual(manifest.default_permissions, {
metadata: "read", contents: "write", issues: "write", pull_requests: "write", checks: "read",
metadata: "read",
actions: "read",
checks: "read",
contents: "write",
deployments: "read",
environments: "read",
issues: "write",
organization_projects: "write",
pull_requests: "write",
repository_projects: "write",
variables: "read",
});
assert.deepEqual(manifest.default_events, []);
assert.equal(manifest.hook_attributes.active, false);
Expand Down
Loading