scm

package
v1.0.0-alpha.21 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 27 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

Overview

Package scm reaches a source-code host through one interface. GitHub and GitLab are the adapters so far.

Index

Constants

View Source
const (
	ReviewApproved         = "APPROVED"
	ReviewChangesRequested = "CHANGES_REQUESTED"
	ReviewCommented        = "COMMENTED"
	ReviewDismissed        = "DISMISSED"
	ReviewPending          = "PENDING"
)

The review states a host lists. A webhook writes them in lower case.

View Source
const (
	EventPullRequest              = "pull_request"
	EventCheckRun                 = "check_run"
	EventInstallation             = "installation"
	EventInstallationRepositories = "installation_repositories"
)

The events the App queues. Every other event is acknowledged and dropped.

View Source
const (
	InstallationCreated     = "created"
	InstallationDeleted     = "deleted"
	InstallationSuspended   = "suspend"
	InstallationUnsuspended = "unsuspend"
	RepositoriesAdded       = "added"
	RepositoriesRemoved     = "removed"
)

The installation actions the App queues. Each changes what the App's installations table holds.

View Source
const (

	// ReplayWindow is how far an event's signed instant may sit from now.
	ReplayWindow = 10 * time.Minute
	// DeliveryRetention is how long a delivery id stays claimed: GitHub's
	// redelivery window, "the past 3 days" on its redelivering-webhooks page
	// as read on 2026-11-09. It outlasts the replay window because a
	// check_run states no instant, so the claim is what refuses its replay.
	DeliveryRetention = 72 * time.Hour
)
View Source
const (
	// ApproveAction is the identifier of the check's approve button.
	ApproveAction = "approve"
)
View Source
const (
	// DefaultAPI is github.com's API root.
	DefaultAPI = "https://api.github.com"
)

Variables

View Source
var (
	ErrAuthorApproval = errors.New("scm: the pull request's author cannot approve it")
	ErrNoWriteRole    = errors.New("scm: the approver holds no write role")
	ErrStaleHead      = errors.New("scm: the pull request's head has moved")
	ErrNotAnApproval  = errors.New("scm: the event is not an approval")
	ErrNotApproved    = errors.New("scm: the review does not approve the change")
	ErrNoApprover     = errors.New("scm: the review names no signed-in approver")
	ErrBotApproval    = errors.New("scm: an App's account cannot approve")
	ErrOffHead        = errors.New("scm: the review is not on the pull request's head")
	ErrExpiredReview  = errors.New("scm: the review is older than an approval lasts")
	ErrNoApproval     = errors.New("scm: no review approves the pull request's head")
)

The refusals an approval can answer.

View Source
var ErrIgnoredEvent = errors.New("scm: event not processed")

ErrIgnoredEvent reports an event the App does not process.

View Source
var ErrNoCheck = errors.New("scm: this host takes no check from this token")

ErrNoCheck reports a host where the adapter posts no check.

View Source
var ErrNoCommit = errors.New("scm: no commit on the ref touched the path")

ErrNoCommit reports a ref where no commit touched the path asked about.

View Source
var ErrNotFound = errors.New("scm: not found")

ErrNotFound reports a file or an object the host does not have.

Functions

func AppJWT

func AppJWT(ctx context.Context, signer Signer, appID string, now time.Time) (string, error)

AppJWT mints the App's RS256 JSON Web Token.

func Verify

func Verify(secret, body []byte, header string) bool

Verify checks a delivery's X-Hub-Signature-256 header in constant time.

Types

type AppTokens

type AppTokens struct {
	API          string
	AppID        string
	Installation int64
	Signer       Signer
	Now          func() time.Time
	// Client is as in GitHubOptions.
	Client *http.Client
	// contains filtered or unexported fields
}

AppTokens mints installation tokens with the App's minimum permissions and holds each until it nears its expiry.

func (*AppTokens) Token

func (a *AppTokens) Token(ctx context.Context) (string, error)

Token returns a live installation token.

type Approval

type Approval struct {
	PullRequest int
	Approver    string
	HeadSHA     string
	At          time.Time
	// ReviewID names the review that approved, 0 for the App's button.
	ReviewID int64
}

Approval records who approved which commit, and when. A failed check that an approval binds concludes neutral and names the approver.

func ApprovalOf

func ApprovalOf(ctx context.Context, roles Roles, rules ApprovalRules, pull PullRequest, reviews []Review, now time.Time) (Approval, error)

ApprovalOf finds the newest review that approves the pull request's head and passes every rule. Each reviewer's own latest approval, request for changes or dismissal is their standing: a later comment leaves it as it was. With no approval, the error says why the newest approval was refused.

func Approve

func Approve(ctx context.Context, host Host, request ApprovalRequest, now time.Time) (Approval, error)

Approve verifies one approval against the host. Any error refuses it.

func CountReview

func CountReview(ctx context.Context, roles Roles, rules ApprovalRules, pull PullRequest, review Review, now time.Time) (Approval, error)

CountReview holds one review to every rule. pull is the pull request as the host answers now, so a review of a commit the head has since left never counts. The write role is asked last, because it costs a request.

func (Approval) Holds

func (a Approval) Holds(head string) bool

Holds reports whether the approval still binds the pull request's head. A new push moves the head, and the approval lapses.

type ApprovalRequest

type ApprovalRequest struct {
	PullRequest int
	Approver    string
	HeadSHA     string
	// AllowAuthor lets a pull request's author approve it. It is off by default.
	AllowAuthor bool
}

ApprovalRequest is one press of the approve action.

func RequestFrom

func RequestFrom(event Event) (ApprovalRequest, error)

RequestFrom reads an approval out of a queued event.

type ApprovalRules

type ApprovalRules struct {
	AllowAuthor bool
	Lasts       time.Duration
}

ApprovalRules are what a repository asks of an approval: whether the author may approve, and how long an approval lasts.

type CheckRun

type CheckRun struct {
	Name       string
	HeadSHA    string
	Conclusion string
	Title      string
	Summary    string
	Text       string
	Completed  time.Time
}

CheckRun is one completed check.

type CommentFinder

type CommentFinder interface {
	// HasComment reports whether the token's own account wrote a comment on
	// the pull request that opens with marker.
	HasComment(ctx context.Context, pullRequest int, marker string) (bool, error)
}

CommentFinder finds a sticky comment without writing one.

type DeliveryStore

type DeliveryStore interface {
	// Claim reports true the first time an id is seen.
	Claim(ctx context.Context, delivery string, now time.Time) (bool, error)
	// Release forgets an id whose event could not be queued, so a redelivery
	// is processed.
	Release(ctx context.Context, delivery string) error
}

DeliveryStore gives each delivery id one claim.

type Event

type Event struct {
	Delivery        string
	Name            string
	Action          string
	Installation    int64
	Repository      string
	Sender          string
	PullRequest     int
	HeadSHA         string
	RequestedAction string
	// BaseBranch is the base branch of the pull request a check_run names,
	// empty when the payload states none in its format.
	BaseBranch string
	// Account is the login of the account an installation event's
	// installation belongs to.
	Account string
	// Added and Removed are the repositories an installation event gives the
	// installation and takes from it. A created installation lists its
	// repositories in Added.
	Added, Removed []InstalledRepository
	// At is the instant the signed payload states for this event. It is zero
	// for a check_run, whose payload holds no instant of the click.
	At time.Time
}

Event is the part of a webhook the App acts on. Every string passed a check against its own format, because the rest of the App treats them as safe.

func ParseEvent

func ParseEvent(name string, body []byte) (Event, error)

ParseEvent reads a verified webhook body.

type ForkHeads

type ForkHeads interface {
	// OpenPullsFrom lists this repository's open pull requests whose head is
	// branch in a repository owner holds.
	OpenPullsFrom(ctx context.Context, owner, branch string) ([]OpenPull, error)
	// BranchesAt lists this repository's branches whose head is the commit.
	BranchesAt(ctx context.Context, sha string) ([]string, error)
}

ForkHeads is what a fork's follow-up asks before it posts on a commit.

type GitHub

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

GitHub is the Host for one repository.

func NewGitHub

func NewGitHub(options GitHubOptions) (*GitHub, error)

NewGitHub returns the adapter. The token never travels over plain HTTP, except to a loopback address.

func (*GitHub) BranchHead

func (g *GitHub) BranchHead(ctx context.Context, branch string) (string, error)

BranchHead reads the commit at the head of a branch through the git refs API. The answer must name the branch's own ref, so a prefix never matches.

func (*GitHub) BranchesAt

func (g *GitHub) BranchesAt(ctx context.Context, sha string) ([]string, error)

BranchesAt lists this repository's branches whose head is the commit.

func (*GitHub) CanWrite

func (g *GitHub) CanWrite(ctx context.Context, login string) (bool, error)

CanWrite reads the collaborator's permission field.

func (*GitHub) CheckRuns

