webhook

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

pkg/controller/webhook

The webhook adapter resolves watched-resource rules to GroupVersionKinds and routes AdmissionReview requests from pkg/webhook.Server through the synchronous dry-run validation pipeline.

Lifecycle

The controller creates one process-owned HTTPS listener and passes it through Config.Server. Each iteration atomically installs a complete validator generation. Teardown replaces it with an empty fail-closed generation and waits for active requests before releasing iteration dependencies. The listener stays bound for the next iteration.

When Config.Server is nil, the component creates, serves, shuts down, and joins its own server. Tests use this owned mode with fixed certificate bytes.

Configuration

Field Purpose
Server Process-owned server to adopt. Omit only when the component should own the listener.
Port, Path Owned-server address settings; defaults are 9443 and /validate.
CertDir Directory containing mounted tls.crt and tls.key for reloadable certificates.
CertPEM, KeyPEM Fixed certificate bytes used when CertDir is empty.
Rules Watched resources to validate, normally from ExtractWebhookRules.
DryRunValidator Synchronous ValidateDirect implementation; required when Rules isn't empty.
ResourceAdmissionTimeout Inner validation deadline, default 9s.
OnGenerationRetired Releases state captured by an adopted server's retired table.

restMapper resolves each rule's GroupVersionResource to a GroupVersionKind. The optional metrics recorder receives request duration and allow, deny, or unregistered outcomes.

Validation flow

Start resolves all rules and installs their validators as one generation. A request then passes structural checks and runs DryRunValidator.ValidateDirect against selector-aware overlays for every configured alias of the request GVR. The returned warnings are included in the AdmissionResponse.

Missing validators and canceled iteration validators deny with status 503. The chart's watched-resource rules use failurePolicy: Fail and a 10-second timeout, one second longer than the controller deadline. The chart doesn't create a HAProxyTemplateConfig webhook; complete config sets are validated through the ADR-0016 preflight and load gates.

See pkg/webhook, pkg/controller/dryrunvalidator, and pkg/controller/proposalvalidator.

Documentation

Overview

Package webhook connects the admission server to controller validation.

Index

Constants

View Source
const (
	// ComponentName is the unique identifier for this component.
	ComponentName = "webhook"

	// DefaultWebhookPort is the default HTTPS port for the webhook server.
	DefaultWebhookPort = 9443

	// DefaultWebhookPath is the default URL path for validation requests.
	DefaultWebhookPath = "/validate"

	// DefaultResourceAdmissionTimeout bounds watched-resource (for example,
	// Ingress) dry-run admission. The chart pairs it with a 10-second Kubernetes
	// webhook timeout. Keeping this path at nine seconds limits per-request work
	// and preserves fail-closed admission under untrusted routing-resource load.
	DefaultResourceAdmissionTimeout = 9 * time.Second

	// MaximumAdmissionTimeout is the largest safe controller-side deadline.
	// Kubernetes caps ValidatingWebhookConfiguration.timeoutSeconds at 30;
	// keeping one second of response margin makes 29 seconds the hard maximum.
	MaximumAdmissionTimeout = 29 * time.Second
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Component

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

Component is the webhook adapter component that manages webhook lifecycle.

It coordinates the pure webhook library server with the event-driven controller architecture.

func New

func New(logger *slog.Logger, config *Config, restMapper meta.RESTMapper, metrics MetricsRecorder) *Component

New creates a new webhook component.

Parameters:

  • logger: Structured logger
  • config: Component configuration (must include CertPEM and KeyPEM)
  • restMapper: RESTMapper for resolving resource kinds from GVR
  • metrics: Optional metrics recorder (can be nil)

Returns:

  • A new Component instance ready to be started

func (*Component) Listening

func (c *Component) Listening() <-chan struct{}

Listening returns a channel that is closed once the underlying webhook server has bound its TLS listener. Until this channel is closed, an admission request routed at the controller fails with "connection refused", because the listening socket simply doesn't exist yet.

func (*Component) Start

func (c *Component) Start(ctx context.Context) error

Start starts the webhook component.

This method: 1. Validates TLS certificates from configuration 2. Creates and starts the webhook HTTPS server 3. Publishes lifecycle events

The server continues running until the context is cancelled.

type Config

type Config struct {
	// Port is the HTTPS port for the webhook server.
	// Default: 9443
	Port int

	// Path is the URL path for validation requests.
	// Default: "/validate"
	Path string

	// CertDir, when set, is a directory containing tls.crt and tls.key
	// (typically the mounted webhook-cert Secret). The server reads them
	// per-handshake and hot-reloads a rotated certificate without a restart.
	// Takes precedence over CertPEM/KeyPEM; production uses this path.
	CertDir string

	// CertPEM is the PEM-encoded TLS certificate.
	// Used when CertDir is unset (e.g. tests pass certs directly).
	CertPEM []byte

	// KeyPEM is the PEM-encoded TLS private key.
	// Used when CertDir is unset.
	KeyPEM []byte

	// Rules defines which resources the webhook validates.
	// Used for registering validators by GVK.
	Rules []WebhookRule

	// DryRunValidator performs dry-run validation of resources.
	// Required when Rules is non-empty.
	DryRunValidator DryRunValidator

	// ResourceAdmissionTimeout bounds watched-resource dry-run validation.
	// Default: 9s. Keep it below the corresponding Kubernetes webhook
	// timeoutSeconds value so the controller can return a structured decision.
	ResourceAdmissionTimeout time.Duration

	// Server is a caller-owned listener; the component replaces only its validator generation.
	Server *webhook.Server

	// OnGenerationRetired releases resources captured by the installed table.
	OnGenerationRetired func()
}

Config configures the webhook component.

type DryRunValidator

type DryRunValidator interface {
	ValidateDirect(ctx context.Context, gvk, namespace, name string, object, oldObject any, operation string) (allowed bool, reason string, warnings []string)
}

DryRunValidator defines the synchronous interface the webhook uses to validate resources. The implementation in pkg/controller/dryrunvalidator is a library, not a lifecycle component.

Warnings are surfaced via AdmissionResponse.Warnings on both allow and deny paths so kubectl prints them as "Warning:" lines without blocking admission. Pluggable validators (e.g. the SPOA hub running in --validate-socket mode) populate this slice from their non-fatal diagnostics; the standard render+validate pipeline does not.

type MetricsRecorder

type MetricsRecorder interface {
	RecordWebhookRequest(gvk, result string, durationSeconds float64)
	RecordWebhookValidation(gvk, result string)
}

MetricsRecorder defines the interface for recording webhook metrics. This allows the component to work with or without metrics.

type WebhookRule

type WebhookRule struct {
	// APIGroup that this rule matches.
	// Example: "networking.k8s.io"
	APIGroup string

	// APIVersion that this rule matches.
	// Example: "v1"
	APIVersion string

	// Resource that this rule matches (plural, lowercase).
	// Example: "ingresses"
	Resource string
}

WebhookRule specifies which resources a webhook should intercept.

func ExtractWebhookRules

func ExtractWebhookRules(cfg *config.Config) []WebhookRule

ExtractWebhookRules extracts webhook rules from controller configuration.

It iterates through watched resources and creates webhook rules for resources with enable_validation_webhook: true.

Parameters:

  • cfg: Controller configuration containing watched resources

Returns:

  • Slice of webhook rules for resources that have validation enabled
  • Empty slice if no resources have webhook validation enabled

Jump to

Keyboard shortcuts

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