handler

package
v1.43.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 42 Imported by: ? 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 (
	DefaultPolicyPath         = ".policy.yml"
	DefaultSharedRepository   = ".github"
	DefaultSharedPolicyPath   = "policy.yml"
	DefaultStatusCheckContext = "policy-bot"
)
View Source
const (
	DefaultTemplatesDir = "templates"
	DefaultStaticDir    = "static"

	ManifestFile = "manifest.json"
)
View Source
const (
	SessionKeyUsername = "username"
	SessionKeyRedirect = "redirect"
)
View Source
const (
	LogKeyAudit string = "audit"
)
View Source
const (
	LogKeyGitHubSHA = "github_sha"
)

Variables

This section is empty.

Functions

func Health

func Health() http.Handler

func LoadTemplates

func LoadTemplates(c *FilesConfig, basePath string, githubURL string) (templatetree.Tree[*template.Template], error)

func Login

func Login(c githubapp.Config, basePath string, sessions *scs.Manager) oauth2.LoginCallback

func Metrics added in v1.34.0

func Metrics(r metrics.Registry, config prometheus.Config) http.Handler

func PostStatus added in v1.27.0

func PostStatus(ctx context.Context, client *github.Client, owner, repo, ref string, status github.RepoStatus) error

PostStatus posts a GitHub commit status with consistent logging.

func RequireLogin

func RequireLogin(sessions *scs.Manager, basePath string) func(http.Handler) http.Handler

func Static

func Static(prefix string, c *FilesConfig) http.Handler

func Validate

func Validate() http.Handler

Types

type Base

type Base struct {
	githubapp.ClientCreator

	Installations githubapp.InstallationsService
	GlobalCache   pull.GlobalCache
	ConfigFetcher *ConfigFetcher
	BaseConfig    *baseapp.HTTPConfig
	PullOpts      *PullEvaluationOptions

	AppName string
}

func (*Base) Evaluate

func (b *Base) Evaluate(ctx context.Context, installationID int64, trigger common.Trigger, loc pull.Locator) error

func (*Base) NewEvalContext added in v1.27.0

func (b *Base) NewEvalContext(ctx context.Context, installationID int64, loc pull.Locator) (*EvalContext, error)

func (*Base) PreparePRContext

func (b *Base) PreparePRContext(ctx context.Context, installationID int64, pr *github.PullRequest) (context.Context, zerolog.Logger)

type CheckRun

type CheckRun struct {
	Base
}

func (*CheckRun) Handle

func (h *CheckRun) Handle(ctx context.Context, eventType, deliveryID string, payload []byte) error

func (*CheckRun) Handles

func (h *CheckRun) Handles() []string

type ConfigFetcher

type ConfigFetcher struct {
	Loader          ConfigLoader
	Options         *policy.GlobalOptions
	SeenPolicyCache *SeenPolicyCache
}

func (*ConfigFetcher) ConfigForRepositoryBranch added in v1.28.0

func (cf *ConfigFetcher) ConfigForRepositoryBranch(ctx context.Context, client *github.Client, owner, repository, branch string) FetchedConfig

type ConfigLoader added in v1.41.2

type ConfigLoader interface {
	LoadConfig(ctx context.Context, client *github.Client, owner, repo, ref string) (appconfig.Config, error)
	LoadRemoteRef(ctx context.Context, client *github.Client, clientOwner string, remote appconfig.RemoteRef) (appconfig.Config, error)
}

ConfigLoader allows ConfigFetcher to unit test policy loading decisions

type CrossOrgMembershipContext

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

func NewCrossOrgMembershipContext

func NewCrossOrgMembershipContext(ctx context.Context, client *github.Client, orgName string, installations githubapp.InstallationsService, clientCreator githubapp.ClientCreator) *CrossOrgMembershipContext

func (*CrossOrgMembershipContext) IsOrgMember