func (g *GitHub) CheckRuns(ctx context.Context, sha, name string) ([]ListedCheck, error)

CheckRuns lists the commit's completed check runs named name, every attempt included, that GitHub Actions or this token's own App posted.

func (*GitHub) FirstCommit

func (g *GitHub) FirstCommit(ctx context.Context, path, ref string) (time.Time, error)

FirstCommit returns the committer date of the oldest commit on ref that touched path. The commits API lists the newest first, so it pages to the end. A ref where no commit touched path is ErrNoCommit.

func (*GitHub) HasComment

func (g *GitHub) HasComment(ctx context.Context, pullRequest int, marker string) (bool, error)

HasComment reports whether the token's own account wrote a comment that opens with marker, as UpsertComment finds one. It writes nothing.

func (*GitHub) OpenPullsFrom

func (g *GitHub) OpenPullsFrom(ctx context.Context, owner, branch string) ([]OpenPull, error)

OpenPullsFrom lists the open pull requests whose head is branch in a repository owner holds. It asks by branch, not by commit: GitHub's list of a commit's pull requests leaves out a fork's.

func (*GitHub) PostCheck

func (g *GitHub) PostCheck(ctx context.Context, check CheckRun) (int64, error)

PostCheck creates the check run and returns its id. Only a GitHub App can create one, and the answer names that App, so the adapter takes the App's account as the token's own from then on.

func (*GitHub) PullCommits

func (g *GitHub) PullCommits(ctx context.Context, number int) ([]string, bool, error)

PullCommits pages through the pull request's commits, oldest first. GitHub lists 250 at most, and a list that reaches 250 is capped.

func (*GitHub) PullRequest

func (g *GitHub) PullRequest(ctx context.Context, number int) (PullRequest, error)

PullRequest reads the head and the author.

func (*GitHub) ReadFile

func (g *GitHub) ReadFile(ctx context.Context, path, ref string) ([]byte, error)

ReadFile reads one file through the contents API.

func (*GitHub) Reviews

func (g *GitHub) Reviews(ctx context.Context, number int) ([]Review, error)

Reviews pages through the pull request's reviews in the order GitHub lists them. A review whose account was deleted names no reviewer, and a pending review states no time.

func (*GitHub) UpdateCheck

func (g *GitHub) UpdateCheck(ctx context.Context, id int64, check CheckRun) error

UpdateCheck rewrites the output of a check run this token created. The conclusion stays as it was posted.

func (*GitHub) UpsertComment

func (g *GitHub) UpsertComment(ctx context.Context, pullRequest int, marker, body string) error

UpsertComment edits the sticky comment in place. Only a comment the token's own account wrote qualifies, so neither a person nor another App that writes the marker into its own comment can have it rewritten.

func (*GitHub) Visibility

func (g *GitHub) Visibility(ctx context.Context) (Visibility, error)

Visibility asks the host, and an answer that omits the field is an error.

type GitHubOptions

type GitHubOptions struct {
	// API is the API root, DefaultAPI when empty.
	API string
	// Repository is owner/name.
	Repository string
	Tokens     TokenSource
	// Client makes the requests, under this package's timeout and redirect
	// rule. Required, so that a service can pass one bound by its allowlist.
	Client *http.Client
	// Limits and Installation apply the App's write limits. A token from CI
	// has neither.
	Limits       *Limiter
	Installation int64
}

GitHubOptions configures a GitHub adapter.

type GitLab

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

GitLab is the Reporter for one project. It reaches GitLab's REST API v4, and it has run against a stub built from GitLab's documentation and on a self-managed GitLab CE 19.5.1 (e2e/gitlab), not on gitlab.com.

func NewGitLab

func NewGitLab(options GitLabOptions) (*GitLab, error)

NewGitLab returns the adapter. The token never travels over plain HTTP, except to a loopback address.

func (*GitLab) BranchHead

func (g *GitLab) BranchHead(ctx context.Context, branch string) (string, error)

BranchHead reads the commit at the head of a branch through the repository branches API.

func (*GitLab) PostCheck

func (g *GitLab) PostCheck(context.Context, CheckRun) (int64, error)

PostCheck posts nothing. A commit status needs the Developer role and a note needs less, so the note's token cannot set one, and a status has no neutral state to state.

func (*GitLab) ReadFile

func (g *GitLab) ReadFile(ctx context.Context, path, ref string) ([]byte, error)

ReadFile reads one file through the repository files API.

func (*GitLab) UpdateCheck

func (g *GitLab) UpdateCheck(context.Context, int64, CheckRun) error

