github

package
v4.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	CampaignNameMax        = 50
	CampaignDescriptionMax = 255
	// CampaignAlertsMax is the most alerts one campaign can hold.
	CampaignAlertsMax = 1000
)

Limits GitHub puts on a campaign.

View Source
const (
	CampaignOpen   = "open"
	CampaignClosed = "closed"
)

Campaign states.

View Source
const DefaultAPIURL = "https://api.github.com"

DefaultAPIURL is github.com's REST endpoint.

View Source
const MaxSARIFUploadBytes = 10 << 20

MaxSARIFUploadBytes is code scanning's limit on the gzipped document.

Variables

View Source
var ErrNoToken = errors.New("no GitHub token found: set GITHUB_TOKEN or run 'gh auth login'")

ErrNoToken is returned when no GitHub token can be found.

View Source
var ErrRateLimited = errors.New("GitHub API rate limit exhausted")

ErrRateLimited is returned when the rate limit outlasts MaxWait.

Functions

func APIURL

func APIURL() string

APIURL is GITHUB_API_URL, or github.com's.

func AdvisoryMarker

func AdvisoryMarker(hash string) string

AdvisoryMarker is the line that ties an advisory to the finding group it was made from.

func CampaignEnd

func CampaignEnd(t time.Time) string

CampaignEnd formats a campaign end time the way the API takes it.

func CampaignMarker

func CampaignMarker(uuid string) string

CampaignMarker is the line that ties a GitHub campaign to the Vulnetix campaign it was made from.

func CampaignMarkerOf

func CampaignMarkerOf(description string) string

CampaignMarkerOf returns the Vulnetix campaign uuid in a description, or "".

func CampaignName

func CampaignName(name string) string

CampaignName is the GitHub name for a Vulnetix campaign, within the limit.

func DefaultCorrelator

func DefaultCorrelator() string

DefaultCorrelator is vulnetix/<workflow>/<job> from the Actions environment.

func DownloadAsset

func DownloadAsset(ctx context.Context, token string, a ReleaseAsset, destDir string) (string, error)

DownloadAsset writes an asset into destDir and returns its path.

func EncodeSARIF

func EncodeSARIF(sarifJSON []byte) (string, error)

EncodeSARIF gzips and base64-encodes a SARIF document as the API wants.

func GitHubPurl

func GitHubPurl(purl string) string

GitHubPurl rewrites a package URL into the form the dependency graph accepts. GitHub Actions are pkg:githubactions/<owner>/<repo>@<ref> there; this CLI's SBOMs carry pkg:github-actions/<owner>%2F<repo>@<ref>, which the API rejects as an invalid type (HTTP 422) and which then fails the whole snapshot. Every other purl is returned unchanged.

func IsPermission

func IsPermission(err error) bool

IsPermission reports a refusal that more permissions would fix: 401, 403 (not a rate limit) or 404, which GitHub answers for a resource the token cannot see. Publishing treats these as warnings.

func IsStatus

func IsStatus(err error, statuses ...int) bool

IsStatus reports whether err is an APIError with one of the statuses.

func MarkerOf

func MarkerOf(description string) string

MarkerOf returns the marker hash in an advisory's description, or "".

func RejectedPurl

func RejectedPurl(err error) string

RejectedPurl returns the package URL a 422 from the snapshot API names as invalid, or "".

func RepoFromRemote

func RepoFromRemote(remote string) string

RepoFromRemote reads owner/name from a git remote URL (https or ssh), or returns "".

func ResolveToken

func ResolveToken() (token, source string, err error)

