准入控制器

简要概述

准入控制器的在 kube-apiserver 中的配置。

配置示例

apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: PodSecurity
  configuration:
    apiVersion: pod-security.admission.config.k8s.io/v1
    kind: PodSecurityConfiguration
    defaults:
      enforce: "baseline"
      enforce-version: "latest"
      audit: "restricted"
      audit-version: "latest"
      warn: "restricted"
      warn-version: "latest"
    exemptions:
      usernames: []
      runtimeClasses: []
      namespaces: [kube-system]

内置准入控制器

k8s.io/apiserver/pkg/apis/apiserver/v1/types.go

AdmissionConfiguration

// AdmissionConfiguration provides versioned configuration for admission controllers.
type AdmissionConfiguration struct {
    metav1.TypeMeta `json:",inline"`

    // Plugins allows specifying a configuration per admission control plugin.
    // +optional
    Plugins []AdmissionPluginConfiguration `json:"plugins"`
}

AdmissionPluginConfiguration

// AdmissionPluginConfiguration provides the configuration for a single plug-in.
type AdmissionPluginConfiguration struct {
    // Name is the name of the admission controller.
    // It must match the registered admission plugin name.
    Name string `json:"name"`

    // Path is the path to a configuration file that contains the plugin's
    // configuration
    // +optional
    Path string `json:"path"`

    // Configuration is an embedded configuration object to be used as the plugin's
    // configuration. If present, it will be used instead of the path to the configuration file.
    // +optional
    Configuration *runtime.Unknown `json:"configuration"`
}

动态准入控制器

k8s.io/api/admission/v1/types.go

AdmissionReview

// AdmissionReview describes an admission review request/response.
type AdmissionReview struct {
    metav1.TypeMeta `json:",inline"`
    // Request describes the attributes for the admission request.
    // +optional
    Request *AdmissionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"`
    // Response describes the attributes for the admission response.
    // +optional
    Response *AdmissionResponse `json:"response,omitempty" protobuf:"bytes,2,opt,name=response"`
}

AdmissionRequest

