2019-07-15 16:07:56 -07:00
|
|
|
package webhooks
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/golang/glog"
|
2019-08-14 10:01:47 -07:00
|
|
|
kyverno "github.com/nirmata/kyverno/pkg/api/kyverno/v1alpha1"
|
2019-10-18 17:45:24 -07:00
|
|
|
policyvalidate "github.com/nirmata/kyverno/pkg/engine/policy"
|
2019-07-15 16:07:56 -07:00
|
|
|
v1beta1 "k8s.io/api/admission/v1beta1"
|
|
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
|
|
)
|
|
|
|
|
|
|
|
//HandlePolicyValidation performs the validation check on policy resource
|
2019-08-27 16:44:10 -07:00
|
|
|
func (ws *WebhookServer) handlePolicyValidation(request *v1beta1.AdmissionRequest) *v1beta1.AdmissionResponse {
|
2019-09-03 14:51:51 -07:00
|
|
|
var policy *kyverno.ClusterPolicy
|
2019-08-08 13:09:40 -07:00
|
|
|
admissionResp := &v1beta1.AdmissionResponse{
|
|
|
|
Allowed: true,
|
|
|
|
}
|
2019-08-21 16:42:42 -07:00
|
|
|
|
2019-08-27 16:44:10 -07:00
|
|
|
//TODO: can this happen? wont this be picked by OpenAPI spec schema ?
|
2019-08-21 16:42:42 -07:00
|
|
|
raw := request.Object.Raw
|
2019-08-08 13:09:40 -07:00
|
|
|
if err := json.Unmarshal(raw, &policy); err != nil {
|
|
|
|
glog.Errorf("Failed to unmarshal policy admission request, err %v\n", err)
|
2019-08-21 12:38:15 -07:00
|
|
|
return &v1beta1.AdmissionResponse{Allowed: false,
|
|
|
|
Result: &metav1.Status{
|
|
|
|
Message: fmt.Sprintf("Failed to unmarshal policy admission request err %v", err),
|
|
|
|
}}
|
2019-08-08 13:09:40 -07:00
|
|
|
}
|
2019-09-26 18:02:24 -07:00
|
|
|
|
2019-10-18 17:45:24 -07:00
|
|
|
if err := policyvalidate.Validate(*policy); err != nil {
|
2019-09-26 18:02:24 -07:00
|
|
|
admissionResp = &v1beta1.AdmissionResponse{
|
|
|
|
Allowed: false,
|
|
|
|
Result: &metav1.Status{
|
|
|
|
Message: err.Error(),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2019-08-07 18:01:28 -07:00
|
|
|
|
2019-09-04 13:43:12 -07:00
|
|
|
if admissionResp.Allowed {
|
2019-10-03 17:00:05 -07:00
|
|
|
if policy.HasMutateOrValidate() {
|
2019-09-04 13:43:12 -07:00
|
|
|
// create mutating resource mutatingwebhookconfiguration if not present
|
|
|
|
if err := ws.webhookRegistrationClient.CreateResourceMutatingWebhookConfiguration(); err != nil {
|
|
|
|
glog.Error("failed to created resource mutating webhook configuration, policies wont be applied on the resource")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-08-07 18:01:28 -07:00
|
|
|
return admissionResp
|
2019-07-15 16:07:56 -07:00
|
|
|
}
|
|
|
|
|
2019-09-26 18:02:24 -07:00
|
|
|
func failResponseWithMsg(msg string) *v1beta1.AdmissionResponse {
|
2019-07-15 16:07:56 -07:00
|
|
|
return &v1beta1.AdmissionResponse{
|
2019-09-26 18:02:24 -07:00
|
|
|
Allowed: false,
|
|
|
|
Result: &metav1.Status{
|
|
|
|
Message: msg,
|
|
|
|
},
|
2019-07-15 16:07:56 -07:00
|
|
|
}
|
|
|
|
}
|