From b9d87149ef44a61d4a9069f2ae8eb523b8a67823 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 28 Oct 2026 17:55:14 +0000 Subject: [PATCH 1/2] feat(security): the App's installation tokens carry only the permissions the roadmap jobs use Each token request now sends a permissions body from CONST_GITHUB_APP_TOKEN_PERMISSIONS: issues, pull_requests and contents write, and checks, actions and metadata read. The installation grants read and write on every repository permission, so a token without this body could change settings, secrets, variables, environments and workflows. gidgethub's get_installation_access_token sends no body, so gidgethub's GitHubAPI signs the JWT and posts the request. The log names the permissions of GitHub's reply, without levels or the token. A reply that grants more is no error. GitHub refuses an ungranted permission with HTTP 422 and does not say which one, so the error names each permission that the token asks for. ADR 0015, the k8s README and the knowledge base say that each token is scoped to these permissions. --- ...as-a-github-app-on-the-personal-account.md | 6 +- k8s/README.md | 2 +- .../2473-app-token-permissions/.openspec.yaml | 2 + .../2473-app-token-permissions/design.md | 23 ++++++ .../2473-app-token-permissions/proposal.md | 38 ++++++++++ .../specs/github-app-identity/spec.md | 22 ++++++ .../2473-app-token-permissions/tasks.md | 16 ++++ .../it_domains/tools/github_cli.md | 2 +- src/devops_cli/config/constants.py | 11 +++ src/devops_cli/github/app_installation.py | 75 +++++++++++++----- src/devops_cli/lang/en/errors.py | 4 + tests/test_github_app_identity.py | 76 ++++++++++++++++++- 12 files changed, 252 insertions(+), 25 deletions(-) create mode 100644 openspec/changes/2473-app-token-permissions/.openspec.yaml create mode 100644 openspec/changes/2473-app-token-permissions/design.md create mode 100644 openspec/changes/2473-app-token-permissions/proposal.md create mode 100644 openspec/changes/2473-app-token-permissions/specs/github-app-identity/spec.md create mode 100644 openspec/changes/2473-app-token-permissions/tasks.md diff --git a/docs/adr/0015-roadmap-jobs-act-as-a-github-app-on-the-personal-account.md b/docs/adr/0015-roadmap-jobs-act-as-a-github-app-on-the-personal-account.md index 536a119162..0f04c9d96f 100644 --- a/docs/adr/0015-roadmap-jobs-act-as-a-github-app-on-the-personal-account.md +++ b/docs/adr/0015-roadmap-jobs-act-as-a-github-app-on-the-personal-account.md @@ -4,6 +4,8 @@ ADR 0015 supersedes [ADR 0002](0002-roadmap-jobs-act-as-a-machine-account.md). Amended on 2026-10-28 ([#2454](https://github.com/dan-petty/devops-cli/issues/2454)): the owner made the App as `devops-cli-service`, with read and write on every repository permission, for planned repository-management work. +Amended on 2026-10-28 ([#2473](https://github.com/dan-petty/devops-cli/issues/2473)): each installation token asks only for the permissions that the roadmap jobs use, whatever the App grants. + ADR 0002 gave the roadmap jobs a machine account with a classic token, because only a classic token can reach a project board that a personal account owns. GitHub suspended that machine account on 2026-10-11 ([#1562](https://github.com/dan-petty/devops-cli/issues/1562)). Since then, no roadmap job can call GitHub without a person, and `deployment/roadmap-service` stays at `replicas: 0`. On 2026-10-28 the owner decided that the repositories and the board stay on the personal account, and that no organization is made. The owner also said: "roadmap should perform all expected functionality even if project board is unavailable for the repository". @@ -12,7 +14,7 @@ On 2026-10-28 the owner decided that the repositories and the board stay on the - **The jobs act as a GitHub App.** The personal account owns the App `devops-cli-service` and installs it on its managed repositories. The roadmap jobs need these repository permissions: Issues read and write, Pull requests read and write, Contents read and write, Checks read, Actions read and Metadata read. The owner gave the App read and write on every repository permission, for planned repository-management work. It has no webhook and no user authorization. - **The private key selects the App.** A process whose environment holds the App's private key, `DEVOPS_CLI_SERVICE_GITHUB_APP_PRIVATE_KEY`, acts as the App. Secret `devops/devops-cli` gives the key to the Service and to each cluster Job. A workstation keeps the key only in the OS keyring, for `devops k8s push-secrets`, so a workstation run keeps the gh login of its person. gh applies the same rule to `GH_TOKEN`: a token in the environment takes precedence over a stored login. -- **gidgethub mints the token.** The process signs a JWT with the key and exchanges it for an installation token with `gidgethub.apps.get_installation_access_token`. An installation token expires one hour after GitHub makes it, and the process mints a new one when less than ten minutes are left. Each gh and git child gets the current token as `GH_TOKEN`. git gets it through `gh auth git-credential`. +- **gidgethub mints the token.** gidgethub's `GitHubAPI` signs a JWT with the key, and the process exchanges it for an installation token at `POST /app/installations//access_tokens`. The request body asks for the roadmap jobs' permissions only, from `CONST_GITHUB_APP_TOKEN_PERMISSIONS`: `issues`, `pull_requests` and `contents` write, and `checks`, `actions` and `metadata` read. `gidgethub.apps.get_installation_access_token` sends no body, so the process does not use it. An installation token expires one hour after GitHub makes it, and the process mints a new one when less than ten minutes are left. Each gh and git child gets the current token as `GH_TOKEN`. git gets it through `gh auth git-credential`. - **The installation is the identity.** The quota ledger and the GitHub session are keyed by the installation, so each new token keeps them. The session reads the current token for each request. - **The login is the bot's.** An installation token cannot read `GET /user`, so the login is `[bot]`, from `service.github_app.slug`. The job clone commits as that login, with the email `+@users.noreply.github.com`. The ID comes from `GET /users/`. The roadmap's webhook consumer refuses a delivery whose sender is that login. - **The settings.** `service.github_app.app_id`, `service.github_app.installation_id` and `service.github_app.slug` go into ConfigMap `devops-cli-config`. The private key is the managed credential `service.github_app.private_key`, which a person stores with `devops config set --from-file`. The settings `service.machine_account` and `k8s.github_account` are removed. @@ -28,6 +30,6 @@ On 2026-10-28 the owner decided that the repositories and the board stay on the ## Consequences - An installation token cannot read or write the project board of a personal account, because GitHub gives Apps the "Projects" permission only for an organization. [ADR 0016](0016-labels-hold-the-roadmap-items-fields.md) moves the roadmap state to labels and milestones, so that the roadmap works without the board. `deployment/roadmap-service` stays at `replicas: 0` until a person moves the board's values to labels one time and pushes the App's key. -- The App's private key is in Secret `devops/devops-cli`. It reaches only the installed repositories, and each token that it mints expires after one hour. With read and write on every repository permission, the key can also change repository settings, Actions secrets and variables, environments and workflows, which AGENTS.md leaves to a person, and a key that leaks reaches all of that until it is rotated. A permission that no job uses can go from the App with no change to the code. +- The App's private key is in Secret `devops/devops-cli`. It reaches only the installed repositories, and each token that it mints expires after one hour. Each token is scoped to the roadmap jobs' permissions, whatever the App grants: a token that a bug, a prompt injection or a leak reaches cannot change repository settings, Actions secrets and variables, environments or workflows, which AGENTS.md leaves to a person. The key itself is not scoped: with read and write on every repository permission, a key that leaks can mint a token with all of them until it is rotated. A permission that no job uses can go from the App with no change to the code. If the installation does not grant one of the token's permissions, GitHub refuses the token with HTTP 422 and does not say which permission is missing, so the error names each permission that the token asks for. A later feature that needs more permissions asks for a token with its own set. - The App's writes show as `devops-cli-service[bot]`, so a person can tell them from their own writes. - The webhooks of each repository stay. The App's own webhook can replace them in a later item. diff --git a/k8s/README.md b/k8s/README.md index 9b6e7fa5ea..10443a0731 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -513,7 +513,7 @@ kubectl -n devops logs -f job/ > **Held at `replicas: 0`.** The Service acts as GitHub App `devops-cli-service`, which the personal account owns ([ADR 0015](../docs/adr/0015-roadmap-jobs-act-as-a-github-app-on-the-personal-account.md)). Labels and milestones hold the roadmap state ([ADR 0016](../docs/adr/0016-labels-hold-the-roadmap-items-fields.md)). `deployment/roadmap-service` stays at `replicas: 0` until a person moves the board's values to labels one time and steps 1 to 3 are done. Do not scale the deployment until then, and keep each managed repository's webhook disabled. -1. Create the GitHub App on the personal account (Settings > Developer settings > GitHub Apps > New GitHub App): name `devops-cli-service`, webhook off, "Only on this account". The roadmap jobs need these repository permissions: Issues read and write, Pull requests read and write, Contents read and write, Checks read, Actions read, Metadata read. The owner's App has read and write on every repository permission ([ADR 0015](../docs/adr/0015-roadmap-jobs-act-as-a-github-app-on-the-personal-account.md) records the risk). Install it on each managed repository, and generate a private key. The App page shows the App ID, and the installation's settings page has the installation ID at the end of its URL. +1. Create the GitHub App on the personal account (Settings > Developer settings > GitHub Apps > New GitHub App): name `devops-cli-service`, webhook off, "Only on this account". The roadmap jobs need these repository permissions: Issues read and write, Pull requests read and write, Contents read and write, Checks read, Actions read, Metadata read. The owner's App has read and write on every repository permission ([ADR 0015](../docs/adr/0015-roadmap-jobs-act-as-a-github-app-on-the-personal-account.md) records the risk). Each installation token that the Service and the Jobs mint is scoped to the permissions above, whatever the App grants, so the App must grant at least those: GitHub refuses a token with HTTP 422 when the installation does not grant one of them. Install it on each managed repository, and generate a private key. The App page shows the App ID, and the installation's settings page has the installation ID at the end of its URL. 2. `uv run devops config set service.repos ` (each repository the service works for), then `uv run devops config set service.webhook_secrets` (hidden prompt; a JSON object mapping `owner/name` to its secret). Set the App with `uv run devops config set service.github_app.app_id `, `service.github_app.installation_id `, `service.github_app.slug devops-cli-service` and `service.github_app.private_key --from-file `, then delete the downloaded key file. deploy-stack refuses the devops stack until `service.repos` and the App's settings are set. 3. `uv run devops k8s push-secrets --stack devops`. It writes the App's private key to Secret `devops/devops-cli`. deploy-stack also pushes it once namespace `devops` exists. 4. Check that the GHCR `service` package is public (#741 made it so): `DOCKER_CONFIG=$(mktemp -d) docker pull ghcr.io/dan-petty/devops-cli/service:`. diff --git a/openspec/changes/2473-app-token-permissions/.openspec.yaml b/openspec/changes/2473-app-token-permissions/.openspec.yaml new file mode 100644 index 0000000000..1bb6456d11 --- /dev/null +++ b/openspec/changes/2473-app-token-permissions/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-28 diff --git a/openspec/changes/2473-app-token-permissions/design.md b/openspec/changes/2473-app-token-permissions/design.md new file mode 100644 index 0000000000..0f1853aef2 --- /dev/null +++ b/openspec/changes/2473-app-token-permissions/design.md @@ -0,0 +1,23 @@ +# Design + +## Context + +The Service and the cluster Jobs act as GitHub App `devops-cli-service` (ADR 0015). `mint_installation_token` exchanges the App's JWT for an installation token over the session's client, and `core.process` gives the token to every gh and git child. The installation grants read and write on every repository permission. Without a `permissions` body, GitHub gives each token all of them. + +## Decisions + +- **One constant holds the token's permissions.** `CONST_GITHUB_APP_TOKEN_PERMISSIONS` maps each permission that the roadmap jobs use to its level. The token request sends it as `permissions`. A later feature that needs more asks for a token with its own set. The App's grant stays the owner's setting. +- **gidgethub's `GitHubAPI` posts the request.** gidgethub 6.0.0's `get_installation_access_token` posts an empty body. `GitHubAPI` takes the App's ID and key, signs the JWT, and posts a JSON body, so the request still goes through gidgethub and the session's client, to GitHub's API origin only. +- **The log names the granted permissions only.** After a token is minted, one INFO record names the permissions of GitHub's reply, sorted, with no level and no token. A reply that grants more than the request asks for is no error: GitHub decides what the token carries, and the log shows it. +- **A 422 names each permission that the token asks for.** `classify_http_error` gives the status of the refusal. On HTTP 422 the reason adds each permission of the request with its level, after GitHub's text. Any other refusal keeps its reason as before. + +## Rejected Alternatives + +- **Read the installation's permissions after a 422 and name only the missing ones.** `GET /app/installations/{installation_id}` gives the installation's `permissions`. But the read is a second request after a refusal, it can fail too, and its failure would hide the 422 or need its own error path. GitHub's 422 also answers a request that the endpoint thinks is spam ("Validation failed, or the endpoint has been spammed"), so a 422 alone does not prove a missing permission. The six names in the error are enough for a person to compare with the App's settings page. +- **Keep `gidgethub.apps.get_installation_access_token`.** It posts `data=b""` and takes no `permissions` argument (gidgethub 6.0.0, `gidgethub/apps.py`), so it cannot scope the token. +- **Also scope the token to `service.repos` with `repositories`.** The issue asks for permissions only. The App is installed only on the managed repositories (`k8s/README.md`, "Roadmap service", step 1), so the installation already limits which repositories a token reaches. +- **Fail when the reply grants more than the request asks for.** The issue's acceptance criteria say that such a reply is no error. The token's permissions are GitHub's decision; the log shows them, so a person can see a difference. + +## Risks + +- A roadmap job that starts to use a permission outside the set fails at the request that needs it, with GitHub's 403. The fix is to add the permission to the constant, in a pull request that says why. diff --git a/openspec/changes/2473-app-token-permissions/proposal.md b/openspec/changes/2473-app-token-permissions/proposal.md new file mode 100644 index 0000000000..3712986b76 --- /dev/null +++ b/openspec/changes/2473-app-token-permissions/proposal.md @@ -0,0 +1,38 @@ +# Proposal + +## Why + +Issue #2473: on 2026-10-28 the owner gave GitHub App `devops-cli-service` read and write on every repository permission, for planned repository-management work (ADR 0015, #2454). `src/devops_cli/github/app_installation.py` minted each installation token with no request body, so each token got every permission of the installation: Administration, Secrets, Variables, Environments and Workflows too, which AGENTS.md leaves to a person. A bug, a prompt injection that reaches a write, or a token that leaks could use all of them. The roadmap jobs use only Issues, Pull requests and Contents read and write, and Checks, Actions and Metadata read (`k8s/README.md`, "Roadmap service", step 1). + +## What Changes + +- One constant, `CONST_GITHUB_APP_TOKEN_PERMISSIONS` in `src/devops_cli/config/constants.py`, holds the token's permissions: `issues`, `pull_requests` and `contents` write, and `checks`, `actions` and `metadata` read. +- The token request sends `{"permissions": CONST_GITHUB_APP_TOKEN_PERMISSIONS}` as its body. gidgethub's `GitHubAPI` signs the App's JWT and posts the request over the session's client, as before. The process no longer calls `gidgethub.apps.get_installation_access_token`, which sends no body. +- The process logs the names of the permissions in GitHub's reply, without their levels and without the token. A reply that grants more than the request asks for is no error. +- When GitHub refuses the request with HTTP 422, the error names each permission that the token asks for, with GitHub's status and reply text. GitHub's reply does not say which permission the installation does not grant. +- ADR 0015, the "Roadmap service" text of `k8s/README.md` and the knowledge base's GitHub CLI page say that each token is scoped to these permissions, whatever the App grants. +- The change alters the request that the Service and the cluster Jobs send to GitHub, an error message and a log line, so it carries a spec delta: an ADDED requirement in `github-app-identity`. +- This change fits one pull request. + +## Capabilities + +### Modified Capabilities + +- `github-app-identity`: each installation token carries only the permissions that the roadmap jobs use. + +## Impact + +- `src/devops_cli/github/app_installation.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/lang/en/errors.py`. +- `tests/test_github_app_identity.py`. +- `docs/adr/0015-roadmap-jobs-act-as-a-github-app-on-the-personal-account.md`, `k8s/README.md`, `src/devops_cli/ai/knowledge_base/it_domains/tools/github_cli.md`. + +## Feasibility + +- GitHub's REST documentation, "Create an installation access token for an app" (`POST /app/installations/{installation_id}/access_tokens`, API version 2022-11-28), lists the body parameters `repositories`, `repository_ids` and `permissions`. It says: "If permissions is not specified, the installation access token will have all of the permissions" of the installation, and "The installation access token cannot be granted permissions that the app was not granted." The keys `issues`, `pull_requests`, `contents`, `checks`, `actions` and `metadata` each take `read` or `write`. The answers are 201, 401, 403, 404 and 422, and the 201 reply holds the token's `permissions`. +- The documentation names no error for a permission that the installation does not grant. Public reports show that GitHub answers HTTP 422 with "The permissions requested are not granted to this installation." and does not say which permission is missing: `actions/create-github-app-token` in ScottCooper92/binge-companions#235, and Renovate in MikaelSiidorow/systems#77. So the issue's premise that the error can name the missing permission fails as written. The error names each permission that the token asks for, and GitHub's status and text. The design records why the change does not read the installation's permissions after a refusal. +- gidgethub 6.0.0, as installed: `gidgethub/apps.py` `get_installation_access_token(gh, *, installation_id, app_id, private_key)` posts `data=b""` and takes no permissions and no body. `gidgethub.abc.GitHubAPI.__init__` takes `app_id` and `private_key` and signs an RS256 JWT whose issuer is the App ID (`_get_app_jwt`), and `GitHubAPI.post(url, *, data)` sends `data` as a JSON body. So the change posts the request through the same `gidgethub.httpx.GitHubAPI` over `session_client()` that the code already used. +- On `origin/main` 960e3573, the three new tests failed: the exchange's body was empty (`JSONDecodeError`), no log record named the permissions, and the 422 error named no permission. + +## Existing Tool Considered + +GitHub's documented `permissions` body parameter of the token endpoint, sent through gidgethub's `GitHubAPI.post`, which signs the App's JWT. Nothing is built. The change deletes the call to `gidgethub.apps.get_installation_access_token`, which cannot send a body. diff --git a/openspec/changes/2473-app-token-permissions/specs/github-app-identity/spec.md b/openspec/changes/2473-app-token-permissions/specs/github-app-identity/spec.md new file mode 100644 index 0000000000..3d1b7835e6 --- /dev/null +++ b/openspec/changes/2473-app-token-permissions/specs/github-app-identity/spec.md @@ -0,0 +1,22 @@ +## ADDED Requirements + +### Requirement: Each installation token asks only for the roadmap jobs' permissions +A process that acts as the App SHALL send the body `{"permissions": CONST_GITHUB_APP_TOKEN_PERMISSIONS}` with each exchange at `POST /app/installations//access_tokens`. The constant SHALL give `issues`, `pull_requests` and `contents` the level `write`, and `checks`, `actions` and `metadata` the level `read`. + +#### Scenario: The token request names the roadmap jobs' permissions +- **WHEN** the process acts as App 1001 on installation 42 and mints a token +- **THEN** the body of `POST /app/installations/42/access_tokens` is `{"permissions": {"issues": "write", "pull_requests": "write", "contents": "write", "checks": "read", "actions": "read", "metadata": "read"}}` + +### Requirement: The log names the minted token's permissions only +After GitHub gives a token, the process SHALL log the names of the permissions in GitHub's reply, sorted, without their levels and without the token. It SHALL use the token when the reply grants more permissions than the request asks for. + +#### Scenario: GitHub's reply grants one more permission +- **WHEN** GitHub's reply gives the token `ghs_first` with the six permissions and `administration: write` +- **THEN** the token is `ghs_first`, and one log record ends with `actions, administration, checks, contents, issues, metadata, pull_requests` and holds no `ghs_first`, `write` or `read` + +### Requirement: A refused permission names each permission that the token asks for +When GitHub answers the exchange with HTTP 422, the `GitHubUnauthenticatedError` SHALL name each permission that the token asks for, with its level, because GitHub's reply does not say which permission the installation does not grant. + +#### Scenario: The installation does not grant a permission that the token asks for +- **WHEN** GitHub answers the exchange with HTTP 422 and "The permissions requested are not granted to this installation." +- **THEN** the token lookup raises `GitHubUnauthenticatedError` whose message holds `devops-roadmap[bot]`, `HTTP 422` and `actions (read), checks (read), contents (write), issues (write), metadata (read), pull_requests (write)` diff --git a/openspec/changes/2473-app-token-permissions/tasks.md b/openspec/changes/2473-app-token-permissions/tasks.md new file mode 100644 index 0000000000..4888ad339d --- /dev/null +++ b/openspec/changes/2473-app-token-permissions/tasks.md @@ -0,0 +1,16 @@ +# Tasks + +## 1. Scope each installation token to the roadmap jobs' permissions + +- [x] Add failing tests: the exchange's body holds exactly the six permissions; a reply that grants one more keeps the token and logs only the permission names; a 422 names each permission that the token asks for + - Verification: `uv run devops ci test tests/test_github_app_identity.py` +- [x] Add `CONST_GITHUB_APP_TOKEN_PERMISSIONS`, post the exchange with its `permissions` body through gidgethub's `GitHubAPI`, log the names of the reply's permissions, and name the asked permissions on HTTP 422 + - Verification: `uv run devops ci test tests/test_github_app_identity.py` +- [x] Update ADR 0015, the "Roadmap service" text of `k8s/README.md` and the knowledge base's GitHub CLI page, and regenerate the documentation + - Verification: `uv run devops docs generate --sync-readme` + +## 2. Archive + +- [ ] Archive the change + - Verification: `uv run devops openspec archive 2473-app-token-permissions` +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/src/devops_cli/ai/knowledge_base/it_domains/tools/github_cli.md b/src/devops_cli/ai/knowledge_base/it_domains/tools/github_cli.md index 0599f033c5..c2a1e242b4 100644 --- a/src/devops_cli/ai/knowledge_base/it_domains/tools/github_cli.md +++ b/src/devops_cli/ai/knowledge_base/it_domains/tools/github_cli.md @@ -20,7 +20,7 @@ The GitHub CLI (`gh`) brings GitHub pull requests, issues, Actions workflows, re ## 2. Usage Information & Architecture -- **Token Authentication**: One GitHub identity per process: on the first GitHub call `gh auth token` runs once (it applies `GH_TOKEN`, then `GITHUB_TOKEN`, then gh's stored login), and every gh and git child gets that token as `GH_TOKEN`. `gh auth` subcommands are exempt and see the environment unchanged. In the cluster, a process whose environment holds `DEVOPS_CLI_SERVICE_GITHUB_APP_PRIVATE_KEY` acts as GitHub App `devops-cli-service` instead: it mints an installation token, mints a new one before the token expires, and gives the current token to each gh and git child as `GH_TOKEN` (ADR 0015). +- **Token Authentication**: One GitHub identity per process: on the first GitHub call `gh auth token` runs once (it applies `GH_TOKEN`, then `GITHUB_TOKEN`, then gh's stored login), and every gh and git child gets that token as `GH_TOKEN`. `gh auth` subcommands are exempt and see the environment unchanged. In the cluster, a process whose environment holds `DEVOPS_CLI_SERVICE_GITHUB_APP_PRIVATE_KEY` acts as GitHub App `devops-cli-service` instead: it mints an installation token that carries only the permissions the roadmap jobs use, whatever the App grants, mints a new one before the token expires, and gives the current token to each gh and git child as `GH_TOKEN` (ADR 0015). - **API Client**: Programmatic interaction via `src/devops_cli/github/client.py` and rate-managed CLI invocation via `run_gh([CONST_GH_CLI, ...])`. - **Active Monitoring**: When creating or updating PRs, DevOps CLI actively polls and verifies remote GitHub Actions check runs. - **CLI Subcommands**: `devops pr`, `devops gh` and `devops repos` commands wrap GitHub operations. diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index d972e92c26..766c64ad6e 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -1335,6 +1335,17 @@ CONST_GITHUB_APP_PRIVATE_KEY_ENV: Final[str] = "DEVOPS_CLI_SERVICE_GITHUB_APP_PRIVATE_KEY" # How an App installation names its quota ledger: one ledger for every token of the installation. CONST_GITHUB_APP_LEDGER_KEY: Final[str] = "app-installation-{installation_id}" +# The permissions that each installation token of the App asks for: those the roadmap jobs use +# (ADR 0015). The token carries only these, whatever the installation grants. GitHub refuses a +# token with HTTP 422 when the installation does not grant one of them (#2473). +CONST_GITHUB_APP_TOKEN_PERMISSIONS: Final[dict[str, str]] = { + "issues": "write", + "pull_requests": "write", + "contents": "write", + "checks": "read", + "actions": "read", + "metadata": "read", +} # GitHub's commit email of an account, `+@users.noreply.github.com`, for a bot too. CONST_GITHUB_NOREPLY_EMAIL: Final[str] = "{account_id}+{login}@users.noreply.github.com" # Hex characters of the identity key's SHA-256 that name an identity's cache directory. diff --git a/src/devops_cli/github/app_installation.py b/src/devops_cli/github/app_installation.py index 7ce08950fa..8905c55dce 100644 --- a/src/devops_cli/github/app_installation.py +++ b/src/devops_cli/github/app_installation.py @@ -3,30 +3,38 @@ A process acts as the App when its environment holds the App's private key, `DEVOPS_CLI_SERVICE_GITHUB_APP_PRIVATE_KEY`, as Secret `devops/devops-cli` gives it to the cluster's pods. The App's ID, its installation's ID and its slug come from `service.github_app`. -gidgethub signs a JWT with the key and exchanges it for an installation token -(`gidgethub.apps.get_installation_access_token`), over the session's client, so the request goes -to GitHub's API origin only. `core.process` keeps the token, gives it to every gh and git child -and mints a new one before it expires. The App's login is its bot's, `[bot]`: an -installation token cannot read `GET /user`. +gidgethub signs a JWT with the key, and the process exchanges it for an installation token at +`POST /app/installations//access_tokens`, over the session's client, so the request goes to +GitHub's API origin only. The request asks for `CONST_GITHUB_APP_TOKEN_PERMISSIONS` only, the +permissions the roadmap jobs use, so the token carries no other permission that the installation +grants (#2473). `gidgethub.apps.get_installation_access_token` sends no body, so the process +posts the request through gidgethub's `GitHubAPI`. `core.process` keeps the token, gives it to +every gh and git child and mints a new one before it expires. The App's login is its bot's, +`[bot]`: an installation token cannot read `GET /user`. """ from __future__ import annotations +import logging import os from dataclasses import dataclass, field from datetime import datetime +from http import HTTPStatus from typing import Any from devops_cli.config import options as opt from devops_cli.config.constants import ( CONST_GITHUB_APP_LEDGER_KEY, CONST_GITHUB_APP_PRIVATE_KEY_ENV, + CONST_GITHUB_APP_TOKEN_PERMISSIONS, CONST_GITHUB_USER_AGENT, CONST_URL_GITHUB_API_BASE, ) from devops_cli.exceptions import ConfigurationError from devops_cli.lang import ERRORS +logger = logging.getLogger(__name__) + @dataclass(frozen=True) class GitHubApp: @@ -80,8 +88,12 @@ def configured_app() -> GitHubApp: def mint_installation_token() -> tuple[str, str, datetime | None]: """A new installation token of the App and when it expires, or "" and why GitHub gave none. + The token carries only `CONST_GITHUB_APP_TOKEN_PERMISSIONS`, and the log names the + permissions of GitHub's reply, without their levels. A reply that grants more is no error. The reason names the request and GitHub's status, or says that the key could not sign a JWT; - it never holds the key or a token. + it never holds the key or a token. GitHub refuses with HTTP 422 a permission that the + installation does not grant, and its reply does not say which, so the reason then names each + permission that the token asks for. """ import httpx2 from gidgethub import HTTPException @@ -92,18 +104,41 @@ def mint_installation_token() -> tuple[str, str, datetime | None]: app = configured_app() if not _is_rsa_private_key(app.private_key): return "", _token_failed(app, ERRORS.git.github_app_key_unreadable), None - path = f"/app/installations/{app.installation_id}/access_tokens" try: answer = _exchange(app) except DevOpsCLIError as refusal: return "", _token_failed(app, refusal.message), None except (HTTPException, httpx2.HTTPError, ValueError, LookupError) as error: - failure = classify_http_error(error, method="POST", path=path) - return "", _token_failed(app, failure.message), None + failure = classify_http_error(error, method="POST", path=_token_path(app)) + reason = failure.message + if failure.details.get("status") == HTTPStatus.UNPROCESSABLE_ENTITY: + reason = ERRORS.git.github_app_permissions_not_granted.format( + reason=reason, permissions=_asked_permissions() + ) + return "", _token_failed(app, reason), None try: - return str(answer["token"]), "", datetime.fromisoformat(answer["expires_at"]) + token, expires_at = str(answer["token"]), datetime.fromisoformat(answer["expires_at"]) except KeyError, TypeError, ValueError: return "", _token_failed(app, ERRORS.git.github_app_answer_unreadable), None + granted = answer.get("permissions") + logger.info( + "GitHub App %s has a new installation token with these permissions: %s", + app.bot_login, + ", ".join(sorted(granted)) if isinstance(granted, dict) else "", + ) + return token, "", expires_at + + +def _token_path(app: GitHubApp) -> str: + """Where the App exchanges its JWT for an installation token.""" + return f"/app/installations/{app.installation_id}/access_tokens" + + +def _asked_permissions() -> str: + """Each permission that the token asks for, with its level, as an error names them.""" + return ", ".join( + f"{name} ({level})" for name, level in sorted(CONST_GITHUB_APP_TOKEN_PERMISSIONS.items()) + ) def _is_rsa_private_key(pem: str) -> bool: @@ -128,26 +163,30 @@ def _token_failed(app: GitHubApp, reason: str) -> str: def _exchange(app: GitHubApp) -> dict[str, Any]: - """GitHub's answer to the exchange of the App's JWT for an installation token. + """GitHub's answer to the exchange of the App's JWT for an installation token that carries + only `CONST_GITHUB_APP_TOKEN_PERMISSIONS`. - It runs on a loop of its own, so a caller on any thread, an event loop's included, can wait - for it. + gidgethub signs the JWT with the App's ID and key. The exchange runs on a loop of its own, so + a caller on any thread, an event loop's included, can wait for it. """ from anyio.from_thread import start_blocking_portal - from gidgethub.apps import get_installation_access_token from gidgethub.httpx import GitHubAPI from devops_cli.github.session_transport import session_client async def exchange() -> dict[str, Any]: async with session_client() as client: - api = GitHubAPI(client, CONST_GITHUB_USER_AGENT, base_url=CONST_URL_GITHUB_API_BASE) - return await get_installation_access_token( - api, - installation_id=str(app.installation_id), + api = GitHubAPI( + client, + CONST_GITHUB_USER_AGENT, + base_url=CONST_URL_GITHUB_API_BASE, app_id=str(app.app_id), private_key=app.private_key, ) + answer: dict[str, Any] = await api.post( + _token_path(app), data={"permissions": dict(CONST_GITHUB_APP_TOKEN_PERMISSIONS)} + ) + return answer with start_blocking_portal() as portal: return portal.call(exchange) diff --git a/src/devops_cli/lang/en/errors.py b/src/devops_cli/lang/en/errors.py index 37bfd859d3..14b15f6ea9 100644 --- a/src/devops_cli/lang/en/errors.py +++ b/src/devops_cli/lang/en/errors.py @@ -51,6 +51,10 @@ class GitErrorMessages: "GitHub App {login} has no installation token: {reason}. Check the App ID, the " "installation ID and the private key in {key_env}." ) + github_app_permissions_not_granted: str = ( + "{reason} The installation must grant each permission that the token asks for: " + "{permissions}" + ) github_app_key_unreadable: str = "the private key is not an RSA private key in PEM form" github_app_answer_unreadable: str = "GitHub's answer holds no token and expiry time" diff --git a/tests/test_github_app_identity.py b/tests/test_github_app_identity.py index 554973e122..64ae9b54eb 100644 --- a/tests/test_github_app_identity.py +++ b/tests/test_github_app_identity.py @@ -6,6 +6,8 @@ from __future__ import annotations +import json +import logging import subprocess import time from collections.abc import Callable @@ -32,6 +34,15 @@ BOT_LOGIN = "devops-roadmap[bot]" MINT = "/app/installations/42/access_tokens" REPO = "/repos/example-org/app" +# The permissions the roadmap jobs use (ADR 0015), which each token asks for. +ROADMAP_PERMISSIONS = { + "issues": "write", + "pull_requests": "write", + "contents": "write", + "checks": "read", + "actions": "read", + "metadata": "read", +} @pytest.fixture(scope="module") @@ -66,10 +77,16 @@ def app_identity( return github_api -def _installation_token(token: str, expires_in: timedelta) -> httpx2.Response: - """GitHub's answer to the exchange: the token, and when it expires.""" +def _installation_token( + token: str, expires_in: timedelta, permissions: dict[str, str] | None = None +) -> httpx2.Response: + """GitHub's answer to the exchange: the token, when it expires and, when given, the + permissions it carries.""" expires_at = (datetime.now(UTC) + expires_in).strftime("%Y-%m-%dT%H:%M:%SZ") - return github_json({"token": token, "expires_at": expires_at}, status=201) + answer: dict[str, Any] = {"token": token, "expires_at": expires_at} + if permissions is not None: + answer["permissions"] = permissions + return github_json(answer, status=201) def _finished(*_args: Any, **_kwargs: Any) -> subprocess.CompletedProcess[str]: @@ -103,6 +120,59 @@ def test_the_app_mints_an_installation_token_and_a_new_one_before_it_expires( ) +def test_the_token_request_asks_only_for_the_permissions_the_roadmap_jobs_use( + app_identity: GitHubApiFake, +) -> None: + """The installation may grant more, but the exchange's body names only the roadmap jobs' + permissions, so the token carries no other one (#2473).""" + app_identity.route("POST", MINT, _installation_token("ghs_first", timedelta(hours=1))) + github_token() + assert json.loads(app_identity.sent[0].content) == {"permissions": ROADMAP_PERMISSIONS} + + +def test_a_reply_that_grants_more_keeps_the_token_and_logs_only_the_permission_names( + app_identity: GitHubApiFake, caplog: pytest.LogCaptureFixture +) -> None: + """GitHub's reply names the token's permissions. A reply that grants one more is no error, + and the log names the permissions but not their levels or the token.""" + granted = {**ROADMAP_PERMISSIONS, "administration": "write"} + app_identity.route( + "POST", MINT, _installation_token("ghs_first", timedelta(hours=1), permissions=granted) + ) + with caplog.at_level(logging.INFO, logger="devops_cli.github.app_installation"): + token = github_token() + names = "actions, administration, checks, contents, issues, metadata, pull_requests" + logged = [r.getMessage() for r in caplog.records if r.name.endswith("app_installation")] + assert ( + token, + [message.endswith(names) for message in logged], + [any(word in message for word in ("ghs_first", "write", "read")) for message in logged], + ) == ("ghs_first", [True], [False]) + + +def test_an_installation_without_a_requested_permission_fails_naming_the_permissions( + app_identity: GitHubApiFake, +) -> None: + """GitHub refuses a permission that the installation does not grant with HTTP 422, and its + reply does not say which one, so the error names each permission that the token asks for.""" + app_identity.route( + "POST", + MINT, + github_json( + {"message": "The permissions requested are not granted to this installation."}, + status=422, + ), + ) + with pytest.raises(GitHubUnauthenticatedError) as raised: + github_token() + assert ( + BOT_LOGIN in raised.value.message, + "HTTP 422" in raised.value.message, + "actions (read), checks (read), contents (write), issues (write), metadata (read), " + "pull_requests (write)" in raised.value.message, + ) == (True, True, True) + + def test_the_apps_login_is_its_bot_and_no_get_user_is_sent(app_identity: GitHubApiFake) -> None: """The App's login comes from its slug; the session asks GitHub nothing for it.""" assert (get_github_session().login, app_identity.requested) == (BOT_LOGIN, []) From 93510d3e3679b38cb2d7663f7f6ef652b9931f14 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 28 Oct 2026 17:55:37 +0000 Subject: [PATCH 2/2] docs(openspec): archive 2473-app-token-permissions --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/github-app-identity/spec.md | 0 .../tasks.md | 2 +- openspec/specs/github-app-identity/spec.md | 21 +++++++++++++++++++ 6 files changed, 22 insertions(+), 1 deletion(-) rename openspec/changes/{2473-app-token-permissions => archive/2026-10-28-2473-app-token-permissions}/.openspec.yaml (100%) rename openspec/changes/{2473-app-token-permissions => archive/2026-10-28-2473-app-token-permissions}/design.md (100%) rename openspec/changes/{2473-app-token-permissions => archive/2026-10-28-2473-app-token-permissions}/proposal.md (100%) rename openspec/changes/{2473-app-token-permissions => archive/2026-10-28-2473-app-token-permissions}/specs/github-app-identity/spec.md (100%) rename openspec/changes/{2473-app-token-permissions => archive/2026-10-28-2473-app-token-permissions}/tasks.md (97%) diff --git a/openspec/changes/2473-app-token-permissions/.openspec.yaml b/openspec/changes/archive/2026-10-28-2473-app-token-permissions/.openspec.yaml similarity index 100% rename from openspec/changes/2473-app-token-permissions/.openspec.yaml rename to openspec/changes/archive/2026-10-28-2473-app-token-permissions/.openspec.yaml diff --git a/openspec/changes/2473-app-token-permissions/design.md b/openspec/changes/archive/2026-10-28-2473-app-token-permissions/design.md similarity index 100% rename from openspec/changes/2473-app-token-permissions/design.md rename to openspec/changes/archive/2026-10-28-2473-app-token-permissions/design.md diff --git a/openspec/changes/2473-app-token-permissions/proposal.md b/openspec/changes/archive/2026-10-28-2473-app-token-permissions/proposal.md similarity index 100% rename from openspec/changes/2473-app-token-permissions/proposal.md rename to openspec/changes/archive/2026-10-28-2473-app-token-permissions/proposal.md diff --git a/openspec/changes/2473-app-token-permissions/specs/github-app-identity/spec.md b/openspec/changes/archive/2026-10-28-2473-app-token-permissions/specs/github-app-identity/spec.md similarity index 100% rename from openspec/changes/2473-app-token-permissions/specs/github-app-identity/spec.md rename to openspec/changes/archive/2026-10-28-2473-app-token-permissions/specs/github-app-identity/spec.md diff --git a/openspec/changes/2473-app-token-permissions/tasks.md b/openspec/changes/archive/2026-10-28-2473-app-token-permissions/tasks.md similarity index 97% rename from openspec/changes/2473-app-token-permissions/tasks.md rename to openspec/changes/archive/2026-10-28-2473-app-token-permissions/tasks.md index 4888ad339d..babe285a1d 100644 --- a/openspec/changes/2473-app-token-permissions/tasks.md +++ b/openspec/changes/archive/2026-10-28-2473-app-token-permissions/tasks.md @@ -11,6 +11,6 @@ ## 2. Archive -- [ ] Archive the change +- [x] Archive the change - Verification: `uv run devops openspec archive 2473-app-token-permissions` - Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/openspec/specs/github-app-identity/spec.md b/openspec/specs/github-app-identity/spec.md index dd852131f7..cddaaa29ee 100644 --- a/openspec/specs/github-app-identity/spec.md +++ b/openspec/specs/github-app-identity/spec.md @@ -92,3 +92,24 @@ Secret `devops/devops-cli` SHALL hold `DEVOPS_CLI_SERVICE_GITHUB_APP_PRIVATE_KEY #### Scenario: The ConfigMap without the App's IDs - **WHEN** the active config sets `service.repos` and only `service.github_app.slug`, and the ConfigMap is rendered - **THEN** the render raises `KubernetesContextError` naming `service.github_app.app_id` and `service.github_app.installation_id` + +### Requirement: Each installation token asks only for the roadmap jobs' permissions +A process that acts as the App SHALL send the body `{"permissions": CONST_GITHUB_APP_TOKEN_PERMISSIONS}` with each exchange at `POST /app/installations//access_tokens`. The constant SHALL give `issues`, `pull_requests` and `contents` the level `write`, and `checks`, `actions` and `metadata` the level `read`. + +#### Scenario: The token request names the roadmap jobs' permissions +- **WHEN** the process acts as App 1001 on installation 42 and mints a token +- **THEN** the body of `POST /app/installations/42/access_tokens` is `{"permissions": {"issues": "write", "pull_requests": "write", "contents": "write", "checks": "read", "actions": "read", "metadata": "read"}}` + +### Requirement: The log names the minted token's permissions only +After GitHub gives a token, the process SHALL log the names of the permissions in GitHub's reply, sorted, without their levels and without the token. It SHALL use the token when the reply grants more permissions than the request asks for. + +#### Scenario: GitHub's reply grants one more permission +- **WHEN** GitHub's reply gives the token `ghs_first` with the six permissions and `administration: write` +- **THEN** the token is `ghs_first`, and one log record ends with `actions, administration, checks, contents, issues, metadata, pull_requests` and holds no `ghs_first`, `write` or `read` + +### Requirement: A refused permission names each permission that the token asks for +When GitHub answers the exchange with HTTP 422, the `GitHubUnauthenticatedError` SHALL name each permission that the token asks for, with its level, because GitHub's reply does not say which permission the installation does not grant. + +#### Scenario: The installation does not grant a permission that the token asks for +- **WHEN** GitHub answers the exchange with HTTP 422 and "The permissions requested are not granted to this installation." +- **THEN** the token lookup raises `GitHubUnauthenticatedError` whose message holds `devops-roadmap[bot]`, `HTTP 422` and `actions (read), checks (read), contents (write), issues (write), metadata (read), pull_requests (write)`