UpdateCheck sends nothing, because PostCheck creates no check.

func (*GitLab) UpsertComment

func (g *GitLab) UpsertComment(ctx context.Context, mergeRequest int, marker, body string) error

UpsertComment edits the sticky note in place. Only a note this token's own user wrote qualifies, because a note's author carries no bot field. A failed search posts nothing, so a merge request never holds a second note.

func (*GitLab) Visibility

func (g *GitLab) Visibility(ctx context.Context) (Visibility, error)

Visibility asks the host. An answer outside GitLab's three values is an error, and internal counts as private.

type GitLabOptions

type GitLabOptions struct {
	// API is the instance's REST root, CI_API_V4_URL in a job. It has no
	// default, so a self-managed instance's token never reaches gitlab.com.
	API string
	// Project is the project's numeric id.
	Project string
	Tokens  TokenSource
	// Client is as in GitHubOptions.
	Client *http.Client
}

GitLabOptions configures a GitLab adapter.

type History

type History interface {
	// PullCommits lists the pull request's commits, oldest first. Capped says
	// the list reached the most the host lists, so later commits can be
	// missing from it.
	PullCommits(ctx context.Context, number int) (commits []string, capped bool, err error)
	// CheckRuns lists the commit's completed check runs named name that
	// GitHub Actions or the App this token belongs to posted. No other App's
	// check run is listed, whatever its name.
	CheckRuns(ctx context.Context, sha, name string) ([]ListedCheck, error)
}

History reads what earlier reports posted on a pull request.

type Host

type Host interface {
	Reporter
	PullRequest(ctx context.Context, number int) (PullRequest, error)
	// CanWrite reports whether login holds a write role on the repository.
	CanWrite(ctx context.Context, login string) (bool, error)
}

Host is one repository a person can approve a change on.

type InstalledRepository

type InstalledRepository struct {
	ID       int64
	FullName string
}

InstalledRepository is one repository an installation reaches: its id and owner/name.

type KMS

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

KMS calls AWS KMS in one region with the credentials it was given. Its errors name the call and AWS's error type, never a key, a token or a signature.

func KMSFromEnvironment

func KMSFromEnvironment(getenv func(string) string, keyID string, client *http.Client, now func() time.Time) (*KMS, error)

KMSFromEnvironment reads AWS's credentials, region and endpoint from the environment's variables. A key ARN names its region, which then needs no variable. The client is required, as GitHubOptions.Client is.

func (*KMS) Host

func (k *KMS) Host() string

Host is the host every call goes to, for an egress allowlist.

func (*KMS) PrepareImport

func (k *KMS) PrepareImport(ctx context.Context, keyID string) (*KeyImport, error)

PrepareImport asks KMS for the wrapping key and import token of keyID, for the RSA_AES_KEY_WRAP_SHA_256 algorithm, the one KMS takes for an RSA private key.

func (*KMS) Signer

func (k *KMS) Signer(keyID string) Signer

Signer returns the Signer for one asymmetric KMS key, whose key usage is SIGN_VERIFY. The private key stays in KMS.

type KMSError

type KMSError struct {
	Action string
	Status int
	// Type is AWS's error type, such as AccessDeniedException.
	Type string
}

KMSError is an answer of KMS other than 200.

func (*KMSError) Error

func (e *KMSError) Error() string

type KeyImport

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

KeyImport is one import into a KMS key created with origin EXTERNAL: its wrapping public key and import token, valid for 24 hours.

func (*KeyImport) Import

func (i *KeyImport) Import(ctx context.Context, material []byte) error

Import wraps an RSA private key, PKCS #8 in DER, and imports it with no expiry. The AES key it draws is zeroed before it returns. The caller owns material and zeroes it.

type LimitError

type LimitError struct {
	Wait time.Duration
}

LimitError says a request was held back, and for how long to wait.

func (*LimitError) Error

func (e *LimitError) Error() string

type Limiter

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

Limiter holds GitHub's limits per installation: two token buckets for content writes, and a ceiling on requests in flight.

func NewLimiter

func NewLimiter(now func() time.Time) *Limiter

NewLimiter returns a Limiter reading the given clock.

func (*Limiter) Admit

func (l *Limiter) Admit(installation int64, write bool) (release func(), err error)

Admit claims a place for one request. The caller runs release when the request ends. A refused request takes nothing from either bucket.

type ListedCheck

type ListedCheck struct {
	ID   int64
	Text string
}

ListedCheck is one completed check run as a commit's list gives it.