func (c *CrossOrgMembershipContext) IsOrgMember(org, user string) (bool, error)

func (*CrossOrgMembershipContext) IsTeamMember

func (c *CrossOrgMembershipContext) IsTeamMember(team, user string) (bool, error)

func (*CrossOrgMembershipContext) OrganizationMembers

func (c *CrossOrgMembershipContext) OrganizationMembers(org string) ([]string, error)

func (*CrossOrgMembershipContext) TeamMembers

func (c *CrossOrgMembershipContext) TeamMembers(team string) ([]string, error)

type Details

type Details struct {
	Base
	Sessions  *scs.Manager
	Templates templatetree.Tree[*template.Template]
}

func (*Details) ServeHTTP

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

type DetailsReviewers added in v1.32.0

type DetailsReviewers struct {
	Details
}

func (*DetailsReviewers) ServeHTTP added in v1.32.0

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

type DetailsReviewersData added in v1.32.0

type DetailsReviewersData struct {
	PullRequest *github.PullRequest
	Reviewers   []string
	Incomplete  bool
}

type DetailsState added in v1.32.0

type DetailsState struct {
	Ctx         context.Context
	Logger      zerolog.Logger
	EvalContext *EvalContext

	Username    string
	PullRequest *github.PullRequest
}

DetailsState combines fields that the Details handler and related sub-handlers need to process requests

type ErrorResponse added in v1.33.0

type ErrorResponse struct {
	Error string `json:"error"`
}

type EvalContext added in v1.27.0

type EvalContext struct {
	Client   *github.Client
	V4Client *githubv4.Client

	Options   *PullEvaluationOptions
	PublicURL string

	PullContext pull.Context
	Config      FetchedConfig

	// If true, store statuses in the Status field instead of posting them to
	// GitHub. Only the last status is saved, so when this option is enabled,
	// callers should check for a non-nil status after each method call.
	SkipPostStatus bool
	Status         *github.RepoStatus
}

EvalContext contains common fields and methods used to evaluate policy requests. Handlers construct an EvalContext once they decide to handle a request or event, then call the appropriate methods for each stage of evaluation. Handlers with no special requirements can simply call Evaluate.

func (*EvalContext) Evaluate added in v1.27.0

func (ec *EvalContext) Evaluate(ctx context.Context, trigger common.Trigger) error

Evaluate runs the full process for evaluating a pull request.

func (*EvalContext) EvaluatePolicy added in v1.27.0

func (ec *EvalContext) EvaluatePolicy(ctx context.Context, evaluator common.Evaluator) (common.Result, error)

EvaluatePolicy evaluates the policy for a PR and generates a result. The evaluator must be non-nil, meaning callers should check the output of ParseConfig before calling this method.

func (*EvalContext) ParseConfig added in v1.27.0

func (ec *EvalContext) ParseConfig(ctx context.Context, trigger common.Trigger) (*policy.ParsedPolicy, error)

ParseConfig reports policy loading or validation errors and returns the policy if it exists, is valid, and requires evaluation for the trigger.

func (*EvalContext) PostStatus added in v1.27.0

func (ec *EvalContext) PostStatus(ctx context.Context, state, message string)

PostStatus posts a status for the evaluated PR.

func (*EvalContext) RunPostEvaluateActions added in v1.27.0

func (ec *EvalContext) RunPostEvaluateActions(ctx context.Context, result common.Result, trigger common.Trigger)

RunPostEvaluateActions executes additional actions that should happen after evaluation completes, like assigning reviewers or dismissing reviews. These actions happen after a status is posted to GitHub for the main evaluation.

Post-evaluate actions are best effort, so this function logs failures instead of returning an error.

type FetchedConfig

type FetchedConfig struct {
	Config     *policy.Config
	Policy     *policy.ParsedPolicy
	LoadError  error
	ParseError error

	// Sources starts with the leaf lookup, even if no policy was found.
	Sources []PolicyLocation

	SeenPolicy bool
}

