172 lines
5.4 KiB
Go
172 lines
5.4 KiB
Go
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
|
|
}
|