blob: 1d02e1a3fb9fc935d7e185f16deb1211471e3060 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package policy
18
19import (
20 "fmt"
21 "io/ioutil"
22
23 "k8s.io/apimachinery/pkg/runtime/schema"
24 auditinternal "k8s.io/apiserver/pkg/apis/audit"
25 auditv1alpha1 "k8s.io/apiserver/pkg/apis/audit/v1alpha1"
26 auditv1beta1 "k8s.io/apiserver/pkg/apis/audit/v1beta1"
27 "k8s.io/apiserver/pkg/apis/audit/validation"
28 "k8s.io/apiserver/pkg/audit"
29
30 "github.com/golang/glog"
31)
32
33var (
34 apiGroupVersions = []schema.GroupVersion{
35 auditv1beta1.SchemeGroupVersion,
36 auditv1alpha1.SchemeGroupVersion,
37 }
38 apiGroupVersionSet = map[schema.GroupVersion]bool{}
39)
40
41func init() {
42 for _, gv := range apiGroupVersions {
43 apiGroupVersionSet[gv] = true
44 }
45}
46
47func LoadPolicyFromFile(filePath string) (*auditinternal.Policy, error) {
48 if filePath == "" {
49 return nil, fmt.Errorf("file path not specified")
50 }
51 policyDef, err := ioutil.ReadFile(filePath)
52 if err != nil {
53 return nil, fmt.Errorf("failed to read file path %q: %+v", filePath, err)
54 }
55
56 policy := &auditinternal.Policy{}
57 decoder := audit.Codecs.UniversalDecoder(apiGroupVersions...)
58
59 _, gvk, err := decoder.Decode(policyDef, nil, policy)
60 if err != nil {
61 return nil, fmt.Errorf("failed decoding file %q: %v", filePath, err)
62 }
63
64 // Ensure the policy file contained an apiVersion and kind.
65 if !apiGroupVersionSet[schema.GroupVersion{Group: gvk.Group, Version: gvk.Version}] {
66 return nil, fmt.Errorf("unknown group version field %v in policy file %s", gvk, filePath)
67 }
68
69 if err := validation.ValidatePolicy(policy); err != nil {
70 return nil, err.ToAggregate()
71 }
72
73 policyCnt := len(policy.Rules)
74 if policyCnt == 0 {
75 return nil, fmt.Errorf("loaded illegal policy with 0 rules from file %s", filePath)
76 }
77 glog.V(4).Infof("Loaded %d audit policy rules from file %s", policyCnt, filePath)
78 return policy, nil
79}