ResolveToken finds a GitHub token: GITHUB_TOKEN, then GH_TOKEN (the gh CLI's convention), then `gh auth token`. source names where it came from ("env:GITHUB_TOKEN", "env:GH_TOKEN", "gh-cli") for status output; the token itself is never printed.

Types

type APIError

type APIError struct {
	Method, Path string
	Status       int
	Message      string
}

APIError is a non-2xx answer.

func (*APIError) Error

func (e *APIError) Error() string

type AdvisoryPackage

type AdvisoryPackage struct {
	Ecosystem string `json:"ecosystem"`
	Name      string `json:"name,omitempty"`
}

AdvisoryPackage names the affected package.

type AdvisoryRequest

type AdvisoryRequest struct {
	Summary         string                  `json:"summary"`
	Description     string                  `json:"description"`
	Vulnerabilities []AdvisoryVulnerability `json:"vulnerabilities,omitempty"`
	CWEIDs          []string                `json:"cwe_ids,omitempty"`
	Severity        string                  `json:"severity,omitempty"`
}

AdvisoryRequest is the create and update body. Severity and a CVSS vector are mutually exclusive in the API; only Severity is ever sent.

type AdvisoryVulnerability

type AdvisoryVulnerability struct {
	Package AdvisoryPackage `json:"package"`
}

AdvisoryVulnerability is one affected package.

type Alert

type Alert struct {
	Number int    `json:"number"`
	State  string `json:"state"`
	Rule   struct {
		ID   string   `json:"id"`
		Tags []string `json:"tags"`
	} `json:"rule"`
	MostRecentInstance struct {
		Category string `json:"category"`
		Message  struct {
			Text string `json:"text"`
		} `json:"message"`
		Location struct {
			Path string `json:"path"`
		} `json:"location"`
	} `json:"most_recent_instance"`
}

Alert is a code scanning alert, reduced to what mapping needs.

type Artifact

type Artifact struct {
	ID                 int64     `json:"id"`
	NodeID             string    `json:"node_id"`
	Name               string    `json:"name"`
	SizeInBytes        int64     `json:"size_in_bytes"`
	URL                string    `json:"url"`
	ArchiveDownloadURL string    `json:"archive_download_url"`
	Expired            bool      `json:"expired"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
	ExpiresAt          time.Time `json:"expires_at"`
}

Artifact represents a GitHub Actions artifact

type ArtifactCollector

type ArtifactCollector struct {
	// contains filtered or unexported fields
}

ArtifactCollector handles collection of GitHub Actions artifacts

func NewArtifactCollector

func NewArtifactCollector(token, apiURL, repository, runID string) *ArtifactCollector

NewArtifactCollector creates a new artifact collector

func (*ArtifactCollector) DownloadArtifact

func (c *ArtifactCollector) DownloadArtifact(ctx context.Context, artifact Artifact) (string, error)

DownloadArtifact downloads an artifact and extracts it to a temporary directory

func (*ArtifactCollector) GetRepository

func (c *ArtifactCollector) GetRepository(ctx context.Context) (*Repository, error)

GetRepository fetches the repository's metadata.

func (*ArtifactCollector) GetWorkflowRun

func (c *ArtifactCollector) GetWorkflowRun(ctx context.Context) (*WorkflowRun, error)

GetWorkflowRun fetches this run's metadata.

func (*ArtifactCollector) ListArtifacts

func (c *ArtifactCollector) ListArtifacts(ctx context.Context) ([]Artifact, error)

ListArtifacts lists all artifacts for the current workflow run

func (*ArtifactCollector) ListPullsForCommit

func (c *ArtifactCollector) ListPullsForCommit(ctx context.Context, sha string) ([]PullRequestRef, error)

ListPullsForCommit finds the pull requests a commit belongs to. Used on a push to a branch that has an open PR, where the event payload carries no PR number.

type ArtifactMetadata

type ArtifactMetadata struct {
	Repository      string            `json:"repository"`
	RepositoryOwner string            `json:"repository_owner"`
	RunID           string            `json:"run_id"`
	RunNumber       string            `json:"run_number"`
	WorkflowName    string            `json:"workflow_name"`
	JobName         string            `json:"job"`
	SHA             string            `json:"sha"`
	RefName         string            `json:"ref_name"`
	RefType         string            `json:"ref_type"`
	EventName       string            `json:"event_name"`
	Actor           string            `json:"actor"`
	ServerURL       string            `json:"server_url"`
	APIURL          string            `json:"api_url"`
	Artifacts       []string          `json:"artifacts"`
	ExtraEnvVars    map[string]string `json:"extra_env_vars,omitempty"`
}

ArtifactMetadata contains metadata about the workflow and artifacts

func CollectMetadata

func CollectMetadata(artifactNames []string) *ArtifactMetadata

CollectMetadata collects metadata from GitHub Actions environment

type ArtifactsResponse

type ArtifactsResponse struct {
	TotalCount int        `json:"total_count"`
	Artifacts  []Artifact `json:"artifacts"`
}

ArtifactsResponse represents the GitHub API response for artifacts

type AssetEntry

type AssetEntry struct {
	ID                 int64  `json:"id"`
	Name               string `json:"name"`
	Size               int64  `json:"size"`
	BrowserDownloadURL string `json:"browser_download_url"`
}

AssetEntry is an uploaded release asset.

type Campaign

type Campaign struct {
	Number      int    `json:"number"`
	Name        string `json:"name"`
	Description string `json:"description"`
	State       string `json:"state"`
	EndsAt      string `json:"ends_at"`
	ContactLink string `json:"contact_link"`
	HTMLURL     string `json:"html_url"`
}

Campaign is a GitHub security campaign as listed.

type CampaignAlerts

type CampaignAlerts struct {
	RepositoryID int   `json:"repository_id"`
	AlertNumbers []int `json:"alert_numbers"`
}

CampaignAlerts names the code scanning alerts of one repository.

type CampaignCreate

type CampaignCreate struct {
	Name               string           `json:"name"`
	Description        string           `json:"description"`
	EndsAt             string           `json:"ends_at"`
	ContactLink        string           `json:"contact_link,omitempty"`
	CodeScanningAlerts []CampaignAlerts `json:"code_scanning_alerts"`
	GenerateIssues     bool             `json:"generate_issues"`
}

CampaignCreate is the create body.

type CampaignPatch

type CampaignPatch struct {
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	EndsAt      string `json:"ends_at,omitempty"`
	ContactLink string `json:"contact_link,omitempty"`
	State       string `json:"state,omitempty"`
}

CampaignPatch is the update body. Empty fields are left out and so stay as they are.

type Client

type Client struct {
	BaseURL string
	Token   string
	HTTP    *http.Client
	// MaxWait bounds the time one request spends waiting out rate limits.
	MaxWait time.Duration
	// Calls counts requests made.
	Calls int
}

Client makes authenticated GitHub REST calls.

func NewClient

func NewClient(token string) *Client

NewClient returns a client for GITHUB_API_URL with token.

func (*Client) CreateAdvisory

func (c *Client) CreateAdvisory(ctx context.Context, repo string, req AdvisoryRequest) (*RepositoryAdvisory, error)

CreateAdvisory creates a draft advisory.

func (*Client) CreateCampaign

func (c *Client) CreateCampaign(ctx context.Context, org string, req CampaignCreate) (*Campaign, error)

CreateCampaign creates a campaign.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body, out any) (http.Header, error)

Do sends body (JSON-encoded unless it is []byte or nil) and decodes a JSON answer into out (when non-nil). It returns the response headers.

func (*Client) EnsureRelease

func (c *Client) EnsureRelease(ctx context.Context, repo, tag string, create bool) (*ReleaseInfo, bool, error)

EnsureRelease returns the release for tag. When there is none it creates it as a draft if create is set, so nothing is published by accident, and otherwise returns the 404. Needs contents: write.

func (*Client) GetAll

func (c *Client) GetAll(ctx context.Context, path string, out any) error

GetAll fetches every page of a list endpoint and decodes the concatenated items into out (a pointer to a slice).

func (*Client) ListAdvisories

func (c *Client) ListAdvisories(ctx context.Context, repo string) ([]RepositoryAdvisory, error)

ListAdvisories returns every repository advisory, all states.

func (*Client) ListCampaigns

func (c *Client) ListCampaigns(ctx context.Context, org string) ([]Campaign, error)

ListCampaigns returns the organization's campaigns, open and closed.

func (*Client) ListOpenAlerts

func (c *Client) ListOpenAlerts(ctx context.Context, repo string) ([]Alert, error)

ListOpenAlerts returns the repository's open code scanning alerts.

func (*Client) PatchCampaign

func (c *Client) PatchCampaign(ctx context.Context, org string, number int, req CampaignPatch) (*Campaign, error)

PatchCampaign updates a campaign by its number.

func (*Client) RepositoryID

func (c *Client) RepositoryID(ctx context.Context, repo string) (int, error)

RepositoryID returns the numeric id of owner/name.

func (*Client) SubmitSnapshot

func (c *Client) SubmitSnapshot(ctx context.Context, repo string, s *Snapshot) (*SnapshotResult, error)

SubmitSnapshot posts a snapshot.

func (*Client) SubmitSnapshotLenient

func (c *Client) SubmitSnapshotLenient(ctx context.Context, repo string, s *Snapshot) (*SnapshotResult, []string, error)

SubmitSnapshotLenient posts a snapshot and, when GitHub refuses one package as invalid, drops that package and posts again, so one purl the API does not know cannot cost the repository its whole dependency graph. It returns the packages it left out.

func (*Client) UpdateAdvisory

func (c *Client) UpdateAdvisory(ctx context.Context, repo, ghsaID string, req AdvisoryRequest) (*RepositoryAdvisory, error)

UpdateAdvisory edits a draft advisory. It never sends a state, so it cannot publish one.

func (*Client) UploadAsset

func (c *Client) UploadAsset(ctx context.Context, repo string, rel *ReleaseInfo, path, name string, clobber bool) (*AssetEntry, error)

UploadAsset uploads the file at path to the release under name. An asset of the same name is replaced when clobber is set, and is an error otherwise, since GitHub refuses a duplicate name.

func (*Client) UploadSARIF

func (c *Client) UploadSARIF(ctx context.Context, t Target, sarifJSON []byte, checkoutURI string) (*SARIFUpload, error)

UploadSARIF posts one SARIF document for the target commit and ref.

func (*Client) WaitSARIF

func (c *Client) WaitSARIF(ctx context.Context, repo, id string, timeout, interval time.Duration) (*SARIFUpload, error)

WaitSARIF polls an upload until it is complete or failed, or until timeout. A timeout is not an error: GitHub keeps processing, and the upload stands.

type Manifest

type Manifest struct {
	Name     string                     `json:"name"`
	File     *ManifestFile              `json:"file,omitempty"`
	Resolved map[string]ResolvedPackage `json:"resolved"`
}

Manifest is one manifest's resolved packages.

type ManifestFile

type ManifestFile struct {
	SourceLocation string `json:"source_location"`
}

ManifestFile is the manifest's path in the repository.

type PullRequestRef

type PullRequestRef struct {
	Number int    `json:"number"`
	State  string `json:"state"`
	Base   struct {
		Ref string `json:"ref"`
	} `json:"base"`
	Head struct {
		Ref string `json:"ref"`
	} `json:"head"`
}

PullRequestRef is one PR a commit belongs to.

type Release

type Release struct {
	TagName string         `json:"tag_name"`
	Assets  []ReleaseAsset `json:"assets"`
}

func FetchReleaseByTag

func FetchReleaseByTag(ctx context.Context, token, apiURL, repository, tag string) (*Release, error)

FetchReleaseByTag reads one release by its tag.

apiURL is a parameter rather than a constant because GitHub Enterprise serves a different host, and guessing github.com there would read the wrong instance.

func (*Release) AssetMatching

func (r *Release) AssetMatching(substr string) *ReleaseAsset

AssetMatching finds the first asset whose name contains substr, ignoring case.

Substring rather than exact match because projects spell the same file checksums.txt, SHA256SUMS and tool_checksums.txt, and requiring each repository to declare which would be a per-repository input for a question the release itself already answers.

type ReleaseAsset

type ReleaseAsset struct {
	Name               string `json:"name"`
	BrowserDownloadURL string `json:"browser_download_url"`
}

type ReleaseInfo

type ReleaseInfo struct {
	ID        int64        `json:"id"`
	TagName   string       `json:"tag_name"`
	UploadURL string       `json:"upload_url"`
	HTMLURL   string       `json:"html_url"`
	Draft     bool         `json:"draft"`
	Assets    []AssetEntry `json:"assets"`
}

ReleaseInfo is a release as the write side needs it.

type Repository

type Repository struct {
	ID            int64  `json:"id"`
	FullName      string `json:"full_name"`
	Private       bool   `json:"private"`
	Visibility    string `json:"visibility"`
	DefaultBranch string `json:"default_branch"`
	Owner         *User  `json:"owner"`
	License       *struct {
		SpdxID string `json:"spdx_id"`
	} `json:"license"`
}

Repository is the subset of GET /repos/{repo} worth keeping.

type RepositoryAdvisory

type RepositoryAdvisory struct {
	GHSAID      string `json:"ghsa_id"`
	Summary     string `json:"summary"`
	Description string `json:"description"`
	State       string `json:"state"`
	HTMLURL     string `json:"html_url"`
}

RepositoryAdvisory is an advisory as listed.

type ResolvedPackage

type ResolvedPackage struct {
	PackageURL   string   `json:"package_url"`
	Relationship string   `json:"relationship,omitempty"`
	Scope        string   `json:"scope,omitempty"`
	Dependencies []string `json:"dependencies,omitempty"`
}

ResolvedPackage is one package in a manifest.

type SARIFUpload

type SARIFUpload struct {
	ID               string   `json:"id"`
	URL              string   `json:"url"`
	ProcessingStatus string   `json:"processing_status,omitempty"`
	AnalysesURL      string   `json:"analyses_url,omitempty"`
	Errors           []string `json:"errors,omitempty"`
}

SARIFUpload is one upload's id and processing state.

type Snapshot

type Snapshot struct {
	Version   int                 `json:"version"`
	SHA       string              `json:"sha"`
	Ref       string              `json:"ref"`
	Job       SnapshotJob         `json:"job"`
	Detector  SnapshotDetector    `json:"detector"`
	Scanned   string              `json:"scanned"`
	Manifests map[string]Manifest `json:"manifests"`
}

Snapshot is the dependency submission API's request body.

func BuildSnapshot

func BuildSnapshot(cdxJSON []byte, o SnapshotOptions) (*Snapshot, error)

BuildSnapshot turns a CycloneDX JSON document into a snapshot.

func (*Snapshot) Drop

func (s *Snapshot) Drop(purl string) bool

Drop removes a package, and every reference to it, from the snapshot. It reports whether the package was there.

func (*Snapshot) ManifestCount

func (s *Snapshot) ManifestCount() int

ManifestCount and PackageCount summarise a snapshot.

func (*Snapshot) PackageCount

func (s *Snapshot) PackageCount() int

type SnapshotDetector

type SnapshotDetector struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	URL     string `json:"url"`
}

SnapshotDetector names the tool.

type SnapshotJob

type SnapshotJob struct {
	Correlator string `json:"correlator"`
	ID         string `json:"id"`
	HTMLURL    string `json:"html_url,omitempty"`
}

SnapshotJob identifies the run; the correlator is what makes a later snapshot replace this one rather than add to it.

type SnapshotOptions

type SnapshotOptions struct {
	Target          Target
	Correlator      string
	JobID           string
	JobURL          string
	DetectorVersion string
	// DefaultManifest names the manifest for components with no
	// vulnetix:source-file (an SBOM this CLI did not write).
	DefaultManifest string
	Now             time.Time
}

SnapshotOptions are the run details a snapshot carries.

type SnapshotResult

type SnapshotResult struct {
	ID        int64  `json:"id"`
	CreatedAt string `json:"created_at"`
	Result    string `json:"result"`
	Message   string `json:"message"`
}

SnapshotResult is the API's answer.

type Target

type Target struct {
	// Repo is owner/name.
	Repo string
	// SHA is the full commit SHA.
	SHA string
	// Ref is the full ref (refs/heads/main, refs/pull/7/merge).
	Ref string
}

Target is the repository, commit and ref a publish applies to.

func ResolveTarget

func ResolveTarget(dir, repo, sha, ref string) (Target, error)

ResolveTarget works out the repository, commit and ref, explicit values first, then the GitHub Actions environment (GITHUB_REPOSITORY, GITHUB_SHA, GITHUB_REF; on pull_request the merge ref and merge commit, which is what code scanning expects), then the git checkout at dir. It errors when any of the three is still unknown.

func (Target) Name

func (t Target) Name() string

func (Target) Owner

func (t Target) Owner() string

Owner and Name split Repo.

type User

type User struct {
	Login string `json:"login"`
	Type  string `json:"type"`
}

User is a GitHub account reference.

type WorkflowRun

type WorkflowRun struct {
	ID              int64  `json:"id"`
	Name            string `json:"name"`
	RunNumber       int    `json:"run_number"`
	RunAttempt      int    `json:"run_attempt"`
	Event           string `json:"event"`
	Status          string `json:"status"`
	Conclusion      string `json:"conclusion"`
	HeadBranch      string `json:"head_branch"`
	HeadSHA         string `json:"head_sha"`
	HTMLURL         string `json:"html_url"`
	Path            string `json:"path"`
	Actor           *User  `json:"actor"`
	TriggeringActor *User  `json:"triggering_actor"`
	PullRequests    []struct {
		Number int `json:"number"`
	} `json:"pull_requests"`
}

WorkflowRun is the subset of GET /repos/{repo}/actions/runs/{id} worth keeping.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL