integration

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 47 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 integration is the integration-controller's engine: the edge between patchy and its external systems, driven by Integration resources.

Inbound, the receiver terminates the provider webhook paths (/github/webhooks, /google-cloud/webhooks, /wiz/webhooks and /generic/{name}/webhooks), authenticates each delivery against the configured Integrations' credentials, and turns scanner events into Finding resources through the pkg/source handler interface (accumulating alerts into an open finding for the accumulation window). Outbound, the Finding projection reconciler renders each Finding, with its Investigation and Remediation children, as a tracking issue: body, labels, comments, assignment, alert dismissal, and closure. Human signals on the tracking item (/approve comments, issue close/reopen, pull-request merge) flow back as Finding writes.

v1alpha1 simplification: one issues-enabled Integration and one code-scanning-enabled Integration per namespace (they are usually the same object). Ambiguity surfaces as an error condition rather than a guess; a routing field can widen this later.

Index

Constants

View Source
const (
	// AnnotationProjectedBody is the hash of the last rendered body+labels.
	AnnotationProjectedBody = "patchy.bitwisemedia.uk/projected-body"
	// AnnotationProjectedEnrichments is the hash of the last projected
	// enrichment sticky comments.
	AnnotationProjectedEnrichments = "patchy.bitwisemedia.uk/projected-enrichments"
	// AnnotationProjectedInvestigation names the Investigation whose report
	// comment was posted.
	AnnotationProjectedInvestigation = "patchy.bitwisemedia.uk/projected-investigation"
	// AnnotationProjectedRemediation names the Remediation whose report
	// comment was posted.
	AnnotationProjectedRemediation = "patchy.bitwisemedia.uk/projected-remediation"
	// AnnotationProjectedNotice records the phase whose human notice
	// (hold/hand-off/failure) was posted.
	AnnotationProjectedNotice = "patchy.bitwisemedia.uk/projected-notice"
	// AnnotationResolvedSource records the phase whose verdict was written
	// back to the originating source. It is separate from the notice
	// annotation because telling the scanner and telling the humans are
	// independent, so a failure of either must not suppress the other.
	AnnotationResolvedSource = "patchy.bitwisemedia.uk/resolved-source"
)

Projection-state annotations on the Finding: what has already been pushed to the tracking item, so re-reconciles stay idempotent without re-reading comments. All are integration-controller-owned.

View Source
const (
	// AccessTTL is how long a probe result is reused.
	AccessTTL = 5 * time.Minute
)

Repository-access cache bounds. A result is cached for AccessTTL whether it is good or bad, so a page left open does not turn into GitHub API traffic; a transient failure (AccessError) is cached only briefly.

View Source
const BranchPrefix = "patchy/"

BranchPrefix prefixes every remediation branch; the finding name follows, so pull-request webhooks resolve their Finding from the head ref alone.

View Source
const (
	// DefaultBackfillTTL is how long a finished (or never-decided) request
	// is kept. The status page's backfill cooldown reads finished requests,
	// so the TTL must outlast the cooldown.
	DefaultBackfillTTL = 7 * 24 * time.Hour
)

Backfill request timing.

View Source
const DefaultWindow = time.Hour

DefaultWindow is the accumulation window when unconfigured.

View Source
const GenericPathPattern = generic.PathPattern

GenericPathPattern is the wildcard route generic integrations deliver to. The pattern itself lives with the contract helpers in internal/generic (a k8s-free package the CLI dev harness also hosts it from); the /generic/ prefix keeps the ingress path list static and keeps integration names out of the provider routes' namespace.

View Source
const GitHubPath = "/" + string(v1alpha1.IntegrationProviderGitHub) + "/webhooks"

GitHubPath is the receiver route GitHub webhooks target.

View Source
const KeyHashIndex = "labels.key-hash"

KeyHashIndex is the field index over the key-hash label. Every ingested alert selects its finding family by this value. Without the index that List is a full informer-store scan per alert, O(backlog), which is ruinous on a brownfield estate. The index lookup is O(1).

View Source
const SCCPath = "/" + string(v1alpha1.IntegrationProviderGoogleCloud) + "/webhooks"

SCCPath is the receiver route Pub/Sub push subscriptions target. It matches the path integration_controller advertises on status.webhookPath, which is derived from the provider name.

View Source
const TrackingURLIndex = "status.tracking.url"

TrackingURLIndex is the field-indexer key mapping a tracking item's html URL to its Finding.

View Source
const WizPath = "/" + string(v1alpha1.IntegrationProviderWiz) + "/webhooks"

WizPath is the receiver route Wiz automation actions target. It matches the path integration_controller advertises on status.webhookPath, which is derived from the provider name. Both Wiz feeds (Issues and Defend) share it: an automation action carries no event-type header, so the decoder discriminates by payload shape instead.

Variables

View Source
var (
	// ErrNoIntegration: no enabled Integration provides the capability.
	ErrNoIntegration = integrationcap.ErrNoIntegration
	// ErrAmbiguousIntegration: several Integrations provide the capability.
	// v1alpha1 requires exactly one per namespace.
	ErrAmbiguousIntegration = integrationcap.ErrAmbiguousIntegration
)

Sentinel errors for integration selection, shared with every other capability consumer through integrationcap.

View Source
var ErrNoCredential = errors.New("integration has no credential secret")

ErrNoCredential reports that the Integration names no credential Secret. This is legal (a google-cloud integration authenticates its inbound deliveries by OIDC and calls no API), so callers that only optionally need one check for it rather than treating it as a failure.

Functions

func GenericPathFor added in v0.9.1

func GenericPathFor(name string) string

GenericPathFor is the concrete webhook path of one generic Integration, advertised on status.webhookPath.

func KeyHashIndexer added in v0.10.0

func KeyHashIndexer(obj client.Object) []string

KeyHashIndexer extracts the index value: the finding's key-hash label. Exported so fake-client tests register the same recipe the manager does.

Types

type BackfillReconciler added in v0.16.0

type BackfillReconciler struct {
	client.Client
	// Creds builds the GitHub listers.
	Creds *Creds
	// Ingest folds the listed alerts into Findings.
	Ingest *Ingestor
	// TTL is how long a finished request is kept; <= 0 means
	// DefaultBackfillTTL.
	TTL time.Duration
	// Log receives reconcile diagnostics; nil discards.
	Log *slog.Logger
	// Now tells time; nil means time.Now (tests override).
	Now func() time.Time
	// ListerFor overrides backfill-lister construction in tests; nil means
	// the ghas lister built from the Integration's credential. ok=false
	// reports a provider with no listing capability.
	ListerFor func(ctx context.Context, integ *v1alpha1.Integration) (lister source.Lister, ok bool, err error)
}

BackfillReconciler walks BackfillRequests: one bounded list-alerts walk per request, through the named Integration's credential, ingesting every listed alert (ingestion is idempotent: an alert a live finding already tracks changes nothing). It is the single writer of BackfillRequest status, and deletes finished requests once their TTL has passed. The work queue runs one reconcile at a time, so walks never overlap.

func (*BackfillReconciler) Reconcile added in v0.16.0