type MemoryDeliveries

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

MemoryDeliveries is a DeliveryStore for one process. Only verified deliveries reach it, and it holds each for DeliveryRetention.

func NewMemoryDeliveries

func NewMemoryDeliveries() *MemoryDeliveries

NewMemoryDeliveries returns an empty store.

func (*MemoryDeliveries) Claim

func (m *MemoryDeliveries) Claim(_ context.Context, delivery string, now time.Time) (bool, error)

Claim implements DeliveryStore.

func (*MemoryDeliveries) Release

func (m *MemoryDeliveries) Release(_ context.Context, delivery string) error

Release implements DeliveryStore.

type OpenPull

type OpenPull struct {
	Number  int
	HeadSHA string
	// HeadRepository is owner/name, empty when the host no longer has it.
	HeadRepository string
}

OpenPull is one open pull request as the host lists it.

type PullRequest

type PullRequest struct {
	Number  int
	HeadSHA string
	Author  string
}

PullRequest is what an approval needs to know about a pull request.

type Queue

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

Queue carries events from the handler to the workers.

func NewQueue

func NewQueue(size int) *Queue

NewQueue returns a Queue that holds size events.

func (*Queue) Offer

func (q *Queue) Offer(event Event) bool

Offer queues an event without blocking and reports whether it fit.

func (*Queue) Run

func (q *Queue) Run(ctx context.Context, process func(context.Context, Event))

Run hands events to process until ctx ends.

type Reporter

type Reporter interface {
	// PostCheck returns the check's id. A host without one answers ErrNoCheck.
	PostCheck(ctx context.Context, check CheckRun) (int64, error)
	// UpdateCheck replaces the output of check run id with check's title,
	// summary and text. A host without checks answers ErrNoCheck.
	UpdateCheck(ctx context.Context, id int64, check CheckRun) error
	// UpsertComment edits the comment that opens with marker and that the
	// token's own account wrote, or creates it when there is none.
	UpsertComment(ctx context.Context, pullRequest int, marker, body string) error
	// ReadFile reads a file at a ref. A missing file is ErrNotFound.
	ReadFile(ctx context.Context, path, ref string) ([]byte, error)
	Visibility(ctx context.Context) (Visibility, error)
}

Reporter is what a report needs from one repository on one source-code host.

type Review

type Review struct {
	ID       int64
	Reviewer string
	// State is one of the Review states, in upper case.
	State       string
	CommitID    string
	SubmittedAt time.Time
}

Review is one pull request review as the host lists it.

type ReviewLister

type ReviewLister interface {
	Reviews(ctx context.Context, number int) ([]Review, error)
}

ReviewLister lists a pull request's reviews.

type Roles

type Roles interface {
	CanWrite(ctx context.Context, login string) (bool, error)
}

Roles answers whether an account can write to the repository.

type Signer

type Signer interface {
	Sign(ctx context.Context, digest [sha256.Size]byte) ([]byte, error)
}

Signer signs a SHA-256 digest with RSASSA-PKCS1-v1_5. The production signer is a KMS call, so the private key never reaches this process.

type StaticToken

type StaticToken string

StaticToken is a token CI hands the process.

func (StaticToken) Token

func (t StaticToken) Token(context.Context) (string, error)

Token returns the token.

type StatusError

type StatusError struct {
	Method     string
	Path       string
	Status     int
	RetryAfter time.Duration
}

StatusError is an answer the host refused. It never carries the body, which is the host's text and can echo the request.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Is

func (e *StatusError) Is(target error) bool

Is makes a 404 match ErrNotFound.

type TokenSource

type TokenSource interface {
	Token(ctx context.Context) (string, error)
}

TokenSource supplies the bearer token of each request.

type Visibility

type Visibility int

Visibility is who can read a repository.

const (
	Private Visibility = iota
	Public
)

A repository is public or it is not. Internal counts as private.

type Webhook

type Webhook struct {
	Secret     []byte
	Deliveries DeliveryStore
	Queue      *Queue
	Now        func() time.Time
}

Webhook verifies GitHub deliveries and queues them. It does no processing, so its answer stays inside the budget whatever a worker is doing.

func (*Webhook) ServeHTTP

func (h *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request)

Directories

Path Synopsis
Package kmstest stands in for AWS KMS in tests.
Package kmstest stands in for AWS KMS in tests.
Package scmtest holds stub GitHub and GitLab APIs for tests.
Package scmtest holds stub GitHub and GitLab APIs for tests.

Jump to

Keyboard shortcuts

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