Documentation
¶
Overview ¶
Package ghclient is patchy's GitHub REST client: GitHub App and personal-access-token authentication, installation-scoped clients and short-lived scoped tokens, and a narrow, fake-able surface (IssueStore, AlertStore, RepoStore) over the handful of endpoints the controllers use. Consumers depend on the per-concern interfaces, never on go-github types, so tests fake them with a struct.
Every client shares a rate-limit-aware transport that waits out GitHub's advertised primary and secondary rate-limit delays before retrying, so callers never see a bare 403/429 that a short pause would have cured.
Index ¶
- Constants
- Variables
- func IsNotFound(err error) bool
- func RepoMatches(entries []string, repo Repo) bool
- func ValidateProxy(rawURL string) error
- type AccessStatus
- type Alert
- type AlertKind
- type AlertStore
- type App
- func (a *App) Deliveries(ctx context.Context, visit func(Delivery) bool) (complete bool, err error)
- func (a *App) Installation(ctx context.Context, repo Repo) (*Client, error)
- func (a *App) InstallationAccounts(ctx context.Context) ([]InstallationAccount, error)
- func (a *App) InstallationPermissions(ctx context.Context, repo Repo) (contents string, err error)
- func (a *App) Installations(ctx context.Context) ([]*Client, error)
- func (a *App) Redeliver(ctx context.Context, deliveryID int64) error
- func (a *App) ScopedToken(ctx context.Context, repo Repo, perms TokenPerms) (string, time.Time, error)
- type AppAlertEnumerator
- type AppConfig
- type AppSecretAlertEnumerator
- type BranchPush
- type Client
- func (c *Client) AddLabels(ctx context.Context, repo Repo, number int, add []string) error
- func (c *Client) Assign(ctx context.Context, repo Repo, number int, logins []string) error
- func (c *Client) Close(ctx context.Context, repo Repo, number int) error
- func (c *Client) Comment(ctx context.Context, repo Repo, number int, body string) error
- func (c *Client) Create(ctx context.Context, repo Repo, req IssueRequest) (*Issue, error)
- func (c *Client) CreatePR(ctx context.Context, repo Repo, req PRRequest) (*PR, error)
- func (c *Client) DefaultBranch(ctx context.Context, repo Repo) (string, error)
- func (c *Client) DeleteIssue(ctx context.Context, repo Repo, number int) error
- func (c *Client) DismissAlert(ctx context.Context, repo Repo, number int, reason, comment string) error
- func (c *Client) EditBody(ctx context.Context, repo Repo, number int, body string) error
- func (c *Client) EditComment(ctx context.Context, repo Repo, commentID int64, body string) error
- func (c *Client) FindPRByHead(ctx context.Context, repo Repo, branch string) (*PR, error)
- func (c *Client) GetAlert(ctx context.Context, repo Repo, number int) (*Alert, error)
- func (c *Client) GetIssue(ctx context.Context, repo Repo, number int) (*Issue, error)
- func (c *Client) GetSecretAlert(ctx context.Context, repo Repo, number int) (*SecretAlert, error)
- func (c *Client) HeadSHA(ctx context.Context, repo Repo, branch string) (string, error)
- func (c *Client) InstallationRepos(ctx context.Context) (repos []Repo, complete bool, err error)
- func (c *Client) ListComments(ctx context.Context, repo Repo, number int) ([]*Comment, error)
- func (c *Client) ListOpen(ctx context.Context, repo Repo, labels []string) ([]*Issue, error)
- func (c *Client) ListOrgAlerts(ctx context.Context, org string, yield func(Repo, *Alert) bool) (complete bool, err error)
- func (c *Client) ListOrgSecretAlerts(ctx context.Context, org string, yield func(Repo, *SecretAlert) bool) (complete bool, err error)
- func (c *Client) ListRepoAlerts(ctx context.Context, repo Repo, yield func(*Alert) bool) (complete bool, err error)
- func (c *Client) ListRepoSecretAlerts(ctx context.Context, repo Repo, yield func(*SecretAlert) bool) (complete bool, err error)
- func (c *Client) OpenAlert(ctx context.Context, repo Repo, number int) error
- func (c *Client) ProbeAlerts(ctx context.Context, repo Repo, kind AlertKind) (AccessStatus, string)
- func (c *Client) PushBranch(ctx context.Context, repo Repo, req BranchPush) (string, error)
- func (c *Client) RemoveLabel(ctx context.Context, repo Repo, number int, name string) error
- func (c *Client) ReopenSecretAlert(ctx context.Context, repo Repo, number int) error
- func (c *Client) ResolveSecretAlert(ctx context.Context, repo Repo, number int, resolution, comment string) error
- func (c *Client) SearchIssues(ctx context.Context, query string) ([]*Issue, error)
- func (c *Client) Tarball(ctx context.Context, repo Repo, ref string) (io.ReadCloser, error)
- type Comment
- type CommitFile
- type Delivery
- type InstallationAccount
- type Issue
- type IssueRequest
- type IssueStore
- type Option
- type PATAlertEnumerator
- type PATSecretAlertEnumerator
- type PR
- type PRRequest
- type Repo
- type RepoStore
- type SecretAlert
- type SecretAlertStore
- type SecretLocation
- type TokenPerms
Constants ¶
const ( SecretResolutionFalsePositive = "false_positive" SecretResolutionUsedInTests = "used_in_tests" SecretResolutionWontFix = "wont_fix" )
Secret-scanning resolutions patchy writes.
const DefaultMaxAlerts = 10000
DefaultMaxAlerts bounds one backfill enumeration (100 alerts per page, so ~100 API pages). An estate that exceeds it reports itself incomplete rather than paging through an unbounded alert inventory; the operator re-runs with a narrower repository prefix.
Variables ¶
ErrDeleteUnauthorized reports the credential cannot delete issues: GitHub restricts the deleteIssue mutation to admin-permission user tokens; App installation tokens and fine-grained PATs are always refused ("Viewer not authorized to delete"). Callers may fall back to closing the issue.
Functions ¶
func IsNotFound ¶ added in v0.4.0
IsNotFound reports whether err (anywhere in its chain) is a GitHub API 404: the projected object no longer exists on the forge.
func RepoMatches ¶ added in v0.10.0
RepoMatches reports whether repo matches any filter entry. An entry is a prefix of "owner/name" ("owner/", "owner/name", which also matches "owner/name-suffix", or "owner/name-prefix-"), and a slash-less entry is normalized to an owner prefix, so "acme" cannot match "acmex/..". Matching is case-insensitive, as GitHub owner and repository names are. An empty filter matches everything.
func ValidateProxy ¶ added in v0.11.2
ValidateProxy checks rawURL is a usable proxy URL ("" is valid: no proxy).
Types ¶
type AccessStatus ¶ added in v0.15.0
type AccessStatus string
AccessStatus classifies whether a credential can read a repository's alerts.
const ( // AccessOK: the listing answered, so a backfill can read the alerts. AccessOK AccessStatus = "ok" // AccessNotInstalled: the GitHub App is not installed on the repository. AccessNotInstalled AccessStatus = "not_installed" // AccessForbidden: the credential lacks security_events (or the // secret-scanning permission), or GitHub Advanced Security is off. AccessForbidden AccessStatus = "forbidden" // AccessNotFound: the repository is invisible to the credential, or the // alert family is disabled on it. AccessNotFound AccessStatus = "not_found" // AccessNoAnalysis: code scanning has never analysed the repository, so // there are no alerts to read yet. AccessNoAnalysis AccessStatus = "no_analysis" // AccessError: anything else (rate limits, outages); worth retrying. AccessError AccessStatus = "error" )
Access statuses. NotInstalled is the App installation lookup's 404; ProbeAlerts itself never returns it, but ClassifyAccess does for that lookup's error.
func ClassifyAccess ¶ added in v0.15.0
func ClassifyAccess(err error) (AccessStatus, string)
ClassifyAccess maps a GitHub API error onto an AccessStatus and a caller-safe detail. A nil error is AccessOK. A 404 from the App's installation lookup (GET /repos/{o}/{r}/installation) is AccessNotInstalled; any other 404 is AccessNotFound, or AccessNoAnalysis when code scanning says it has no analysis.
type Alert ¶
type Alert struct {
Number int
RuleID string
RuleName string
RuleDescription string
RuleHelp string
Tags []string
Severity string
State string
HTMLURL string
Path string
StartLine int
EndLine int
Snippet string
MostRecentSHA string
}
Alert is patchy's view of a code-scanning alert: the rule, the severity (security_severity_level falling back to the rule severity), and the most recent instance's location, message snippet, and commit.
type AlertKind ¶ added in v0.15.0
type AlertKind string
AlertKind names one alert family a repository's access is probed for.
type AlertStore ¶
type AlertStore interface {
// GetAlert fetches one code-scanning alert.
GetAlert(ctx context.Context, repo Repo, number int) (*Alert, error)
// DismissAlert dismisses an alert; reason must be one of GitHub's
// "false positive", "won't fix", or "used in tests".
DismissAlert(ctx context.Context, repo Repo, number int, reason, comment string) error
}
AlertStore is the code-scanning surface.
type App ¶
type App struct {
// contains filtered or unexported fields
}
App mints installation-scoped clients and tokens for a GitHub App.
func (*App) Deliveries ¶ added in v0.5.4
Deliveries walks the App webhook's delivery log newest-first, calling visit for each attempt until visit returns false or the log is exhausted. complete is false when the page cap ended the walk instead.
func (*App) Installation ¶
Installation returns a Client authenticated as the installation covering repo. Both the repo → installation lookup and the per-installation client are cached, so repeated calls cost no API requests.
func (*App) InstallationAccounts ¶ added in v0.10.0
func (a *App) InstallationAccounts(ctx context.Context) ([]InstallationAccount, error)
InstallationAccounts returns one entry per installation of the App: the account-shaped fan-out for cross-estate walks like the alert backfill.
func (*App) InstallationPermissions ¶ added in v0.15.0
InstallationPermissions reports the contents permission ("read", "write", or "" for none) of the installation covering repo. It shares the installation cache, re-reading the permission when it is older than a few minutes. A repository the App is not installed on is a 404 error (IsNotFound).
func (*App) Installations ¶
Installations returns one client per installation of the App: the fan-out for cross-repository sweeps like the reconcile searches.
type AppAlertEnumerator ¶ added in v0.10.0
type AppAlertEnumerator struct {
App *App
// MaxAlerts bounds the walk; <= 0 means DefaultMaxAlerts.
MaxAlerts int
}
AppAlertEnumerator walks the open code-scanning alerts of every account the App is installed on, picking the walk whose cost matches the filter:
- an account none of the repos entries name is skipped outright;
- an account whose entries all carry a name segment ("owner/name", "owner/name-prefix-") is walked by enumerating its repository inventory and listing only matching repositories, so cost scales with repository count, not the org's alert count;
- a bare "owner/" entry (or an empty filter) keeps the full walk: the single org-wide listing for an organization account, the installation-repository fan-out for a user account, which has no org-wide listing.
The per-repository filter here is also the caller's safety net in ghas; applying it at both levels keeps the enumerator free to choose the cheap walk without changing what comes out.
func (*AppAlertEnumerator) Enumerate ¶ added in v0.10.0
func (e *AppAlertEnumerator) Enumerate( ctx context.Context, repos []string, yield func(Repo, *Alert) bool, ) (complete bool, err error)
Enumerate implements the backfill enumeration over the App's installations. complete is false when the alert budget, a repository page cap, or the caller's yield ended the walk before the estate was exhausted.
type AppConfig ¶
type AppConfig struct {
AppID int64
PrivateKey []byte // PEM-encoded RSA private key
BaseURL string // default https://api.github.com/ ; tests and GHES override
ProxyURL string // forward proxy for all the App's traffic; "" = environment
}
AppConfig configures GitHub App authentication.
type AppSecretAlertEnumerator ¶ added in v0.15.0
type AppSecretAlertEnumerator struct {
App *App
// MaxAlerts bounds the walk; <= 0 means DefaultMaxAlerts.
MaxAlerts int
}
AppSecretAlertEnumerator is AppAlertEnumerator for open secret-scanning alerts. Every listing asks GitHub to hide the secret values.
type BranchPush ¶ added in v0.3.0
type BranchPush struct {
Branch string
BaseSHA string
Message string
Files []CommitFile
Deletes []string
}
BranchPush describes one commit to create on top of BaseSHA and the branch to point at it.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps the GitHub REST API with patchy's narrow, fake-able surface. Construct one with NewToken or App.Installation.
func NewToken ¶
NewToken returns a Client authenticated with a personal access token, the dev-mode fallback. baseURL "" means api.github.com.
func (*Client) DefaultBranch ¶
DefaultBranch returns the repository's default branch name.
func (*Client) DeleteIssue ¶ added in v0.5.7
DeleteIssue permanently deletes an issue. The REST API cannot delete issues; only the GraphQL deleteIssue mutation can, and it needs the issue's node ID, so this fetches the issue first. Deleting requires admin-level repository permission; it exists for the demo reset, which removes the tracking issues a replayed demo would otherwise duplicate. A missing issue is success: deletion is idempotent.
func (*Client) DismissAlert ¶
func (c *Client) DismissAlert(ctx context.Context, repo Repo, number int, reason, comment string) error
DismissAlert dismisses a code-scanning alert. reason must be one of GitHub's "false positive", "won't fix", or "used in tests".
func (*Client) EditComment ¶ added in v0.5.3
EditComment replaces the body of an existing issue comment.
func (*Client) FindPRByHead ¶ added in v0.4.0
FindPRByHead returns the open pull request whose head is branch, or nil. It is the idempotency check before creating a remediation PR (a crash between push and status write must not open a duplicate).
func (*Client) GetIssue ¶ added in v0.4.0
GetIssue fetches one issue: the projection reconciler's current-state read before diffing labels and body.
func (*Client) GetSecretAlert ¶ added in v0.15.0
GetSecretAlert fetches one secret-scanning alert, without its secret, and up to maxSecretLocations of its locations.
func (*Client) HeadSHA ¶ added in v0.3.0
HeadSHA resolves the current commit SHA of refs/heads/<branch>.
func (*Client) InstallationRepos ¶ added in v0.10.0
InstallationRepos lists the repositories the installation's token can see (GET /installation/repositories). complete is false when the page cap ended the walk before the inventory was exhausted.
func (*Client) ListComments ¶
ListComments returns every comment on the issue, following pagination.
func (*Client) ListOpen ¶
ListOpen returns every open issue in repo carrying all of labels, following pagination. Pull requests (which the issues API also returns) are skipped.
func (*Client) ListOrgAlerts ¶ added in v0.10.0
func (c *Client) ListOrgAlerts( ctx context.Context, org string, yield func(Repo, *Alert) bool, ) (complete bool, err error)
ListOrgAlerts walks the organization's open code-scanning alerts, calling yield with each alert and the repository it was raised in, until yield returns false or the listing is exhausted. complete is false when yield ended the walk early.
func (*Client) ListOrgSecretAlerts ¶ added in v0.15.0
func (c *Client) ListOrgSecretAlerts( ctx context.Context, org string, yield func(Repo, *SecretAlert) bool, ) (complete bool, err error)
ListOrgSecretAlerts walks the organization's open secret-scanning alerts, with ListOrgAlerts' contract.
func (*Client) ListRepoAlerts ¶ added in v0.10.0
func (c *Client) ListRepoAlerts( ctx context.Context, repo Repo, yield func(*Alert) bool, ) (complete bool, err error)
ListRepoAlerts walks one repository's open code-scanning alerts, calling yield until it returns false or the listing is exhausted. complete is false when yield ended the walk early.
A 404 on the first page is an empty listing, not an error: GitHub answers "no analysis found" for a repository code scanning has never analyzed, which has no alerts to backfill. Failing there would wedge a whole backfill on one repository without scanning.
func (*Client) ListRepoSecretAlerts ¶ added in v0.15.0
func (c *Client) ListRepoSecretAlerts( ctx context.Context, repo Repo, yield func(*SecretAlert) bool, ) (complete bool, err error)
ListRepoSecretAlerts walks one repository's open secret-scanning alerts, with ListRepoAlerts' contract (a first-page 404 is an empty listing).
func (*Client) OpenAlert ¶ added in v0.5.7
OpenAlert reopens a code-scanning alert (undoes a dismissal). Only a dismissed alert can be reopened, so the current state is read first and anything else is success: an alert that is already open, fixed, or gone with the repository that held it has no dismissal left to undo. Reopening is therefore convergent rather than authoritative: the retried cleanup of a repository that was deleted or recreated since the dismissal still succeeds. GitHub rejects every illegal transition with the same opaque 400 ("There was an issue creating the request. Please try again."), so the state is read rather than inferred from the error.
func (*Client) ProbeAlerts ¶ added in v0.15.0
ProbeAlerts asks for one open alert of the given family on repo, to learn whether the client can read that family's alerts at all. It costs one API request and never returns an error: the outcome is the status, with GitHub's own message as the detail.
func (*Client) PushBranch ¶ added in v0.3.0
PushBranch creates one commit on top of req.BaseSHA carrying req's file changes and points refs/heads/<Branch> at it, force-updating an existing branch so a retried event re-applies cleanly. It is the git-less push: blob → tree → commit → ref through the Git Data API. It returns the pushed commit's SHA.
func (*Client) RemoveLabel ¶
RemoveLabel removes one label from the issue. A 404 (the label is already absent) is not an error, so removals are idempotent.
func (*Client) ReopenSecretAlert ¶ added in v0.15.0
ReopenSecretAlert reopens a resolved secret-scanning alert, with the same convergent semantics as OpenAlert: an alert that is already open, or gone, has no resolution left to undo, so both are success.
func (*Client) ResolveSecretAlert ¶ added in v0.15.0
func (c *Client) ResolveSecretAlert(ctx context.Context, repo Repo, number int, resolution, comment string) error
ResolveSecretAlert closes a secret-scanning alert with resolution, one of GitHub's false_positive, used_in_tests, wont_fix or revoked.
func (*Client) SearchIssues ¶
SearchIssues runs an issue search query and returns every matching issue, following pagination.
type CommitFile ¶ added in v0.3.0
type CommitFile struct {
Path string
// Mode is the git file mode: "100644", "100755", or "120000".
Mode string
// Content is the raw blob; for a symlink ("120000"), the link target.
Content []byte
}
CommitFile is one file created or modified by a BranchPush.
type Delivery ¶ added in v0.5.4
type Delivery struct {
ID int64
GUID string
DeliveredAt time.Time
// Redelivery marks a redelivered attempt.
Redelivery bool
// OK reports whether the receiver answered 2xx.
OK bool
Event string
}
Delivery is one attempt from the App webhook's delivery log. Attempts of the same logical delivery (the original and its redeliveries) share a GUID.
type InstallationAccount ¶ added in v0.10.0
type InstallationAccount struct {
// Client is authenticated as the installation.
Client *Client
// Account is the org or user login the App is installed on.
Account string
// Org reports an organization account; false is a user account, which
// has no org-wide listings.
Org bool
}
InstallationAccount is one account the App is installed on, with a client authenticated as that installation.
type Issue ¶
type Issue struct {
// Repo is the issue's repository, populated from the list/search
// response so cross-repository sweeps can act on their results.
Repo Repo
Number int
Title string
Body string
State string
Labels []string
Assignees []string
CreatedAt time.Time
}
Issue is patchy's thin view of a GitHub issue, decoupled from go-github.
type IssueRequest ¶
IssueRequest is the payload for creating an issue.
type IssueStore ¶
type IssueStore interface {
// ListOpen returns every open issue in repo carrying all of labels.
ListOpen(ctx context.Context, repo Repo, labels []string) ([]*Issue, error)
// Create opens a new issue.
Create(ctx context.Context, repo Repo, req IssueRequest) (*Issue, error)
// Comment adds a comment to the issue.
Comment(ctx context.Context, repo Repo, number int, body string) error
// ListComments returns every comment on the issue, oldest first.
ListComments(ctx context.Context, repo Repo, number int) ([]*Comment, error)
// EditBody replaces the issue body.
EditBody(ctx context.Context, repo Repo, number int, body string) error
// AddLabels adds labels to the issue, creating them as needed.
AddLabels(ctx context.Context, repo Repo, number int, add []string) error
// RemoveLabel removes one label; a label already absent is not an error.
RemoveLabel(ctx context.Context, repo Repo, number int, name string) error
// Assign adds assignees to the issue.
Assign(ctx context.Context, repo Repo, number int, logins []string) error
// Close closes the issue.
Close(ctx context.Context, repo Repo, number int) error
}
IssueStore is the issue surface the controllers use; *Client implements it, controller tests fake it.
type PATAlertEnumerator ¶ added in v0.10.0
type PATAlertEnumerator struct {
Client *Client
// MaxAlerts bounds the walk; <= 0 means DefaultMaxAlerts.
MaxAlerts int
}
PATAlertEnumerator walks the open code-scanning alerts of an explicit repository list with a PAT client. A PAT sees no installation inventory, so it cannot discover repositories: every entry must be an exact "owner/name". A bare "owner/" prefix is an error, not an empty result.
func (*PATAlertEnumerator) Enumerate ¶ added in v0.10.0
func (e *PATAlertEnumerator) Enumerate( ctx context.Context, repos []string, yield func(Repo, *Alert) bool, ) (complete bool, err error)
Enumerate implements the backfill enumeration over the exact repositories named. complete is false when the alert budget (or the caller's yield) ended the walk early.
type PATSecretAlertEnumerator ¶ added in v0.15.0
type PATSecretAlertEnumerator struct {
Client *Client
// MaxAlerts bounds the walk; <= 0 means DefaultMaxAlerts.
MaxAlerts int
}
PATSecretAlertEnumerator is PATAlertEnumerator for open secret-scanning alerts: exact owner/name entries only.
type RepoStore ¶
type RepoStore interface {
// DefaultBranch returns the repository's default branch name.
DefaultBranch(ctx context.Context, repo Repo) (string, error)
// HeadSHA resolves the current commit SHA of refs/heads/<branch>.
HeadSHA(ctx context.Context, repo Repo, branch string) (string, error)
// CreatePR opens a pull request.
CreatePR(ctx context.Context, repo Repo, req PRRequest) (*PR, error)
// SearchIssues runs an issue search query (cross-repo reconcile
// queries) and returns every matching issue.
SearchIssues(ctx context.Context, query string) ([]*Issue, error)
}
RepoStore is the repository/PR/search surface.
type SecretAlert ¶ added in v0.15.0
type SecretAlert struct {
Number int
SecretType string
SecretTypeDisplayName string
Provider string
Validity string
PubliclyLeaked bool
MultiRepo bool
PushProtectionBypassed bool
State string
HTMLURL string
Locations []SecretLocation
}
SecretAlert is patchy's view of a secret-scanning alert. It deliberately has no field for the secret value: the client asks GitHub to hide it (hide_secret=true) and never reads it even if one comes back, so the value cannot reach a Finding, an issue, a prompt or a log through here.
type SecretAlertStore ¶ added in v0.15.0
type SecretAlertStore interface {
// GetSecretAlert fetches one secret-scanning alert and its locations.
GetSecretAlert(ctx context.Context, repo Repo, number int) (*SecretAlert, error)
// ResolveSecretAlert resolves an alert; resolution must be one of
// GitHub's false_positive, used_in_tests, wont_fix or revoked.
ResolveSecretAlert(ctx context.Context, repo Repo, number int, resolution, comment string) error
// ReopenSecretAlert undoes a resolution; an open or missing alert is
// success.
ReopenSecretAlert(ctx context.Context, repo Repo, number int) error
}
SecretAlertStore is the secret-scanning surface. No method returns or accepts a secret value.
type SecretLocation ¶ added in v0.15.0
type SecretLocation struct {
// Type is GitHub's location kind ("commit", "issue_body", ...).
Type string
Path string
StartLine int
EndLine int
StartColumn int
EndColumn int
CommitSHA string
// URL links to the location on GitHub: the blob for a commit location,
// the issue, comment or discussion otherwise.
URL string
}
SecretLocation is one place a secret was found. Only commit and wiki-commit locations name a file; the other kinds (an issue body, a pull request comment, a discussion) carry just the URL of where it was seen.
type TokenPerms ¶
type TokenPerms struct {
Contents string
}
TokenPerms is the permission set for a scoped token; string values are "read"/"write" per the GitHub API; empty means not requested.