// AdmissionRequest describes the admission.Attributes for the admission request.
type AdmissionRequest struct {
    // UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are
    // otherwise identical (parallel requests, requests when earlier requests did not modify etc)
    // The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request.
    // It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging.
    UID types.UID `json:"uid" protobuf:"bytes,1,opt,name=uid"`
    // Kind is the fully-qualified type of object being submitted (for example, v1.Pod or autoscaling.v1.Scale)
    Kind metav1.GroupVersionKind `json:"kind" protobuf:"bytes,2,opt,name=kind"`
    // Resource is the fully-qualified resource being requested (for example, v1.pods)
    Resource metav1.GroupVersionResource `json:"resource" protobuf:"bytes,3,opt,name=resource"`
    // SubResource is the subresource being requested, if any (for example, "status" or "scale")
    // +optional
    SubResource string `json:"subResource,omitempty" protobuf:"bytes,4,opt,name=subResource"`

    // RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale).
    // If this is specified and differs from the value in "kind", an equivalent match and conversion was performed.
    //
    // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of
    // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`,
    // an API request to apps/v1beta1 deployments would be converted and sent to the webhook
    // with `kind: {group:"apps", version:"v1", kind:"Deployment"}` (matching the rule the webhook registered for),
    // and `requestKind: {group:"apps", version:"v1beta1", kind:"Deployment"}` (indicating the kind of the original API request).
    //
    // See documentation for the "matchPolicy" field in the webhook configuration type for more details.
    // +optional
    RequestKind *metav1.GroupVersionKind `json:"requestKind,omitempty" protobuf:"bytes,13,opt,name=requestKind"`
    // RequestResource is the fully-qualified resource of the original API request (for example, v1.pods).
    // If this is specified and differs from the value in "resource", an equivalent match and conversion was performed.
    //
    // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of
    // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`,
    // an API request to apps/v1beta1 deployments would be converted and sent to the webhook
    // with `resource: {group:"apps", version:"v1", resource:"deployments"}` (matching the resource the webhook registered for),
    // and `requestResource: {group:"apps", version:"v1beta1", resource:"deployments"}` (indicating the resource of the original API request).
    //
    // See documentation for the "matchPolicy" field in the webhook configuration type.
    // +optional
    RequestResource *metav1.GroupVersionResource `json:"requestResource,omitempty" protobuf:"bytes,14,opt,name=requestResource"`
    // RequestSubResource is the name of the subresource of the original API request, if any (for example, "status" or "scale")
    // If this is specified and differs from the value in "subResource", an equivalent match and conversion was performed.
    // See documentation for the "matchPolicy" field in the webhook configuration type.
    // +optional
    RequestSubResource string `json:"requestSubResource,omitempty" protobuf:"bytes,15,opt,name=requestSubResource"`

    // Name is the name of the object as presented in the request.  On a CREATE operation, the client may omit name and
    // rely on the server to generate the name.  If that is the case, this field will contain an empty string.
    // +optional
    Name string `json:"name,omitempty" protobuf:"bytes,5,opt,name=name"`
    // Namespace is the namespace associated with the request (if any).
    // +optional
    Namespace string `json:"namespace,omitempty" protobuf:"bytes,6,opt,name=namespace"`
    // Operation is the operation being performed. This may be different than the operation
    // requested. e.g. a patch can result in either a CREATE or UPDATE Operation.
    Operation Operation `json:"operation" protobuf:"bytes,7,opt,name=operation"`
    // UserInfo is information about the requesting user
    UserInfo authenticationv1.UserInfo `json:"userInfo" protobuf:"bytes,8,opt,name=userInfo"`
    // Object is the object from the incoming request.
    // +optional
    Object runtime.RawExtension `json:"object,omitempty" protobuf:"bytes,9,opt,name=object"`
    // OldObject is the existing object. Only populated for DELETE and UPDATE requests.
    // +optional
    OldObject runtime.RawExtension `json:"oldObject,omitempty" protobuf:"bytes,10,opt,name=oldObject"`
    // DryRun indicates that modifications will definitely not be persisted for this request.
    // Defaults to false.
    // +optional
    DryRun *bool `json:"dryRun,omitempty" protobuf:"varint,11,opt,name=dryRun"`
    // Options is the operation option structure of the operation being performed.
    // e.g. `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This may be
    // different than the options the caller provided. e.g. for a patch request the performed
    // Operation might be a CREATE, in which case the Options will a
    // `meta.k8s.io/v1.CreateOptions` even though the caller provided `meta.k8s.io/v1.PatchOptions`.
    // +optional
    Options runtime.RawExtension `json:"options,omitempty" protobuf:"bytes,12,opt,name=options"`
}

AdmissionResponse

// AdmissionResponse describes an admission response.
type AdmissionResponse struct {
    // UID is an identifier for the individual request/response.
    // This must be copied over from the corresponding AdmissionRequest.
    UID types.UID `json:"uid" protobuf:"bytes,1,opt,name=uid"`

    // Allowed indicates whether or not the admission request was permitted.
    Allowed bool `json:"allowed" protobuf:"varint,2,opt,name=allowed"`

    // Result contains extra details into why an admission request was denied.
    // This field IS NOT consulted in any way if "Allowed" is "true".
    // +optional
    Result *metav1.Status `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`

    // The patch body. Currently we only support "JSONPatch" which implements RFC 6902.
    // +optional
    Patch []byte `json:"patch,omitempty" protobuf:"bytes,4,opt,name=patch"`

    // The type of Patch. Currently we only allow "JSONPatch".
    // +optional
    PatchType *PatchType `json:"patchType,omitempty" protobuf:"bytes,5,opt,name=patchType"`

    // AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted).
    // MutatingAdmissionWebhook and ValidatingAdmissionWebhook admission controller will prefix the keys with
    // admission webhook name (e.g. imagepolicy.example.com/error=image-blacklisted). AuditAnnotations will be provided by
    // the admission webhook to add additional context to the audit log for this request.
    // +optional
    AuditAnnotations map[string]string `json:"auditAnnotations,omitempty" protobuf:"bytes,6,opt,name=auditAnnotations"`

    // warnings is a list of warning messages to return to the requesting API client.
    // Warning messages describe a problem the client making the API request should correct or be aware of.
    // Limit warnings to 120 characters if possible.
    // Warnings over 256 characters and large numbers of warnings may be truncated.
    // +optional
    Warnings []string `json:"warnings,omitempty" protobuf:"bytes,7,rep,name=warnings"`
}

