# The job token

> Use $BRANCHD_TOKEN with git and curl, ask for more with permissions:, and what it can never do.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

Every job gets `BRANCHD_TOKEN`, a short-lived token for its run. `git` uses it
without set-up, and branchd's API takes it as a bearer token. **It reads its
own repository and nothing else**: another repository, even one of the same
team, answers "not found", as it would for anyone who may not read it.
`permissions:` asks for more, in this repository only.

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# The job token, $BRANCHD_TOKEN, with nothing installed but curl and git.
# Without permissions: a job reads this repository and nothing else.
name: CI
on:
  push:
    branches: [main]
  pull_request:
jobs:
  test:
    image: golang:1.26
    steps:
      - run: go test -coverprofile=c.out ./... && go tool cover -func=c.out | tail -1 > summary.txt
    artifacts: [summary.txt]
  coverage:
    # Comment the coverage on the pull request: pull-requests: write is
    # under the default ceiling, so it works on the pull request's own run.
    if: event == 'pull_request'
    needs: [test]
    image: golang:1.26
    permissions: {pull-requests: write}
    steps:
      - run: |
          body=$(sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/\t/ /g' summary.txt | awk '{printf "%s\\n", $0}')
          curl -fsS -H "Authorization: Bearer $BRANCHD_TOKEN" -H 'Content-Type: application/json' \
            "$BRANCHD_API_URL/xeonr.forge.v1.ReviewService/CreateComment" \
            -d "{\"pullRequest\":\"$BRANCHD_REPOSITORY!$BRANCHD_PR\",\"body\":\"Coverage: $body\"}"
  tag:
    # Tag main's commit once the tests pass: contents: write on a
    # protected branch. git uses the token with no set-up.
    if: branch == 'main' && event == 'push'
    needs: [test]
    image: golang:1.26
    permissions: {contents: write}
    steps:
      - run: |
          git tag "build-$FORGE_RUN_NUMBER" "$FORGE_SHA"
          git push origin "build-$FORGE_RUN_NUMBER"
  report:
    # Report a check of your own on the commit.
    needs: [test]
    image: alpine:3.20
    permissions: {checks: write}
    steps:
      - run: |
          apk add --no-cache curl >/dev/null
          curl -fsS -H "Authorization: Bearer $($BRANCHD_TOKEN_COMMAND)" -H 'Content-Type: application/json' \
            "$BRANCHD_API_URL/xeonr.forge.v1.CheckService/CreateCheck" \
            -d "{\"repository\":\"$BRANCHD_REPOSITORY\",\"headOid\":\"$FORGE_SHA\",\"name\":\"coverage-recorded\",\"state\":\"CHECK_STATE_SUCCEEDED\"}"
```

```yaml title=".branchd/pipelines/nightly.yaml"
# .branchd/pipelines/nightly.yaml
# Every night, start this repository's Release pipeline on main with an
# input: pipelines: write. (Release's on: lists manual.)
name: Nightly
on:
  schedule:
    - name: nightly-release
      cron: '0 2 * * *'
jobs:
  kick:
    image: golang:1.26
    permissions: {pipelines: write}
    steps:
      - run: |
          curl -fsS -H "Authorization: Bearer $BRANCHD_TOKEN" -H 'Content-Type: application/json' \
            "$BRANCHD_API_URL/xeonr.forge.v1.RunService/CreateRun" \
            -d "{\"repository\":\"$BRANCHD_REPOSITORY\",\"ref\":\"main\",\"pipeline\":\"Release\",\"inputs\":{\"channel\":\"beta\"}}"
```

```yaml title=".branchd/pipelines/release.yaml"
# .branchd/pipelines/release.yaml
# Started by hand, or by the nightly job above, with its channel input.
name: Release
on:
  manual:
    inputs:
      channel:
        type: choice
        options: [stable, beta]
        default: beta
jobs:
  publish:
    image: golang:1.26
    steps:
      - run: echo "publishing to ${{ inputs.channel }}"
```

## Calling the API

Each call is an HTTP `POST` of JSON to
`$BRANCHD_API_URL/xeonr.forge.v1.<Service>/<Method>`, with
`Authorization: Bearer $BRANCHD_TOKEN` and `Content-Type: application/json`.
Fields are the request's, in lowerCamelCase. A repository is named by its path
(`$BRANCHD_REPOSITORY`), a pull request as `<path>!<number>`. A refusal is a
non-2xx answer whose JSON `message` says why; `curl -fsS` fails the step on
it.

- **A body built from text the job made must be valid JSON**: escape `\` and
  `"`, and turn tabs and newlines into spaces or `\n`, as the coverage job
  does with `sed` and `awk`.
- **A token lives for minutes.** `git` gets a fresh one when it needs one. A
  long job's later `curl` uses `"$($BRANCHD_TOKEN_COMMAND)"`, which prints a
  fresh token, as the `report` job does.
- **The variables:** `BRANCHD_TOKEN`; `BRANCHD_TOKEN_COMMAND`;
  `BRANCHD_API_URL` (branchd's API); `BRANCHD_REPOSITORY` (this repository's
  path); `BRANCHD_PR` (the pull request's number, on a pull request's run).
- **The CLI is not in the job.** Everything above is `curl` and `git`, which
  work on `golang:1.26` or any image with `curl` and a shell.

> **Not yet available** (cli in a job): the `branchd` CLI has no download a job can reach with its own token. It reads `BRANCHD_TOKEN` without set-up once it is on the `PATH`, so this changes when it has one.

## permissions:

| Permission        | `read`                                                                                                                                   | `write`                                                                                                                                                                                                                                    |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `contents`        | Always granted: this repository's commits, trees, blobs, diffs, branches and tags; `git fetch`.                                          | `git push`; creating and deleting branches and tags.                                                                                                                                                                                       |
| `pull-requests`   | Pull requests, their diffs, revisions, reviews and comments.                                                                             | Comment; edit and delete its own comments; resolve threads; a review that only comments; open, edit (not the target branch), close and reopen a pull request.                                                                              |
| `checks`          | Checks on commits.                                                                                                                       | Report a check on a commit (an external check: it never decides a merge).                                                                                                                                                                  |
| `releases`        | Releases and their files.                                                                                                                | Create, edit and delete releases; upload their files (`ReleaseService/CreateReleaseAsset`, the upload URL it answers, then `CompleteReleaseAsset`).                                                                                        |
| `packages`        | The repository's container images and generic packages, and the npm packages a CI grant lets it reach: list, pull, download and install. | Push images: `docker login -u job` with the token as the password. Publish [generic](https://docs.branchd.run/branchd/packages/generic#in-a-pipeline) and [npm](https://docs.branchd.run/branchd/packages/npm#in-a-pipeline) packages, and move their aliases and dist-tags; never delete. |
| `pipelines`       | Runs, their logs, plans and failures.                                                                                                    | Start, retry and cancel runs.                                                                                                                                                                                                              |
| `terraform-state` | This repository's [Terraform states](https://docs.branchd.run/branchd/terraform-state#in-a-pipeline).                                                            | Write them and take and release their locks; never delete.                                                                                                                                                                                 |

- **Where.** At the top of the file, `permissions:` is the default for every
  job; a job's own `permissions:` replaces it. With neither, `contents: read`.
- **Levels.** `read` or `write`; `write` includes `read`. An unknown name or
  level is refused with its line, and so is an empty `permissions:`.
- **Protected refs.** A `contents`, `releases`, `packages` or `terraform-state` write needs a
  protected ref, and a push or manual run by a person, an agent or the
  team's own bot. A scheduled or triggered run only reads them. Branch rules
  still apply to a push.
- **Pull requests and unprotected branches.** A pull request can change its
  own pipeline file, so on its run, and on any unprotected branch, writes are
  capped by the repository's ceiling: by default `pull-requests: write` and
  `checks: write`, and then only on that pull request and that commit. A
  repository's maintainers can lower the ceiling or add `pipelines` to it
  (the job token ceiling in its settings). Reads are never capped.
- **Never**, whatever is declared: change the repository's settings,
  variables, secrets, branch rules, members or visibility; approve, request
  changes on, merge or queue a pull request; release a manual job; write to
  another repository.
- **Called pipelines and composite steps.** A called pipeline's jobs get the
  calling job's permissions, and may narrow them, never widen them. A
  composite step runs with the permissions of the job that uses it.
- **Audit.** Every API call the token makes is recorded, allowed or refused,
  with the job, the permission and what it was limited to. A `git push` is
  recorded as a push by the job.

## Other repositories

The token reads another repository only where that repository grants it.
To use one:

- **its steps or pipelines**: `uses: <group>/<repo>/<path>@v1`
  ([Other repositories](https://docs.branchd.run/branchd/pipelines/other-repositories)), which
  branchd reads when the run is compiled;
- **its pipeline**: a `trigger:` job ([Trigger another repository](https://docs.branchd.run/branchd/pipelines/trigger-another-repository));
- **its packages** (images and generic packages): a
  [CI grant](https://docs.branchd.run/branchd/packages/access#another-repositorys-jobs) made
  there for this repository, which this job's own token then uses;
- **its Terraform states**: a [CI grant on the Terraform state area](https://docs.branchd.run/branchd/terraform-state#let-another-repositorys-jobs-in)
  made there, and `terraform-state: read` in this job's `permissions:`.
  `outputs` is enough for `terraform_remote_state`;
- **an npm scope or package**, which belongs to a group and not to a
  repository: a [CI grant on the scope or the package](https://docs.branchd.run/branchd/packages/npm#pipelines).
  A repository in the group that claimed the scope has one already;
- **its files at run time**: a [secret](https://docs.branchd.run/branchd/pipelines/secrets)
  holding a token that may read it.

A job also reads its team's private Go modules through branchd's module
proxy, with nothing to set up.

Source: https://docs.branchd.run/branchd/pipelines/job-token
