feat(forge/github): authenticate as a GitHub App and mint per-repository git credentials (archie #1817)
publish / publish (push) Failing after 1s

This commit is contained in:
sam committed 2026-11-09 00:14:02 +11:00
1 parent 4195ddc5bc
commit 8f13cfe725
8 files changed
+545 -110

No files matched your search

+171
View File
@@ -0,0 +1,171 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/google/go-github/v78/github"
"github.com/samcharles93/archipelago/sdk/forge"
)
// appCredential is the connection credential of a GitHub App: its ID and
// PEM private key, stored together as one JSON secret.
type appCredential struct {
AppID int64 `json:"app_id"`
PrivateKey string `json:"private_key"`
}
// parseAppCredential reports whether token is an app credential rather than
// a personal access token.
func parseAppCredential(token string) (appCredential, bool) {
var c appCredential
if !strings.HasPrefix(strings.TrimSpace(token), "{") || json.Unmarshal([]byte(token), &c) != nil {
return appCredential{}, false
}
return c, c.AppID != 0 && c.PrivateKey != ""
}
// app authenticates as a GitHub App. Each repository owner is a separate
// installation with its own short-lived token, so requests are routed to the
// installation of the owner in their path.
type app struct {
apps *ghinstallation.AppsTransport
jwt *github.Client
// public reads public user records, which neither the app's JWT nor an
// installation token is scoped to.
public *github.Client
base http.RoundTripper
apiBase string
mu sync.Mutex
installations map[string]*ghinstallation.Transport
contents map[string]string
identityOnce sync.Once
slug string
email string
identityErr error
}
func newApp(base http.RoundTripper, cred appCredential, apiBase string, enterprise func(*github.Client) (*github.Client, error)) (*app, error) {
apps, err := ghinstallation.NewAppsTransport(base, cred.AppID, []byte(cred.PrivateKey))
if err != nil {
return nil, fmt.Errorf("read GitHub App key: %w", err)
}
apps.BaseURL = apiBase
jwtClient, err := enterprise(github.NewClient(&http.Client{Transport: apps}))
if err != nil {
return nil, err
}
public, err := enterprise(github.NewClient(&http.Client{Transport: base}))
if err != nil {
return nil, err
}
return &app{apps: apps, jwt: jwtClient, public: public, base: base, apiBase: apiBase, installations: map[string]*ghinstallation.Transport{}, contents: map[string]string{}}, nil
}
// installation returns the token transport for owner's installation.
func (a *app) installation(ctx context.Context, owner, repo string) (*ghinstallation.Transport, error) {
key := strings.ToLower(owner)
a.mu.Lock()
defer a.mu.Unlock()
if tr, ok := a.installations[key]; ok {
return tr, nil
}
var inst *github.Installation
var err error
if repo != "" {
inst, _, err = a.jwt.Apps.FindRepositoryInstallation(ctx, owner, repo)
} else {
inst, _, err = a.jwt.Apps.FindUserInstallation(ctx, owner)
}
if err != nil {
return nil, apiError(fmt.Sprintf("find the app installation for %s", owner), err)
}
tr := ghinstallation.NewFromAppsTransport(a.apps, inst.GetID())
a.installations[key] = tr
a.contents[key] = inst.GetPermissions().GetContents()
return tr, nil
}
// RoundTrip sends the request with the token of the installation owning the
// repository in its path.
func (a *app) RoundTrip(req *http.Request) (*http.Response, error) {
owner, repo := pathOwner(req.URL.Path)
if owner == "" {
return nil, fmt.Errorf("GitHub App request %s names no repository owner", req.URL.Path)
}
tr, err := a.installation(req.Context(), owner, repo)
if err != nil {
return nil, err
}
return tr.RoundTrip(req)
}
// pathOwner reads the owner and repository from a /repos/{owner}/{repo}
// path, with or without an Enterprise /api/v3 prefix.
func pathOwner(path string) (string, string) {
parts := strings.Split(strings.TrimPrefix(path, "/api/v3"), "/")
if len(parts) >= 4 && parts[1] == "repos" {
return parts[2], parts[3]
}
return "", ""
}
// identity is the app's bot login and its noreply commit email.
func (a *app) identity(ctx context.Context) (string, string, error) {
a.identityOnce.Do(func() {
self, _, err := a.jwt.Apps.Get(ctx, "")
if err != nil {
a.identityErr = apiError("read the GitHub App", err)
return
}
a.slug = self.GetSlug() + "[bot]"
bot, _, err := a.public.Users.Get(ctx, a.slug)
if err != nil {
a.identityErr = apiError("read the app's bot user", err)
return
}
a.email = fmt.Sprintf("%d+%s@users.noreply.github.com", bot.GetID(), a.slug)
})
return a.slug, a.email, a.identityErr
}
// GitCredential mints an installation token for one repository and names the
// app's bot as the commit identity.
func (c *GitHubClient) GitCredential(ctx context.Context, owner, repo string) (forge.GitCredential, error) {
if c.app == nil {
return forge.GitCredential{}, errors.ErrUnsupported
}
tr, err := c.app.installation(ctx, owner, repo)
if err != nil {
return forge.GitCredential{}, err
}
token, err := tr.Token(ctx)
if err != nil {
return forge.GitCredential{}, fmt.Errorf("mint an installation token for %s/%s: %w", owner, repo, err)
}
expires, _, _ := tr.Expiry()
name, email, err := c.app.identity(ctx)
if err != nil {
return forge.GitCredential{}, err
}
return forge.GitCredential{Username: "x-access-token", Token: token, ExpiresAt: expires, CommitName: name, CommitEmail: email}, nil
}
// canPush reports whether owner's installation may write repository contents.
func (a *app) canPush(ctx context.Context, owner, repo string) (bool, error) {
if _, err := a.installation(ctx, owner, repo); err != nil {
return false, err
}
a.mu.Lock()
defer a.mu.Unlock()
return a.contents[strings.ToLower(owner)] == "write", nil
}
+47 -6
View File
@@ -33,21 +33,47 @@ type GitHubClient struct {
loginMu sync.Mutex
login string
// app is set when the connection authenticates as a GitHub App.
app *app
}
// NewGitHub creates a GitHub-backed Forge implementation. Non-github.com
// hosts are configured using GitHub Enterprise's API and upload URL conventions.
func newGitHub(token, host string, log *slog.Logger) (forge.Forge, error) {
client := github.NewClient(github_ratelimit.NewClient(nil,
github_secondary_ratelimit.WithSingleSleepLimit(maxRateLimitWait, nil)))
if strings.TrimRight(host, "/") != "https://github.com" {
var err error
client, err = client.WithEnterpriseURLs(host, host)
host = strings.TrimRight(host, "/")
base := github_ratelimit.NewClient(nil, github_secondary_ratelimit.WithSingleSleepLimit(maxRateLimitWait, nil)).Transport
enterprise := func(c *github.Client) (*github.Client, error) {
if host == "https://github.com" {
return c, nil
}
c, err := c.WithEnterpriseURLs(host, host)
if err != nil {
return nil, fmt.Errorf("configure GitHub host %q: %w", host, err)
}
return c, nil
}
return &GitHubClient{gh: client.WithAuthToken(token), log: log}, nil
cred, isApp := parseAppCredential(token)
if !isApp {
client, err := enterprise(github.NewClient(&http.Client{Transport: base}))
if err != nil {
return nil, err
}
return &GitHubClient{gh: client.WithAuthToken(token), log: log}, nil
}
apiBase := "https://api.github.com"
if host != "https://github.com" {
apiBase = host + "/api/v3"
}
a, err := newApp(base, cred, apiBase, enterprise)
if err != nil {
return nil, err
}
client, err := enterprise(github.NewClient(&http.Client{Transport: a}))
if err != nil {
return nil, err
}
return &GitHubClient{gh: client, log: log, app: a}, nil
}
// AcceptInvitations accepts pending repository invitations, but only to the
@@ -55,6 +81,9 @@ func newGitHub(token, host string, log *slog.Logger) (forge.Forge, error) {
// as a collaborator to a configured repository is all a human has to do. An
// invitation to anything else is left pending.
func (c *GitHubClient) AcceptInvitations(ctx context.Context, repos []forge.RepoRef) error {
if c.app != nil {
return nil // an app reaches repositories by installation, not invitation
}
invites, _, err := c.gh.Users.ListInvitations(ctx, nil)
if err != nil {
return apiError("list invitations", err)
@@ -410,6 +439,11 @@ func (c *GitHubClient) selfLogin(ctx context.Context) (string, error) {
if c.login != "" {
return c.login, nil
}
if c.app != nil {
login, _, err := c.app.identity(ctx)
c.login = login
return login, err
}
user, _, err := c.gh.Users.Get(ctx, "")
if err != nil {
return "", apiError("read the token's user", err)
@@ -553,6 +587,13 @@ func (c *GitHubClient) SetStateLabel(ctx context.Context, owner, repo string, nu
// VerifyPush confirms the token can push to the repo (permission check
// at startup so misconfiguration surfaces before any work is claimed).
func (c *GitHubClient) VerifyPush(ctx context.Context, owner, repo string) error {
if c.app != nil {
ok, err := c.app.canPush(ctx, owner, repo)
if err == nil && !ok {
err = fmt.Errorf("the GitHub App needs Contents: write on %s/%s", owner, repo)
}
return err
}
r, _, err := c.gh.Repositories.Get(ctx, owner, repo)
if err != nil {
return apiError(fmt.Sprintf("get repository %s/%s", owner, repo), err)