Write an Admission Webhook Function
Validate with Admission Webhooks runs vet-kyverno-server and vet-opa-gatekeeper, which validate configuration against the admission webhooks of Kyverno and OPA Gatekeeper before it is released. If you use another policy engine, you can build your own validation function on the example's webhook package. The simplest start is the example itself: add a package like its kyverno and gatekeeper packages, and register its function in main.go.
Project setup
Start from a copy of the example and add a package for your engine, here mypolicyengine, next to its kyverno and gatekeeper packages:
cp -r examples/custom-workers/admission-webhook my-webhook-bot && cd my-webhook-bot
mkdir mypolicyengine
Writing the function
The webhook package provides three main components:
admissionwebhook.WebhookClientsends AdmissionReview requests to a webhook endpoint.admissionwebhook.K8sDiscoveryClientdiscovers ValidatingWebhookConfigurations from the Kubernetes API. It supports both in-cluster and kubeconfig-based authentication. The companionadmissionwebhook.WebhookWatcherwatches for changes so the endpoint list stays current.admissionwebhook.ValidateResourcesiterates over all resources in the configuration data, matches them against discovered webhooks, calls the webhooks, and aggregates the results into aValidationResult.
Here is a minimal example:
package mypolicyengine
import (
"context"
"fmt"
"log/slog"
"strings"
"github.com/cockroachdb/errors"
"github.com/confighub/sdk/configkit/k8skit"
"github.com/confighub/sdk/core/function/api"
"github.com/confighub/sdk/core/function/handler"
"github.com/confighub/sdk/core/third_party/gaby"
admissionwebhook "github.com/confighub/examples/custom-workers/admission-webhook/webhook"
)
const (
envURL = "MY_POLICY_URL"
envCACertPath = "MY_POLICY_CA_CERT_PATH"
envSkipTLSVerify = "MY_POLICY_SKIP_TLS_VERIFY"
)
var (
webhookClient *admissionwebhook.WebhookClient
watcher *admissionwebhook.WebhookWatcher
)
// Init creates the webhook client and starts watching for webhook changes.
// It is called once at startup via FunctionRegistration.FunctionInit.
func Init() error {
client, err := admissionwebhook.NewWebhookClient(
envURL, envCACertPath, envSkipTLSVerify,
)
if err != nil {
return err
}
discoveryClient, err := admissionwebhook.NewK8sDiscoveryClient()
if err != nil {
return errors.Wrap(err, "failed to create K8s discovery client")
}
// Configure the selector to match your policy engine's VWCs.
selector := admissionwebhook.WebhookSelector{
LabelSelector: "my-policy-engine.io/managed-by%3Dcontroller",
ConfigNames: []string{"my-policy-engine-webhook-config"},
}
w := admissionwebhook.NewWebhookWatcher(discoveryClient, selector)
if err := w.Start(context.Background()); err != nil {
return errors.Wrap(err, "failed to start webhook watcher")
}
webhookClient = client
watcher = w
return nil
}
// GetSignature returns the function signature.
func GetSignature() api.FunctionSignature {
return api.FunctionSignature{
FunctionName: "vet-my-policy-engine",
Parameters: []api.FunctionParameter{},
RequiredParameters: 0,
OutputInfo: &api.FunctionOutput{
ResultName: "passed",
Description: "True if all resources pass policy validation",
OutputType: api.OutputTypeValidationResult,
},
Mutating: false,
Validating: true,
Hermetic: false,
Idempotent: true,
Description: "Validates Kubernetes resources against my-policy-engine.",
FunctionType: api.FunctionTypeCustom,
AffectedResourceTypes: []api.ResourceType{api.ResourceTypeAny},
}
}
// Function is the function implementation.
func Function(fArgs handler.FunctionImplementationArguments) (gaby.Container, any, error) {
if webhookClient == nil || watcher == nil {
return fArgs.ParsedData, nil, errors.New("not initialized")
}
webhooks := watcher.GetEndpoints()
return admissionwebhook.ValidateResources(
webhookClient, webhooks,
k8skit.NewK8sResourceProvider(), fArgs.ParsedData,
responseConverter,
)
}
// responseConverter parses your policy engine's response format into
// details and failed attributes.
func responseConverter(
resp *admissionwebhook.AdmissionResponse,
resourceInfo api.ResourceInfo,
) ([]string, []api.AttributeValue) {
var details []string
var failedAttrs []api.AttributeValue
if resp.Status != nil && resp.Status.Message != "" {
// Parse the message according to your policy engine's format.
// For example, split on newlines and extract structured fields.
for _, line := range strings.Split(resp.Status.Message, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
details = append(details, line)
failedAttrs = append(failedAttrs, api.AttributeValue{
AttributeInfo: api.AttributeInfo{
AttributeIdentifier: api.AttributeIdentifier{
ResourceInfo: resourceInfo,
},
AttributeMetadata: api.AttributeMetadata{
AttributeName: api.AttributeNameNone,
},
},
Issues: []api.Issue{{
Identifier: "policy-violation",
Message: line,
}},
})
}
}
return details, failedAttrs
}
The ResponseConverter callback is where you parse your policy engine's specific message format. Kyverno uses a policy-name:\n rule-name: message format. Gatekeeper uses [constraint-name] message. Your engine will have its own format.
Registering the function
Register the function in the example's main.go next to the two it already serves, with FunctionInit for one-time initialization:
if err := exec.RegisterFunction(workerapi.ToolchainKubernetesYAML, handler.FunctionRegistration{
FunctionSignature: mypolicyengine.GetSignature(),
Function: mypolicyengine.Function,
FunctionInit: mypolicyengine.Init,
}); err != nil {
log.Fatalf("Failed to register function: %v", err)
}
FunctionInit is called once when RegisterFunction is called, before the bot claims its Channel. Here it creates the webhook client and starts the webhook watcher. The rest of main.go serves the functions on a Channel, as in external functions; after adding a function, declare it on the Channel again from --print-commands.
Key design decisions
WebhookSelector controls which ValidatingWebhookConfigurations are discovered:
LabelSelectorfilters VWCs by label (URL-encoded, e.g.,key%3Dvalue). This is passed to the Kubernetes API as a query parameter.ConfigNamesfilters VWCs by name after retrieval. Many policy engines create multiple VWCs (for policies, exceptions, etc.) but only one handles user resource validation.
WebhookWatcher keeps the endpoint list current without re-discovering on every function invocation. It uses the Kubernetes watch API and falls back to periodic re-listing (every 30 seconds) if the watch stream breaks.
ResponseConverter is the only part that differs between policy engines. Everything else (client, discovery, webhook matching, AdmissionReview construction, result aggregation) is handled by the webhook package.
Containerizing and deploying
Build an image from the example's Dockerfile, then run it as the admission-webhook example is run; see In a cluster.
Related reading
- Validate with Admission Webhooks, for running the bot and using its functions in Triggers
- Write and Run External Functions, for functions of any kind served on a Channel