types.UID

k8s.io/apimachinery/pkg/types/uid.go

// UID is a type that holds unique ID values, including UUIDs.  Because we
// don't ONLY use UUIDs, this is an alias to string.  Being a type captures
// intent and helps make sure that UIDs and names do not get conflated.
type UID string

Operation

// Operation is the type of resource operation being checked for admission control
type Operation string

// Operation constants
const (
    Create  Operation = "CREATE"
    Update  Operation = "UPDATE"
    Delete  Operation = "DELETE"
    Connect Operation = "CONNECT"
)

authenticationv1.UserInfo

k8s.io/api/authentication/v1/types.go

TODO;

runtime.RawExtension

k8s.io/apimachinery/pkg/runtime/types.go

TODO;

PatchType

// PatchType is the type of patch being used to represent the mutated object
type PatchType string

// PatchType constants.
const (
    PatchTypeJSONPatch PatchType = "JSONPatch"
)

即时配置 Webhook

ValidatingWebhookConfiguration

// ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it.
type ValidatingWebhookConfiguration struct {
    metav1.TypeMeta `json:",inline"`
    // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
    // +optional
    metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    // Webhooks is a list of webhooks and the affected resources and operations.
    // +optional
    // +patchMergeKey=name
    // +patchStrategy=merge
    Webhooks []ValidatingWebhook `json:"webhooks,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,2,rep,name=Webhooks"`
}

ValidatingWebhook

