...
1
16
17 package admission
18
19 import (
20 "net/http"
21
22 jsonpatch "gomodules.xyz/jsonpatch/v2"
23 admissionv1 "k8s.io/api/admission/v1"
24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
25 )
26
27
28
29 func Allowed(message string) Response {
30 return ValidationResponse(true, message)
31 }
32
33
34
35 func Denied(message string) Response {
36 return ValidationResponse(false, message)
37 }
38
39
40
41
42 func Patched(message string, patches ...jsonpatch.JsonPatchOperation) Response {
43 resp := Allowed(message)
44 resp.Patches = patches
45
46 return resp
47 }
48
49
50 func Errored(code int32, err error) Response {
51 return Response{
52 AdmissionResponse: admissionv1.AdmissionResponse{
53 Allowed: false,
54 Result: &metav1.Status{
55 Code: code,
56 Message: err.Error(),
57 },
58 },
59 }
60 }
61
62
63 func ValidationResponse(allowed bool, message string) Response {
64 code := http.StatusForbidden
65 reason := metav1.StatusReasonForbidden
66 if allowed {
67 code = http.StatusOK
68 reason = ""
69 }
70 resp := Response{
71 AdmissionResponse: admissionv1.AdmissionResponse{
72 Allowed: allowed,
73 Result: &metav1.Status{
74 Code: int32(code),
75 Reason: reason,
76 },
77 },
78 }
79 if len(message) > 0 {
80 resp.Result.Message = message
81 }
82 return resp
83 }
84
85
86
87
88 func PatchResponseFromRaw(original, current []byte) Response {
89 patches, err := jsonpatch.CreatePatch(original, current)
90 if err != nil {
91 return Errored(http.StatusInternalServerError, err)
92 }
93 return Response{
94 Patches: patches,
95 AdmissionResponse: admissionv1.AdmissionResponse{
96 Allowed: true,
97 PatchType: func() *admissionv1.PatchType {
98 if len(patches) == 0 {
99 return nil
100 }
101 pt := admissionv1.PatchTypeJSONPatch
102 return &pt
103 }(),
104 },
105 }
106 }
107
108
109 func validationResponseFromStatus(allowed bool, status metav1.Status) Response {
110 resp := Response{
111 AdmissionResponse: admissionv1.AdmissionResponse{
112 Allowed: allowed,
113 Result: &status,
114 },
115 }
116 return resp
117 }
118
119
120
121 func (r Response) WithWarnings(warnings ...string) Response {
122 r.AdmissionResponse.Warnings = append(r.AdmissionResponse.Warnings, warnings...)
123 return r
124 }
125
View as plain text