Something went wrong. Try again.
Hands pods short-lived GitHub, Gitea, and atproto credentials for their ServiceAccount tokens
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256// Package github is everything lanyard asks of GitHub, as a GitHub App:// who the App is, and a token for one repository of an installation.//// An App proves itself with a JWT that it signs with its private key.// GitHub answers an installation token to that, limited to the// repositories and permissions the request names, and good for an hour.package github
import ( "bytes" "context" "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/json" "encoding/pem" "errors" "fmt" "io" "net/http" "strings" "time"
"github.com/prometheus/client_golang/prometheus"
"tangled.org/guid.foo/lanyard/metrics")
// PublicURL is the address of GitHub's own API.const PublicURL = "https://api.github.com"
var ( // ErrRefused means GitHub refused the App's signature: the key is not // one of the App's, or was deleted. ErrRefused = errors.New("GitHub refused the App's key") // ErrUnknownApp means GitHub knows no App of the client ID. ErrUnknownApp = errors.New("GitHub knows no App of the client ID") // ErrNotInstalled means no installation of the App covers the // repository, or the repository does not exist. ErrNotInstalled = errors.New("the App is not installed on the repository") // ErrPermissions means the request asked for a permission that the // App's installation does not hold. ErrPermissions = errors.New("the App does not hold the permissions"))
// App is one GitHub App's identity.type App struct { ClientID string Key *rsa.PrivateKey}
// Token is an installation token.type Token struct { Value string ExpiresAt time.Time}
// The operations of lanyard_github_calls_total, one for each request// lanyard sends.const ( operationApp = "app" operationInstallation = "installation" operationAccessToken = "access_token" operationRepository = "repository" operationRevoke = "revoke")
// Client sends lanyard's requests to GitHub.type Client struct { url string http *http.Client now func() time.Time calls *metrics.Calls}
// New answers a Client for the API at url, whose calls register on// registerer.func New(url string, registerer prometheus.Registerer) *Client { calls := metrics.NewCalls(registerer, "github", operationApp, operationInstallation, operationAccessToken, operationRepository, operationRevoke) return &Client{url: strings.TrimRight(url, "/"), http: &http.Client{Timeout: 30 * time.Second}, now: time.Now, calls: calls}}
// Slug answers the App's name in GitHub's addresses, which proves that// GitHub accepts its key.func (c *Client) Slug(ctx context.Context, app App) (string, error) { statement, err := c.statement(app) if err != nil { return "", err } var answered struct { Slug string `json:"slug"` } if _, err := c.send(ctx, operationApp, http.MethodGet, "/app", statement, nil, &answered); err != nil { return "", err } return answered.Slug, nil}
// Mint answers a new token for one repository, with the permissions,// and whether the repository is a fork.func (c *Client) Mint(ctx context.Context, app App, owner, repository string, permissions map[string]string) (Token, bool, error) { statement, err := c.statement(app) if err != nil { return Token{}, false, err } var installation struct { ID int64 `json:"id"` } path := "/repos/" + owner + "/" + repository if status, err := c.send(ctx, operationInstallation, http.MethodGet, path+"/installation", statement, nil, &installation); err != nil { if status == http.StatusNotFound && !errors.Is(err, ErrUnknownApp) { return Token{}, false, ErrNotInstalled } return Token{}, false, err } asked, err := json.Marshal(map[string]any{"repositories": []string{repository}, "permissions": permissions}) if err != nil { return Token{}, false, err } var issued struct { Token string `json:"token"` ExpiresAt time.Time `json:"expires_at"` } status, err := c.send(ctx, operationAccessToken, http.MethodPost, fmt.Sprintf("/app/installations/%d/access_tokens", installation.ID), statement, asked, &issued) if err != nil { if status == http.StatusUnprocessableEntity { return Token{}, false, fmt.Errorf("%w: %w", ErrPermissions, err) } return Token{}, false, err } token := Token{Value: issued.Token, ExpiresAt: issued.ExpiresAt} var read struct { Fork bool `json:"fork"` } if _, err := c.send(ctx, operationRepository, http.MethodGet, path, token.Value, nil, &read); err != nil { // A token whose repository lanyard could not read is one it // cannot judge, so nobody gets it. c.Revoke(context.WithoutCancel(ctx), token) return Token{}, false, fmt.Errorf("reading %s/%s with its new token: %w", owner, repository, err) } return token, read.Fork, nil}
// Revoke ends a token before its hour is over.func (c *Client) Revoke(ctx context.Context, token Token) error { _, err := c.send(ctx, operationRevoke, http.MethodDelete, "/installation/token", token.Value, nil, nil) return err}
// statement signs the JWT that proves a request comes from the App.// GitHub refuses one that claims more than ten minutes, and the start a// minute in the past allows for a clock that runs ahead of GitHub's.func (c *Client) statement(app App) (string, error) { now := c.now() header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`)) claims, err := json.Marshal(map[string]any{ "iss": app.ClientID, "iat": now.Add(-time.Minute).Unix(), "exp": now.Add(5 * time.Minute).Unix(), }) if err != nil { return "", err } signed := header + "." + base64.RawURLEncoding.EncodeToString(claims) digest := sha256.Sum256([]byte(signed)) signature, err := rsa.SignPKCS1v15(rand.Reader, app.Key, crypto.SHA256, digest[:]) if err != nil { return "", err } return signed + "." + base64.RawURLEncoding.EncodeToString(signature), nil}
// send makes one request with a bearer credential, counts it under its// operation, and decodes a success into out. It answers the status of a// refusal with its error: ErrRefused for a 401, and ErrUnknownApp for// the 404 that GitHub answers to a statement from a client ID it does// not know.func (c *Client) send(ctx context.Context, operation, method, path, credential string, body []byte, out any) (status int, err error) { request, err := http.NewRequestWithContext(ctx, method, c.url+path, bytes.NewReader(body)) if err != nil { return 0, err } started := time.Now() defer func() { c.calls.Observe(operation, status, time.Since(started)) }() request.Header.Set("Authorization", "Bearer "+credential) request.Header.Set("Accept", "application/vnd.github+json") request.Header.Set("X-GitHub-Api-Version", "2022-11-28") request.Header.Set("User-Agent", "lanyard") response, err := c.http.Do(request) if err != nil { return 0, fmt.Errorf("%s %s: %w", method, path, err) } defer response.Body.Close() answered, err := io.ReadAll(io.LimitReader(response.Body, 1<<20)) if err != nil { return response.StatusCode, fmt.Errorf("%s %s: %w", method, path, err) } if response.StatusCode == http.StatusUnauthorized { return response.StatusCode, ErrRefused } if response.StatusCode >= 300 { var refusal struct { Message string `json:"message"` } json.Unmarshal(answered, &refusal) if response.StatusCode == http.StatusNotFound && refusal.Message == "Integration not found" { return response.StatusCode, ErrUnknownApp } return response.StatusCode, fmt.Errorf("%s %s: GitHub answered %d: %s", method, path, response.StatusCode, refusal.Message) } if out == nil || len(answered) == 0 { return response.StatusCode, nil } return response.StatusCode, json.Unmarshal(answered, out)}
// ParseKey reads an App's private key from PEM, in either form GitHub// and its converters write: PKCS #1 or PKCS #8. A secret manager can// turn a key's line breaks into spaces, and ParseKey reads that too.func ParseKey(text []byte) (*rsa.PrivateKey, error) { block, _ := pem.Decode(text) if block == nil { block, _ = pem.Decode(restoreLines(text)) } if block == nil { return nil, errors.New("the key is not PEM") } if key, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil { return key, nil } parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, errors.New("the key is neither a PKCS #1 nor a PKCS #8 private key") } key, ok := parsed.(*rsa.PrivateKey) if !ok { return nil, errors.New("the key is not an RSA key") } return key, nil}
// restoreLines puts the line breaks back into PEM whose lines were// joined with spaces: one after the opening line, and one before the// closing line. The base64 between them may hold spaces, which the PEM// decoder ignores.func restoreLines(text []byte) []byte { parts := strings.Split(strings.TrimSpace(string(text)), "-----") if len(parts) != 5 { return text } return []byte("-----" + parts[1] + "-----\n" + strings.TrimSpace(parts[2]) + "\n-----" + parts[3] + "-----\n")}