// ValidatingWebhook describes an admission webhook and the resources and operations it applies to.
type ValidatingWebhook struct {
    // The name of the admission webhook.
    // Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where
    // "imagepolicy" is the name of the webhook, and kubernetes.io is the name
    // of the organization.
    // Required.
    Name string `json:"name" protobuf:"bytes,1,opt,name=name"`

    // ClientConfig defines how to communicate with the hook.
    // Required
    ClientConfig WebhookClientConfig `json:"clientConfig" protobuf:"bytes,2,opt,name=clientConfig"`

    // Rules describes what operations on what resources/subresources the webhook cares about.
    // The webhook cares about an operation if it matches _any_ Rule.
    // However, in order to prevent ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks
    // from putting the cluster in a state which cannot be recovered from without completely
    // disabling the plugin, ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks are never called
    // on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects.
    Rules []RuleWithOperations `json:"rules,omitempty" protobuf:"bytes,3,rep,name=rules"`

    // FailurePolicy defines how unrecognized errors from the admission endpoint are handled -
    // allowed values are Ignore or Fail. Defaults to Fail.
    // +optional
    FailurePolicy *FailurePolicyType `json:"failurePolicy,omitempty" protobuf:"bytes,4,opt,name=failurePolicy,casttype=FailurePolicyType"`

    // matchPolicy defines how the "rules" list is used to match incoming requests.
    // Allowed values are "Exact" or "Equivalent".
    //
    // - Exact: match a request only if it exactly matches a specified rule.
    // For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1,
    // but "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`,
    // a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the webhook.
    //
    // - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version.
    // For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1,
    // and "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`,
    // a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the webhook.
    //
    // Defaults to "Equivalent"
    // +optional
    MatchPolicy *MatchPolicyType `json:"matchPolicy,omitempty" protobuf:"bytes,9,opt,name=matchPolicy,casttype=MatchPolicyType"`

	//......
    NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty" protobuf:"bytes,5,opt,name=namespaceSelector"`

	//......
	ObjectSelector *metav1.LabelSelector `json:"objectSelector,omitempty" protobuf:"bytes,10,opt,name=objectSelector"`
	
    // SideEffects states whether this webhook has side effects.
    // Acceptable values are: None, NoneOnDryRun (webhooks created via v1beta1 may also specify Some or Unknown).
    // Webhooks with side effects MUST implement a reconciliation system, since a request may be
    // rejected by a future step in the admission chain and the side effects therefore need to be undone.
    // Requests with the dryRun attribute will be auto-rejected if they match a webhook with
    // sideEffects == Unknown or Some.
    SideEffects *SideEffectClass `json:"sideEffects" protobuf:"bytes,6,opt,name=sideEffects,casttype=SideEffectClass"`

    // TimeoutSeconds specifies the timeout for this webhook. After the timeout passes,
    // the webhook call will be ignored or the API call will fail based on the
    // failure policy.
    // The timeout value must be between 1 and 30 seconds.
    // Default to 10 seconds.
    // +optional
    TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty" protobuf:"varint,7,opt,name=timeoutSeconds"`

    // AdmissionReviewVersions is an ordered list of preferred `AdmissionReview`
    // versions the Webhook expects. API server will try to use first version in
    // the list which it supports. If none of the versions specified in this list
    // supported by API server, validation will fail for this object.
    // If a persisted webhook configuration specifies allowed versions and does not
    // include any versions known to the API Server, calls to the webhook will fail
    // and be subject to the failure policy.
    AdmissionReviewVersions []string `json:"admissionReviewVersions" protobuf:"bytes,8,rep,name=admissionReviewVersions"`
}

MutatingWebhookConfiguration

// MutatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and may change the object.
type MutatingWebhookConfiguration struct {
    metav1.TypeMeta `json:",inline"`
    // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
    // +optional
    metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    // Webhooks is a list of webhooks and the affected resources and operations.
    // +optional
    // +patchMergeKey=name
    // +patchStrategy=merge
    Webhooks []MutatingWebhook `json:"webhooks,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,2,rep,name=Webhooks"`
}

MutatingWebhook

