From 0753cbda692c582ddf8780a638c711ccadd24ec0 Mon Sep 17 00:00:00 2001 From: r4yharris Date: Sun, 27 Sep 2026 21:06:21 -0400 Subject: [PATCH] feat: add agent capability policy Bootstrap root agent-policy.yml (human-only path). --- .github/copilot-instructions.md | 6 ++ AGENTS.md | 16 ++++ README.md | 9 +- agent-policy.yml | 9 ++ docs/HARNESSES.md | 14 ++- docs/ONBOARDING.md | 7 +- docs/POLICY.md | 97 ++++++++++++++++++++ docs/ROLES.md | 37 ++++++++ examples/agent-policy.yml | 9 ++ scripts/agent-pr.mjs | 60 ++++++++++++- scripts/load-agent-policy.mjs | 142 ++++++++++++++++++++++++++++++ skills/agent-policy/SKILL.md | 38 ++++++++ skills/signed-bot-commit/SKILL.md | 10 ++- tests/agent-pr.test.mjs | 141 ++++++++++++++++++++++++++++- tests/load-agent-policy.test.mjs | 104 ++++++++++++++++++++++ 15 files changed, 686 insertions(+), 13 deletions(-) create mode 100644 agent-policy.yml create mode 100644 docs/POLICY.md create mode 100644 docs/ROLES.md create mode 100644 examples/agent-policy.yml create mode 100644 scripts/load-agent-policy.mjs create mode 100644 skills/agent-policy/SKILL.md create mode 100644 tests/load-agent-policy.test.mjs diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 2133f52..554673a 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -6,6 +6,10 @@ This workspace is **github-agent-contracts** only. - Edit no paths outside this repository. - Do not request or embed credentials. - Prefer Node 20 ESM scripts with zero dependencies. +- Load root `agent-policy.yml` through `scripts/load-agent-policy.mjs` and follow `skills/agent-policy/SKILL.md` before publication or GitHub writes. Missing or invalid policy denies all actions; never fall back to the example or a different role. +- Agents must not edit, create, replace, or delete `agent-policy.yml` to grant themselves rights, or modify the executor to bypass a denial. A human reviews and publishes active policy changes. +- App permissions, branch protection/environments, and policy are cumulative gates. The coder publisher requires `commit_branch` and `open_pr`, checks the reviewed default-branch policy, and has no merge/protected-push/deploy or role-override mode. Humans merge; no deploys. +- Follow `docs/ROLES.md`: use separate role Apps, and keep only the coder key on the WSL orchestration host. Never use merger/deploy credentials or a human token there. - Agents must commit and publish through `node scripts/agent-pr.mjs`, never raw `git commit`, `git push`, or a separate `gh pr create`. Never commit as R4yHarris or use a human token as a fallback. - Follow `skills/signed-bot-commit/SKILL.md`. App environment variables never authorize use of the signed-in human's identity, and missing App configuration means stop. Never merge or enable auto-merge. - Invoke the helper only after authorization for commit, push, and a draft PR. A request to stop after writing files and testing means no publication. Humans may perform their own bootstrap commits. @@ -18,5 +22,7 @@ This workspace is **github-agent-contracts** only. Authorized publication example: ```bash +node scripts/load-agent-policy.mjs --role coder --capability commit_branch +node scripts/load-agent-policy.mjs --role coder --capability open_pr node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model unknown --files README.md ``` diff --git a/AGENTS.md b/AGENTS.md index 81a3f06..c34e80a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,6 +23,19 @@ Reusable conventions and small tools so Copilot, GitHub Agentic Workflows (`gh-a - Do not grant agents `admin`, `delete`, or unscoped `repo` power in examples. - Default writes on GitHub are **safe outputs only**: comments, labels, draft PRs — never force-push, never merge without a human. +## Capability policy + +- Follow `skills/agent-policy/SKILL.md` and load root `agent-policy.yml` with `scripts/load-agent-policy.mjs` before publication or any GitHub write, including safe outputs. Missing or invalid policy denies every capability; never fall back to the example. +- App permissions, branch protection/environments, and the policy allow-list must all permit an action. A task prompt, available tool, App environment variable, or broader token does not override a denial. +- Agents must not create, edit, replace, or delete root `agent-policy.yml` to grant themselves rights. Humans review and publish policy changes. Do not bypass policy by changing the loader, publisher, or harness configuration. +- The publisher is fixed to coder and requires `commit_branch` plus `open_pr`, matching the reviewed default-branch policy. There is no role or policy-path override. Merge, protected pushes, and deploys are unsupported by the coder publisher; humans merge and deployments remain disabled. +- Use separate user/org-owned role Apps. The WSL orchestration host holds only the coder key, never merger/deploy keys or human fallback credentials. Follow `docs/POLICY.md` and `docs/ROLES.md`. + +```bash +node scripts/load-agent-policy.mjs --role coder --capability commit_branch +node scripts/load-agent-policy.mjs --role coder --capability open_pr +``` + ## Agent publication - Follow `skills/signed-bot-commit/SKILL.md` for all publishing. The security control is the required PR check plus protected branch, bot author, and trailers; an App installation supplies authentication, not a merge exemption. @@ -56,6 +69,9 @@ node scripts/check-agent-trailers.mjs --message-file path/to/msg.txt # Publication help only; this does not read a key or contact GitHub node scripts/agent-pr.mjs --help +# Policy help only; no policy or credentials are read +node scripts/load-agent-policy.mjs --help + # Tests node --test tests/*.test.mjs ``` diff --git a/README.md b/README.md index a27101b..661a2e5 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ This is community OSS for GitHub, not a GitHub replacement. ## Enable agent identity in 3 steps 1. **[Register App from manifest](docs/app-manifest.json).** Create an App owned by you or your organization, keep it private to that account, and choose **Only select repositories** during installation. -2. **Configure and copy.** Supply `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` outside git, then copy AGENTS.md, the signed-bot-commit skill, publisher, and check Action/workflow as listed in [ONBOARDING.md](docs/ONBOARDING.md). CI stores the key in the `GITHUB_APP_PRIVATE_KEY` secret. +2. **Configure and copy.** Supply `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` outside git, then copy AGENTS.md, the policy and commit skills, publisher/loader, and check Action/workflow as listed in [ONBOARDING.md](docs/ONBOARDING.md). A human installs the root capability policy. CI stores the key in the `GITHUB_APP_PRIVATE_KEY` secret. 3. **Protect and publish.** Require `check-agent-trailers`, disallow direct pushes to `main` and agent bypass, and reserve merges for humans. Tell the agent: "Use signed-bot-commit / scripts/agent-pr.mjs for all publish." The manifest is a static template, not a hosted registration button. An owner-controlled manifest callback is a follow-on; placeholder URLs must be replaced before completing GitHub's flow. The [onboarding guide](docs/ONBOARDING.md) describes that boundary and the manual registration fallback. @@ -27,6 +27,7 @@ Use it so Copilot, [GitHub Agentic Workflows](https://github.com/github/gh-aw), | Contract | Where | | --- | --- | | Agent instructions | `AGENTS.md` | +| Default-deny capabilities | `examples/agent-policy.yml` + `docs/POLICY.md` | | Copilot instructions | `.github/copilot-instructions.md` | | Portable skills | `skills/*/SKILL.md` | | Bot identity | `docs/github-app-agent-identity.md` | @@ -53,6 +54,12 @@ See [HARNESSES.md](docs/HARNESSES.md) for the minimal integration in each runtim Follow the [adoption guide](docs/adopt.md) and copy the [consumer workflow](examples/consumer-repo/.github/workflows/check-agent-trailers.yml). Reference the pinned public Action without copying scripts, or vendor the Action and both scripts together. No package registry or GitHub App credentials are needed for the trailer check. +## Capability policy + +Hermes, Copilot, Claude Code, and Cursor share one human-owned root `agent-policy.yml`. The [example](examples/agent-policy.yml) allows coder branch commits, draft PRs, comments, and labels; merger and deploy allow-lists are empty. Missing policy denies publication, and agents must not edit policy to grant themselves rights. + +Read [POLICY.md](docs/POLICY.md) for the three permission layers and human bootstrap, and [ROLES.md](docs/ROLES.md) for separate role Apps and a WSL host holding only the coder key. The coder publisher has no merge, protected-push, or deployment mode. No active root policy or hosted control plane is installed by this pack. + ## Non-goals - No self-hosted forge diff --git a/agent-policy.yml b/agent-policy.yml new file mode 100644 index 0000000..5066032 --- /dev/null +++ b/agent-policy.yml @@ -0,0 +1,9 @@ +version: 1 +default: deny +roles: + coder: + allow: [commit_branch, open_pr, comment, label] + merger: + allow: [] + deploy: + allow: [] \ No newline at end of file diff --git a/docs/HARNESSES.md b/docs/HARNESSES.md index d652bf0..fca5c2b 100644 --- a/docs/HARNESSES.md +++ b/docs/HARNESSES.md @@ -1,9 +1,11 @@ # Harnesses -The common contract is [AGENTS.md](../AGENTS.md), which requires [signed-bot-commit](../skills/signed-bot-commit/SKILL.md) and [scripts/agent-pr.mjs](../scripts/agent-pr.mjs) for authorized publication. Use the consuming user's or organization's App from [ONBOARDING.md](ONBOARDING.md), never a shared maintainer App for private repositories. +The common contract is [AGENTS.md](../AGENTS.md), which requires [agent-policy](../skills/agent-policy/SKILL.md) first, then [signed-bot-commit](../skills/signed-bot-commit/SKILL.md) and [scripts/agent-pr.mjs](../scripts/agent-pr.mjs) for authorized publication. Use the consuming user's or organization's App from [ONBOARDING.md](ONBOARDING.md), never a shared maintainer App for private repositories. Harness setup does not replace the required `check-agent-trailers` check, branch protection, bot authorship, or trailers. No harness may publish as the signed-in human, print credentials, or merge an agent PR. App environment variables do not themselves authorize publication. +Every harness reads the same human-owned root `agent-policy.yml` through [the loader](../scripts/load-agent-policy.mjs), not a harness-specific allow-list or cached fallback. Missing policy denies writes. No harness may edit policy to grant itself rights, change its assigned role, or deploy by default. [POLICY.md](POLICY.md) defines the shared capabilities; [ROLES.md](ROLES.md) defines operator-controlled role and key boundaries. + ## Copilot Use **AGENTS.md + .github/copilot-instructions.md only** as the Copilot configuration. The Copilot file points to the common repository rules, and those rules point to the commit skill and publisher. No custom agent mode, extra prompt file, or MCP server is required for publishing. @@ -16,12 +18,18 @@ Keep [CLAUDE.md](../CLAUDE.md) as a short pointer to AGENTS.md. Claude Code read ## Hermes -Load AGENTS.md as repository instructions and [skills/signed-bot-commit/SKILL.md](../skills/signed-bot-commit/SKILL.md) as the publication skill using the installed runtime's supported mechanism. For GitHub issue, PR, or code reads, also follow the [GitHub MCP allowlist skill](../skills/github-mcp-allowlist/SKILL.md). +Load AGENTS.md as repository instructions, the agent-policy skill before writes, and [skills/signed-bot-commit/SKILL.md](../skills/signed-bot-commit/SKILL.md) for publication using the installed runtime's supported mechanism. For GitHub issue, PR, or code reads, also follow the [GitHub MCP allowlist skill](../skills/github-mcp-allowlist/SKILL.md). Safe-output handlers must enforce the shared policy in addition to their tool allowlists. Use repository-scoped installation tokens supplied by a trusted launcher; never store tokens in repository MCP configuration. Keep default agent tools read-only and write-capable credentials in the approved publication context. No Hermes runtime changes are needed. +## Cursor + +Load AGENTS.md as the project's instructions. If the installed version needs a project-rule pointer, point it at AGENTS.md rather than duplicating capability grants. Read the shared policy through the same loader and use the same coder publisher; enabling a Cursor tool or changing an agent mode does not override a policy denial. + +Keep root policy changes human-owned. No Cursor-specific credential, role override, merge tool, or deploy capability is granted by this integration. + ## Generic agents -If you honor **AGENTS.md**, you honor **signed-bot-commit**. Read the referenced skill and invoke the same helper after explicit authorization, regardless of whether your runtime has a native skill loader. +If you honor **AGENTS.md**, you honor **agent-policy** and **signed-bot-commit**. Read the referenced skills and invoke the same helper after policy checks and explicit authorization, regardless of whether your runtime has a native skill loader. When the necessary instructions, App environment, or publishing tools are unavailable, stop and report the missing prerequisite. Do not fall back to raw Git, human credentials, or automatic merging. Humans review and merge. \ No newline at end of file diff --git a/docs/ONBOARDING.md b/docs/ONBOARDING.md index 92e7ae2..28caafe 100644 --- a/docs/ONBOARDING.md +++ b/docs/ONBOARDING.md @@ -29,16 +29,21 @@ Copy these files into the consuming repository, preserving paths and merging exi ```text AGENTS.md +skills/agent-policy/SKILL.md skills/signed-bot-commit/SKILL.md scripts/agent-pr.mjs +scripts/load-agent-policy.mjs scripts/check-agent-trailers.mjs scripts/check-pr-agent-trailers.mjs +examples/agent-policy.yml .github/actions/check-agent-trailers/action.yml .github/workflows/check-agent-trailers.yml ``` Use Node 20+, Git, and `gh` for publication. Adapt the workspace name and test command in the copied rules. Follow [HARNESSES.md](HARNESSES.md) for the small harness-specific pointers, and [adopt.md](adopt.md) for the pinned public-Action alternative and vendoring details. No private-package infrastructure or runtime dependency installation is needed. +A human must review [the policy example](../examples/agent-policy.yml), install it as root `agent-policy.yml`, and publish it on the default branch through the existing human review process. Include that reviewed version in the feature branch too. Keep merger and deploy allow-lists empty. The publisher requires coder `commit_branch` and `open_pr`, checks the default-branch policy, and refuses root-policy edits; there is no example fallback. See [POLICY.md](POLICY.md) and [ROLES.md](ROLES.md). Copy their guidance with the skills when adopting the pack. + For the local Action, land the Action and both checker scripts on the target branch before enabling the workflow, because it executes the base revision's trusted checker. A human bootstraps workflow changes: the App intentionally has no workflows-write permission. Keep human review on changes to the workflow, instructions, and publisher. ## 3. Protect the branch and publish @@ -51,7 +56,7 @@ After a successful trial PR run, configure branch protection or a ruleset for `m Tell the agent: -> Use signed-bot-commit / scripts/agent-pr.mjs for all publish. Never publish as the signed-in human, print tokens, or merge. Stop if App authentication is unavailable. +> Load agent-policy first, then use signed-bot-commit / scripts/agent-pr.mjs for all publish. Never grant yourself policy rights, publish as the signed-in human, print tokens, merge, or deploy. Stop if policy or App authentication is unavailable. Authorize a specific feature-branch publication, then let the agent use the helper. Check the bot author/committer and trailers on the resulting commits. The helper creates a draft PR or reuses an existing open PR. **Humans review and merge.** Local commits do not independently authorize a push. diff --git a/docs/POLICY.md b/docs/POLICY.md new file mode 100644 index 0000000..416d671 --- /dev/null +++ b/docs/POLICY.md @@ -0,0 +1,97 @@ +# Agent capability policy + +One human-owned root `agent-policy.yml` is the capability allow-list for Hermes, Copilot, Claude Code, Cursor, and other agents. **Default deny, human-only merge, and no deploys remain the defaults.** The file is not a credential or permission to bypass GitHub protections. + +This pack ships an [example](../examples/agent-policy.yml), a [local parser and checker](../scripts/load-agent-policy.mjs), and an [agent-policy skill](../skills/agent-policy/SKILL.md). It does not install an active root policy automatically or provide a hosted control plane. Missing or invalid policy authorizes no capabilities; the loader never falls back to the example. + +## Three layers + +All three layers must permit an operation, along with the human's task authorization: + +| Layer | Responsibility | +| --- | --- | +| GitHub App permissions | Bound the API operations and selected repositories accessible to a role's installation token. A broad App permission does not grant an equivalent policy capability. | +| Branch protection and environments | Require the trailer check, human reviews, protected-branch restrictions, and protected-environment approval. Give agents no bypass; keep deploy credentials behind environment gates. | +| Repository policy | Allow only the explicitly listed capabilities for the trusted role. Omitted roles, empty lists, and unlisted actions deny access. | + +A policy grant is necessary, not sufficient: it cannot widen a token, remove a required check, authorize a different repository, or disable a stricter script or human-review rule. The existing attribution control remains required PR check + protected branch + bot author + trailers. See [THREAT_MODEL.md](THREAT_MODEL.md). + +## Capabilities and defaults + +```yaml +version: 1 +default: deny +roles: + coder: + allow: [commit_branch, open_pr, comment, label] + merger: + allow: [] + deploy: + allow: [] +``` + +| Capability | Meaning | Default | +| --- | --- | --- | +| `commit_branch` | Commit and push an authorized, unprotected feature branch | Coder only | +| `open_pr` | Open a draft PR or update its branch through the publisher | Coder only | +| `comment` | Request an approved comment output | Coder only | +| `label` | Request approved label changes | Coder only | +| `merge` | Merge a PR or enable automatic merging | Denied | +| `push_protected` | Directly update a protected branch | Denied | +| `deploy` | Start a deployment or use deployment credentials | Denied | + +Roles do not inherit or combine each other's lists. Capability names are exact and case-sensitive. These are publication and GitHub-write capabilities, not general permission to read arbitrary files or expand a local editing task. + +`comment` and `label` do not enable raw MCP write tools. An approved output handler must check the same policy for its assigned role and repository before acting, in addition to its own tool allowlist and token scope. Existing gh-aw safe-output declarations are a separate gate; gh-aw does not automatically read this file. Keep unattended output handlers disabled until the trusted executor performs this check. Human-reviewed outputs remain the fallback, not an unrestricted agent write tool. + +## Human bootstrap + +1. A human reviews the example and chooses grants for the consuming repository. Agents must not create, edit, replace, or delete the active root policy to grant themselves rights. +2. The human installs the chosen file as root `agent-policy.yml` and publishes it through the repository's existing human review process. Land it on the default branch and include that reviewed version in the feature branch before using the publisher. Do not bypass branch rules for bootstrap. +3. Copy the loader beside the publisher, keep the policy skill with the other shared skills, and require human review of policy, instruction, and executor changes. Restrict who can approve these changes using the repository's review controls. +4. Run the read-only checks below. Role assignment and credential release belong to a trusted launcher or operator, not the agent's prompt or choice of CLI arguments. + +No active root policy is added by this change. Until a human installs one, publication is deliberately blocked. Other required App environment settings remain unchanged. + +## Read-only checks + +From the consuming repository root: + +```bash +node scripts/load-agent-policy.mjs +node scripts/load-agent-policy.mjs --role coder --capability commit_branch +node scripts/load-agent-policy.mjs --role coder --capability open_pr +node scripts/load-agent-policy.mjs --role merger --capability merge +``` + +The last command exits `1` with the example policy because `merger.allow` is empty. Exit `0` means valid policy or a listed capability; `1` means denied, unreadable, or invalid policy; `2` means invalid CLI usage. `--help` does not read the policy. The CLI never performs a GitHub operation and `--role` does not assign that role to the caller. + +Other trusted Node executors can import `loadAgentPolicy` and `requireCapability` from [the loader](../scripts/load-agent-policy.mjs). Load the human-controlled policy for the target repository, then require each capability before releasing credentials or taking that action. An executor must not accept a role or alternative policy from untrusted task content. + +## Supported format + +Version 1 deliberately supports a small YAML subset with zero runtime dependencies: + +- Required root fields: `version: 1` and `default: deny`. The optional `roles` mapping recognizes only `coder`, `merger`, and `deploy`; missing entries deny all actions for that role. +- Each role may contain only `allow`. Lists use the inline form above or a block list indented six spaces beneath `allow:`. An omitted or empty list denies all capabilities. Empty mappings `roles: {}` and `coder: {}` are accepted. +- Use plain, unquoted capability names, two-space mapping indentation, and four spaces before `allow`. Blank lines, CRLF, and full-line or whitespace-separated `#` comments are supported. +- Unknown fields, roles, or capabilities; duplicate fields or list entries; wildcards; tabs; anchors; aliases; tags; quoted values; YAML document markers; and unsupported syntax are errors. `default: allow` is never accepted. +- The root file must be a regular file, not a symlink, and at most 64 KiB. There are no includes, environment substitutions, policy-path overrides, or credential fields. + +Unsupported YAML is rejected rather than interpreted permissively. Use the supplied example instead of assuming compatibility with an arbitrary YAML emitter. + +## Publisher enforcement + +[agent-pr.mjs](../scripts/agent-pr.mjs) is fixed to the **coder** role. It requires both `commit_branch` and `open_pr` before key access or Git commands, even when an existing PR might be reused. It has no `--role` or `--policy` override. + +After App authentication, it reads root policy from origin's default branch and requires its grants to match the local policy. It refuses staged or specified root-policy changes, checks the new commit for policy edits, and verifies the policy in the committed tree before pushing. A feature-branch or working-copy self-grant cannot replace the default branch's policy. API or validation failures stop publication, with no human-token fallback. + +The helper checks both branch protection and active rules before committing and again before pushing. Any applicable rule is treated conservatively as protection. Failure to determine protection state denies publication, even if it is only an availability or permission problem. + +The coder helper has **no merge, protected-push, or deployment implementation**. `--merge`, `--push-protected`, and `--deploy` are rejected; adding those capabilities to a policy does not turn them on. A protected push first requires `push_protected`, then remains unsupported by this helper even with a grant. There is no merger or deploy script shipped in this change. Keep their allow-lists empty and let humans merge. + +Any future privileged executor would require a separately authorized implementation, a separately controlled role App, an explicit human-reviewed grant, and the branch or environment gates. It must not reuse the coder key or reinterpret a successful read-only policy check as authorization to execute. See [ROLES.md](ROLES.md). + +## Limits + +This is not a sandbox against a malicious human, compromised runner, or an agent that can replace its own trusted executor. Protect the default branch, loader, publisher, harness launch configuration, and credential storage. The policy checker does not create GitHub branch rules, scan all history for secrets, or independently prevent API calls made outside an approved executor. App permissions and GitHub protection rules remain necessary enforcement boundaries. \ No newline at end of file diff --git a/docs/ROLES.md b/docs/ROLES.md new file mode 100644 index 0000000..dbd6597 --- /dev/null +++ b/docs/ROLES.md @@ -0,0 +1,37 @@ +# Agent roles and key custody + +Use separate, user/org-owned GitHub Apps for **coder**, **merger**, and **deploy** trust boundaries. A role is assigned by an operator-controlled launcher and credential boundary, not by an agent choosing a name in a prompt. The [policy](POLICY.md) alone is not an App-to-role identity registry. + +| Role | Intended authority | Default state | +| --- | --- | --- | +| Coder | Commit unprotected feature branches, open draft PRs, request comments and labels | Only the four explicit grants in the example policy | +| Merger | A possible future, separately reviewed merge executor | Empty allow-list; humans merge | +| Deploy | A possible future executor behind approved environment gates | Empty allow-list; no deployments | + +Only the coder publisher exists in this pack. Do not provision or distribute merger/deploy keys merely because role names appear in the example. An eventual human-authorized extension must use a separate App, executor, permissions review, and explicit policy grants without bypassing branch or environment protections. + +## Permissions by role + +The coder App needs metadata read, contents write for authorized feature branches, and pull requests write for draft PRs. Issues write is optional for approved comment/label handlers; the publisher's installation token only requests contents and pull requests write. Keep repositories explicitly selected and retain human review and merge controls. + +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. + +Merger and deploy Apps, if ever approved, must have only the permissions their independently reviewed executor requires. Keep deployment credentials behind protected environments with human approval and approved branch restrictions. Do not add administration, secret-management, workflow-editing, or organization-member permissions to the coder App to work around a failed operation. + +## WSL orchestration host + +The WSL orchestration box holds **only the coder App key**, stored outside the checkout and supplied to an approved publishing process. It must not hold a merger key, deploy key, production cloud credential, or a human token used as a fallback. Do not mount or forward those credentials into WSL from another host, a secret store, or an agent's environment. + +The trusted launcher fixes the publisher to the coder App and coder role. Do not let an agent change the key path or select a more privileged App. Prefer separate execution identities and an isolated publication context over giving every harness process the key. A process that can read a key can mint tokens within that App's installations; a role label cannot prevent that. + +Future merger/deploy execution belongs in separately controlled environments, with separate credentials released only after the applicable human and GitHub gates. No WSL orchestration service or hosted control plane is added here. + +## Human-owned policy + +All harnesses read the same root `agent-policy.yml` through the [policy loader](../scripts/load-agent-policy.mjs). The default `merger.allow` and `deploy.allow` lists remain empty. Unknown roles and missing grants deny access, and coder grants do not carry over to other roles. + +Only humans review and publish active policy changes. Agents must not edit that file to grant themselves rights, switch to a different copy, or modify the loader to bypass a denial. Use [POLICY.md](POLICY.md) for bootstrap and [HARNESSES.md](HARNESSES.md) for shared harness instructions. + +## Incident response + +Revoke the affected App key and active tokens, inspect its installations and published changes, and rotate through an authorized operator. The private-key holder can mint tokens for all installations of that App; storing three role keys together defeats the separation. Never paste PEM or token contents into logs, issues, chat, policy files, or this repository. \ No newline at end of file diff --git a/examples/agent-policy.yml b/examples/agent-policy.yml new file mode 100644 index 0000000..5066032 --- /dev/null +++ b/examples/agent-policy.yml @@ -0,0 +1,9 @@ +version: 1 +default: deny +roles: + coder: + allow: [commit_branch, open_pr, comment, label] + merger: + allow: [] + deploy: + allow: [] \ No newline at end of file diff --git a/scripts/agent-pr.mjs b/scripts/agent-pr.mjs index 14e1ee9..346b409 100644 --- a/scripts/agent-pr.mjs +++ b/scripts/agent-pr.mjs @@ -6,6 +6,7 @@ import { lstatSync, readFileSync } from "node:fs"; import { isAbsolute, relative, resolve, sep } from "node:path"; import { pathToFileURL } from "node:url"; import { checkMessage } from "./check-agent-trailers.mjs"; +import { AgentPolicyError, loadAgentPolicy, parseAgentPolicy, requireCapability } from "./load-agent-policy.mjs"; class AgentPrError extends Error {} @@ -32,7 +33,7 @@ export function createAppJwt(appId, privateKey, now = Date.now()) { } } -async function githubRequest(path, token, { method = "GET", body, fetchImpl = globalThis.fetch } = {}) { +async function githubRequest(path, token, { method = "GET", body, fetchImpl = globalThis.fetch, allowMissing = false } = {}) { let response; try { response = await fetchImpl(`https://api.github.com${path}`, { @@ -51,6 +52,7 @@ async function githubRequest(path, token, { method = "GET", body, fetchImpl = gl } catch { throw new AgentPrError("GitHub API request failed; check connectivity and authentication."); } + if (allowMissing && response.status === 404) return undefined; if (!response.ok) { throw new AgentPrError(`GitHub API request failed (HTTP ${Number(response.status)}).`); } @@ -149,6 +151,8 @@ export function parseArgs(argv) { throw new AgentPrError("--message and --model each need a value."); } options[argument === "--model" ? "model" : "message"] = value; + } else if (["--merge", "--push-protected", "--push_protected", "--deploy"].includes(argument)) { + throw new AgentPrError("agent-pr is coder-only: merge, push_protected, and deploy are not implemented. Human-only merge and no deploys remain enforced."); } else { throw new AgentPrError("Unknown argument; use --help for usage."); } @@ -199,9 +203,13 @@ export async function publishAgentPr(options, { env = process.env, fetchImpl = globalThis.fetch, readPrivateKey = (path) => readFileSync(path), + loadPolicy = loadAgentPolicy, run = runCommand, now = Date.now(), } = {}) { + const policy = loadPolicy({ cwd }); + requireCapability(policy, "coder", "commit_branch"); + requireCapability(policy, "coder", "open_pr"); validateCommitInput(options.message, options.model); const appId = env.GITHUB_APP_ID; if (!appId || !/^[1-9][0-9]*$/.test(appId) || !env.GITHUB_APP_PRIVATE_KEY_PATH) { @@ -246,11 +254,17 @@ export async function publishAgentPr(options, { } invoke("gh", ["--version"], "GitHub CLI availability check"); const readStaged = () => git(["diff", "--cached", "--name-only", "--no-renames", "-z"], "Staged-file lookup").split("\0").filter(Boolean); + const rejectPolicyChanges = (changes) => { + if (changes.some((file) => file.toLowerCase() === "agent-policy.yml")) { + throw new AgentPrError("Agents cannot publish changes to root agent-policy.yml; a human must review and publish policy changes."); + } + }; const checkIndex = () => { const indexed = git(["ls-files", "--cached", "-z"], "Index lookup").split("\0").filter(Boolean); for (const file of indexed) safeFile(file, cwd, privateKeyPath); }; const files = [...new Set((options.files ?? []).map((file) => safeFile(file, cwd, privateKeyPath)))]; + rejectPolicyChanges(files); for (const file of files) { try { if (lstatSync(resolve(cwd, file)).isDirectory()) { @@ -263,6 +277,7 @@ export async function publishAgentPr(options, { } } const staged = readStaged(); + rejectPolicyChanges(staged); checkIndex(); for (const file of staged) safeFile(file, cwd, privateKeyPath); if (files.length && staged.some((file) => !files.includes(file))) { @@ -305,11 +320,44 @@ export async function publishAgentPr(options, { throw new AgentPrError("GitHub did not return an active repository matching origin."); } if (branch === repository.default_branch) throw new AgentPrError("Refusing to publish directly to the default branch."); + const approvedFile = await githubRequest(`${repoPath}/contents/agent-policy.yml?ref=${encodeURIComponent(repository.default_branch)}`, token, { fetchImpl }); + if ( + approvedFile?.type !== "file" || approvedFile.encoding !== "base64" || + typeof approvedFile.content !== "string" || approvedFile.content.length > 100_000 + ) { + throw new AgentPrError("Cannot verify agent-policy.yml on the default branch; refusing publication."); + } + const approvedPolicy = parseAgentPolicy(Buffer.from(approvedFile.content, "base64").toString("utf8")); + requireCapability(approvedPolicy, "coder", "commit_branch"); + requireCapability(approvedPolicy, "coder", "open_pr"); + const verifyApprovedPolicy = (candidate) => { + for (const role of Object.keys(approvedPolicy.roles)) { + const approved = approvedPolicy.roles[role].allow; + const actual = candidate.roles[role].allow; + if (actual.length !== approved.length || actual.some((capability) => !approved.includes(capability))) { + throw new AgentPrError("agent-policy.yml differs from the default branch's reviewed policy; refusing publication."); + } + } + }; + verifyApprovedPolicy(policy); + const checkProtectedBranch = async () => { + const rules = await githubRequest(`${repoPath}/rules/branches/${encodeURIComponent(branch)}`, token, { fetchImpl }); + const remoteBranch = await githubRequest(`${repoPath}/branches/${encodeURIComponent(branch)}`, token, { fetchImpl, allowMissing: true }); + if (!Array.isArray(rules) || (remoteBranch !== undefined && (remoteBranch?.name !== branch || typeof remoteBranch.protected !== "boolean"))) { + throw new AgentPrError("Cannot verify branch protection; refusing publication."); + } + if (rules.length || remoteBranch?.protected) { + requireCapability(approvedPolicy, "coder", "push_protected"); + throw new AgentPrError("Protected-branch publication is unsupported by the coder helper, even with a policy grant."); + } + }; + await checkProtectedBranch(); checkBranch(); if (files.length) { git(["add", "--", ...files], "Staging selected files", { env: { ...baseEnv, GIT_LITERAL_PATHSPECS: "1" } }); } const selected = readStaged(); + rejectPolicyChanges(selected); checkIndex(); for (const file of selected) safeFile(file, cwd, privateKeyPath); if (!selected.length || (files.length && selected.some((file) => !files.includes(file)))) { @@ -337,6 +385,9 @@ export async function publishAgentPr(options, { } const committedFiles = git(["ls-tree", "-r", "--name-only", "-z", "HEAD"], "Committed file verification").split("\0").filter(Boolean); for (const file of committedFiles) safeFile(file, cwd, privateKeyPath); + rejectPolicyChanges(git(["diff-tree", "--root", "--no-commit-id", "--no-renames", "--name-only", "-r", "-z", actual[0]], "Committed policy-change verification").split("\0").filter(Boolean)); + verifyApprovedPolicy(parseAgentPolicy(git(["show", `${actual[0]}:agent-policy.yml`], "Committed policy verification"))); + await checkProtectedBranch(); checkBranch(); const header = `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`; git(["push", "--no-follow-tags", pushUrl, `${actual[0]}:refs/heads/${branch}`], "Branch push", { @@ -365,7 +416,7 @@ export async function publishAgentPr(options, { } result = { commit: actual[0], botName, createdPullRequest: !pullRequests.length }; } catch (error) { - const detail = error instanceof AgentPrError ? error.message : "Publication failed; details were withheld to protect credentials."; + const detail = error instanceof AgentPrError || error instanceof AgentPolicyError ? error.message : "Publication failed; details were withheld to protect credentials."; failure = new AgentPrError(`${detail}${committed ? " The local commit remains; do not create a duplicate commit to retry." : ""}`); } finally { try { @@ -392,8 +443,11 @@ export async function main(argv, { stdout = process.stdout, stderr = process.std Without --files, commits the reviewed staged changes. --files must be last. Requires Node 20+, Git, gh, GITHUB_APP_ID, and GITHUB_APP_PRIVATE_KEY_PATH. +Requires root agent-policy.yml with coder commit_branch and open_pr grants, +matching the reviewed policy on origin's default branch. No example fallback. Discovers your configured App's bot identity, pushes the current feature branch to origin, and creates a draft PR only when no open PR exists. Never force-pushes or merges. +No role/policy override, merge, push_protected, or deploy flags are supported. An invocation authorizes commit, push, and PR creation. Keep secrets out of arguments. `); return 0; @@ -404,7 +458,7 @@ An invocation authorizes commit, push, and PR creation. Keep secrets out of argu stdout.write(result.createdPullRequest ? "Created a draft pull request.\n" : "Updated the branch for its existing pull request.\n"); return 0; } catch (error) { - stderr.write(`${error instanceof AgentPrError ? error.message : "agent-pr failed; details were withheld to protect credentials."}\n`); + stderr.write(`${error instanceof AgentPrError || error instanceof AgentPolicyError ? error.message : "agent-pr failed; details were withheld to protect credentials."}\n`); return 1; } } diff --git a/scripts/load-agent-policy.mjs b/scripts/load-agent-policy.mjs new file mode 100644 index 0000000..0dae153 --- /dev/null +++ b/scripts/load-agent-policy.mjs @@ -0,0 +1,142 @@ +#!/usr/bin/env node + +import { lstatSync, readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +const ROLES = ["coder", "merger", "deploy"]; +const CAPABILITIES = ["commit_branch", "open_pr", "comment", "label", "merge", "push_protected", "deploy"]; + +export class AgentPolicyError extends Error {} + +export function parseAgentPolicy(source) { + if (typeof source !== "string" || source.length > 65_536) { + throw new AgentPolicyError("Invalid agent policy; no capabilities are authorized."); + } + const policy = { version: 1, default: "deny", roles: {} }; + const rootKeys = new Set(); + const allowKeys = new Set(); + let inRoles = false; + let role; + let inAllowList = false; + const invalid = () => { + throw new AgentPolicyError("Invalid or unsupported agent-policy.yml; expected the strict version 1 format in docs/POLICY.md."); + }; + const addCapability = (capability) => { + if (!CAPABILITIES.includes(capability) || policy.roles[role].allow.includes(capability)) invalid(); + policy.roles[role].allow.push(capability); + }; + + for (const original of source.replace(/\r\n/g, "\n").split("\n")) { + if (original.includes("\t")) invalid(); + const line = original.replace(/(?:^|\s+)#.*$/, "").trimEnd(); + if (!line) continue; + const root = /^(version|default|roles):(?: (.*))?$/.exec(line); + if (root) { + if (rootKeys.has(root[1])) invalid(); + rootKeys.add(root[1]); + inRoles = root[1] === "roles" && root[2] === undefined; + role = undefined; + inAllowList = false; + if (root[1] === "version" && root[2] !== "1") invalid(); + if (root[1] === "default" && root[2] !== "deny") invalid(); + if (root[1] === "roles" && root[2] !== undefined && root[2] !== "{}") invalid(); + continue; + } + const roleEntry = /^ ([a-z_]+):(?: (.*))?$/.exec(line); + if (roleEntry) { + if (!inRoles || !ROLES.includes(roleEntry[1]) || Object.hasOwn(policy.roles, roleEntry[1])) invalid(); + if (roleEntry[2] !== undefined && roleEntry[2] !== "{}") invalid(); + policy.roles[roleEntry[1]] = { allow: [] }; + role = roleEntry[2] === "{}" ? undefined : roleEntry[1]; + inAllowList = false; + continue; + } + const allow = /^ allow:(?: (.*))?$/.exec(line); + if (allow) { + if (!inRoles || !role || allowKeys.has(role)) invalid(); + allowKeys.add(role); + inAllowList = allow[1] === undefined; + if (!inAllowList) { + if (!/^\[(?:[a-z_]+(?:, *[a-z_]+)*)?\]$/.test(allow[1])) invalid(); + for (const capability of allow[1].slice(1, -1).split(",").filter(Boolean)) addCapability(capability.trim()); + } + continue; + } + const item = /^ - ([a-z_]+)$/.exec(line); + if (!item || !inRoles || !role || !inAllowList) invalid(); + addCapability(item[1]); + } + if (!rootKeys.has("version") || !rootKeys.has("default")) invalid(); + for (const name of ROLES) { + policy.roles[name] ??= { allow: [] }; + Object.freeze(policy.roles[name].allow); + Object.freeze(policy.roles[name]); + } + Object.freeze(policy.roles); + return Object.freeze(policy); +} + +export function loadAgentPolicy({ cwd = process.cwd() } = {}) { + let source; + try { + const path = join(cwd, "agent-policy.yml"); + const status = lstatSync(path); + if (!status.isFile() || status.isSymbolicLink() || status.size > 65_536) { + throw new Error("Not a small regular policy file"); + } + source = readFileSync(path, "utf8"); + } catch { + throw new AgentPolicyError("Cannot read a regular root agent-policy.yml; no capabilities are authorized. Ask a human to install or repair the policy."); + } + return parseAgentPolicy(source); +} + +export function allowsCapability(policy, role, capability) { + return Boolean( + policy?.version === 1 && policy.default === "deny" && ROLES.includes(role) && + CAPABILITIES.includes(capability) && Array.isArray(policy.roles?.[role]?.allow) && + policy.roles[role].allow.includes(capability) + ); +} + +export function requireCapability(policy, role, capability) { + if (!allowsCapability(policy, role, capability)) { + const action = ROLES.includes(role) && CAPABILITIES.includes(capability) ? `${role}.${capability}` : "the requested capability"; + throw new AgentPolicyError(`Agent policy denies ${action}. No action was authorized.`); + } +} + +export function main(argv, { cwd = process.cwd(), stdout = process.stdout, stderr = process.stderr } = {}) { + if (argv.length === 1 && ["--help", "-h"].includes(argv[0])) { + stdout.write(`Usage: node scripts/load-agent-policy.mjs [--role ROLE --capability CAPABILITY] + +Read root agent-policy.yml; without flags, print its validated policy. +Missing or invalid policy denies all actions. No example fallback or role inheritance. +Exit 0: valid policy or allowed capability; 1: denied/unreadable/invalid; 2: usage error. +This command does not execute a capability or confer a role on the caller. +`); + return 0; + } + if (argv.length && (argv.length !== 4 || argv[0] !== "--role" || argv[2] !== "--capability")) { + stderr.write("Use --role ROLE --capability CAPABILITY, or --help.\n"); + return 2; + } + try { + const policy = loadAgentPolicy({ cwd }); + if (argv.length) { + requireCapability(policy, argv[1], argv[3]); + stdout.write("Capability allowed by policy; App, repository rules, and human authorization still apply.\n"); + } else { + stdout.write(`${JSON.stringify(policy, null, 2)}\n`); + } + return 0; + } catch (error) { + stderr.write(`${error instanceof AgentPolicyError ? error.message : "Policy check failed; no capabilities are authorized."}\n`); + return 1; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + process.exitCode = main(process.argv.slice(2)); +} \ No newline at end of file diff --git a/skills/agent-policy/SKILL.md b/skills/agent-policy/SKILL.md new file mode 100644 index 0000000..4b92629 --- /dev/null +++ b/skills/agent-policy/SKILL.md @@ -0,0 +1,38 @@ +--- +name: agent-policy +description: Use before agent publication or GitHub write actions to load the shared repository capability allow-list, enforce default deny, prevent self-grants, and keep coder, merger, and deploy roles separate. +--- + +# Agent capability policy + +## Load first + +1. Read `AGENTS.md`, `docs/POLICY.md`, and the root `agent-policy.yml` through `scripts/load-agent-policy.mjs` before requesting or executing a GitHub write. Follow `docs/ROLES.md` for the trusted role and its App credentials. +2. Missing, unreadable, malformed, or unsupported policy means no authorized capability. Do not fall back to `examples/agent-policy.yml`, a previous decision, another role, or a human credential. +3. Require an explicit allow-list entry for every requested operation. App permissions, branch protection/environments, and policy must all permit the action, and the human's task must authorize it. +4. Never create, edit, replace, or delete the active root policy to grant yourself rights. Never change the loader, publisher, or harness configuration to bypass a denial. A human must review and publish policy changes. + +## Checks + +Run from the consuming repository root after a human has installed its policy: + +```bash +node scripts/load-agent-policy.mjs --role coder --capability commit_branch +node scripts/load-agent-policy.mjs --role coder --capability open_pr +``` + +These commands only check policy; they do not confer the coder role or authorize a GitHub write. A nonzero result means stop the requested operation. An allow result still requires the other layers and human authorization. + +The capabilities are `commit_branch`, `open_pr`, `comment`, `label`, `merge`, `push_protected`, and `deploy`. The example permits the first four for coder only. Merger and deploy allow-lists are empty. Unknown actions and roles deny access; there are no inherited grants or wildcards. + +## Publication + +Use `scripts/agent-pr.mjs` and `skills/signed-bot-commit/SKILL.md` for authorized coder publication. The publisher checks local policy before key access, verifies the default branch's human-reviewed policy and the committed copy, and refuses to publish root-policy edits. It requires both coder `commit_branch` and `open_pr`. + +The coder publisher has no role/policy override and no merge, protected-push, or deploy implementation. Do not use raw Git or MCP tools to do what the helper refuses. A policy grant cannot create a missing executor or bypass stricter repository rules. Default remains human-only merge and no deploys. + +Comments and labels must pass the same policy check in an approved safe-output handler; do not enable direct MCP write tools just because the capability is listed. If the handler cannot enforce policy, stop and ask a human to publish the output. + +## Custody + +Use separate user/org-owned Apps for coder and any separately approved future privileged roles. The WSL orchestration host holds only the coder key, never merger/deploy keys or human fallback tokens. Never request, print, or commit PEM contents or tokens. No hosted control plane is required or provided. \ No newline at end of file diff --git a/skills/signed-bot-commit/SKILL.md b/skills/signed-bot-commit/SKILL.md index 30ab1c8..e7b9994 100644 --- a/skills/signed-bot-commit/SKILL.md +++ b/skills/signed-bot-commit/SKILL.md @@ -13,11 +13,11 @@ Never recommend the maintainer's `r4yharris-agent-coder` App for private or prod ## Do -1. Read `AGENTS.md` and confirm the human authorized **commit, push, and draft PR creation**. A request to stop after editing or testing prohibits running the helper. +1. Read `AGENTS.md`, load the root policy through `scripts/load-agent-policy.mjs`, and follow `skills/agent-policy/SKILL.md`. Require coder `commit_branch` and `open_pr`, then confirm the human authorized **commit, push, and draft PR creation**. Missing or denied policy means stop. A request to stop after editing or testing prohibits running the helper. 2. Use only `node scripts/agent-pr.mjs` from the repository root. Do not run raw `git commit`, `git push`, or a separate `gh pr create`; do not fall back to a human identity or credentials. 3. Confirm Node 20+, Git, and `gh` are available. The human supplies `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` through the environment; CI uses the `GITHUB_APP_PRIVATE_KEY` secret through an approved temporary-file bootstrap. Never read the PEM into chat, display tokens, or commit `.env` or private-key files. The helper does not load `.env` automatically. Missing App configuration means stop, not use the signed-in human. 4. Review the staged changes, or select individual repository files with `--files`. Do not pass directories. The helper refuses unrelated staged files when explicit files are selected. Run `node --test tests/*.test.mjs` before publishing. -5. Keep the current branch a feature branch. The helper uses only origin's repository, refuses default-branch publication, and never force-pushes or merges. Require `check-agent-trailers` and human approval on protected branches, grant the App no bypass, and leave merging to humans. +5. Keep the current branch an unprotected feature branch. The helper uses only origin's repository, checks branch protection and active rules, and never force-pushes, merges, or deploys. Require `check-agent-trailers` and human approval on protected branches, grant the App no bypass, and leave merging to humans. ## Identity and trailers @@ -34,6 +34,8 @@ Use `--model` to replace `unknown` when the actual model is known. It checks the ## Usage +The human must first publish root `agent-policy.yml` on the default branch and include its reviewed version in the feature branch. See `docs/POLICY.md`. The helper checks that the local and committed policy match the reviewed grants, refuses root-policy edits, and provides no role or policy-path override. Agents must not change policy to authorize themselves. + With reviewed changes already staged: ```bash @@ -46,7 +48,7 @@ To stage and commit named files, put `--files` last: node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --files README.md AGENTS.md ``` -`--help` does not read the key or contact GitHub. Normal invocation signs an App JWT, discovers the repository installation, and requests an installation token scoped to that repository with contents and pull requests write permissions. It makes an unsigned bot commit, pushes with in-memory authentication, reuses an open PR for the branch or runs `gh pr create --draft`, then revokes the token. New PR titles follow the repository's `[area] summary` convention with `[agent]` as the default area. +`--help` does not read policy, the key, or contact GitHub. Normal invocation first requires the local coder grants, then signs an App JWT, discovers the repository installation, and requests an installation token scoped to that repository with contents and pull requests write permissions. After checking the approved policy and branch protections, it makes an unsigned bot commit, pushes with in-memory authentication, reuses an open PR for the branch or runs `gh pr create --draft`, then revokes the token. New PR titles follow the repository's `[area] summary` convention with `[agent]` as the default area. ## Failure handling @@ -58,6 +60,8 @@ Despite this skill's name, the current helper creates **unsigned Git commits**. - Commit as R4yHarris or another human, including during bootstrap. A human can commit a bootstrap slice themselves. - Force-push any branch or merge a PR. +- Deploy, switch to a merger/deploy App, or use a policy grant to bypass the coder helper's fixed capabilities. +- Edit, replace, or delete root `agent-policy.yml` to grant yourself rights or publish a policy change through this helper. - Amend someone else's commit. - Write tokens, App private keys, or signing keys into the repository. - Bypass a repository's signing or human-approval requirement. diff --git a/tests/agent-pr.test.mjs b/tests/agent-pr.test.mjs index a980ec5..a5ee33a 100644 --- a/tests/agent-pr.test.mjs +++ b/tests/agent-pr.test.mjs @@ -9,7 +9,10 @@ import { buildCommitMessage, createAppJwt, main, mintInstallationToken, parseArgs, parseOrigin, publishAgentPr, } from "../scripts/agent-pr.mjs"; +import { AgentPolicyError, loadAgentPolicy, parseAgentPolicy } from "../scripts/load-agent-policy.mjs"; +const policySource = readFileSync(new URL("../examples/agent-policy.yml", import.meta.url), "utf8"); +const approvedPolicyFile = { type: "file", encoding: "base64", content: Buffer.from(policySource).toString("base64") }; const AGENT = "example-org-agent"; const BOT_NAME = `${AGENT}[bot]`; const BOT_EMAIL = `789+${BOT_NAME}@users.noreply.github.com`; @@ -28,6 +31,9 @@ function mockGitHub(responses) { const fetchImpl = async (url, options) => { calls.push({ url, ...options }); if (url === `https://api.github.com/users/${encodeURIComponent(BOT_NAME)}`) return Response.json(bot); + if (url.endsWith("/contents/agent-policy.yml?ref=main")) return Response.json(approvedPolicyFile); + if (url.includes("/rules/branches/")) return Response.json([]); + if (url.includes("/branches/")) return Response.json({ name: decodeURIComponent(url.split("/branches/")[1]), protected: false }); assert.ok(responses.length, "Unexpected GitHub request"); const response = responses.shift(); return response instanceof Response ? response : Response.json(response); @@ -108,6 +114,7 @@ function mockPublication({ branch = "feat/bot-helper", staged = ["README.md"], i const dependencies = { ...github, cwd, + loadPolicy: () => parseAgentPolicy(policySource), env: { GITHUB_APP_ID: "123", GITHUB_APP_PRIVATE_KEY_PATH: "not-read.pem", @@ -129,7 +136,8 @@ function mockPublication({ branch = "feat/bot-helper", staged = ["README.md"], i if (args[0] === "symbolic-ref") return branch; if (args[0] === "remote") return "git@github.com:example-owner/example-repo.git\n"; if (args[0] === "config") return ""; - if (args[0] === "diff") return staged.map((file) => `${file}\0`).join(""); + if (args[0] === "show") return policySource; + if (args[0] === "diff" || args[0] === "diff-tree") return staged.map((file) => `${file}\0`).join(""); if (args[0] === "ls-files" || args[0] === "ls-tree") return indexed.map((file) => `${file}\0`).join(""); if (args.includes("commit")) { message = options.input; return "commit output"; } if (args[0] === "log") return [commitSha, BOT_NAME, BOT_EMAIL, BOT_NAME, BOT_EMAIL, message].join("\0"); @@ -220,6 +228,131 @@ test("an existing open PR is reused without running gh pr create", async () => { assert.ok(!mock.commands.some((call) => call.command === "gh" && call.args[0] === "pr")); }); +test("missing, invalid, or insufficient local policy denies publication before commands, key access, or network calls", async () => { + for (const source of [undefined, "default: allow", "version: 1\ndefault: deny\n", policySource.replace("open_pr, ", "")]) { + const mock = mockPublication(); + mock.dependencies.loadPolicy = () => { + if (source === undefined) throw new AgentPolicyError("Missing policy; no capabilities are authorized."); + return parseAgentPolicy(source); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /policy|agent-policy/i); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.commands.length, 0); + assert.equal(mock.requests.length, 0); + } +}); + +test("the coder CLI refuses merge, protected push, deploy, and role or policy overrides", async () => { + for (const flag of ["--merge", "--push-protected", "--deploy", "--role", "--policy"]) { + const mock = mockPublication(); + const output = []; + assert.equal(await main(["--message", "feat: helper", flag], { + ...mock.dependencies, stderr: { write: (text) => output.push(text) }, + }), 2); + assert.ok(output.length); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.commands.length, 0); + assert.equal(mock.requests.length, 0); + } +}); + +test("policy edits cannot be staged or selected through the agent publisher", async () => { + for (const options of [{ files: ["agent-policy.yml"] }, {}]) { + const mock = mockPublication({ staged: ["agent-policy.yml"] }); + await assert.rejects(publishAgentPr({ message: "feat: helper", ...options }, mock.dependencies), /cannot publish changes to root agent-policy/); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.requests.length, 0); + } +}); + +test("a different, missing, or denying default-branch policy prevents self-grants", async () => { + for (const response of [ + Response.json({ message: "Not found" }, { status: 404 }), + Response.json({ ...approvedPolicyFile, content: Buffer.from("version: 1\ndefault: deny\n").toString("base64") }), + Response.json({ ...approvedPolicyFile, content: Buffer.from(policySource.replace("comment, label", "comment")).toString("base64") }), + ]) { + const mock = mockPublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => url.includes("/contents/agent-policy.yml") ? response : originalFetch(url, options); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /HTTP 404|policy denies|differs from/); + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push")); + assert.equal(mock.requests.at(-1).method, "DELETE"); + } +}); + +test("a protected branch or matching ruleset requires push_protected and is refused", async () => { + for (const protectedBy of ["legacy", "ruleset"]) { + const mock = mockPublication({ branch: "release" }); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => { + if (protectedBy === "ruleset" && url.includes("/rules/branches/")) return Response.json([{ type: "pull_request" }]); + if (protectedBy === "legacy" && url.endsWith("/branches/release") && !url.includes("/rules/branches/")) return Response.json({ name: "release", protected: true }); + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /policy denies coder\.push_protected/); + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push")); + assert.equal(mock.requests.at(-1).method, "DELETE"); + } +}); + +test("branch-protection lookup errors fail closed instead of assuming an unprotected branch", async () => { + const mock = mockPublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => url.includes("/rules/branches/") + ? Response.json({ message: access.token }, { status: 403 }) : originalFetch(url, options); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /HTTP 403/); + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push")); +}); + +test("a policy grant cannot enable protected pushes through the coder-only helper", async () => { + const source = policySource.replace("commit_branch,", "commit_branch, push_protected,"); + const mock = mockPublication(); + mock.dependencies.loadPolicy = () => parseAgentPolicy(source); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => { + if (url.includes("/contents/agent-policy.yml")) return Response.json({ ...approvedPolicyFile, content: Buffer.from(source).toString("base64") }); + if (url.includes("/rules/branches/")) return Response.json([{ type: "pull_request" }]); + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /unsupported by the coder helper/); + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push")); +}); + +test("a changed policy in the committed tree cannot hide behind a clean working copy", async () => { + const mock = mockPublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => args[0] === "show" + ? policySource.replace("comment, label", "comment, label, merge") : originalRun(command, args, options); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), (error) => { + assert.match(error.message, /differs from the default branch/); + assert.match(error.message, /local commit remains/); + return true; + }); + assert.ok(!mock.commands.some((call) => call.args[0] === "push")); + assert.equal(mock.requests.at(-1).method, "DELETE"); +}); + +test("new protection discovered after the commit prevents the push", async () => { + const mock = mockPublication(); + const originalFetch = mock.dependencies.fetchImpl; + let protectionChecks = 0; + mock.dependencies.fetchImpl = (url, options) => { + if (url.includes("/rules/branches/") && ++protectionChecks === 2) return Response.json([{ type: "pull_request" }]); + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /denies coder\.push_protected/); + assert.ok(mock.commands.some((call) => call.args.includes("commit"))); + assert.ok(!mock.commands.some((call) => call.args[0] === "push")); +}); + +test("a new branch can be published when no applicable rules are returned", async () => { + const mock = mockPublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => url.includes("/branches/") && !url.includes("/rules/branches/") + ? Response.json({ message: "Not found" }, { status: 404 }) : originalFetch(url, options); + assert.equal((await publishAgentPr({ message: "feat: helper" }, mock.dependencies)).createdPullRequest, true); +}); + test("an invalid or human account cannot stand in for the configured App bot", async () => { for (const invalid of [{ ...bot, type: "User" }, { ...bot, login: "another-app[bot]" }, { ...bot, id: 0 }]) { const mock = mockPublication(); @@ -423,6 +556,9 @@ test("local Git integration commits selected and staged files with bot provenanc ...args, ], { cwd: directory, env: gitEnvironment, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], ...options }); localGit(["init", "--quiet", "--initial-branch=feat/test-publication", "--object-format=sha1"]); + writeFileSync(join(directory, "agent-policy.yml"), policySource); + localGit(["add", "--", "agent-policy.yml"]); + localGit(["-c", `user.name=${BOT_NAME}`, "-c", `user.email=${BOT_EMAIL}`, "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "test: policy fixture"]); const github = mockGitHub([ installation, access, repository, [], new Response(null, { status: 204 }), installation, access, repository, [{ number: 1 }], new Response(null, { status: 204 }), @@ -430,6 +566,7 @@ test("local Git integration commits selected and staged files with bot provenanc const dependencies = { ...github, cwd: directory, + loadPolicy: loadAgentPolicy, env: { ...gitEnvironment, GITHUB_APP_ID: "123", GITHUB_APP_PRIVATE_KEY_PATH: "never-read.pem" }, readPrivateKey: () => privateKey, run: (command, args, options) => { @@ -444,7 +581,7 @@ test("local Git integration commits selected and staged files with bot provenanc const first = await publishAgentPr({ message: "feat: selected files", files: ["selected.txt"] }, dependencies); assert.match(first.commit, /^[0-9a-f]{40}$/); assert.equal(first.createdPullRequest, true); - assert.equal(localGit(["ls-tree", "-r", "--name-only", "HEAD"]).trim(), "selected.txt"); + assert.equal(localGit(["ls-tree", "-r", "--name-only", "HEAD"]).trim(), "agent-policy.yml\nselected.txt"); assert.equal(localGit(["log", "-1", "--format=%an%n%ae%n%cn%n%ce"]).trim(), [BOT_NAME, BOT_EMAIL, BOT_NAME, BOT_EMAIL].join("\n")); assert.ok(localGit(["log", "-1", "--format=%B"]).includes(`AI-Agent: ${AGENT}\nAI-Model: unknown`)); writeFileSync(join(directory, "selected.txt"), "updated contents\n"); diff --git a/tests/load-agent-policy.test.mjs b/tests/load-agent-policy.test.mjs new file mode 100644 index 0000000..0e0672e --- /dev/null +++ b/tests/load-agent-policy.test.mjs @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + allowsCapability, loadAgentPolicy, main, parseAgentPolicy, requireCapability, +} from "../scripts/load-agent-policy.mjs"; + +const repository = fileURLToPath(new URL("../", import.meta.url)); +const example = readFileSync(new URL("../examples/agent-policy.yml", import.meta.url), "utf8"); + +function temporaryRepository(context) { + const directory = mkdtempSync(join(repository, ".policy-test-")); + context.after(() => rmSync(directory, { recursive: true, force: true, maxRetries: 3 })); + return directory; +} + +test("the example grants coder actions only and leaves merger and deploy empty", () => { + const policy = parseAgentPolicy(example); + assert.deepEqual(policy.roles.coder.allow, ["commit_branch", "open_pr", "comment", "label"]); + assert.deepEqual(policy.roles.merger.allow, []); + assert.deepEqual(policy.roles.deploy.allow, []); + assert.equal(allowsCapability(policy, "coder", "commit_branch"), true); + for (const capability of ["merge", "push_protected", "deploy"]) { + for (const role of ["coder", "merger", "deploy"]) { + assert.equal(allowsCapability(policy, role, capability), false); + } + } + assert.throws(() => requireCapability(policy, "merger", "merge"), /denies merger\.merge/); +}); + +test("omitted roles and allow lists deny everything without inheriting grants", () => { + for (const source of ["version: 1\ndefault: deny\n", "version: 1\ndefault: deny\nroles: {}\n", "version: 1\ndefault: deny\nroles:\n coder: {}\n"]) { + const policy = parseAgentPolicy(source); + assert.equal(allowsCapability(policy, "coder", "commit_branch"), false); + assert.equal(allowsCapability(policy, "merger", "merge"), false); + } + const policy = parseAgentPolicy(example); + assert.equal(allowsCapability(policy, "merger", "open_pr"), false); + assert.equal(allowsCapability(policy, "unknown", "commit_branch"), false); + assert.equal(allowsCapability(policy, "__proto__", "commit_branch"), false); + assert.equal(allowsCapability(policy, "coder", "unknown"), false); + assert.equal(allowsCapability(undefined, "coder", "commit_branch"), false); +}); + +test("block allow lists and comments produce the same policy as inline lists", () => { + const source = "# Human-owned policy\r\nversion: 1\r\ndefault: deny # No implicit grants\r\nroles:\r\n coder:\r\n allow:\r\n - commit_branch\r\n - open_pr\r\n - comment\r\n - label\r\n"; + assert.deepEqual(parseAgentPolicy(source), parseAgentPolicy(example)); +}); + +test("an explicit grant applies only to the named role", () => { + const policy = parseAgentPolicy("version: 1\ndefault: deny\nroles:\n merger:\n allow: [merge]\n"); + assert.doesNotThrow(() => requireCapability(policy, "merger", "merge")); + assert.equal(allowsCapability(policy, "coder", "merge"), false); + assert.equal(allowsCapability(policy, "merger", "push_protected"), false); + assert.throws(() => policy.roles.merger.allow.push("deploy"), TypeError); +}); + +test("invalid, unknown, wildcard, duplicate, and unsupported YAML entries fail closed", () => { + for (const source of [ + "", "version: 1\n", "default: deny\n", "version: 2\ndefault: deny\n", + example.replace("default: deny", "default: allow"), + `${example}default: deny\n`, + `${example}defaults: allow\n`, + example.replace(" coder:", " owner:"), + example.replace("allow: [commit_branch, open_pr, comment, label]", "allow: [*]"), + example.replace("allow: [commit_branch, open_pr, comment, label]", "allow: [commit_branch, commit_branch]"), + example.replace("open_pr", "open_pull_request"), + example.replace(" merger:", " coder:"), + example.replace(" allow: []", " allow: []\n allow: [merge]"), + example.replace(" allow: []", " deny: []"), + example.replace("roles:", "roles: &roles"), + `${example}---\n${example}`, + example.replace(" coder:", "\tcoder:"), + example.replace("default: deny", "default: !custom deny"), + example.replace(" coder:", " coder: {}\n allow: [merge]"), + ]) { + assert.throws(() => parseAgentPolicy(source), /Invalid or unsupported agent-policy/); + } + assert.throws(() => parseAgentPolicy(" ".repeat(65_537)), /no capabilities/); +}); + +test("a missing or malformed root policy never falls back to the example", (context) => { + const cwd = temporaryRepository(context); + assert.throws(() => loadAgentPolicy({ cwd }), /no capabilities are authorized/); + writeFileSync(join(cwd, "agent-policy.yml"), "default: allow\n"); + assert.throws(() => loadAgentPolicy({ cwd }), /Invalid or unsupported/); + writeFileSync(join(cwd, "agent-policy.yml"), example); + assert.deepEqual(loadAgentPolicy({ cwd }), parseAgentPolicy(example)); +}); + +test("the read-only CLI refuses merge with an empty merger allow list", (context) => { + const cwd = temporaryRepository(context); + writeFileSync(join(cwd, "agent-policy.yml"), example); + const output = []; + const options = { cwd, stdout: { write: (text) => output.push(text) }, stderr: { write: (text) => output.push(text) } }; + assert.equal(main(["--role", "merger", "--capability", "merge"], options), 1); + assert.match(output.join(""), /denies merger\.merge/); + assert.equal(main(["--role", "coder", "--capability", "commit_branch"], options), 0); + assert.equal(main(["--role", "coder", "--capability", "deploy"], options), 1); + assert.equal(main(["--role", "unknown", "--capability", "merge"], options), 1); + assert.equal(main(["--policy", "examples/agent-policy.yml"], options), 2); +}); \ No newline at end of file