Documentation
¶
Overview ¶
Package tokens mints GitHub App installation tokens for the factory's App identities (design/workstreams/provider-github/LLD/github-provider.md §Auth and tokens).
Every token is scoped to exactly one repository and to an explicit permission subset of what the identity's installation was granted: the only way in is Minter.Token, which takes a provider.GitCredentialRequest, refuses what its Validate refuses, refuses ReadRepos and an empty permission set, and always sends "repositories": [<name>] and "permissions": {…}. So an unscoped token can't be minted by construction. The two exceptions carry no repository write: OrgToken (organisation permissions only) and the metadata: read token InstallationRepos keeps to itself.
Tokens are cached per (identity, repo, permissions) and reused until RefreshBefore before GitHub's expiry; concurrent requests for the same key share one GitHub call. Installation IDs are resolved per (identity, account) and cached too.
Index ¶
- Constants
- Variables
- func GraphQLURL(api *url.URL) *url.URL
- func HostForAPI(api *url.URL) string
- func NextPage(h http.Header) (url.Values, bool)
- type APIError
- type AppInfo
- type GraphQLError
- type Identity
- type Minter
- func (m *Minter) App(ctx context.Context, identityName string) (AppInfo, error)
- func (m *Minter) AppGet(ctx context.Context, identityName, path string, query url.Values, out any) (http.Header, error)
- func (m *Minter) CheckApp(ctx context.Context, identityName string) error
- func (m *Minter) Do(ctx context.Context, token, method, path string, query url.Values, in any, ...) (http.Header, error)
- func (m *Minter) Get(ctx context.Context, token, path string, query url.Values, out any) (http.Header, error)
- func (m *Minter) GraphQL(ctx context.Context, token, op, query string, vars map[string]any, out any) error
- func (m *Minter) Identities() []string
- func (m *Minter) InstallationRepos(ctx context.Context, identityName, owner string) ([]string, error)
- func (m *Minter) OrgToken(ctx context.Context, identityName, org string, perms map[string]string) (string, time.Time, error)
- func (m *Minter) Token(ctx context.Context, req provider.GitCredentialRequest) (provider.Credential, error)
- type Options
Constants ¶
const ( // DefaultAPIURL is github.com's REST API. DefaultAPIURL = "https://api.github.com" // DefaultHost is github.com's git host. DefaultHost = "github.com" // Username is the git username that goes with an installation token. Username = "x-access-token" // MaxTTL caps a credential's lifetime; GitHub's installation tokens last an hour. MaxTTL = time.Hour // RefreshBefore is how long before GitHub's expiry a cached token stops being reused. RefreshBefore = 5 * time.Minute // DefaultInstallationTTL is how long an installation lookup is cached. DefaultInstallationTTL = time.Hour // DefaultTimeout bounds each GitHub call when the HTTP client has no timeout of its own. DefaultTimeout = 30 * time.Second )
Defaults and limits.
Variables ¶
var ( ErrUnauthorized = errors.New("github: unauthorized") // ErrForbidden is a 403 that isn't a rate limit: the App may not do this. Errors that // match it match provider.ErrForbidden too. ErrForbidden = errors.New("github: forbidden") )
Errors for GitHub's authentication failures; match them with errors.Is. 404 and 422 match provider.ErrNotFound and provider.ErrInvalid instead.
Functions ¶
func GraphQLURL ¶
GraphQLURL is the GraphQL endpoint of a REST API base: https://api.github.com/graphql for github.com, https://<host>/api/graphql for GHE (whose REST base is https://<host>/api/v3), else <base>/graphql.
func HostForAPI ¶
HostForAPI is the git host of a REST API base: github.com for api.github.com, the GHE host otherwise.
Types ¶
type APIError ¶
type APIError struct {
// Op is the call that failed ("create installation token").
Op string
StatusCode int
// Message is GitHub's error message, truncated.
Message string
// RequestID is GitHub's X-GitHub-Request-Id, for support.
RequestID string
// contains filtered or unexported fields
}
APIError is a GitHub error response. errors.Is maps its status: 401 → ErrUnauthorized, 403 → ErrForbidden and provider.ErrForbidden (not a 403 that is a rate limit), 404 and 410 (a deleted issue) → provider.ErrNotFound, 422 → provider.ErrInvalid. Rate limits and 5xx come wrapped in a *provider.RetryableError instead.
type AppInfo ¶
type AppInfo struct {
ID int64
// Slug is the App's URL name; the App acts on GitHub as the user "<slug>[bot]".
Slug string
}
AppInfo is what GET /app says about an identity's App.
type GraphQLError ¶
type GraphQLError struct {
// Op is the operation that failed ("Observe").
Op string
// Type is GitHub's error type (NOT_FOUND, FORBIDDEN, RATE_LIMITED, …), when it has one.
Type string
// Message is GitHub's message, truncated.
Message string
// Count is how many errors the response had.
Count int
}
GraphQLError is a GraphQL response's first error (GitHub answers 200 with "errors"). errors.Is maps its type: NOT_FOUND → provider.ErrNotFound, FORBIDDEN (a field or object the token's permissions don't reach) → ErrForbidden and provider.ErrForbidden; a RATE_LIMITED error comes wrapped in a *provider.RetryableError instead.
func (*GraphQLError) Error ¶
func (e *GraphQLError) Error() string
func (*GraphQLError) Is ¶
func (e *GraphQLError) Is(target error) bool
Is maps the type to the package's and the provider's errors.
type Identity ¶
type Identity struct {
AppID int64
// PrivateKey is the App's PEM private key (PKCS#1, as GitHub issues it, or PKCS#8).
PrivateKey []byte
}
Identity is one GitHub App the minter acts as.
type Minter ¶
type Minter struct {
// contains filtered or unexported fields
}
Minter mints installation tokens. It is safe for concurrent use.
func New ¶
New returns a Minter for identities (by name: "author", "reviewer"). It parses every private key up front, so a bad key fails here rather than at the first mint.
func (*Minter) App ¶
App authenticates as the identity's App (GET /app) and returns its ID and slug.
func (*Minter) AppGet ¶
func (m *Minter) AppGet(ctx context.Context, identityName, path string, query url.Values, out any) (http.Header, error)
AppGet makes one GET authenticated as the identity's App (the App JWT: /app/… endpoints such as the webhook deliveries) and decodes a 200 into out. It returns the response headers, for Link pagination. Errors map as Token's do.
func (*Minter) CheckApp ¶
CheckApp authenticates as the identity's App (GET /app): it proves the App ID, the private key and GitHub's reachability, without minting a token.
func (*Minter) Do ¶
func (m *Minter) Do(ctx context.Context, token, method, path string, query url.Values, in any, want int, out any) (http.Header, error)
Do makes one call authenticated with an installation token from Token: in (when not nil) is sent as the JSON body, and a want-status response is decoded into out (when not nil). It returns the response headers. Errors map as Get's do; the token is never logged.
func (*Minter) Get ¶
func (m *Minter) Get(ctx context.Context, token, path string, query url.Values, out any) (http.Header, error)
Get makes one GET authenticated with an installation token from Token or OrgToken and decodes a 200 into out. It returns the response headers, for Link pagination. Errors map as Token's do: *APIError (errors.Is: ErrUnauthorized, ErrForbidden, provider.ErrNotFound, provider.ErrInvalid) or *provider.RetryableError. The token is never logged.
func (*Minter) GraphQL ¶
func (m *Minter) GraphQL(ctx context.Context, token, op, query string, vars map[string]any, out any) error
GraphQL posts one query (named op, for errors and logs) with an installation token from Token and decodes the response's data into out. HTTP errors map as Get's do. A response with errors is a *GraphQLError, even when it carries partial data: an observation built from partial data could miss what rules decide on. The token, the query's variables and the response are never logged.
func (*Minter) Identities ¶
Identities returns the identity names, sorted.
func (*Minter) InstallationRepos ¶
func (m *Minter) InstallationRepos(ctx context.Context, identityName, owner string) ([]string, error)
InstallationRepos returns the full names ("owner/name") of the repos the identity's App is installed on in the account owner (an organisation or a user), sorted. The adapter expands a RuleSet scope's repo globs with it.
Listing an installation's repos needs a token that isn't scoped to one repo, so this is the second token body without "repositories" (OrgToken is the first). It carries only metadata: read, which every installation has, it lives and is cached inside the Minter, and it is never returned: the caller gets repo names only. The installation is found with GET /orgs/{owner}/installation, then GET /users/{owner}/installation when owner isn't an organisation.
func (*Minter) OrgToken ¶
func (m *Minter) OrgToken(ctx context.Context, identityName, org string, perms map[string]string) (string, time.Time, error)
OrgToken returns an installation token on an organisation with only organisation permissions (members: read, to resolve teams and org roles), and its GitHub expiry. It is the one token whose body has no "repositories": organisation permissions don't apply to repositories, so there is no repo to scope it to, and the permission check below keeps every repository permission out of it. It is for the adapter's own reads and is never handed to an agent.
It refuses with provider.ErrInvalid an unknown identity, an empty org, no permissions, a permission that isn't an organisation permission in orgPermissions, a level other than read, and permissions the installation wasn't granted. Tokens are cached and shared like Token's.
func (*Minter) Token ¶
func (m *Minter) Token(ctx context.Context, req provider.GitCredentialRequest) (provider.Credential, error)
Token returns an installation token for req: one repo (req.Repo), req.Permissions (a subset of what the identity's installation on the repo's owner was granted), and an ExpiresAt no later than GitHub's expiry nor min(req.TTL, MaxTTL) from now. A cached token for the same (identity, repo, permissions) is reused while it has more than RefreshBefore left.
It refuses with provider.ErrInvalid a request GitCredentialRequest.Validate refuses, one with ReadRepos (every token covers exactly one repo), one with no permissions, unknown permission names or levels, a repo that isn't "owner/name", an unknown identity, and permissions the installation wasn't granted. GitHub's errors map to *APIError (errors.Is: ErrUnauthorized, ErrForbidden, provider.ErrNotFound, provider.ErrInvalid) or, for rate limits, 5xx and transport failures, *provider.RetryableError.
type Options ¶
type Options struct {
// APIURL is the REST API base (default DefaultAPIURL; "https://<host>/api/v3" on GHE).
APIURL string
// HTTPClient makes the calls (default: a client with DefaultTimeout). Its Transport is
// wrapped with the App JWT; redirects are never followed, so the JWT can't leave APIURL.
HTTPClient *http.Client
// Clock times the caches and credential expiry (default clock.Real).
Clock clock.Clock
// Logger gets debug lines for mints and cache hits; tokens and JWTs are never logged.
Logger *slog.Logger
// Provider is the Provider instance name set on credentials ("github-public").
Provider string
// Host is the git host set on credentials (default: APIURL's host, "github.com" for
// api.github.com).
Host string
// InstallationTTL is how long an installation lookup is reused (default
// DefaultInstallationTTL).
InstallationTTL time.Duration
}
Options configure a Minter. The zero value mints against github.com with the wall clock.