func (FetchedConfig) PolicyLocation added in v1.43.0

func (fc FetchedConfig) PolicyLocation() string

type FilesConfig

type FilesConfig struct {
	Static    string `yaml:"static"`
	Templates string `yaml:"templates"`
}

type HealthCheck

type HealthCheck struct {
	Status  string `json:"status"`
	Version string `json:"version"`
}

type Index

type Index struct {
	Base

	GithubConfig *githubapp.Config
	Templates    templatetree.Tree[*template.Template]
}

func (*Index) ServeHTTP

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

type Installation added in v1.24.0

type Installation struct {
	Base
}

func (*Installation) Handles added in v1.24.0

func (h *Installation) Handles() []string

type IssueComment

type IssueComment struct {
	Base
}

func (*IssueComment) Handle

func (h *IssueComment) Handle(ctx context.Context, eventType, deliveryID string, payload []byte) error

Handle issue_comment See https://developer.github.com/v3/activity/events/types/#issuecommentevent

func (*IssueComment) Handles

func (h *IssueComment) Handles() []string

type Membership added in v1.25.0

type Membership struct {
	Name string
	Link string
}

type MergeGroup added in v1.28.0

type MergeGroup struct {
	Base
}

func (*MergeGroup) Handle added in v1.28.0

func (h *MergeGroup) Handle(ctx context.Context, eventType, devlieryID string, payload []byte) error

Handle merge_group https://docs.github.com/webhooks-and-events/webhooks/webhook-events-and-payloads#merge_group

func (*MergeGroup) Handles added in v1.28.0

func (h *MergeGroup) Handles() []string

type PolicyLocation added in v1.43.0

type PolicyLocation struct {
	Source string
	Path   string
}

func (PolicyLocation) String added in v1.43.0

func (p PolicyLocation) String() string

type PullEvaluationOptions

type PullEvaluationOptions struct {
	PolicyPath string `yaml:"policy_path"`

	SharedRepository *string `yaml:"shared_repository"`
	SharedPolicyPath *string `yaml:"shared_policy_path"`

	// Ignore PolicyPath and use SharedRepository and SharedPolicyPath only.
	ForceSharedPolicy bool `yaml:"force_shared_policy"`

	// AllowPrivateRemotes enables loading remote policies from private repositories
	// owned by a different GitHub user or organization. This can expose policy
	// content and repository existence to users without direct access; see the README.
	AllowPrivateRemotes bool `yaml:"allow_private_remotes"`

	// StatusCheckContext will be used to create the status context. It will be used in the following
	// pattern: <StatusCheckContext>: <Base Branch Name>
	StatusCheckContext string `yaml:"status_check_context"`

	// ExpandRequiredReviewers enables a UI feature where the details page
	// shows a list of the users who can approve each rule. Enabling this
	// feature can leak information about team membership and permissions that
	// is otherwise private. See the README for details.
	ExpandRequiredReviewers bool `yaml:"expand_required_reviewers"`

	// StrictReviewDismissal enables sending unconditional GitHub dismissals
	// for reviews associated with rules of invalidated approval candidates
	// even if that same approval candidate satifies another rule.
	StrictReviewDismissal bool `yaml:"strict_review_dismissal"`

	// PostInsecureStatusChecks enables the sending of a second status using just StatusCheckContext as the context,
	// no templating. This is turned off by default. This is to support legacy workflows that depend on the original
	// context behaviour, and will be removed in 2.0
	PostInsecureStatusChecks bool `yaml:"post_insecure_status_checks"`

	// IgnoreEditedComments enables ignoring comments that have been edited when evaluating approval rules.
	// This provides a server-side option to ignore edited comments across all rules.
	IgnoreEditedComments *bool `yaml:"ignore_edited_comments"`

	// ApprovalDefaults defines default values for all approval rules evaluated
	// by the server. Use this to change things like the default approval
	// comments or `invalidate_on_push` behavior globally. Policies may
	// override these default by providing their own values.
	ApprovalDefaults *approval.Defaults `yaml:"approval_defaults"`

	// This field is unused but is left to avoid breaking configuration files.
	// This value is now loaded from the GitHub API.
	//
	// TODO(bkeyes): remove in version 2.0
	Deprecated_AppName string `yaml:"app_name"`

	// This field is unused but is left to avoid breaking configuration files.
	// It enabled a temporary workaround for a GitHub API issue.
	//
	// TODO(bkeyes): remove in version 2.0
	Deprecated_DoNotLoadCommitPushedDate bool `yaml:"do_not_load_commit_pushed_date"`
}

