Merge pull request #65891 from CaoShuFeng/audit_v1_stable

Automatic merge from submit-queue. If you want to cherry-pick this change to another branch, please follow the instructions <a href="https://github.com/kubernetes/community/blob/master/contributors/devel/cherry-picks.md">here</a>.

upgrade Audit api version to stable

Partial Fix: https://github.com/kubernetes/kubernetes/issues/65266

TODO:
    use v1 version of advanced audit policy in [kubeadm](86b9a53226/cmd/kubeadm/app/util/audit/utils.go (L29)), [gce script](86b9a53226/cluster/gce/gci/configure-helper.sh (L743)), [kubemark](86b9a53226/test/kubemark/resources/start-kubemark-master.sh (L349))



**What this PR does / why we need it**:

**Which issue(s) this PR fixes** *(optional, in `fixes #<issue number>(, fixes #<issue_number>, ...)` format, will close the issue(s) when PR gets merged)*:
Fixes #

**Special notes for your reviewer**:

**Release note**:

```release-note
audit.k8s.io api group is upgraded from v1beta1 to v1.
Deprecated element metav1.ObjectMeta and Timestamp are removed from audit Events in v1 version.
Default value of option --audit-webhook-version and --audit-log-version will be changed from `audit.k8s.io/v1beta1` to `audit.k8s.io/v1` in release 1.13
```
pull/8/head
Kubernetes Submit Queue 2018-08-08 02:17:24 -07:00 committed by GitHub
commit 28b2b21287
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 5057 additions and 577 deletions

View File

@ -529,6 +529,7 @@ staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating
staging/src/k8s.io/apiserver/pkg/apis/apiserver
staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1
staging/src/k8s.io/apiserver/pkg/apis/audit
staging/src/k8s.io/apiserver/pkg/apis/audit/v1
staging/src/k8s.io/apiserver/pkg/apis/audit/v1alpha1
staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1
staging/src/k8s.io/apiserver/pkg/apis/audit/validation

View File

@ -84,6 +84,7 @@ PACKAGES=(
k8s.io/metrics/pkg/apis/external_metrics/v1beta1
k8s.io/apiserver/pkg/apis/audit/v1alpha1
k8s.io/apiserver/pkg/apis/audit/v1beta1
k8s.io/apiserver/pkg/apis/audit/v1
k8s.io/apiserver/pkg/apis/example2/v1
)

View File

@ -61,6 +61,7 @@ openapi_library(
"k8s.io/apimachinery/pkg/runtime",
"k8s.io/apimachinery/pkg/util/intstr",
"k8s.io/apimachinery/pkg/version",
"k8s.io/apiserver/pkg/apis/audit/v1",
"k8s.io/apiserver/pkg/apis/audit/v1alpha1",
"k8s.io/apiserver/pkg/apis/audit/v1beta1",
"k8s.io/apiserver/pkg/apis/example/v1",

View File

@ -1254,6 +1254,10 @@
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/install",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/v1",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/v1alpha1",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

View File

@ -37,6 +37,7 @@ filegroup(
":package-srcs",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/fuzzer:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/install:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1alpha1:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:all-srcs",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/validation:all-srcs",

View File

@ -15,6 +15,7 @@ go_library(
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/runtime:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1alpha1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
],

View File

@ -22,6 +22,7 @@ import (
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apiserver/pkg/apis/audit"
"k8s.io/apiserver/pkg/apis/audit/v1"
"k8s.io/apiserver/pkg/apis/audit/v1alpha1"
"k8s.io/apiserver/pkg/apis/audit/v1beta1"
)
@ -29,7 +30,8 @@ import (
// Install registers the API group and adds types to a scheme
func Install(scheme *runtime.Scheme) {
utilruntime.Must(audit.AddToScheme(scheme))
utilruntime.Must(v1.AddToScheme(scheme))
utilruntime.Must(v1beta1.AddToScheme(scheme))
utilruntime.Must(v1alpha1.AddToScheme(scheme))
utilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))
utilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))
}

View File

