1/*
2Copyright 2021 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 api
18
19import (
20	"fmt"
21
22	"k8s.io/apimachinery/pkg/util/errors"
23	policyapi "k8s.io/pod-security-admission/api"
24)
25
26var requiredErr = fmt.Errorf("required")
27
28// TODO: deduplicate against PolicyToEvaluate
29func ToPolicy(defaults PodSecurityDefaults) (policyapi.Policy, error) {
30	var (
31		err  error
32		errs []error
33		p    policyapi.Policy
34	)
35
36	if len(defaults.Enforce) == 0 {
37		errs = appendErr(errs, requiredErr, "Enforce.Level")
38	} else {
39		p.Enforce.Level, err = policyapi.ParseLevel(defaults.Enforce)
40		errs = appendErr(errs, err, "Enforce.Level")
41	}
42
43	if len(defaults.EnforceVersion) == 0 {
44		errs = appendErr(errs, requiredErr, "Enforce.Version")
45	} else {
46		p.Enforce.Version, err = policyapi.ParseVersion(defaults.EnforceVersion)
47		errs = appendErr(errs, err, "Enforce.Version")
48	}
49
50	if len(defaults.Audit) == 0 {
51		errs = appendErr(errs, requiredErr, "Audit.Level")
52	} else {
53		p.Audit.Level, err = policyapi.ParseLevel(defaults.Audit)
54		errs = appendErr(errs, err, "Audit.Level")
55	}
56
57	if len(defaults.AuditVersion) == 0 {
58		errs = appendErr(errs, requiredErr, "Audit.Version")
59	} else {
60		p.Audit.Version, err = policyapi.ParseVersion(defaults.AuditVersion)
61		errs = appendErr(errs, err, "Audit.Version")
62	}
63
64	if len(defaults.Warn) == 0 {
65		errs = appendErr(errs, requiredErr, "Warn.Level")
66	} else {
67		p.Warn.Level, err = policyapi.ParseLevel(defaults.Warn)
68		errs = appendErr(errs, err, "Warn.Level")
69	}
70
71	if len(defaults.WarnVersion) == 0 {
72		errs = appendErr(errs, requiredErr, "Warn.Version")
73	} else {
74		p.Warn.Version, err = policyapi.ParseVersion(defaults.WarnVersion)
75		errs = appendErr(errs, err, "Warn.Version")
76	}
77
78	return p, errors.NewAggregate(errs)
79}
80
81// appendErr is a helper function to collect field-specific errors.
82func appendErr(errs []error, err error, field string) []error {
83	if err != nil {
84		return append(errs, fmt.Errorf("%s: %s", field, err.Error()))
85	}
86	return errs
87}
88