From 2ebc7e65adcd7c794acce12b874422a198b8c510 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Wed, 2 Dec 2026 15:17:33 +0100 Subject: [PATCH] Mint and renew the GitHub App installation tokens in tamis, so a run can last more than an hour --- README.md | 10 +- action.yml | 12 +- cmd/tamis/main.go | 59 ++++++++-- cmd/tamis/main_test.go | 83 ++++++++++++- docs/configuration.md | 8 +- docs/security.md | 3 +- docs/setup.md | 6 +- internal/github/app.go | 107 +++++++++++++++++ internal/github/app_test.go | 219 +++++++++++++++++++++++++++++++++++ internal/github/client.go | 35 +++++- internal/setup/setup.go | 12 +- internal/setup/setup_test.go | 17 +-- 12 files changed, 524 insertions(+), 47 deletions(-) create mode 100644 internal/github/app.go create mode 100644 internal/github/app_test.go diff --git a/README.md b/README.md index 028c8f1..5687035 100644 --- a/README.md +++ b/README.md @@ -109,13 +109,6 @@ jobs: permissions: contents: read steps: - - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 - id: app - with: - client-id: ${{ vars.TAMIS_CLIENT_ID }} - private-key: ${{ secrets.TAMIS_PRIVATE_KEY }} - owner: your-org - repositories: your-project - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: your-org/your-project @@ -129,7 +122,8 @@ jobs: since: "2026-10-22" advisory: ${{ inputs.advisory }} api-key: ${{ secrets.ANTHROPIC_API_KEY }} - github-token: ${{ steps.app.outputs.token }} + app-client-id: ${{ vars.TAMIS_CLIENT_ID }} + app-private-key: ${{ secrets.TAMIS_PRIVATE_KEY }} bot-login: your-app-slug[bot] # List every branch your project supports. Each ref must exist in the checkout. references: master origin/release-branch diff --git a/action.yml b/action.yml index 7d9f7e3..84772dd 100644 --- a/action.yml +++ b/action.yml @@ -25,8 +25,14 @@ inputs: description: Login the comments are posted as, required with a GitHub App token, e.g. `my-app[bot]`. Found through the token otherwise. required: false github-token: - description: Token able to read and comment the repository advisories. - required: true + description: Token able to read and comment the repository advisories. Required without `app-client-id`. + required: false + app-client-id: + description: Client ID of the GitHub App tamis mints its installation tokens with, in place of `github-token` and `issues-token`. tamis replaces each token before it expires, so a run can last more than the hour one token lasts. + required: false + app-private-key: + description: Private key of the GitHub App of `app-client-id`. + required: false repository: description: Repository owning the advisories. default: ${{ github.repository }} @@ -136,6 +142,8 @@ runs: MODEL: ${{ inputs.model }} LLM_API_KEY: ${{ inputs.api-key }} GH_TOKEN: ${{ inputs.github-token }} + APP_CLIENT_ID: ${{ inputs.app-client-id }} + APP_PRIVATE_KEY: ${{ inputs.app-private-key }} BOT_LOGIN: ${{ inputs.bot-login }} REPOSITORY: ${{ inputs.repository }} REPO_PATH: ${{ inputs.path }} diff --git a/cmd/tamis/main.go b/cmd/tamis/main.go index a7bc1b4..e11f7cb 100644 --- a/cmd/tamis/main.go +++ b/cmd/tamis/main.go @@ -194,16 +194,9 @@ func run(ctx context.Context, log *slog.Logger) error { if cfg.Repo == "" { return errors.New("REPOSITORY is required") } - token := os.Getenv("GH_TOKEN") - if token == "" { - return errors.New("GH_TOKEN is required") - } - if cfg.IssuesRepository != "" { - issues := os.Getenv("ISSUES_TOKEN") - if issues == "" || issues == token { - return errors.New("ISSUES_REPOSITORY needs an ISSUES_TOKEN of its own, which only reaches that repository") - } - cfg.Issues = github.New(issues) + gh, err := githubClients(&cfg) + if err != nil { + return err } if v := os.Getenv("CLOSE_DUPLICATES"); v != "" { if cfg.CloseDuplicates, err = strconv.ParseBool(v); err != nil { @@ -242,7 +235,51 @@ func run(ctx context.Context, log *slog.Logger) error { defer reader.Close() reader.Daybreak = daybreak - return triage.Run(ctx, cfg, github.New(token), reader, log) + return triage.Run(ctx, cfg, gh, reader, log) +} + +// githubClients returns the client of the advisories and the board, and sets the one that writes the issues. +// With the credentials of a GitHub App, tamis mints the tokens itself and replaces them before they expire. +func githubClients(cfg *triage.Config) (*github.Client, error) { + clientID, key := os.Getenv("APP_CLIENT_ID"), os.Getenv("APP_PRIVATE_KEY") + // docker and git inherit the environment, and the key never expires. + os.Unsetenv("APP_PRIVATE_KEY") + if clientID == "" && key == "" { + token := os.Getenv("GH_TOKEN") + if token == "" { + return nil, errors.New("GH_TOKEN, or APP_CLIENT_ID and APP_PRIVATE_KEY, are required") + } + if cfg.IssuesRepository != "" { + issues := os.Getenv("ISSUES_TOKEN") + if issues == "" || issues == token { + return nil, errors.New("ISSUES_REPOSITORY needs an ISSUES_TOKEN of its own, which only reaches that repository") + } + cfg.Issues = github.New(issues) + } + + return github.New(token), nil + } + if clientID == "" || key == "" { + return nil, errors.New("APP_CLIENT_ID and APP_PRIVATE_KEY go together") + } + if os.Getenv("GH_TOKEN") != "" || os.Getenv("ISSUES_TOKEN") != "" { + return nil, errors.New("GH_TOKEN and ISSUES_TOKEN must stay unset with APP_CLIENT_ID") + } + app, err := github.NewAppKey(clientID, key) + if err != nil { + return nil, err + } + if cfg.IssuesRepository == "" { + return app.Client([]string{cfg.Repo}, nil) + } + // Only the issues token writes issues, and it cannot reach the repository of the advisories. + issues, err := app.Client([]string{cfg.IssuesRepository}, map[string]string{"issues": "write", "organization_projects": "write"}) + if err != nil { + return nil, err + } + cfg.Issues = issues + + return app.Client([]string{cfg.Repo, cfg.IssuesRepository}, map[string]string{"repository_advisories": "write", "organization_projects": "write", "issues": "read"}) } func parseSince(v string) (time.Time, error) { diff --git a/cmd/tamis/main_test.go b/cmd/tamis/main_test.go index 239a8ea..c13d521 100644 --- a/cmd/tamis/main_test.go +++ b/cmd/tamis/main_test.go @@ -2,12 +2,22 @@ package main import ( "context" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/json" + "encoding/pem" + "fmt" "io" "log/slog" + "net/http" + "net/http/httptest" "os" "testing" "time" + "github.com/php/tamis/internal/github" + "github.com/php/tamis/internal/triage" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.yaml.in/yaml/v3" @@ -55,13 +65,23 @@ func TestSelectAgent(t *testing.T) { func TestRunValidatesConfiguration(t *testing.T) { log := slog.New(slog.NewTextHandler(io.Discard, nil)) + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + key := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(rsaKey)})) for name, tc := range map[string]struct { env map[string]string want string }{ "since required": {map[string]string{"REPOSITORY": "o/r", "GH_TOKEN": "t", "LLM_API_KEY": "k", "COMMENT": "true"}, "SINCE is required with COMMENT"}, "since optional": {map[string]string{"REPOSITORY": "o/r", "GH_TOKEN": "t", "LLM_API_KEY": "k"}, "OUTPUT_DIR is required"}, - "token required": {map[string]string{"REPOSITORY": "o/r", "SINCE": "2026-10-22", "LLM_API_KEY": "k"}, "GH_TOKEN is required"}, + "token required": {map[string]string{"REPOSITORY": "o/r", "SINCE": "2026-10-22", "LLM_API_KEY": "k"}, "GH_TOKEN, or APP_CLIENT_ID and APP_PRIVATE_KEY, are required"}, + "app key alone": {map[string]string{"REPOSITORY": "o/r", "LLM_API_KEY": "k", "APP_PRIVATE_KEY": key}, "APP_CLIENT_ID and APP_PRIVATE_KEY go together"}, + "app client id alone": {map[string]string{"REPOSITORY": "o/r", "LLM_API_KEY": "k", "APP_CLIENT_ID": "Iv1"}, "APP_CLIENT_ID and APP_PRIVATE_KEY go together"}, + "app and token": {map[string]string{"REPOSITORY": "o/r", "LLM_API_KEY": "k", "APP_CLIENT_ID": "Iv1", "APP_PRIVATE_KEY": key, "GH_TOKEN": "t"}, "GH_TOKEN and ISSUES_TOKEN must stay unset with APP_CLIENT_ID"}, + "app and issues token": {map[string]string{"REPOSITORY": "o/r", "LLM_API_KEY": "k", "APP_CLIENT_ID": "Iv1", "APP_PRIVATE_KEY": key, "ISSUES_REPOSITORY": "o/r-security", "ISSUES_TOKEN": "t"}, "GH_TOKEN and ISSUES_TOKEN must stay unset with APP_CLIENT_ID"}, + "invalid app key": {map[string]string{"REPOSITORY": "o/r", "LLM_API_KEY": "k", "APP_CLIENT_ID": "Iv1", "APP_PRIVATE_KEY": "key"}, "the App private key is not PEM encoded"}, + "app on two owners": {map[string]string{"REPOSITORY": "o/r", "LLM_API_KEY": "k", "APP_CLIENT_ID": "Iv1", "APP_PRIVATE_KEY": key, "ISSUES_REPOSITORY": "other/r-security"}, "o/r and other/r-security must be repositories of the same owner"}, + "app accepted": {map[string]string{"REPOSITORY": "o/r", "LLM_API_KEY": "k", "APP_CLIENT_ID": "Iv1", "APP_PRIVATE_KEY": key, "ISSUES_REPOSITORY": "o/r-security"}, "OUTPUT_DIR is required"}, "api key required": {map[string]string{"REPOSITORY": "o/r", "SINCE": "2026-10-22", "GH_TOKEN": "t"}, "LLM_API_KEY is required"}, "invalid daybreak": {map[string]string{"REPOSITORY": "o/r", "SINCE": "2026-10-22", "GH_TOKEN": "t", "LLM_API_KEY": "k", "DAYBREAK": "maybe"}, "DAYBREAK"}, "daybreak needs openai": {map[string]string{"REPOSITORY": "o/r", "SINCE": "2026-10-22", "GH_TOKEN": "t", "LLM_API_KEY": "k", "DAYBREAK": "true"}, "DAYBREAK requires ENGINE=openai"}, @@ -75,11 +95,70 @@ func TestRunValidatesConfiguration(t *testing.T) { "references required": {map[string]string{"REPOSITORY": "o/r", "SINCE": "2026-10-22", "GH_TOKEN": "t", "LLM_API_KEY": "k", "OUTPUT_DIR": t.TempDir()}, "REFERENCES must list"}, } { t.Run(name, func(t *testing.T) { - for _, k := range []string{"REPOSITORY", "GITHUB_REPOSITORY", "ADVISORY", "REPO_PATH", "BOT_LOGIN", "DAYBREAK", "SINCE", "GH_TOKEN", "ENGINE", "MODEL", "LLM_API_KEY", "OUTPUT_DIR", "REFERENCES", "PROJECT", "ISSUES_REPOSITORY", "ISSUES_TOKEN", "CLOSE_DUPLICATES", "COMMENT", "PACKS", "FORCE"} { + for _, k := range []string{"REPOSITORY", "GITHUB_REPOSITORY", "ADVISORY", "REPO_PATH", "BOT_LOGIN", "DAYBREAK", "SINCE", "GH_TOKEN", "ENGINE", "MODEL", "LLM_API_KEY", "OUTPUT_DIR", "REFERENCES", "PROJECT", "ISSUES_REPOSITORY", "ISSUES_TOKEN", "CLOSE_DUPLICATES", "COMMENT", "PACKS", "FORCE", "APP_CLIENT_ID", "APP_PRIVATE_KEY"} { t.Setenv(k, tc.env[k]) } require.ErrorContains(t, run(context.Background(), log), tc.want) + assert.Empty(t, os.Getenv("APP_PRIVATE_KEY"), "the App private key stays in the environment docker and git inherit") + }) + } +} + +func TestGitHubClientsScopeTheAppTokens(t *testing.T) { + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + key := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(rsaKey)})) + for name, tc := range map[string]struct { + issues string + want map[string]any + }{ + "with issues": {"o/r-security", map[string]any{ + "o/r": map[string]any{"repositories": []any{"r", "r-security"}, "permissions": map[string]any{"repository_advisories": "write", "organization_projects": "write", "issues": "read"}}, + "o/r-security": map[string]any{"repositories": []any{"r-security"}, "permissions": map[string]any{"issues": "write", "organization_projects": "write"}}, + }}, + "without issues": {"", map[string]any{"o/r": map[string]any{"repositories": []any{"r"}}}}, + } { + t.Run(name, func(t *testing.T) { + // Each repository gets an installation of its own, so a minted token names the client it went to. + installations := map[string]string{"/repos/o/r/installation": "1", "/repos/o/r-security/installation": "2"} + owners := map[string]string{"/app/installations/1/access_tokens": "o/r", "/app/installations/2/access_tokens": "o/r-security"} + minted := map[string]any{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if id, ok := installations[r.URL.Path]; ok { + fmt.Fprintf(w, `{"id":%s}`, id) + return + } + if repo, ok := owners[r.URL.Path]; ok { + var body map[string]any + assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + minted[repo] = body + fmt.Fprintf(w, `{"token":"t","expires_at":%q}`, time.Now().Add(time.Hour).UTC().Format(time.RFC3339)) + return + } + fmt.Fprint(w, `{"login":"acme-tamis[bot]"}`) + })) + t.Cleanup(srv.Close) + for k, v := range map[string]string{"APP_CLIENT_ID": "Iv1", "APP_PRIVATE_KEY": key, "GH_TOKEN": "", "ISSUES_TOKEN": ""} { + t.Setenv(k, v) + } + cfg := triage.Config{Repo: "o/r", IssuesRepository: tc.issues} + + gh, err := githubClients(&cfg) + require.NoError(t, err) + clients := []*github.Client{gh} + if tc.issues != "" { + clients = append(clients, cfg.Issues.(*github.Client)) + } else { + assert.Nil(t, cfg.Issues, "an issues client without an issues repository") + } + for _, c := range clients { + c.BaseURL, c.HTTP = srv.URL, srv.Client() + _, err := c.Login(t.Context()) + require.NoError(t, err) + } + + assert.Equal(t, tc.want, minted) }) } } diff --git a/docs/configuration.md b/docs/configuration.md index 1a5ba41..af1ec86 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -5,7 +5,9 @@ | Input | Default | Description | |---|---|---| | `api-key` | | Required. API key of the model provider, or a Codex access token with `engine: openai`. | -| `github-token` | | Required. Token able to read and comment the repository advisories, and to write `project`. | +| `app-client-id` | | Client ID of the GitHub App tamis mints its installation tokens with, in place of `github-token` and `issues-token`. tamis replaces each token before it expires, so a run can last more than the hour one token lasts. | +| `app-private-key` | | Private key of the App of `app-client-id`. | +| `github-token` | | Required without `app-client-id`. Token able to read and comment the repository advisories, and to write `project`. An installation token expires after an hour, and every GitHub request of the run fails after it. | | `references` | | Required, at most ten. Whitespace-separated local git references, one per supported branch. tamis analyses the first and locates the cited code on it. A missing reference fails the analysis. | | `packs` | | Whitespace-separated [guidance packs](#guidance-packs) added to the agent's method, such as `php-src`. An unknown pack fails the run. | | `since` | | Triage only advisories created after this date, `2026-10-22` or RFC 3339. Required with `comment: true` unless `advisory` is set, so existing advisories get no comment. Without it, every advisory in triage goes on the board. | @@ -19,13 +21,13 @@ | `comment` | `false` | With `issues-repository`, post on each advisory a comment linking it to the issue tamis creates for it. | | `project` | | Required. Private organisation project the triages go on, as `org/number`, which records the failed attempts in `Attempts`. See [the project board](setup.md#5-project-board). | | `issues-repository` | | Private repository the board items are created in as issues, so duplicates become sub-issues of their original report. Drafts when unset. See [the project board](setup.md#5-project-board). | -| `issues-token` | | Installation token for `issues-repository` only, with the "Issues" and organisation "Projects" permissions in read and write. Required with `issues-repository`. | +| `issues-token` | | Installation token for `issues-repository` only, with the "Issues" and organisation "Projects" permissions in read and write. Required with `issues-repository` and `github-token`. | | `close-duplicates` | `false` | Closes the advisory of an issue a maintainer closed as a duplicate. Needs `issues-repository`. See [the project board](setup.md#5-project-board). | | `runner-image` | tamis agent image, pinned by digest | Image the agent runs in. It must contain the agent CLI, git, curl and `harness-proxy`. The action skips the attestation check for a custom image. | The action refuses to run from a public workflow repository or from a `uses:` that is not a full commit SHA. Update that SHA through a reviewed pull request. -Outside GitHub Actions, tamis reads the same settings from environment variables: `LLM_API_KEY`, `GH_TOKEN`, `BOT_LOGIN`, `REPOSITORY`, `REPO_PATH`, `SINCE`, `ADVISORY`, `ENGINE`, `MODEL`, `DAYBREAK`, `RUNNER_IMAGE`, `REFERENCES`, `PROJECT`, `ISSUES_REPOSITORY`, `ISSUES_TOKEN`, `CLOSE_DUPLICATES`, `COMMENT` and `PACKS`. `OUTPUT_DIR` must name a private directory for the reports. The action creates it in the runner's temporary storage and uploads it to the workflow repository with a seven-day retention. +Outside GitHub Actions, tamis reads the same settings from environment variables: `LLM_API_KEY`, `GH_TOKEN`, `APP_CLIENT_ID`, `APP_PRIVATE_KEY`, `BOT_LOGIN`, `REPOSITORY`, `REPO_PATH`, `SINCE`, `ADVISORY`, `ENGINE`, `MODEL`, `DAYBREAK`, `RUNNER_IMAGE`, `REFERENCES`, `PROJECT`, `ISSUES_REPOSITORY`, `ISSUES_TOKEN`, `CLOSE_DUPLICATES`, `COMMENT` and `PACKS`. `OUTPUT_DIR` must name a private directory for the reports. The action creates it in the runner's temporary storage and uploads it to the workflow repository with a seven-day retention. A local run alone also reads `FORCE=true`, which triages every selected advisory again, `ADVISORY` alone or every one in triage, and updates its board item even when it already holds a triage. A failed new triage leaves the previous one on the board. The action has no such input. diff --git a/docs/security.md b/docs/security.md index 2419002..3816efb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -7,7 +7,7 @@ tamis reads text from an outside reporter, holds access to embargoed advisories | Threat | Mitigation | |---|---| | A prompt injection makes the agent leak other advisories | See [Duplicate search isolation](#duplicate-search-isolation). | -| The agent leaks secrets | The container holds no secret. The model key stays on the runner, the GitHub token never enters the container, and the container gets only the selected commit and its history, with an empty `.git/config`. | +| The agent leaks secrets | The container holds no secret. The model key stays on the runner, the GitHub token and the App private key never enter the container, and the container gets only the selected commit and its history, with an empty `.git/config`. | | The agent exfiltrates data over the network | The container sits on an isolated internal network and only reaches a private egress sidecar. Public GitHub access is a read-only service with no credentials or redirects. The model proxy pins the model and rejects remote URLs, remote MCP servers, hosted tools, stored conversations and background calls. | | The triage loads a remote image carrying data, or pings people | tamis escapes all model text: no links, images, HTML, entities or mentions. | | A report changes during triage | tamis hashes the title, description, metadata and non-bot comments, reads them again before publication and publishes nothing when the revision changed. It does not triage a completed advisory again after a later edit. | @@ -73,6 +73,7 @@ tamis turns off the Codex ChatGPT features that call other routes: plugins, apps - An internal network without a host gateway needs Docker Engine 28 or newer. - The agent CLI state is a writable host directory, removed after each advisory. A run can rewrite its own configuration for the correction round and fill the runner disk, though not leave the network or the model proxy. - The advisory comments API is in public preview and may change. +- With `app-private-key`, tamis holds the App key in memory for the whole run, where a token step holds it for a moment. tamis removes it from the environment docker and git inherit, but a compromised runner exposes a key that works until it is rotated, not a token that expires within the hour. CI builds both agent images and runs the Docker isolation tests on `ubuntu-latest`. They test the model path, direct and proxied host access, DNS, and IPv4 and IPv6 egress, without real provider credentials. Treat both `isolation` jobs as required checks before releasing or updating the deployment SHA. diff --git a/docs/setup.md b/docs/setup.md index f3f8324..611655b 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -110,7 +110,9 @@ Deleting an item by hand triggers a new triage of its advisory on the next run. With `issues-repository` set, for example to `your-org/your-project-security`, new items are issues of that repository instead of drafts, and each duplicate becomes a sub-issue of its `Original report`. Once that report leaves `triage` and `draft`, its duplicates still waiting move under the oldest of them, so a view filtered on `State` shows them, and that issue gets a comment naming the report it left. tamis closes an issue when its advisory is published, closed or withdrawn. Everyone with access to that repository reads the reports, and each new issue notifies its watchers. tamis refuses a public repository and the repository of the advisories, and then leaves the board out of the run. -tamis writes the issues and adds them to the project with `issues-token`, a second installation token that reaches the issues repository only, and refuses it when it also reaches `repository`. `github-token` updates the fields of the items, so it reads the issues repository too, but keep its "Issues" permission at read, so neither token can open an issue on the project: +tamis writes the issues and adds them to the project with a second installation token that reaches the issues repository only, and refuses it when it also reaches `repository`. The main token updates the fields of the items, so it reads the issues repository too, with its "Issues" permission at read, so neither token can open an issue on the project. With `app-client-id`, tamis mints both tokens that way itself. The App needs the "Issues" permission in read and write and an installation on the issues repository. + +With `github-token` instead, mint both tokens in the workflow: ```yaml - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 @@ -134,7 +136,7 @@ tamis writes the issues and adds them to the project with `issues-token`, a seco permission-organization-projects: write ``` -Then pass `issues-token: ${{ steps.issues.outputs.token }}`. The App needs the "Issues" permission in read and write and an installation on the issues repository. +Then pass `github-token: ${{ steps.app.outputs.token }}` and `issues-token: ${{ steps.issues.outputs.token }}`. Both expire after an hour, and a run that lasts longer fails its remaining GitHub requests. With `close-duplicates: true`, closing an issue as a duplicate decides its report. At the start of the next run, tamis credits the reporter as `reporter` on the `Original report` of the issue when that report is still in `triage` or `draft`, comments on the advisory to name that report, and closes it. A note on the issue then names the original and the login credited on it. Reopening the advisory afterwards reopens its issue, and tamis leaves both open. The original is always the one of `Original report`, whichever issue the duplicate was closed against, and an advisory without one stays as it is. The comment names the original even under embargo, and whoever can close an issue of that repository can then close an advisory. diff --git a/internal/github/app.go b/internal/github/app.go new file mode 100644 index 0000000..52019af --- /dev/null +++ b/internal/github/app.go @@ -0,0 +1,107 @@ +package github + +import ( + "context" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "net/http" + "strings" + "time" +) + +// renewBefore is how long before its expiry an installation token is replaced. GitHub makes them last one hour. +const renewBefore = 5 * time.Minute + +// AppKey mints installation tokens of a GitHub App, so a run can outlast the hour one token lasts. +type AppKey struct { + ClientID string + Key *rsa.PrivateKey +} + +// NewAppKey reads the PEM private key GitHub generates for an App. +func NewAppKey(clientID, privateKey string) (*AppKey, error) { + block, _ := pem.Decode([]byte(privateKey)) + if block == nil { + return nil, errors.New("the App private key is not PEM encoded") + } + key, err := x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, errors.New("the App private key is not the RSA key GitHub generates") + } + + return &AppKey{ClientID: clientID, Key: key}, nil +} + +// Client returns a client whose token reaches repositories only, and is replaced before it expires. Without +// permissions, the token holds every permission of the App. The repositories share one owner, whose installation +// of the App mints the tokens. +func (a *AppKey) Client(repositories []string, permissions map[string]string) (*Client, error) { + owner, _, _ := strings.Cut(repositories[0], "/") + names := make([]string, len(repositories)) + for i, r := range repositories { + o, name, ok := strings.Cut(r, "/") + if !ok || !strings.EqualFold(o, owner) || name == "" { + return nil, fmt.Errorf("%s and %s must be repositories of the same owner", repositories[0], r) + } + names[i] = name + } + + var installation int64 + c := New("") + c.renew = func(ctx context.Context) (string, time.Time, error) { + jwt, err := a.jwt() + if err != nil { + return "", time.Time{}, err + } + app := &Client{BaseURL: c.BaseURL, Token: jwt, HTTP: c.HTTP} + if installation == 0 { + var found struct { + ID int64 `json:"id"` + } + if _, err := app.do(ctx, http.MethodGet, fmt.Sprintf("%s/repos/%s/installation", c.BaseURL, repositories[0]), nil, &found); err != nil { + return "", time.Time{}, err + } + installation = found.ID + } + var minted struct { + Token string `json:"token"` + ExpiresAt time.Time `json:"expires_at"` + } + body := map[string]any{"repositories": names} + if permissions != nil { + body["permissions"] = permissions + } + _, err = app.do(ctx, http.MethodPost, fmt.Sprintf("%s/app/installations/%d/access_tokens", c.BaseURL, installation), body, &minted) + + return minted.Token, minted.ExpiresAt, err + } + + return c, nil +} + +// jwt authenticates as the App itself. GitHub refuses one that expires more than ten minutes ahead. +func (a *AppKey) jwt() (string, error) { + now := time.Now() + header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`)) + // iat is a minute in the past, so a clock slightly ahead of GitHub's does not void the token. + claims, err := json.Marshal(map[string]any{"iat": now.Add(-time.Minute).Unix(), "exp": now.Add(9 * time.Minute).Unix(), "iss": a.ClientID}) + if err != nil { + return "", err + } + signed := header + "." + base64.RawURLEncoding.EncodeToString(claims) + sum := sha256.Sum256([]byte(signed)) + sig, err := rsa.SignPKCS1v15(rand.Reader, a.Key, crypto.SHA256, sum[:]) + if err != nil { + return "", err + } + + return signed + "." + base64.RawURLEncoding.EncodeToString(sig), nil +} diff --git a/internal/github/app_test.go b/internal/github/app_test.go new file mode 100644 index 0000000..4656f5e --- /dev/null +++ b/internal/github/app_test.go @@ -0,0 +1,219 @@ +package github + +import ( + "context" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func newTestKey(t *testing.T) (*rsa.PrivateKey, string) { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + return key, string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})) +} + +// checkJWT fails the test unless auth carries a JWT of the App signed by key. +func checkJWT(t *testing.T, key *rsa.PrivateKey, auth string) { + t.Helper() + parts := strings.Split(strings.TrimPrefix(auth, "Bearer "), ".") + if !assert.Len(t, parts, 3, "not a JWT: %q", auth) { + return + } + sig, err := base64.RawURLEncoding.DecodeString(parts[2]) + assert.NoError(t, err) + sum := sha256.Sum256([]byte(parts[0] + "." + parts[1])) + assert.NoError(t, rsa.VerifyPKCS1v15(&key.PublicKey, crypto.SHA256, sum[:], sig), "the JWT is not signed by the App key") + raw, err := base64.RawURLEncoding.DecodeString(parts[1]) + assert.NoError(t, err) + var claims struct { + Iss string `json:"iss"` + Iat int64 `json:"iat"` + Exp int64 `json:"exp"` + } + assert.NoError(t, json.Unmarshal(raw, &claims)) + assert.Equal(t, "Iv1", claims.Iss) + assert.LessOrEqual(t, claims.Exp-claims.Iat, int64(600), "GitHub refuses a JWT living more than ten minutes") + assert.Greater(t, claims.Exp, time.Now().Unix()) +} + +// installation serves the installation of the App on o/r and mints tokens, the first one expiring after first. +func installation(t *testing.T, key *rsa.PrivateKey, first time.Duration, mints *atomic.Int32, minted func(body map[string]any)) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/repos/o/r/installation": + checkJWT(t, key, r.Header.Get("Authorization")) + fmt.Fprint(w, `{"id":42}`) + case r.Method == http.MethodPost && r.URL.Path == "/app/installations/42/access_tokens": + checkJWT(t, key, r.Header.Get("Authorization")) + var body map[string]any + assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + if minted != nil { + minted(body) + } + n := mints.Add(1) + expires := time.Now().Add(time.Hour) + if n == 1 { + expires = time.Now().Add(first) + } + fmt.Fprintf(w, `{"token":"tok%d","expires_at":%q}`, n, expires.UTC().Format(time.RFC3339)) + default: + fmt.Fprintf(w, `{"login":%q}`, r.Header.Get("Authorization")) + } + })) + t.Cleanup(srv.Close) + + return srv +} + +func testClient(t *testing.T, srv *httptest.Server, pemKey string, repositories []string, permissions map[string]string) *Client { + t.Helper() + app, err := NewAppKey("Iv1", pemKey) + require.NoError(t, err) + c, err := app.Client(repositories, permissions) + require.NoError(t, err) + c.BaseURL, c.HTTP = srv.URL, srv.Client() + + return c +} + +func TestAppClientMintsAScopedToken(t *testing.T) { + key, pemKey := newTestKey(t) + var mints atomic.Int32 + var body map[string]any + srv := installation(t, key, time.Hour, &mints, func(b map[string]any) { body = b }) + c := testClient(t, srv, pemKey, []string{"o/r", "O/r-security"}, map[string]string{"issues": "read"}) + + login, err := c.Login(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer tok1", login, "the request does not carry the minted token") + assert.Equal(t, map[string]any{"repositories": []any{"r", "r-security"}, "permissions": map[string]any{"issues": "read"}}, body) + + _, err = c.Login(context.Background()) + require.NoError(t, err) + assert.EqualValues(t, 1, mints.Load(), "a token far from its expiry was minted again") +} + +func TestAppClientWithoutPermissionsAsksForNone(t *testing.T) { + key, pemKey := newTestKey(t) + var mints atomic.Int32 + var body map[string]any + srv := installation(t, key, time.Hour, &mints, func(b map[string]any) { body = b }) + c := testClient(t, srv, pemKey, []string{"o/r"}, nil) + + _, err := c.Login(context.Background()) + require.NoError(t, err) + assert.Equal(t, map[string]any{"repositories": []any{"r"}}, body, "GitHub gives the token every permission of the App only without a permissions field") +} + +func TestAppClientRenewsATokenCloseToItsExpiry(t *testing.T) { + key, pemKey := newTestKey(t) + var mints atomic.Int32 + srv := installation(t, key, time.Minute, &mints, nil) + c := testClient(t, srv, pemKey, []string{"o/r"}, nil) + + first, err := c.Login(context.Background()) + require.NoError(t, err) + second, err := c.Login(context.Background()) + require.NoError(t, err) + third, err := c.Login(context.Background()) + require.NoError(t, err) + + assert.Equal(t, []string{"Bearer tok1", "Bearer tok2", "Bearer tok2"}, []string{first, second, third}) +} + +func TestAppClientKeepsTheTokenWhileARenewalFails(t *testing.T) { + _, pemKey := newTestKey(t) + var mints atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/o/r/installation": + fmt.Fprint(w, `{"id":42}`) + case "/app/installations/42/access_tokens": + if mints.Add(1) > 1 { + w.WriteHeader(http.StatusBadGateway) + return + } + fmt.Fprintf(w, `{"token":"tok1","expires_at":%q}`, time.Now().Add(time.Minute).UTC().Format(time.RFC3339)) + default: + fmt.Fprintf(w, `{"login":%q}`, r.Header.Get("Authorization")) + } + })) + t.Cleanup(srv.Close) + c := testClient(t, srv, pemKey, []string{"o/r"}, nil) + + for range 3 { + login, err := c.Login(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer tok1", login) + } + assert.EqualValues(t, 3, mints.Load(), "each request close to the expiry tries a renewal") +} + +func TestAppClientFailsWithoutAToken(t *testing.T) { + key, pemKey := newTestKey(t) + for name, status := range map[string]int{"no installation": http.StatusNotFound, "refused permissions": http.StatusUnprocessableEntity, "unavailable": http.StatusBadGateway} { + t.Run(name, func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + checkJWT(t, key, r.Header.Get("Authorization")) + if r.URL.Path == "/repos/o/r/installation" && status != http.StatusNotFound { + fmt.Fprint(w, `{"id":42}`) + return + } + if r.URL.Path != "/repos/o/r/installation" && r.URL.Path != "/app/installations/42/access_tokens" { + calls.Add(1) + } + w.WriteHeader(status) + })) + t.Cleanup(srv.Close) + c := testClient(t, srv, pemKey, []string{"o/r"}, map[string]string{"issues": "write"}) + + _, err := c.Login(context.Background()) + require.EqualError(t, err, fmt.Sprintf("renewing the installation token: github: HTTP %d", status)) + assert.NotErrorIs(t, err, ErrNotFound, "a missing installation reads as a missing resource") + assert.Zero(t, calls.Load(), "the request went out without a token") + }) + } +} + +func TestAppClientRefusesRepositoriesOfTwoOwners(t *testing.T) { + _, pemKey := newTestKey(t) + app, err := NewAppKey("Iv1", pemKey) + require.NoError(t, err) + + _, err = app.Client([]string{"o/r", "other/r-security"}, nil) + require.EqualError(t, err, "o/r and other/r-security must be repositories of the same owner") + _, err = app.Client([]string{"o/r", "r-security"}, nil) + require.Error(t, err, "a repository without its owner") +} + +func TestNewAppKeyRefusesAnotherKey(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + pkcs8, err := x509.MarshalPKCS8PrivateKey(key) + require.NoError(t, err) + + _, err = NewAppKey("Iv1", "not a key") + require.EqualError(t, err, "the App private key is not PEM encoded") + _, err = NewAppKey("Iv1", string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}))) + require.EqualError(t, err, "the App private key is not the RSA key GitHub generates") +} diff --git a/internal/github/client.go b/internal/github/client.go index bfe12da..aab360e 100644 --- a/internal/github/client.go +++ b/internal/github/client.go @@ -16,6 +16,7 @@ import ( "slices" "strconv" "strings" + "sync" "time" "golang.org/x/crypto/nacl/box" @@ -96,6 +97,11 @@ type Client struct { BaseURL string Token string HTTP *http.Client + + // renew mints the next token of an App installation, with its expiry. + renew func(ctx context.Context) (string, time.Time, error) + mu sync.Mutex + expires time.Time } func New(token string) *Client { @@ -673,7 +679,11 @@ func (c *Client) once(ctx context.Context, method, u string, body, out any) (*ht } req.Header.Set("Accept", "application/vnd.github+json") req.Header.Set("X-GitHub-Api-Version", "2022-11-28") - req.Header.Set("Authorization", "Bearer "+c.Token) + token, err := c.token(ctx) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+token) if body != nil { req.Header.Set("Content-Type", "application/json") } @@ -696,3 +706,26 @@ func (c *Client) once(ctx context.Context, method, u string, body, out any) (*ht return resp, nil } + +func (c *Client) token(ctx context.Context) (string, error) { + if c.renew == nil { + return c.Token, nil + } + c.mu.Lock() + defer c.mu.Unlock() + if time.Until(c.expires) > renewBefore { + return c.Token, nil + } + token, expires, err := c.renew(ctx) + if err != nil { + // The next request tries again, and GitHub accepts the current token until it expires. + if time.Until(c.expires) > 0 { + return c.Token, nil + } + // Not wrapped, since a status of the token request is not the status of the request it was renewed for. + return "", errors.New("renewing the installation token: " + err.Error()) + } + c.Token, c.expires = token, expires + + return token, nil +} diff --git a/internal/setup/setup.go b/internal/setup/setup.go index 91542a8..83ad4ae 100644 --- a/internal/setup/setup.go +++ b/internal/setup/setup.go @@ -123,7 +123,7 @@ func Run(ctx context.Context, cfg Config, gh GitHub, app AppFlow, out io.Writer) fmt.Fprintf(out, "Created the project board %s\n", project) var w strings.Builder if err := workflow.Execute(&w, map[string]any{ - "Org": org, "Name": name, "Repository": cfg.Repository, "SHA": sha, "Tag": tag, "Since": cfg.Since, + "Repository": cfg.Repository, "SHA": sha, "Tag": tag, "Since": cfg.Since, "Engine": cfg.Engine, "Secret": secret, "Slug": a.Slug, "References": strings.Join(cfg.References, " "), "Project": project, "Packs": strings.Join(cfg.Packs, " "), }); err != nil { @@ -160,13 +160,6 @@ jobs: permissions: contents: read steps: - - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 - id: app - with: - client-id: ${{ vars.TAMIS_CLIENT_ID }} - private-key: ${{ secrets.TAMIS_PRIVATE_KEY }} - owner: [[.Org]] - repositories: [[.Name]] - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: [[.Repository]] @@ -181,7 +174,8 @@ jobs: engine: openai [[- end]] api-key: ${{ secrets.[[.Secret]] }} - github-token: ${{ steps.app.outputs.token }} + app-client-id: ${{ vars.TAMIS_CLIENT_ID }} + app-private-key: ${{ secrets.TAMIS_PRIVATE_KEY }} bot-login: [[.Slug]][bot] references: [[.References]] [[- if .Packs]] diff --git a/internal/setup/setup_test.go b/internal/setup/setup_test.go index e9f3bb6..07ef7d7 100644 --- a/internal/setup/setup_test.go +++ b/internal/setup/setup_test.go @@ -148,14 +148,15 @@ func TestRunInstallsTamisWithItsBoard(t *testing.T) { require.Equal(t, map[string]string{"TAMIS_PRIVATE_KEY": "PEM", "ANTHROPIC_API_KEY": "sk-test"}, gh.secrets) with := step(t, gh.files["acme/tamis-runner/.github/workflows/tamis.yml"]) require.Equal(t, map[string]string{ - "repository": "acme/project", - "since": "2026-10-31", - "advisory": "${{ inputs.advisory }}", - "api-key": "${{ secrets.ANTHROPIC_API_KEY }}", - "github-token": "${{ steps.app.outputs.token }}", - "bot-login": "acme-tamis[bot]", - "references": "main origin/release-1", - "project": "acme/16", + "repository": "acme/project", + "since": "2026-10-31", + "advisory": "${{ inputs.advisory }}", + "api-key": "${{ secrets.ANTHROPIC_API_KEY }}", + "app-client-id": "${{ vars.TAMIS_CLIENT_ID }}", + "app-private-key": "${{ secrets.TAMIS_PRIVATE_KEY }}", + "bot-login": "acme-tamis[bot]", + "references": "main origin/release-1", + "project": "acme/16", }, with) require.Len(t, gh.Views, 1) }