func (r *BackfillReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile advances one BackfillRequest.

func (*BackfillReconciler) SetupWithManager added in v0.16.0

func (r *BackfillReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager wires the reconciler. Integration changes wake the requests they hold: one filed before its Integration's first credential check, or while it was suspended, runs as soon as the Integration is Ready rather than at the next hold retry.

type Creds

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

Creds reads Integration credential Secrets and builds GitHub clients.

func NewCreds

func NewCreds(r client.Reader) *Creds

NewCreds builds a Creds reading through r (the manager's API reader so Secrets stay uncached).

func (*Creds) App added in v0.5.4

func (c *Creds) App(ctx context.Context, integ *v1alpha1.Integration) (app *ghclient.App, ok bool, err error)

App returns the Integration's GitHub App for app-level (JWT) calls like the webhook delivery log. ok is false for a PAT credential, because PATs cannot see App webhook deliveries.

func (*Creds) CheckUserAuthorization added in v0.16.0

func (c *Creds) CheckUserAuthorization(
	ctx context.Context, integ *v1alpha1.Integration,
) (reason, msg string, err error)

CheckUserAuthorization validates the user-authorization settings for the UserAuthorizationReady condition: the OAuth settings resolve, and the configured client ID matches the App's own (GET /app). A GET /app that fails is not a verdict, so the condition stays True with a note.

func (*Creds) Client

func (c *Creds) Client(ctx context.Context, integ *v1alpha1.Integration, repo ghclient.Repo) (*ghclient.Client, error)

Client returns an API client for the Integration, authenticated for repo (App installation) or statically (PAT).

func (*Creds) UserClient added in v0.16.0

func (c *Creds) UserClient(ctx context.Context, integ *v1alpha1.Integration, token string) (*ghclient.Client, error)

UserClient returns an API client acting as a GitHub user, with the Integration's base URL and proxy.

func (*Creds) UserOAuth added in v0.16.0

func (c *Creds) UserOAuth(ctx context.Context, integ *v1alpha1.Integration) (*ghclient.OAuthApp, error)

UserOAuth returns the OAuth settings for the Integration's user authorization: the App's client ID and secret, the web root, and the proxy. It fails for an Integration that has not opted in, for a PAT credential, and for a Secret without the client secret.

func (*Creds) Validate

func (c *Creds) Validate(ctx context.Context, integ *v1alpha1.Integration) error

Validate checks the Integration is usable, by provider: github needs a secret carrying an API credential and a webhook secret; google-cloud, aws and azure hold no credential at all, so only their settings are checked; wiz needs its webhook token, plus API credentials when write-back is configured.

func (*Creds) WebhookSecret

func (c *Creds) WebhookSecret(ctx context.Context, integ *v1alpha1.Integration) ([]byte, error)

WebhookSecret returns the Integration's receiver HMAC secret.

func (*Creds) WizAPICreds added in v0.9.0

func (c *Creds) WizAPICreds(
	ctx context.Context, integ *v1alpha1.Integration,
) (clientID, clientSecret string, err error)

WizAPICreds returns the Wiz API service-account credentials for write-back.

func (*Creds) WizWebhookToken added in v0.9.0

func (c *Creds) WizWebhookToken(ctx context.Context, integ *v1alpha1.Integration) ([]byte, error)

WizWebhookToken returns the shared bearer token the Integration's inbound Wiz deliveries must carry.

type FindingReconciler

type FindingReconciler struct {
	client.Client
	// APIReader reads past the informer cache (the manager's
	// GetAPIReader); nil falls back to the cached Client (tests). The
	// projection's side effects on the forge are not idempotent, so every
	// "already done?" check before one, and every conflict retry recording
	// one, must read the server: the cache can lag this reconciler's own
	// writes, so a reconcile queued behind the one that posted a comment
	// can start from a Finding without the annotation recording it.
	APIReader client.Reader
	// Creds builds Integration API clients.
	Creds *Creds
	// Namespace the Findings live in.
	Namespace string
	// Concurrency is the number of findings projected in parallel; <=1 means
	// serial. The default is conservative: every projection may spend GitHub
	// API requests, and parallelism multiplies burst pressure on the
	// installation's rate limit.
	Concurrency int
	// Now tells time; nil means time.Now.
	Now func() time.Time
	// ClientFor overrides the tracker-client construction in tests.
	ClientFor func(ctx context.Context, integ *v1alpha1.Integration, repo ghclient.Repo) (trackerClient, error)
	// WizAPI overrides the Wiz write-back client construction in tests.
	WizAPI func(ctx context.Context, integ *v1alpha1.Integration) (wiz.IssueRejecter, error)
	// GenericResolver overrides the generic write-back construction in tests.
	GenericResolver func(ctx context.Context, integ *v1alpha1.Integration) (source.Resolver, error)
	// Log receives diagnostics; nil discards.
	Log *slog.Logger
}

FindingReconciler projects each Finding (and its children's results) onto its tracking issue, and owns the accumulation-window condition.

func (*FindingReconciler) Reconcile

func (r *FindingReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile implements the projection control loop.

func (*FindingReconciler) SetupWithManager

func (r *FindingReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager wires the reconciler: Findings plus child watches mapped to the owning Finding, and the tracking-URL field index the Signals handler queries.

type GitHubUser added in v0.16.0

type GitHubUser struct {
	// Reader gets Integrations (the manager's cache).
	Reader client.Reader
	// Creds reads the Integration's App credential and proxy settings.
	Creds *Creds
	// Access probes the Integration's alert access to a repository.
	Access *RepositoryAccess
	// Auth admits only the status server's ServiceAccount.
	Auth      callerAuth
	Namespace string
	Log       *slog.Logger
	// contains filtered or unexported fields
}

GitHubUser serves the internal GitHub-user endpoints (internal/ghuser): the token exchange and refresh of a github Integration's user authorization, and the user-token calls the status server's maintainer grants rest on. Only the status server calls them. User tokens pass through request and response bodies; they are never logged or kept.

func (*GitHubUser) Register added in v0.16.0

func (g *GitHubUser) Register(mux *http.ServeMux)

Register mounts the four endpoints on the internal listener's mux.

type Ingestor

type Ingestor struct {
	client.Client
	// Namespace the Findings live in.
	Namespace string
	// Window is the accumulation window (default DefaultWindow).
	Window time.Duration
	// Now tells time; nil means time.Now.
	Now func() time.Time
	// Log receives ingest diagnostics; nil discards.
	Log *slog.Logger
}

Ingestor folds scanner findings into Finding resources. Idempotency comes from the deterministic name plus an AlreadyExists-tolerant create. There is no in-process mutex: the API server serializes.

func (*Ingestor) Ingest

func (in *Ingestor) Ingest(ctx context.Context, integ *v1alpha1.Integration, f source.Finding) error

Ingest folds one scanner finding into the cluster: append its alert to the live pre-investigation Finding of its family, or create the next generation.

func (*Ingestor) SetupWithManager added in v0.10.0

func (in *Ingestor) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager registers the key-hash field index on the manager's cache. The Ingestor is webhook-driven and runs no reconciler, so this is its only manager hook. Without it every family List errors, a loud failure that is preferable to a silent full scan.

type IntegrationReconciler

type IntegrationReconciler struct {
	client.Client
	// Creds reads and validates the Integration's secret.
	Creds *Creds
	// Log receives reconcile diagnostics; nil discards.
	Log *slog.Logger
	// Now tells time; nil means time.Now (tests override).
	Now func() time.Time
	// ResetDedup drops the in-process webhook receiver's delivery dedup
	// window (webhook.Server.ResetDedup); nil is a no-op. Called when a
	// reset or replay request is consumed, so the redeliveries either
	// triggers are not swallowed as duplicates.
	ResetDedup func()
	// ClientFor overrides forge-client construction in tests; nil means
	// Creds.Client.
	ClientFor func(ctx context.Context, integ *v1alpha1.Integration, repo ghclient.Repo) (resetClient, error)
}

IntegrationReconciler validates Integration credentials and maintains the Ready condition and receiver path.

func (*IntegrationReconciler) Reconcile

func (r *IntegrationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile implements the Integration control loop.

func (*IntegrationReconciler) SetupWithManager

func (r *IntegrationReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager wires the reconciler.

type Receiver

type Receiver struct {
	// Reader lists Integrations (informer cache).
	Reader client.Reader
	// Creds builds Integration API clients.
	Creds *Creds
	// Ingest folds scanner findings into Finding resources.
	Ingest *Ingestor
	// Signals applies human-signal events to Findings.
	Signals *Signals
	// Namespace the Integrations and Findings live in.
	Namespace string
	// OIDCIssuer overrides the issuer the Pub/Sub push route verifies tokens
	// against; empty means Google, the only correct value in production.
	OIDCIssuer string
	// NewVerifier builds the OIDC token verifier for the Pub/Sub push route;
	// nil means discovery against OIDCIssuer.
	NewVerifier func(audience string) webhook.TokenVerifier
	// Log receives receiver diagnostics; nil discards.
	Log *slog.Logger
}

Receiver turns validated provider deliveries into Finding writes. Scanner and cloud findings go through the pkg/source handler interface into the Ingestor; tracking events (issues, comments, pull requests) go to the Signals handler. It serves one webhook.Endpoint per provider.

func (*Receiver) Endpoints added in v0.8.0

func (r *Receiver) Endpoints() []webhook.Endpoint

Endpoints are the provider routes this receiver serves. Each names how its deliveries authenticate and how they are labelled. Everything downstream (queueing, dedup, dispatch) belongs to the server and is the same for every route.

func (*Receiver) Secrets

func (r *Receiver) Secrets(ctx context.Context) [][]byte

Secrets returns every configured github Integration's webhook secret: the candidate set for delivery validation on the GitHub route.

func (*Receiver) WizTokens added in v0.9.0

func (r *Receiver) WizTokens(ctx context.Context) [][]byte

WizTokens returns every configured wiz Integration's webhook bearer token: the candidate set for delivery validation on the Wiz route.

type RepositoryAccess added in v0.15.0

type RepositoryAccess struct {
	// Reader lists Integrations (the manager's cache).
	Reader client.Reader
	// Creds builds the Integration GitHub clients.
	Creds *Creds
	// Forges resolves Forge coverage; nil skips the Forge check.
	Forges forgeCoverage
	// Auth admits only the status server's ServiceAccount.
	Auth      callerAuth
	Namespace string
	Log       *slog.Logger
	// contains filtered or unexported fields
}

RepositoryAccess serves the internal repository-access endpoint (internal/repoaccess): for each requested repository, whether each eligible github Integration can read its alerts, and whether a Forge can remediate it. Only the status server calls it. It never writes anything, and its results live only in a small in-memory cache.

func (*RepositoryAccess) Check added in v0.15.0

func (a *RepositoryAccess) Check(ctx context.Context, repos []string) ([]repoaccess.Result, error)

Check probes each repository, in order, against every eligible Integration and the Forge store.

func (*RepositoryAccess) Handler added in v0.15.0

func (a *RepositoryAccess) Handler() http.Handler

Handler is the internal listener's surface: the one endpoint.

func (*RepositoryAccess) IntegrationAccess added in v0.16.0

func (a *RepositoryAccess) IntegrationAccess(
	ctx context.Context, integ *v1alpha1.Integration, repo ghclient.Repo,
) repoaccess.IntegrationAccess

IntegrationAccess probes one Integration's alert access to one repository, through the shared cache.

type Signals

type Signals struct {
	client.Client
	// Namespace the Findings live in.
	Namespace string
	// Now tells time; nil means time.Now.
	Now func() time.Time
	// Log receives diagnostics; nil discards.
	Log *slog.Logger
}

Signals applies human actions on tracking items to Findings. It writes InReview→Remediated/Failed (PR merged/closed), Dismissed→HandedOff (issue reopened after dismissal), non-terminal→HandedOff (issue closed by a human), and spec.approval.

func (*Signals) Handle

func (s *Signals) Handle(ctx context.Context, integ *v1alpha1.Integration, e webhook.Event) error

Handle applies one tracking-system delivery.

Jump to

Keyboard shortcuts

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