// MutatingWebhook describes an admission webhook and the resources and operations it applies to.
type MutatingWebhook struct {
    // The name of the admission webhook.
    // Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where
    // "imagepolicy" is the name of the webhook, and kubernetes.io is the name
    // of the organization.
    // Required.
    Name string `json:"name" protobuf:"bytes,1,opt,name=name"`

    // ClientConfig defines how to communicate with the hook.
    // Required
    ClientConfig WebhookClientConfig `json:"clientConfig" protobuf:"bytes,2,opt,name=clientConfig"`

    // Rules describes what operations on what resources/subresources the webhook cares about.
    // The webhook cares about an operation if it matches _any_ Rule.
    // However, in order to prevent ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks
    // from putting the cluster in a state which cannot be recovered from without completely
    // disabling the plugin, ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks are never called
    // on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects.
    Rules []RuleWithOperations `json:"rules,omitempty" protobuf:"bytes,3,rep,name=rules"`

    // FailurePolicy defines how unrecognized errors from the admission endpoint are handled -
    // allowed values are Ignore or Fail. Defaults to Fail.
    // +optional
    FailurePolicy *FailurePolicyType `json:"failurePolicy,omitempty" protobuf:"bytes,4,opt,name=failurePolicy,casttype=FailurePolicyType"`

    // matchPolicy defines how the "rules" list is used to match incoming requests.
    // Allowed values are "Exact" or "Equivalent".
    //
    // - Exact: match a request only if it exactly matches a specified rule.
    // For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1,
    // but "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`,
    // a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the webhook.
    //
    // - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version.
    // For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1,
    // and "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`,
    // a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the webhook.
    //
    // Defaults to "Equivalent"
    // +optional
    MatchPolicy *MatchPolicyType `json:"matchPolicy,omitempty" protobuf:"bytes,9,opt,name=matchPolicy,casttype=MatchPolicyType"`

	// ......
	NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty" protobuf:"bytes,5,opt,name=namespaceSelector"`

	// ......
	ObjectSelector *metav1.LabelSelector `json:"objectSelector,omitempty" protobuf:"bytes,11,opt,name=objectSelector"`

    // SideEffects states whether this webhook has side effects.
    // Acceptable values are: None, NoneOnDryRun (webhooks created via v1beta1 may also specify Some or Unknown).
    // Webhooks with side effects MUST implement a reconciliation system, since a request may be
    // rejected by a future step in the admission chain and the side effects therefore need to be undone.
    // Requests with the dryRun attribute will be auto-rejected if they match a webhook with
    // sideEffects == Unknown or Some.
    SideEffects *SideEffectClass `json:"sideEffects" protobuf:"bytes,6,opt,name=sideEffects,casttype=SideEffectClass"`

    // TimeoutSeconds specifies the timeout for this webhook. After the timeout passes,
    // the webhook call will be ignored or the API call will fail based on the
    // failure policy.
    // The timeout value must be between 1 and 30 seconds.
    // Default to 10 seconds.
    // +optional
    TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty" protobuf:"varint,7,opt,name=timeoutSeconds"`

    // AdmissionReviewVersions is an ordered list of preferred `AdmissionReview`
    // versions the Webhook expects. API server will try to use first version in
    // the list which it supports. If none of the versions specified in this list
    // supported by API server, validation will fail for this object.
    // If a persisted webhook configuration specifies allowed versions and does not
    // include any versions known to the API Server, calls to the webhook will fail
    // and be subject to the failure policy.
    AdmissionReviewVersions []string `json:"admissionReviewVersions" protobuf:"bytes,8,rep,name=admissionReviewVersions"`

    // reinvocationPolicy indicates whether this webhook should be called multiple times as part of a single admission evaluation.
    // Allowed values are "Never" and "IfNeeded".
    //
    // Never: the webhook will not be called more than once in a single admission evaluation.
    //
    // IfNeeded: the webhook will be called at least one additional time as part of the admission evaluation
    // if the object being admitted is modified by other admission plugins after the initial webhook call.
    // Webhooks that specify this option *must* be idempotent, able to process objects they previously admitted.
    // Note:
    // * the number of additional invocations is not guaranteed to be exactly one.
    // * if additional invocations result in further modifications to the object, webhooks are not guaranteed to be invoked again.
    // * webhooks that use this option may be reordered to minimize the number of additional invocations.
    // * to validate an object after all mutations are guaranteed complete, use a validating admission webhook instead.
    //
    // Defaults to "Never".
    // +optional
    ReinvocationPolicy *ReinvocationPolicyType `json:"reinvocationPolicy,omitempty" protobuf:"bytes,10,opt,name=reinvocationPolicy,casttype=ReinvocationPolicyType"`
}

WebhookClientConfig