@ -0,0 +1,46 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"generated.pb.go",
"register.go",
"types.go",
"zz_generated.conversion.go",
"zz_generated.deepcopy.go",
"zz_generated.defaults.go",
],
importmap = "k8s.io/kubernetes/vendor/k8s.io/apiserver/pkg/apis/audit/v1",
importpath = "k8s.io/apiserver/pkg/apis/audit/v1",
deps = [
"//staging/src/k8s.io/api/authentication/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/conversion:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//vendor/github.com/gogo/protobuf/proto:go_default_library",
"//vendor/github.com/gogo/protobuf/sortkeys:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@ -0,0 +1,23 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// +k8s:deepcopy-gen=package
// +k8s:conversion-gen=k8s.io/apiserver/pkg/apis/audit
// +k8s:openapi-gen=true
// +k8s:defaulter-gen=TypeMeta
// +groupName=audit.k8s.io
package v1 // import "k8s.io/apiserver/pkg/apis/audit/v1"

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,250 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This file was autogenerated by go-to-protobuf. Do not edit it manually!
syntax = 'proto2';
package k8s.io.apiserver.pkg.apis.audit.v1;
import "k8s.io/api/authentication/v1/generated.proto";
import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto";
import "k8s.io/apimachinery/pkg/runtime/generated.proto";
import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
import "k8s.io/apimachinery/pkg/util/intstr/generated.proto";
import "k8s.io/apiserver/pkg/apis/audit/v1alpha1/generated.proto";
// Package-wide variables from generator "generated".
option go_package = "v1";
// Event captures all the information that can be included in an API audit log.
message Event {
// AuditLevel at which event was generated
optional string level = 1;
// Unique audit ID, generated for each request.
optional string auditID = 2;
// Stage of the request handling when this event instance was generated.
optional string stage = 3;
// RequestURI is the request URI as sent by the client to a server.
optional string requestURI = 4;
// Verb is the kubernetes verb associated with the request.
// For non-resource requests, this is the lower-cased HTTP method.
optional string verb = 5;
// Authenticated user information.
optional k8s.io.api.authentication.v1.UserInfo user = 6;
// Impersonated user information.
// +optional
optional k8s.io.api.authentication.v1.UserInfo impersonatedUser = 7;
// Source IPs, from where the request originated and intermediate proxies.
// +optional
repeated string sourceIPs = 8;
// UserAgent records the user agent string reported by the client.
// Note that the UserAgent is provided by the client, and must not be trusted.
// +optional
optional string userAgent = 16;
// Object reference this request is targeted at.
// Does not apply for List-type requests, or non-resource requests.
// +optional
optional ObjectReference objectRef = 9;
// The response status, populated even when the ResponseObject is not a Status type.
// For successful responses, this will only include the Code and StatusSuccess.
// For non-status type error responses, this will be auto-populated with the error Message.
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.Status responseStatus = 10;
// API object from the request, in JSON format. The RequestObject is recorded as-is in the request
// (possibly re-encoded as JSON), prior to version conversion, defaulting, admission or
// merging. It is an external versioned object type, and may not be a valid object on its own.
// Omitted for non-resource requests. Only logged at Request Level and higher.
// +optional
optional k8s.io.apimachinery.pkg.runtime.Unknown requestObject = 11;
// API object returned in the response, in JSON. The ResponseObject is recorded after conversion
// to the external type, and serialized as JSON. Omitted for non-resource requests. Only logged
// at Response Level.
// +optional
optional k8s.io.apimachinery.pkg.runtime.Unknown responseObject = 12;
// Time the request reached the apiserver.
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.MicroTime requestReceivedTimestamp = 13;
// Time the request reached current audit stage.
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.MicroTime stageTimestamp = 14;
// Annotations is an unstructured key value map stored with an audit event that may be set by
// plugins invoked in the request serving chain, including authentication, authorization and
// admission plugins. Keys should uniquely identify the informing component to avoid name
// collisions (e.g. podsecuritypolicy.admission.k8s.io/policy). Values should be short. Annotations
// are included in the Metadata level.
// +optional
map<string, string> annotations = 15;
}
// EventList is a list of audit Events.
message EventList {
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1;
repeated Event items = 2;
}
// GroupResources represents resource kinds in an API group.
message GroupResources {
// Group is the name of the API group that contains the resources.
// The empty string represents the core API group.
// +optional
optional string group = 1;
// Resources is a list of resources this rule applies to.
//
// For example:
// 'pods' matches pods.
// 'pods/log' matches the log subresource of pods.
// '*' matches all resources and their subresources.
// 'pods/*' matches all subresources of pods.
// '*/scale' matches all scale subresources.
//
// If wildcard is present, the validation rule will ensure resources do not
// overlap with each other.
//
// An empty list implies all resources and subresources in this API groups apply.
// +optional
repeated string resources = 2;
// ResourceNames is a list of resource instance names that the policy matches.
// Using this field requires Resources to be specified.
// An empty list implies that every instance of the resource is matched.
// +optional
repeated string resourceNames = 3;
}
// ObjectReference contains enough information to let you inspect or modify the referred object.
message ObjectReference {
// +optional
optional string resource = 1;
// +optional
optional string namespace = 2;
// +optional
optional string name = 3;
// +optional
optional string uid = 4;
// APIGroup is the name of the API group that contains the referred object.
// The empty string represents the core API group.
// +optional
optional string apiGroup = 5;
// APIVersion is the version of the API group that contains the referred object.
// +optional
optional string apiVersion = 6;
// +optional
optional string resourceVersion = 7;
// +optional
optional string subresource = 8;
}
// Policy defines the configuration of audit logging, and the rules for how different request
// categories are logged.
message Policy {
// ObjectMeta is included for interoperability with API infrastructure.
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1;
// Rules specify the audit Level a request should be recorded at.
// A request may match multiple rules, in which case the FIRST matching rule is used.
// The default audit level is None, but can be overridden by a catch-all rule at the end of the list.
// PolicyRules are strictly ordered.
repeated PolicyRule rules = 2;
// OmitStages is a list of stages for which no events are created. Note that this can also
// be specified per rule in which case the union of both are omitted.
// +optional
repeated string omitStages = 3;
}
// PolicyList is a list of audit Policies.
message PolicyList {
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1;
repeated Policy items = 2;
}
// PolicyRule maps requests based off metadata to an audit Level.
// Requests must match the rules of every field (an intersection of rules).
message PolicyRule {
// The Level that requests matching this rule are recorded at.
optional string level = 1;
// The users (by authenticated user name) this rule applies to.
// An empty list implies every user.
// +optional
repeated string users = 2;
// The user groups this rule applies to. A user is considered matching
// if it is a member of any of the UserGroups.
// An empty list implies every user group.
// +optional
repeated string userGroups = 3;
// The verbs that match this rule.
// An empty list implies every verb.
// +optional
repeated string verbs = 4;
// Resources that this rule matches. An empty list implies all kinds in all API groups.
// +optional
repeated GroupResources resources = 5;
// Namespaces that this rule matches.
// The empty string "" matches non-namespaced resources.
// An empty list implies every namespace.
// +optional
repeated string namespaces = 6;
// NonResourceURLs is a set of URL paths that should be audited.
// *s are allowed, but only as the full, final step in the path.
// Examples:
// "/metrics" - Log requests for apiserver metrics
// "/healthz*" - Log all health checks
// +optional
repeated string nonResourceURLs = 7;
// OmitStages is a list of stages for which no events are created. Note that this can also
// be specified policy wide in which case the union of both are omitted.
// An empty list means no restrictions will apply.
// +optional
repeated string omitStages = 8;
}

View File

@ -0,0 +1,58 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// GroupName is the group name use in this package
const GroupName = "audit.k8s.io"
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"}
// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
var (
SchemeBuilder runtime.SchemeBuilder
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
func init() {
// We only register manually written functions here. The registration of the
// generated functions takes place in the generated files. The separation
// makes the code compile even when the generated files are missing.
localSchemeBuilder.Register(addKnownTypes)
}
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Event{},
&EventList{},
&Policy{},
&PolicyList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -0,0 +1,279 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
authnv1 "k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
)
// Header keys used by the audit system.
const (
// Header to hold the audit ID as the request is propagated through the serving hierarchy. The
// Audit-ID header should be set by the first server to receive the request (e.g. the federation
// server or kube-aggregator).
HeaderAuditID = "Audit-ID"
)
// Level defines the amount of information logged during auditing
type Level string
// Valid audit levels
const (
// LevelNone disables auditing
LevelNone Level = "None"
// LevelMetadata provides the basic level of auditing.
LevelMetadata Level = "Metadata"
// LevelRequest provides Metadata level of auditing, and additionally
// logs the request object (does not apply for non-resource requests).
LevelRequest Level = "Request"
// LevelRequestResponse provides Request level of auditing, and additionally
// logs the response object (does not apply for non-resource requests).
LevelRequestResponse Level = "RequestResponse"
)
// Stage defines the stages in request handling that audit events may be generated.
type Stage string
// Valid audit stages.
const (
// The stage for events generated as soon as the audit handler receives the request, and before it
// is delegated down the handler chain.
StageRequestReceived = "RequestReceived"
// The stage for events generated once the response headers are sent, but before the response body
// is sent. This stage is only generated for long-running requests (e.g. watch).
StageResponseStarted = "ResponseStarted"
// The stage for events generated once the response body has been completed, and no more bytes
// will be sent.
StageResponseComplete = "ResponseComplete"
// The stage for events generated when a panic occurred.
StagePanic = "Panic"
)
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Event captures all the information that can be included in an API audit log.
type Event struct {
metav1.TypeMeta `json:",inline"`
// AuditLevel at which event was generated
Level Level `json:"level" protobuf:"bytes,1,opt,name=level,casttype=Level"`
// Unique audit ID, generated for each request.
AuditID types.UID `json:"auditID" protobuf:"bytes,2,opt,name=auditID,casttype=k8s.io/apimachinery/pkg/types.UID"`
// Stage of the request handling when this event instance was generated.
Stage Stage `json:"stage" protobuf:"bytes,3,opt,name=stage,casttype=Stage"`
// RequestURI is the request URI as sent by the client to a server.
RequestURI string `json:"requestURI" protobuf:"bytes,4,opt,name=requestURI"`
// Verb is the kubernetes verb associated with the request.
// For non-resource requests, this is the lower-cased HTTP method.
Verb string `json:"verb" protobuf:"bytes,5,opt,name=verb"`
// Authenticated user information.
User authnv1.UserInfo `json:"user" protobuf:"bytes,6,opt,name=user"`
// Impersonated user information.
// +optional
ImpersonatedUser *authnv1.UserInfo `json:"impersonatedUser,omitempty" protobuf:"bytes,7,opt,name=impersonatedUser"`
// Source IPs, from where the request originated and intermediate proxies.
// +optional
SourceIPs []string `json:"sourceIPs,omitempty" protobuf:"bytes,8,rep,name=sourceIPs"`
// UserAgent records the user agent string reported by the client.
// Note that the UserAgent is provided by the client, and must not be trusted.
// +optional
UserAgent string `json:"userAgent,omitempty" protobuf:"bytes,16,opt,name=userAgent"`
// Object reference this request is targeted at.
// Does not apply for List-type requests, or non-resource requests.
// +optional
ObjectRef *ObjectReference `json:"objectRef,omitempty" protobuf:"bytes,9,opt,name=objectRef"`
// The response status, populated even when the ResponseObject is not a Status type.
// For successful responses, this will only include the Code and StatusSuccess.
// For non-status type error responses, this will be auto-populated with the error Message.
// +optional
ResponseStatus *metav1.Status `json:"responseStatus,omitempty" protobuf:"bytes,10,opt,name=responseStatus"`
// API object from the request, in JSON format. The RequestObject is recorded as-is in the request
// (possibly re-encoded as JSON), prior to version conversion, defaulting, admission or
// merging. It is an external versioned object type, and may not be a valid object on its own.
// Omitted for non-resource requests. Only logged at Request Level and higher.
// +optional
RequestObject *runtime.Unknown `json:"requestObject,omitempty" protobuf:"bytes,11,opt,name=requestObject"`
// API object returned in the response, in JSON. The ResponseObject is recorded after conversion
// to the external type, and serialized as JSON. Omitted for non-resource requests. Only logged
// at Response Level.
// +optional
ResponseObject *runtime.Unknown `json:"responseObject,omitempty" protobuf:"bytes,12,opt,name=responseObject"`
// Time the request reached the apiserver.
// +optional
RequestReceivedTimestamp metav1.MicroTime `json:"requestReceivedTimestamp" protobuf:"bytes,13,opt,name=requestReceivedTimestamp"`
// Time the request reached current audit stage.
// +optional
StageTimestamp metav1.MicroTime `json:"stageTimestamp" protobuf:"bytes,14,opt,name=stageTimestamp"`
// Annotations is an unstructured key value map stored with an audit event that may be set by
// plugins invoked in the request serving chain, including authentication, authorization and
// admission plugins. Keys should uniquely identify the informing component to avoid name
// collisions (e.g. podsecuritypolicy.admission.k8s.io/policy). Values should be short. Annotations
// are included in the Metadata level.
// +optional
Annotations map[string]string `json:"annotations,omitempty" protobuf:"bytes,15,rep,name=annotations"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// EventList is a list of audit Events.
type EventList struct {
metav1.TypeMeta `json:",inline"`
// +optional
metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
Items []Event `json:"items" protobuf:"bytes,2,rep,name=items"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Policy defines the configuration of audit logging, and the rules for how different request
// categories are logged.
type Policy struct {
metav1.TypeMeta `json:",inline"`
// ObjectMeta is included for interoperability with API infrastructure.
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Rules specify the audit Level a request should be recorded at.
// A request may match multiple rules, in which case the FIRST matching rule is used.
// The default audit level is None, but can be overridden by a catch-all rule at the end of the list.
// PolicyRules are strictly ordered.
Rules []PolicyRule `json:"rules" protobuf:"bytes,2,rep,name=rules"`
// OmitStages is a list of stages for which no events are created. Note that this can also
// be specified per rule in which case the union of both are omitted.
// +optional
OmitStages []Stage `json:"omitStages,omitempty" protobuf:"bytes,3,rep,name=omitStages"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// PolicyList is a list of audit Policies.
type PolicyList struct {
metav1.TypeMeta `json:",inline"`
// +optional
metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
Items []Policy `json:"items" protobuf:"bytes,2,rep,name=items"`
}
// PolicyRule maps requests based off metadata to an audit Level.
// Requests must match the rules of every field (an intersection of rules).
type PolicyRule struct {
// The Level that requests matching this rule are recorded at.
Level Level `json:"level" protobuf:"bytes,1,opt,name=level,casttype=Level"`
// The users (by authenticated user name) this rule applies to.
// An empty list implies every user.
// +optional
Users []string `json:"users,omitempty" protobuf:"bytes,2,rep,name=users"`
// The user groups this rule applies to. A user is considered matching
// if it is a member of any of the UserGroups.
// An empty list implies every user group.
// +optional
UserGroups []string `json:"userGroups,omitempty" protobuf:"bytes,3,rep,name=userGroups"`
// The verbs that match this rule.
// An empty list implies every verb.
// +optional
Verbs []string `json:"verbs,omitempty" protobuf:"bytes,4,rep,name=verbs"`
// Rules can apply to API resources (such as "pods" or "secrets"),
// non-resource URL paths (such as "/api"), or neither, but not both.
// If neither is specified, the rule is treated as a default for all URLs.
// Resources that this rule matches. An empty list implies all kinds in all API groups.
// +optional
Resources []GroupResources `json:"resources,omitempty" protobuf:"bytes,5,rep,name=resources"`
// Namespaces that this rule matches.
// The empty string "" matches non-namespaced resources.
// An empty list implies every namespace.
// +optional
Namespaces []string `json:"namespaces,omitempty" protobuf:"bytes,6,rep,name=namespaces"`
// NonResourceURLs is a set of URL paths that should be audited.
// *s are allowed, but only as the full, final step in the path.
// Examples:
// "/metrics" - Log requests for apiserver metrics
// "/healthz*" - Log all health checks
// +optional
NonResourceURLs []string `json:"nonResourceURLs,omitempty" protobuf:"bytes,7,rep,name=nonResourceURLs"`
// OmitStages is a list of stages for which no events are created. Note that this can also
// be specified policy wide in which case the union of both are omitted.
// An empty list means no restrictions will apply.
// +optional
OmitStages []Stage `json:"omitStages,omitempty" protobuf:"bytes,8,rep,name=omitStages"`
}
// GroupResources represents resource kinds in an API group.
type GroupResources struct {
// Group is the name of the API group that contains the resources.
// The empty string represents the core API group.
// +optional
Group string `json:"group,omitempty" protobuf:"bytes,1,opt,name=group"`
// Resources is a list of resources this rule applies to.
//
// For example:
// 'pods' matches pods.
// 'pods/log' matches the log subresource of pods.
// '*' matches all resources and their subresources.
// 'pods/*' matches all subresources of pods.
// '*/scale' matches all scale subresources.
//
// If wildcard is present, the validation rule will ensure resources do not
// overlap with each other.
//
// An empty list implies all resources and subresources in this API groups apply.
// +optional
Resources []string `json:"resources,omitempty" protobuf:"bytes,2,rep,name=resources"`
// ResourceNames is a list of resource instance names that the policy matches.
// Using this field requires Resources to be specified.
// An empty list implies that every instance of the resource is matched.
// +optional
ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,3,rep,name=resourceNames"`
}
// ObjectReference contains enough information to let you inspect or modify the referred object.
type ObjectReference struct {
// +optional
Resource string `json:"resource,omitempty" protobuf:"bytes,1,opt,name=resource"`
// +optional
Namespace string `json:"namespace,omitempty" protobuf:"bytes,2,opt,name=namespace"`
// +optional
Name string `json:"name,omitempty" protobuf:"bytes,3,opt,name=name"`
// +optional
UID types.UID `json:"uid,omitempty" protobuf:"bytes,4,opt,name=uid,casttype=k8s.io/apimachinery/pkg/types.UID"`
// APIGroup is the name of the API group that contains the referred object.
// The empty string represents the core API group.
// +optional
APIGroup string `json:"apiGroup,omitempty" protobuf:"bytes,5,opt,name=apiGroup"`
// APIVersion is the version of the API group that contains the referred object.
// +optional
APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,6,opt,name=apiVersion"`
// +optional
ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,7,opt,name=resourceVersion"`
// +optional
Subresource string `json:"subresource,omitempty" protobuf:"bytes,8,opt,name=subresource"`
}

View File

@ -0,0 +1,328 @@
// +build !ignore_autogenerated
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by conversion-gen. DO NOT EDIT.
package v1
import (
unsafe "unsafe"
authenticationv1 "k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
conversion "k8s.io/apimachinery/pkg/conversion"
runtime "k8s.io/apimachinery/pkg/runtime"
types "k8s.io/apimachinery/pkg/types"
audit "k8s.io/apiserver/pkg/apis/audit"
)
func init() {
localSchemeBuilder.Register(RegisterConversions)
}
// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
if err := s.AddGeneratedConversionFunc((*Event)(nil), (*audit.Event)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_Event_To_audit_Event(a.(*Event), b.(*audit.Event), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*audit.Event)(nil), (*Event)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_audit_Event_To_v1_Event(a.(*audit.Event), b.(*Event), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*EventList)(nil), (*audit.EventList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_EventList_To_audit_EventList(a.(*EventList), b.(*audit.EventList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*audit.EventList)(nil), (*EventList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_audit_EventList_To_v1_EventList(a.(*audit.EventList), b.(*EventList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*GroupResources)(nil), (*audit.GroupResources)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_GroupResources_To_audit_GroupResources(a.(*GroupResources), b.(*audit.GroupResources), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*audit.GroupResources)(nil), (*GroupResources)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_audit_GroupResources_To_v1_GroupResources(a.(*audit.GroupResources), b.(*GroupResources), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*ObjectReference)(nil), (*audit.ObjectReference)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ObjectReference_To_audit_ObjectReference(a.(*ObjectReference), b.(*audit.ObjectReference), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*audit.ObjectReference)(nil), (*ObjectReference)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_audit_ObjectReference_To_v1_ObjectReference(a.(*audit.ObjectReference), b.(*ObjectReference), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*Policy)(nil), (*audit.Policy)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_Policy_To_audit_Policy(a.(*Policy), b.(*audit.Policy), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*audit.Policy)(nil), (*Policy)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_audit_Policy_To_v1_Policy(a.(*audit.Policy), b.(*Policy), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*PolicyList)(nil), (*audit.PolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_PolicyList_To_audit_PolicyList(a.(*PolicyList), b.(*audit.PolicyList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*audit.PolicyList)(nil), (*PolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_audit_PolicyList_To_v1_PolicyList(a.(*audit.PolicyList), b.(*PolicyList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*PolicyRule)(nil), (*audit.PolicyRule)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_PolicyRule_To_audit_PolicyRule(a.(*PolicyRule), b.(*audit.PolicyRule), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*audit.PolicyRule)(nil), (*PolicyRule)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_audit_PolicyRule_To_v1_PolicyRule(a.(*audit.PolicyRule), b.(*PolicyRule), scope)
}); err != nil {
return err
}
return nil
}
func autoConvert_v1_Event_To_audit_Event(in *Event, out *audit.Event, s conversion.Scope) error {
out.Level = audit.Level(in.Level)
out.AuditID = types.UID(in.AuditID)
out.Stage = audit.Stage(in.Stage)
out.RequestURI = in.RequestURI
out.Verb = in.Verb
// TODO: Inefficient conversion - can we improve it?
if err := s.Convert(&in.User, &out.User, 0); err != nil {
return err
}
out.ImpersonatedUser = (*audit.UserInfo)(unsafe.Pointer(in.ImpersonatedUser))
out.SourceIPs = *(*[]string)(unsafe.Pointer(&in.SourceIPs))
out.UserAgent = in.UserAgent
out.ObjectRef = (*audit.ObjectReference)(unsafe.Pointer(in.ObjectRef))
out.ResponseStatus = (*metav1.Status)(unsafe.Pointer(in.ResponseStatus))
out.RequestObject = (*runtime.Unknown)(unsafe.Pointer(in.RequestObject))
out.ResponseObject = (*runtime.Unknown)(unsafe.Pointer(in.ResponseObject))
out.RequestReceivedTimestamp = in.RequestReceivedTimestamp
out.StageTimestamp = in.StageTimestamp
out.Annotations = *(*map[string]string)(unsafe.Pointer(&in.Annotations))
return nil
}
// Convert_v1_Event_To_audit_Event is an autogenerated conversion function.
func Convert_v1_Event_To_audit_Event(in *Event, out *audit.Event, s conversion.Scope) error {
return autoConvert_v1_Event_To_audit_Event(in, out, s)
}
func autoConvert_audit_Event_To_v1_Event(in *audit.Event, out *Event, s conversion.Scope) error {
out.Level = Level(in.Level)
out.AuditID = types.UID(in.AuditID)
out.Stage = Stage(in.Stage)
out.RequestURI = in.RequestURI
out.Verb = in.Verb
// TODO: Inefficient conversion - can we improve it?
if err := s.Convert(&in.User, &out.User, 0); err != nil {
return err
}
out.ImpersonatedUser = (*authenticationv1.UserInfo)(unsafe.Pointer(in.ImpersonatedUser))
out.SourceIPs = *(*[]string)(unsafe.Pointer(&in.SourceIPs))
out.UserAgent = in.UserAgent
out.ObjectRef = (*ObjectReference)(unsafe.Pointer(in.ObjectRef))
out.ResponseStatus = (*metav1.Status)(unsafe.Pointer(in.ResponseStatus))
out.RequestObject = (*runtime.Unknown)(unsafe.Pointer(in.RequestObject))
out.ResponseObject = (*runtime.Unknown)(unsafe.Pointer(in.ResponseObject))
out.RequestReceivedTimestamp = in.RequestReceivedTimestamp
out.StageTimestamp = in.StageTimestamp
out.Annotations = *(*map[string]string)(unsafe.Pointer(&in.Annotations))
return nil
}
// Convert_audit_Event_To_v1_Event is an autogenerated conversion function.
func Convert_audit_Event_To_v1_Event(in *audit.Event, out *Event, s conversion.Scope) error {
return autoConvert_audit_Event_To_v1_Event(in, out, s)
}
func autoConvert_v1_EventList_To_audit_EventList(in *EventList, out *audit.EventList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
out.Items = *(*[]audit.Event)(unsafe.Pointer(&in.Items))
return nil
}
// Convert_v1_EventList_To_audit_EventList is an autogenerated conversion function.
func Convert_v1_EventList_To_audit_EventList(in *EventList, out *audit.EventList, s conversion.Scope) error {
return autoConvert_v1_EventList_To_audit_EventList(in, out, s)
}
func autoConvert_audit_EventList_To_v1_EventList(in *audit.EventList, out *EventList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
out.Items = *(*[]Event)(unsafe.Pointer(&in.Items))
return nil
}
// Convert_audit_EventList_To_v1_EventList is an autogenerated conversion function.
func Convert_audit_EventList_To_v1_EventList(in *audit.EventList, out *EventList, s conversion.Scope) error {
return autoConvert_audit_EventList_To_v1_EventList(in, out, s)
}
func autoConvert_v1_GroupResources_To_audit_GroupResources(in *GroupResources, out *audit.GroupResources, s conversion.Scope) error {
out.Group = in.Group
out.Resources = *(*[]string)(unsafe.Pointer(&in.Resources))
out.ResourceNames = *(*[]string)(unsafe.Pointer(&in.ResourceNames))
return nil
}
// Convert_v1_GroupResources_To_audit_GroupResources is an autogenerated conversion function.
func Convert_v1_GroupResources_To_audit_GroupResources(in *GroupResources, out *audit.GroupResources, s conversion.Scope) error {
return autoConvert_v1_GroupResources_To_audit_GroupResources(in, out, s)
}
func autoConvert_audit_GroupResources_To_v1_GroupResources(in *audit.GroupResources, out *GroupResources, s conversion.Scope) error {
out.Group = in.Group
out.Resources = *(*[]string)(unsafe.Pointer(&in.Resources))
out.ResourceNames = *(*[]string)(unsafe.Pointer(&in.ResourceNames))
return nil
}
// Convert_audit_GroupResources_To_v1_GroupResources is an autogenerated conversion function.
func Convert_audit_GroupResources_To_v1_GroupResources(in *audit.GroupResources, out *GroupResources, s conversion.Scope) error {
return autoConvert_audit_GroupResources_To_v1_GroupResources(in, out, s)
}
func autoConvert_v1_ObjectReference_To_audit_ObjectReference(in *ObjectReference, out *audit.ObjectReference, s conversion.Scope) error {
out.Resource = in.Resource
out.Namespace = in.Namespace
out.Name = in.Name
out.UID = types.UID(in.UID)
out.APIGroup = in.APIGroup
out.APIVersion = in.APIVersion
out.ResourceVersion = in.ResourceVersion
out.Subresource = in.Subresource
return nil
}
// Convert_v1_ObjectReference_To_audit_ObjectReference is an autogenerated conversion function.
func Convert_v1_ObjectReference_To_audit_ObjectReference(in *ObjectReference, out *audit.ObjectReference, s conversion.Scope) error {
return autoConvert_v1_ObjectReference_To_audit_ObjectReference(in, out, s)
}
func autoConvert_audit_ObjectReference_To_v1_ObjectReference(in *audit.ObjectReference, out *ObjectReference, s conversion.Scope) error {
out.Resource = in.Resource
out.Namespace = in.Namespace
out.Name = in.Name
out.UID = types.UID(in.UID)
out.APIGroup = in.APIGroup
out.APIVersion = in.APIVersion
out.ResourceVersion = in.ResourceVersion
out.Subresource = in.Subresource
return nil
}
// Convert_audit_ObjectReference_To_v1_ObjectReference is an autogenerated conversion function.
func Convert_audit_ObjectReference_To_v1_ObjectReference(in *audit.ObjectReference, out *ObjectReference, s conversion.Scope) error {
return autoConvert_audit_ObjectReference_To_v1_ObjectReference(in, out, s)
}
func autoConvert_v1_Policy_To_audit_Policy(in *Policy, out *audit.Policy, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
out.Rules = *(*[]audit.PolicyRule)(unsafe.Pointer(&in.Rules))
out.OmitStages = *(*[]audit.Stage)(unsafe.Pointer(&in.OmitStages))
return nil
}
// Convert_v1_Policy_To_audit_Policy is an autogenerated conversion function.
func Convert_v1_Policy_To_audit_Policy(in *Policy, out *audit.Policy, s conversion.Scope) error {
return autoConvert_v1_Policy_To_audit_Policy(in, out, s)
}
func autoConvert_audit_Policy_To_v1_Policy(in *audit.Policy, out *Policy, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
out.Rules = *(*[]PolicyRule)(unsafe.Pointer(&in.Rules))
out.OmitStages = *(*[]Stage)(unsafe.Pointer(&in.OmitStages))
return nil
}
// Convert_audit_Policy_To_v1_Policy is an autogenerated conversion function.
func Convert_audit_Policy_To_v1_Policy(in *audit.Policy, out *Policy, s conversion.Scope) error {
return autoConvert_audit_Policy_To_v1_Policy(in, out, s)
}
func autoConvert_v1_PolicyList_To_audit_PolicyList(in *PolicyList, out *audit.PolicyList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
out.Items = *(*[]audit.Policy)(unsafe.Pointer(&in.Items))
return nil
}
// Convert_v1_PolicyList_To_audit_PolicyList is an autogenerated conversion function.
func Convert_v1_PolicyList_To_audit_PolicyList(in *PolicyList, out *audit.PolicyList, s conversion.Scope) error {
return autoConvert_v1_PolicyList_To_audit_PolicyList(in, out, s)
}
func autoConvert_audit_PolicyList_To_v1_PolicyList(in *audit.PolicyList, out *PolicyList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
out.Items = *(*[]Policy)(unsafe.Pointer(&in.Items))
return nil
}
// Convert_audit_PolicyList_To_v1_PolicyList is an autogenerated conversion function.
func Convert_audit_PolicyList_To_v1_PolicyList(in *audit.PolicyList, out *PolicyList, s conversion.Scope) error {
return autoConvert_audit_PolicyList_To_v1_PolicyList(in, out, s)
}
func autoConvert_v1_PolicyRule_To_audit_PolicyRule(in *PolicyRule, out *audit.PolicyRule, s conversion.Scope) error {
out.Level = audit.Level(in.Level)
out.Users = *(*[]string)(unsafe.Pointer(&in.Users))
out.UserGroups = *(*[]string)(unsafe.Pointer(&in.UserGroups))
out.Verbs = *(*[]string)(unsafe.Pointer(&in.Verbs))
out.Resources = *(*[]audit.GroupResources)(unsafe.Pointer(&in.Resources))
out.Namespaces = *(*[]string)(unsafe.Pointer(&in.Namespaces))
out.NonResourceURLs = *(*[]string)(unsafe.Pointer(&in.NonResourceURLs))
out.OmitStages = *(*[]audit.Stage)(unsafe.Pointer(&in.OmitStages))
return nil
}
// Convert_v1_PolicyRule_To_audit_PolicyRule is an autogenerated conversion function.
func Convert_v1_PolicyRule_To_audit_PolicyRule(in *PolicyRule, out *audit.PolicyRule, s conversion.Scope) error {
return autoConvert_v1_PolicyRule_To_audit_PolicyRule(in, out, s)
}
func autoConvert_audit_PolicyRule_To_v1_PolicyRule(in *audit.PolicyRule, out *PolicyRule, s conversion.Scope) error {
out.Level = Level(in.Level)
out.Users = *(*[]string)(unsafe.Pointer(&in.Users))
out.UserGroups = *(*[]string)(unsafe.Pointer(&in.UserGroups))
out.Verbs = *(*[]string)(unsafe.Pointer(&in.Verbs))
out.Resources = *(*[]GroupResources)(unsafe.Pointer(&in.Resources))
out.Namespaces = *(*[]string)(unsafe.Pointer(&in.Namespaces))
out.NonResourceURLs = *(*[]string)(unsafe.Pointer(&in.NonResourceURLs))
out.OmitStages = *(*[]Stage)(unsafe.Pointer(&in.OmitStages))
return nil
}
// Convert_audit_PolicyRule_To_v1_PolicyRule is an autogenerated conversion function.
func Convert_audit_PolicyRule_To_v1_PolicyRule(in *audit.PolicyRule, out *PolicyRule, s conversion.Scope) error {
return autoConvert_audit_PolicyRule_To_v1_PolicyRule(in, out, s)
}

View File

@ -0,0 +1,291 @@
// +build !ignore_autogenerated
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by deepcopy-gen. DO NOT EDIT.
package v1
import (
authenticationv1 "k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Event) DeepCopyInto(out *Event) {
*out = *in
out.TypeMeta = in.TypeMeta
in.User.DeepCopyInto(&out.User)
if in.ImpersonatedUser != nil {
in, out := &in.ImpersonatedUser, &out.ImpersonatedUser
*out = new(authenticationv1.UserInfo)
(*in).DeepCopyInto(*out)
}
if in.SourceIPs != nil {
in, out := &in.SourceIPs, &out.SourceIPs
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.ObjectRef != nil {
in, out := &in.ObjectRef, &out.ObjectRef
*out = new(ObjectReference)
**out = **in
}
if in.ResponseStatus != nil {
in, out := &in.ResponseStatus, &out.ResponseStatus
*out = new(metav1.Status)
(*in).DeepCopyInto(*out)
}
if in.RequestObject != nil {
in, out := &in.RequestObject, &out.RequestObject
*out = new(runtime.Unknown)
(*in).DeepCopyInto(*out)
}
if in.ResponseObject != nil {
in, out := &in.ResponseObject, &out.ResponseObject
*out = new(runtime.Unknown)
(*in).DeepCopyInto(*out)
}
in.RequestReceivedTimestamp.DeepCopyInto(&out.RequestReceivedTimestamp)
in.StageTimestamp.DeepCopyInto(&out.StageTimestamp)
if in.Annotations != nil {
in, out := &in.Annotations, &out.Annotations
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Event.
func (in *Event) DeepCopy() *Event {
if in == nil {
return nil
}
out := new(Event)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Event) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *EventList) DeepCopyInto(out *EventList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Event, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventList.
func (in *EventList) DeepCopy() *EventList {
if in == nil {
return nil
}
out := new(EventList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *EventList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GroupResources) DeepCopyInto(out *GroupResources) {
*out = *in
if in.Resources != nil {
in, out := &in.Resources, &out.Resources
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.ResourceNames != nil {
in, out := &in.ResourceNames, &out.ResourceNames
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GroupResources.
func (in *GroupResources) DeepCopy() *GroupResources {
if in == nil {
return nil
}
out := new(GroupResources)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectReference.
func (in *ObjectReference) DeepCopy() *ObjectReference {
if in == nil {
return nil
}
out := new(ObjectReference)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Policy) DeepCopyInto(out *Policy) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
if in.Rules != nil {
in, out := &in.Rules, &out.Rules
*out = make([]PolicyRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.OmitStages != nil {
in, out := &in.OmitStages, &out.OmitStages
*out = make([]Stage, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Policy.
func (in *Policy) DeepCopy() *Policy {
if in == nil {
return nil
}
out := new(Policy)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Policy) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PolicyList) DeepCopyInto(out *PolicyList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Policy, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyList.
func (in *PolicyList) DeepCopy() *PolicyList {
if in == nil {
return nil
}
out := new(PolicyList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PolicyList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PolicyRule) DeepCopyInto(out *PolicyRule) {
*out = *in
if in.Users != nil {
in, out := &in.Users, &out.Users
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.UserGroups != nil {
in, out := &in.UserGroups, &out.UserGroups
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Verbs != nil {
in, out := &in.Verbs, &out.Verbs
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Resources != nil {
in, out := &in.Resources, &out.Resources
*out = make([]GroupResources, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Namespaces != nil {
in, out := &in.Namespaces, &out.Namespaces
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.NonResourceURLs != nil {
in, out := &in.NonResourceURLs, &out.NonResourceURLs
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.OmitStages != nil {
in, out := &in.OmitStages, &out.OmitStages
*out = make([]Stage, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyRule.
func (in *PolicyRule) DeepCopy() *PolicyRule {
if in == nil {
return nil
}
out := new(PolicyRule)
in.DeepCopyInto(out)
return out
}

View File

@ -0,0 +1,32 @@
// +build !ignore_autogenerated
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by defaulter-gen. DO NOT EDIT.
package v1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// RegisterDefaults adds defaulters functions to the given scheme.
// Public to allow building arbitrary schemes.
// All generated defaulters are covering - they call all nested defaulters.
func RegisterDefaults(scheme *runtime.Scheme) error {
return nil
}

View File

@ -28,6 +28,7 @@ go_library(
"//staging/src/k8s.io/apimachinery/pkg/util/net:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/runtime:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1alpha1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/authentication/user:go_default_library",

View File

@ -35,6 +35,7 @@ go_library(
deps = [
"//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1alpha1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/validation:go_default_library",

View File

@ -22,6 +22,7 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
auditv1alpha1 "k8s.io/apiserver/pkg/apis/audit/v1alpha1"
auditv1beta1 "k8s.io/apiserver/pkg/apis/audit/v1beta1"
"k8s.io/apiserver/pkg/apis/audit/validation"
@ -34,6 +35,7 @@ var (
apiGroupVersions = []schema.GroupVersion{
auditv1beta1.SchemeGroupVersion,
auditv1alpha1.SchemeGroupVersion,
auditv1.SchemeGroupVersion,
}
apiGroupVersionSet = map[schema.GroupVersion]bool{}
)

View File

@ -20,6 +20,7 @@ import (
"io/ioutil"
"os"
"reflect"
"strings"
"testing"
"k8s.io/apimachinery/pkg/util/diff"
@ -31,28 +32,8 @@ import (
"github.com/stretchr/testify/require"
)
const policyDefV1alpha1 = `
apiVersion: audit.k8s.io/v1alpha1
kind: Policy
rules:
- level: None
nonResourceURLs:
- /healthz*
- /version
- level: RequestResponse
users: ["tim"]
userGroups: ["testers", "developers"]
verbs: ["patch", "delete", "create"]
resources:
- group: ""
- group: "rbac.authorization.k8s.io"
resources: ["clusterroles", "clusterrolebindings"]
namespaces: ["default", "kube-system"]
- level: Metadata
`
const policyDefV1beta1 = `
apiVersion: audit.k8s.io/v1beta1
const policyDefPattern = `
apiVersion: audit.k8s.io/{version}
kind: Policy
rules:
- level: None
@ -108,17 +89,20 @@ var expectedPolicy = &audit.Policy{
}},
}
func TestParserV1alpha1(t *testing.T) {
f, err := writePolicy(t, policyDefV1alpha1)
require.NoError(t, err)
defer os.Remove(f)
func TestParser(t *testing.T) {
for _, version := range []string{"v1", "v1alpha1", "v1beta1"} {
policyDef := strings.Replace(policyDefPattern, "{version}", version, 1)
f, err := writePolicy(t, policyDef)
require.NoError(t, err)
defer os.Remove(f)
policy, err := LoadPolicyFromFile(f)
require.NoError(t, err)
policy, err := LoadPolicyFromFile(f)
require.NoError(t, err)
assert.Len(t, policy.Rules, 3) // Sanity check.
if !reflect.DeepEqual(policy, expectedPolicy) {
t.Errorf("Unexpected policy! Diff:\n%s", diff.ObjectDiff(policy, expectedPolicy))
assert.Len(t, policy.Rules, 3) // Sanity check.
if !reflect.DeepEqual(policy, expectedPolicy) {
t.Errorf("Unexpected policy! Diff:\n%s", diff.ObjectDiff(policy, expectedPolicy))
}
}
}
@ -131,27 +115,13 @@ func TestParsePolicyWithNoVersionOrKind(t *testing.T) {
assert.Contains(t, err.Error(), "unknown group version field")
}
func TestParserV1beta1(t *testing.T) {
f, err := writePolicy(t, policyDefV1beta1)
require.NoError(t, err)
defer os.Remove(f)
policy, err := LoadPolicyFromFile(f)
require.NoError(t, err)
assert.Len(t, policy.Rules, 3) // Sanity check.
if !reflect.DeepEqual(policy, expectedPolicy) {
t.Errorf("Unexpected policy! Diff:\n%s", diff.ObjectDiff(policy, expectedPolicy))
}
}
func TestPolicyCntCheck(t *testing.T) {
var testCases = []struct {
caseName, policy string
}{
{
"policyWithNoRule",
`apiVersion: audit.k8s.io/v1beta1
`apiVersion: audit.k8s.io/v1
kind: Policy`,
},
{"emptyPolicyFile", ""},

View File

@ -18,11 +18,12 @@ limitations under the License.
package audit
import (
"k8s.io/apimachinery/pkg/apis/meta/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apiserver/pkg/apis/audit/v1"
"k8s.io/apiserver/pkg/apis/audit/v1alpha1"
"k8s.io/apiserver/pkg/apis/audit/v1beta1"
)
@ -31,7 +32,8 @@ var Scheme = runtime.NewScheme()
var Codecs = serializer.NewCodecFactory(Scheme)
func init() {
v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
metav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
utilruntime.Must(v1.AddToScheme(Scheme))
utilruntime.Must(v1alpha1.AddToScheme(Scheme))
utilruntime.Must(v1beta1.AddToScheme(Scheme))
}

View File

@ -37,6 +37,7 @@ go_library(
"//staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/apiserver:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1alpha1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/audit:go_default_library",

View File

@ -28,6 +28,7 @@ import (
"gopkg.in/natefinch/lumberjack.v2"
"k8s.io/apimachinery/pkg/runtime/schema"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
auditv1alpha1 "k8s.io/apiserver/pkg/apis/audit/v1alpha1"
auditv1beta1 "k8s.io/apiserver/pkg/apis/audit/v1beta1"
"k8s.io/apiserver/pkg/audit"
@ -138,7 +139,8 @@ func NewAuditOptions() *AuditOptions {
Mode: ModeBatch,
BatchConfig: pluginbuffered.NewDefaultBatchConfig(),
},
TruncateOptions: NewAuditTruncateOptions(),
TruncateOptions: NewAuditTruncateOptions(),
// TODO(audit): use v1 API in release 1.13
GroupVersionString: "audit.k8s.io/v1beta1",
},
LogOptions: AuditLogOptions{
@ -147,7 +149,8 @@ func NewAuditOptions() *AuditOptions {
Mode: ModeBlocking,
BatchConfig: defaultLogBatchConfig,
},
TruncateOptions: NewAuditTruncateOptions(),
TruncateOptions: NewAuditTruncateOptions(),
// TODO(audit): use v1 API in release 1.13
GroupVersionString: "audit.k8s.io/v1beta1",
},
}
@ -222,6 +225,7 @@ func validateBackendBatchOptions(pluginName string, options AuditBatchOptions) e
var knownGroupVersions = []schema.GroupVersion{
auditv1alpha1.SchemeGroupVersion,
auditv1beta1.SchemeGroupVersion,
auditv1.SchemeGroupVersion,
}
func validateGroupVersionString(groupVersion string) error {

View File

@ -39,9 +39,11 @@ go_test(
deps = [
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/install:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/audit:go_default_library",
"//vendor/github.com/pborman/uuid:go_default_library",

View File

@ -27,9 +27,11 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
"k8s.io/apiserver/pkg/apis/audit/install"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
auditv1beta1 "k8s.io/apiserver/pkg/apis/audit/v1beta1"
"k8s.io/apiserver/pkg/audit"
)
@ -89,7 +91,7 @@ func TestLogEventsLegacy(t *testing.T) {
},
} {
var buf bytes.Buffer
backend := NewBackend(&buf, FormatLegacy, auditv1beta1.SchemeGroupVersion)
backend := NewBackend(&buf, FormatLegacy, auditv1.SchemeGroupVersion)
backend.ProcessEvents(test.event)
match, err := regexp.MatchString(test.expected, buf.String())
if err != nil {
@ -141,18 +143,21 @@ func TestLogEventsJson(t *testing.T) {
},
},
} {
var buf bytes.Buffer
backend := NewBackend(&buf, FormatJson, auditv1beta1.SchemeGroupVersion)
backend.ProcessEvents(event)
// decode events back and compare with the original one.
result := &auditinternal.Event{}
decoder := audit.Codecs.UniversalDecoder(auditv1beta1.SchemeGroupVersion)
if err := runtime.DecodeInto(decoder, buf.Bytes(), result); err != nil {
t.Errorf("failed decoding buf: %s", buf.String())
continue
}
if !reflect.DeepEqual(event, result) {
t.Errorf("The result event should be the same with the original one, \noriginal: \n%#v\n result: \n%#v", event, result)
versions := []schema.GroupVersion{auditv1.SchemeGroupVersion, auditv1beta1.SchemeGroupVersion}
for _, version := range versions {
var buf bytes.Buffer
backend := NewBackend(&buf, FormatJson, version)
backend.ProcessEvents(event)
// decode events back and compare with the original one.
result := &auditinternal.Event{}
decoder := audit.Codecs.UniversalDecoder(version)
if err := runtime.DecodeInto(decoder, buf.Bytes(), result); err != nil {
t.Errorf("failed decoding buf: %s, apiVersion: %s", buf.String(), version)
continue
}
if !reflect.DeepEqual(event, result) {
t.Errorf("The result event should be the same with the original one, \noriginal: \n%#v\n result: \n%#v, apiVersion: %s", event, result, version)
}
}
}
}

View File

@ -25,7 +25,7 @@ go_test(
deps = [
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:go_default_library",
"//staging/src/k8s.io/apiserver/plugin/pkg/audit/fake:go_default_library",
"//staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook:go_default_library",
"//vendor/github.com/stretchr/testify/require:go_default_library",

View File

@ -24,7 +24,7 @@ import (
"k8s.io/apimachinery/pkg/runtime"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
auditv1beta1 "k8s.io/apiserver/pkg/apis/audit/v1beta1"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
"k8s.io/apiserver/plugin/pkg/audit/fake"
// Importing just for the schema definitions.
_ "k8s.io/apiserver/plugin/pkg/audit/webhook"
@ -82,7 +82,7 @@ func TestTruncatingEvents(t *testing.T) {
event = events[0]
},
}
b := NewBackend(fb, defaultConfig, auditv1beta1.SchemeGroupVersion)
b := NewBackend(fb, defaultConfig, auditv1.SchemeGroupVersion)
b.ProcessEvents(tc.event)
require.Equal(t, !tc.wantDropped, event != nil, "Incorrect event presence")
@ -132,7 +132,7 @@ func TestSplittingBatches(t *testing.T) {
gotBatchCount++
},
}
b := NewBackend(fb, tc.config, auditv1beta1.SchemeGroupVersion)
b := NewBackend(fb, tc.config, auditv1.SchemeGroupVersion)
b.ProcessEvents(tc.events...)
require.Equal(t, tc.wantBatchCount, gotBatchCount)

View File

@ -15,6 +15,7 @@ go_test(
"//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/audit:go_default_library",
"//staging/src/k8s.io/client-go/tools/clientcmd/api/v1:go_default_library",

View File

@ -34,6 +34,7 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
auditv1beta1 "k8s.io/apiserver/pkg/apis/audit/v1beta1"
"k8s.io/apiserver/pkg/audit"
"k8s.io/client-go/tools/clientcmd/api/v1"
@ -112,17 +113,20 @@ func newWebhook(t *testing.T, endpoint string, groupVersion schema.GroupVersion)
}
func TestWebhook(t *testing.T) {
gotEvents := false
defer func() { require.True(t, gotEvents, "no events received") }()
versions := []schema.GroupVersion{auditv1.SchemeGroupVersion, auditv1beta1.SchemeGroupVersion}
for _, version := range versions {
gotEvents := false
s := httptest.NewServer(newWebhookHandler(t, &auditv1beta1.EventList{}, func(events runtime.Object) {
gotEvents = true
}))
defer s.Close()
s := httptest.NewServer(newWebhookHandler(t, &auditv1.EventList{}, func(events runtime.Object) {
gotEvents = true
}))
defer s.Close()
backend := newWebhook(t, s.URL, auditv1beta1.SchemeGroupVersion)
backend := newWebhook(t, s.URL, auditv1.SchemeGroupVersion)
// Ensure this doesn't return a serialization error.
event := &auditinternal.Event{}
require.NoError(t, backend.processEvents(event), "failed to send events")
// Ensure this doesn't return a serialization error.
event := &auditinternal.Event{}
require.NoError(t, backend.processEvents(event), fmt.Sprintf("failed to send events, apiVersion: %s", version))
require.True(t, gotEvents, fmt.Sprintf("no events received, apiVersion: %s", version))
}
}

View File

@ -938,6 +938,10 @@
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/install",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/v1",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/v1alpha1",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

View File

@ -910,6 +910,10 @@
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/install",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/v1",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"ImportPath": "k8s.io/apiserver/pkg/apis/audit/v1alpha1",
"Rev": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

View File

@ -40,6 +40,7 @@ go_library(
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/uuid:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/wait:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount:go_default_library",
"//staging/src/k8s.io/client-go/kubernetes:go_default_library",
@ -48,6 +49,7 @@ go_library(
"//staging/src/k8s.io/client-go/util/cert:go_default_library",
"//test/e2e/common:go_default_library",
"//test/e2e/framework:go_default_library",
"//test/utils:go_default_library",
"//test/utils/image:go_default_library",
"//vendor/github.com/evanphx/json-patch:go_default_library",
"//vendor/github.com/onsi/ginkgo:go_default_library",

File diff suppressed because it is too large Load Diff

View File

@ -10,6 +10,7 @@ go_test(
name = "go_default_test",
size = "large",
srcs = [
"audit_test.go",
"crd_test.go",
"kms_transformation_test.go",
"kube_apiserver_test.go",
@ -37,7 +38,11 @@ go_test(
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/wait:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit/v1beta1:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/authentication/group:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/authentication/request/bearertoken:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/authentication/user:go_default_library",
@ -58,6 +63,8 @@ go_test(
"//staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration:go_default_library",
"//test/integration:go_default_library",
"//test/integration/framework:go_default_library",
"//test/utils:go_default_library",
"//vendor/github.com/evanphx/json-patch:go_default_library",
"//vendor/github.com/ghodss/yaml:go_default_library",
] + select({
"@io_bazel_rules_go//go/platform:android": [

View File

@ -0,0 +1,264 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package master
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
auditv1beta1 "k8s.io/apiserver/pkg/apis/audit/v1beta1"
"k8s.io/client-go/kubernetes"
kubeapiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
"k8s.io/kubernetes/test/integration/framework"
"k8s.io/kubernetes/test/utils"
"github.com/evanphx/json-patch"
)
var (
auditPolicyPattern = `
apiVersion: {version}
kind: Policy
rules:
- level: RequestResponse
resources:
- group: "" # core
resources: ["configmaps"]
`
namespace = "default"
watchTestTimeout int64 = 1
watchOptions = metav1.ListOptions{TimeoutSeconds: &watchTestTimeout}
patch, _ = json.Marshal(jsonpatch.Patch{})
auditTestUser = "system:apiserver"
versions = map[string]schema.GroupVersion{
"audit.k8s.io/v1": auditv1.SchemeGroupVersion,
"audit.k8s.io/v1beta1": auditv1beta1.SchemeGroupVersion,
}
)
// TestAudit ensures that both v1beta1 and v1 version audit api could work.
func TestAudit(t *testing.T) {
for version := range versions {
testAudit(t, version)
}
}
func testAudit(t *testing.T, version string) {
// prepare audit policy file
auditPolicy := []byte(strings.Replace(auditPolicyPattern, "{version}", version, 1))
policyFile, err := ioutil.TempFile("", "audit-policy.yaml")
if err != nil {
t.Fatalf("Failed to create audit policy file: %v", err)
}
defer os.Remove(policyFile.Name())
if _, err := policyFile.Write(auditPolicy); err != nil {
t.Fatalf("Failed to write audit policy file: %v", err)
}
if err := policyFile.Close(); err != nil {
t.Fatalf("Failed to close audit policy file: %v", err)
}
// prepare audit log file
logFile, err := ioutil.TempFile("", "audit.log")
if err != nil {
t.Fatalf("Failed to create audit log file: %v", err)
}
defer os.Remove(logFile.Name())
// start api server
result := kubeapiservertesting.StartTestServerOrDie(t, nil,
[]string{
"--audit-policy-file", policyFile.Name(),
"--audit-log-version", version,
"--audit-log-mode", "blocking",
"--audit-log-path", logFile.Name()},
framework.SharedEtcd())
defer result.TearDownFn()
kubeclient, err := kubernetes.NewForConfig(result.ClientConfig)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
func() {
// create, get, watch, update, patch, list and delete configmap.
configMap := &apiv1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "audit-configmap",
},
Data: map[string]string{
"map-key": "map-value",
},
}
_, err := kubeclient.CoreV1().ConfigMaps(namespace).Create(configMap)
expectNoError(t, err, "failed to create audit-configmap")
_, err = kubeclient.CoreV1().ConfigMaps(namespace).Get(configMap.Name, metav1.GetOptions{})
expectNoError(t, err, "failed to get audit-configmap")
configMapChan, err := kubeclient.CoreV1().ConfigMaps(namespace).Watch(watchOptions)
expectNoError(t, err, "failed to create watch for config maps")
for range configMapChan.ResultChan() {
// Block until watchOptions.TimeoutSeconds expires.
// If the test finishes before watchOptions.TimeoutSeconds expires, the watch audit
// event at stage ResponseComplete will not be generated.
}
_, err = kubeclient.CoreV1().ConfigMaps(namespace).Update(configMap)
expectNoError(t, err, "failed to update audit-configmap")
_, err = kubeclient.CoreV1().ConfigMaps(namespace).Patch(configMap.Name, types.JSONPatchType, patch)
expectNoError(t, err, "failed to patch configmap")
_, err = kubeclient.CoreV1().ConfigMaps(namespace).List(metav1.ListOptions{})
expectNoError(t, err, "failed to list config maps")
err = kubeclient.CoreV1().ConfigMaps(namespace).Delete(configMap.Name, &metav1.DeleteOptions{})
expectNoError(t, err, "failed to delete audit-configmap")
}()
expectedEvents := []utils.AuditEvent{
{
Level: auditinternal.LevelRequestResponse,
Stage: auditinternal.StageResponseComplete,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps", namespace),
Verb: "create",
Code: 201,
User: auditTestUser,
Resource: "configmaps",
Namespace: namespace,
RequestObject: true,
ResponseObject: true,
AuthorizeDecision: "allow",
}, {
Level: auditinternal.LevelRequestResponse,
Stage: auditinternal.StageResponseComplete,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps/audit-configmap", namespace),
Verb: "get",
Code: 200,
User: auditTestUser,
Resource: "configmaps",
Namespace: namespace,
RequestObject: false,
ResponseObject: true,
AuthorizeDecision: "allow",
}, {
Level: auditinternal.LevelRequestResponse,
Stage: auditinternal.StageResponseComplete,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps", namespace),
Verb: "list",
Code: 200,
User: auditTestUser,
Resource: "configmaps",
Namespace: namespace,
RequestObject: false,
ResponseObject: true,
AuthorizeDecision: "allow",
}, {
Level: auditinternal.LevelRequestResponse,
Stage: auditinternal.StageResponseStarted,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps?timeoutSeconds=%d&watch=true", namespace, watchTestTimeout),
Verb: "watch",
Code: 200,
User: auditTestUser,
Resource: "configmaps",
Namespace: namespace,
RequestObject: false,
ResponseObject: false,
AuthorizeDecision: "allow",
}, {
Level: auditinternal.LevelRequestResponse,
Stage: auditinternal.StageResponseComplete,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps?timeoutSeconds=%d&watch=true", namespace, watchTestTimeout),
Verb: "watch",
Code: 200,
User: auditTestUser,
Resource: "configmaps",
Namespace: namespace,
RequestObject: false,
ResponseObject: false,
AuthorizeDecision: "allow",
}, {
Level: auditinternal.LevelRequestResponse,
Stage: auditinternal.StageResponseComplete,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps/audit-configmap", namespace),
Verb: "update",
Code: 200,
User: auditTestUser,
Resource: "configmaps",
Namespace: namespace,
RequestObject: true,
ResponseObject: true,
AuthorizeDecision: "allow",
}, {
Level: auditinternal.LevelRequestResponse,
Stage: auditinternal.StageResponseComplete,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps/audit-configmap", namespace),
Verb: "patch",
Code: 200,
User: auditTestUser,
Resource: "configmaps",
Namespace: namespace,
RequestObject: true,
ResponseObject: true,
AuthorizeDecision: "allow",
}, {
Level: auditinternal.LevelRequestResponse,
Stage: auditinternal.StageResponseComplete,
RequestURI: fmt.Sprintf("/api/v1/namespaces/%s/configmaps/audit-configmap", namespace),
Verb: "delete",
Code: 200,
User: auditTestUser,
Resource: "configmaps",
Namespace: namespace,
RequestObject: true,
ResponseObject: true,
AuthorizeDecision: "allow",
},
}
stream, err := os.Open(logFile.Name())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer stream.Close()
missing, err := utils.CheckAuditLines(stream, expectedEvents, versions[version])
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(missing) > 0 {
t.Errorf("Failed to match all expected events, events %#v not found!", missing)
}
}
func expectNoError(t *testing.T, err error, msg string) {
if err != nil {
t.Fatalf("%s: %v", msg, err)
}
}

View File

@ -8,6 +8,7 @@ load(
go_library(
name = "go_default_library",
srcs = [
"audit.go",
"conditions.go",
"create_resources.go",
"delete_resources.go",
@ -49,6 +50,8 @@ go_library(
"//staging/src/k8s.io/apimachinery/pkg/util/uuid:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/wait:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/watch:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/apis/audit:go_default_library",
"//staging/src/k8s.io/apiserver/pkg/audit:go_default_library",
"//staging/src/k8s.io/client-go/kubernetes:go_default_library",
"//staging/src/k8s.io/client-go/scale:go_default_library",
"//staging/src/k8s.io/client-go/tools/cache:go_default_library",

106
test/utils/audit.go Normal file
View File

@ -0,0 +1,106 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"bufio"
"fmt"
"io"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
"k8s.io/apiserver/pkg/audit"
)
type AuditEvent struct {
Level auditinternal.Level
Stage auditinternal.Stage
RequestURI string
Verb string
Code int32
User string
Resource string
Namespace string
RequestObject bool
ResponseObject bool
AuthorizeDecision string
}
// Search the audit log for the expected audit lines.
func CheckAuditLines(stream io.Reader, expected []AuditEvent, version schema.GroupVersion) (missing []AuditEvent, err error) {
expectations := map[AuditEvent]bool{}
for _, event := range expected {
expectations[event] = false
}
scanner := bufio.NewScanner(stream)
for scanner.Scan() {
line := scanner.Text()
event, err := parseAuditLine(line, version)
if err != nil {
return expected, err
}
// If the event was expected, mark it as found.
if _, found := expectations[event]; found {
expectations[event] = true
}
}
if err := scanner.Err(); err != nil {
return expected, err
}
missing = make([]AuditEvent, 0)
for event, found := range expectations {
if !found {
missing = append(missing, event)
}
}
return missing, nil
}
func parseAuditLine(line string, version schema.GroupVersion) (AuditEvent, error) {
e := &auditinternal.Event{}
decoder := audit.Codecs.UniversalDecoder(version)
if err := runtime.DecodeInto(decoder, []byte(line), e); err != nil {
return AuditEvent{}, fmt.Errorf("failed decoding buf: %s, apiVersion: %s", line, version)
}
event := AuditEvent{
Level: e.Level,
Stage: e.Stage,
RequestURI: e.RequestURI,
Verb: e.Verb,
User: e.User.Username,
}
if e.ObjectRef != nil {
event.Namespace = e.ObjectRef.Namespace
event.Resource = e.ObjectRef.Resource
}
if e.ResponseStatus != nil {
event.Code = e.ResponseStatus.Code
}
if e.ResponseObject != nil {
event.ResponseObject = true
}
if e.RequestObject != nil {
event.RequestObject = true
}
event.AuthorizeDecision = e.Annotations["authorization.k8s.io/decision"]
return event, nil
}