func (*PullEvaluationOptions) SetValuesFromEnv added in v1.24.0

func (p *PullEvaluationOptions) SetValuesFromEnv(prefix string)

type PullRequest

type PullRequest struct {
	Base
}

func (*PullRequest) Handle

func (h *PullRequest) Handle(ctx context.Context, eventType, deliveryID string, payload []byte) error

Handle pull_request https://developer.github.com/v3/activity/events/types/#requestevent

func (*PullRequest) Handles

func (h *PullRequest) Handles() []string

type PullRequestReview

type PullRequestReview struct {
	Base
}

func (*PullRequestReview) Handle

func (h *PullRequestReview) Handle(ctx context.Context, eventType, deliveryID string, payload []byte) error

Handle pull_request_review https://developer.github.com/v3/activity/events/types/#pullrequestreviewevent

func (*PullRequestReview) Handles

func (h *PullRequestReview) Handles() []string

type SeenPolicyCache added in v1.41.2

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

func NewSeenPolicyCache added in v1.41.2

func NewSeenPolicyCache() *SeenPolicyCache

func (*SeenPolicyCache) Get added in v1.41.2

func (c *SeenPolicyCache) Get(key SeenPolicyKey) bool

func (*SeenPolicyCache) Set added in v1.41.2

func (c *SeenPolicyCache) Set(key SeenPolicyKey)

type SeenPolicyKey added in v1.41.2

type SeenPolicyKey struct {
	Owner      string
	Repository string
	BaseBranch string
}

SeenPolicyKey identifies a repo branch where policy-bot has seen a policy file.

type Simulate added in v1.33.0

type Simulate struct {
	Base
}

Simulate provides a baseline for handlers to perform simulated pull request evaluations and either return the result or display it in the ui.

func (*Simulate) ServeHTTP added in v1.33.0

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

type SimulationResponse added in v1.33.0

type SimulationResponse struct {
	Name              string                `json:"name"`
	Description       string                `json:"description"`
	StatusDescription string                `json:"status_description"`
	Status            string                `json:"status"`
	Error             string                `json:"error"`
	Slot              string                `json:"slot,omitempty"`
	Children          []*SimulationResponse `json:"children,omitempty"`
}

SimulationResponse is the response returned from Simulate, this is a trimmed down version of common.Result with json tags. This struct and the newSimulationResponse constructor can be extended to include extra content from common.Result.

type Status

type Status struct {
	Base
}

func (*Status) Handle

func (h *Status) Handle(ctx context.Context, eventType, deliveryID string, payload []byte) error

Handle status https://developer.github.com/v3/activity/events/types/#statusevent

func (*Status) Handles

func (h *Status) Handles() []string

type ValidateCheck

type ValidateCheck struct {
	Message string `json:"message"`
	Version string `json:"version"`
}

type WorkflowRun added in v1.36.0

type WorkflowRun struct {
	Base
}

func (*WorkflowRun) Handle added in v1.36.0

func (h *WorkflowRun) Handle(ctx context.Context, eventType, deliveryID string, payload []byte) error

func (*WorkflowRun) Handles added in v1.36.0

func (h *WorkflowRun) Handles() []string

Jump to

Keyboard shortcuts

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