// WebhookClientConfig contains the information to make a TLS
// connection with the webhook
type WebhookClientConfig struct {
    // `url` gives the location of the webhook, in standard URL form
    // (`scheme://host:port/path`). Exactly one of `url` or `service`
    // must be specified.
    //
    // The `host` should not refer to a service running in the cluster; use
    // the `service` field instead. The host might be resolved via external
    // DNS in some apiservers (e.g., `kube-apiserver` cannot resolve
    // in-cluster DNS as that would be a layering violation). `host` may
    // also be an IP address.
    //
    // Please note that using `localhost` or `127.0.0.1` as a `host` is
    // risky unless you take great care to run this webhook on all hosts
    // which run an apiserver which might need to make calls to this
    // webhook. Such installs are likely to be non-portable, i.e., not easy
    // to turn up in a new cluster.
    //
    // The scheme must be "https"; the URL must begin with "https://".
    //
    // A path is optional, and if present may be any string permissible in
    // a URL. You may use the path to pass an arbitrary string to the
    // webhook, for example, a cluster identifier.
    //
    // Attempting to use a user or basic auth e.g. "user:password@" is not
    // allowed. Fragments ("#...") and query parameters ("?...") are not
    // allowed, either.
    //
    // +optional
    URL *string `json:"url,omitempty" protobuf:"bytes,3,opt,name=url"`

    // `service` is a reference to the service for this webhook. Either
    // `service` or `url` must be specified.
    //
    // If the webhook is running within the cluster, then you should use `service`.
    //
    // +optional
    Service *ServiceReference `json:"service,omitempty" protobuf:"bytes,1,opt,name=service"`

    // `caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate.
    // If unspecified, system trust roots on the apiserver are used.
    // +optional
    CABundle []byte `json:"caBundle,omitempty" protobuf:"bytes,2,opt,name=caBundle"`
}

RuleWithOperations

// RuleWithOperations is a tuple of Operations and Resources. It is recommended to make
// sure that all the tuple expansions are valid.
type RuleWithOperations struct {
    // Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or *
    // for all of those operations and any future admission operations that are added.
    // If '*' is present, the length of the slice must be one.
    // Required.
    // +listType=atomic
    Operations []OperationType `json:"operations,omitempty" protobuf:"bytes,1,rep,name=operations,casttype=OperationType"`
    // Rule is embedded, it describes other criteria of the rule, like
    // APIGroups, APIVersions, Resources, etc.
    Rule `json:",inline" protobuf:"bytes,2,opt,name=rule"`
}

// OperationType specifies an operation for a request.
// +enum
type OperationType string

// The constants should be kept in sync with those defined in k8s.io/kubernetes/pkg/admission/interface.go.
const (
    OperationAll OperationType = "*"
    Create       OperationType = "CREATE"
    Update       OperationType = "UPDATE"
    Delete       OperationType = "DELETE"
    Connect      OperationType = "CONNECT"
)

FailurePolicyType

// FailurePolicyType specifies a failure policy that defines how unrecognized errors from the admission endpoint are handled.
// +enum
type FailurePolicyType string

const (
    // Ignore means that an error calling the webhook is ignored.
    Ignore FailurePolicyType = "Ignore"
    // Fail means that an error calling the webhook causes the admission to fail.
    Fail FailurePolicyType = "Fail"
)

MatchPolicyType

// MatchPolicyType specifies the type of match policy.
// +enum
type MatchPolicyType string

const (
    // Exact means requests should only be sent to the webhook if they exactly match a given rule.
    Exact MatchPolicyType = "Exact"
    // Equivalent means requests should be sent to the webhook if they modify a resource listed in rules via another API group or version.
    Equivalent MatchPolicyType = "Equivalent"
)

SideEffectClass

// SideEffectClass specifies the types of side effects a webhook may have.
// +enum
type SideEffectClass string

const (
    // SideEffectClassUnknown means that no information is known about the side effects of calling the webhook.
    // If a request with the dry-run attribute would trigger a call to this webhook, the request will instead fail.
    SideEffectClassUnknown SideEffectClass = "Unknown"
    // SideEffectClassNone means that calling the webhook will have no side effects.
    SideEffectClassNone SideEffectClass = "None"
    // SideEffectClassSome means that calling the webhook will possibly have side effects.
    // If a request with the dry-run attribute would trigger a call to this webhook, the request will instead fail.
    SideEffectClassSome SideEffectClass = "Some"
    // SideEffectClassNoneOnDryRun means that calling the webhook will possibly have side effects, but if the
    // request being reviewed has the dry-run attribute, the side effects will be suppressed.
    SideEffectClassNoneOnDryRun SideEffectClass = "NoneOnDryRun"
)

ReinvocationPolicyType

// ReinvocationPolicyType specifies what type of policy the admission hook uses.
// +enum
type ReinvocationPolicyType string

const (
    // NeverReinvocationPolicy indicates that the webhook must not be called more than once in a
    // single admission evaluation.
    NeverReinvocationPolicy ReinvocationPolicyType = "Never"
    // IfNeededReinvocationPolicy indicates that the webhook may be called at least one
    // additional time as part of the admission evaluation if the object being admitted is
    // modified by other admission plugins after the initial webhook call.
    IfNeededReinvocationPolicy ReinvocationPolicyType = "IfNeeded"
)

Plugins: PodSecurity

PodSecurityConfiguration

k8s.io/pod-security-admission/admission/api/v1/types.go

type PodSecurityConfiguration struct {
    metav1.TypeMeta
    Defaults   PodSecurityDefaults   `json:"defaults"`
    Exemptions PodSecurityExemptions `json:"exemptions"`
}

PodSecurityDefaults

type PodSecurityDefaults struct {
    Enforce        string `json:"enforce,omitempty"`
    EnforceVersion string `json:"enforce-version,omitempty"`
    Audit          string `json:"audit,omitempty"`
    AuditVersion   string `json:"audit-version,omitempty"`
    Warn           string `json:"warn,omitempty"`
    WarnVersion    string `json:"warn-version,omitempty"`
}
模式 描述
enforce 策略违例会导致 Pod 被拒绝
audit 策略违例会触发审计日志中记录新事件时添加审计注解;但是 Pod 仍是被接受的
warn 策略违例会触发用户可见的警告信息,但是 Pod 仍是被接受的

Pod 通常是通过 Deployment、Job 等工作负载间接创建,为了尽早地捕获违例状况,audit 和 warn 模式都直接应用到负载资源,而 enforce 模式仅应用到所生成的 Pod 对象上,所以在命名空间更改策略模式后,不会影响当前运行应用。

策略 用途 描述
privileged 提供给集群管理服务 不受限制的策略,提供最大可能范围的权限许可
baseline 提供给普通运维服务 限制性最弱的策略,禁止已知的特权提升
restricted 提供给业务运行环境 限制性非常强的策略,遵循当前的保护 Pod 的最佳实践

各模式可取值为:privileged、baseline、restricted,它们之间差异详见 Pod 安全性标准

PodSecurityExemptions

type PodSecurityExemptions struct {
    Usernames      []string `json:"usernames,omitempty"`
    Namespaces     []string `json:"namespaces,omitempty"`
    RuntimeClasses []string `json:"runtimeClasses,omitempty"`
}
属性 描述
usernames 来自用户名已被豁免的、已认证的(或伪装的)的用户的请求会被忽略
runtimeClasses 指定了已豁免的运行时类名称的 Pod 和负载资源会被忽略
namespaces 位于被豁免的名字空间中的 Pod 和负载资源会被忽略

这里配置的是为 Pod 安全性的实施设置豁免(Exemptions) 规则,从而允许创建一些本来会被与给定名字空间相关的策略所禁止的 Pod。

Plugins: WebhookAdmissionConfiguration

WebhookAdmission

k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1/types.go k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1/register.go

// WebhookAdmission provides configuration for the webhook admission controller.
type WebhookAdmission struct {
    metav1.TypeMeta

    // KubeConfigFile is the path to the kubeconfig file.
    KubeConfigFile string
}
// GroupName is the group name use in this package
const GroupName = "apiserver.config.k8s.io"

// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"}

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypeWithName(SchemeGroupVersion.WithKind("WebhookAdmissionConfiguration"),
		&WebhookAdmission{},
	)
	return nil
}