← Back to Pull requests

Implement hns validation webhook #602

Merged
yiqigao217 merged 6 files (453 lines) on Apr 06, 2020 20:41 UTC
View on GitHub
yiqigao217 yiqigao217 commented on Apr 03, 2020 16:15 UTC
Author

Add HierarchicalNamespace and Namespace webhooks. They will allow all
requests from HNC SA.

HNS webhook will deny:
1) creating hns in a forbidden (excluded) namespace;
2) creating hns with an existing namespace name;
3) deleting hns if the owned namespace doesn't allow cascading deletion.

NS webhook will deny:
1) deleting ns if it's owned, no matter if it allows cascading deletion,
since users should delete the hns instance in the owner instead;
2) deleting ns if it has owned ns that cannot be cascading deleted.

Tested with new unit tests and manually tested on GKE cluster to see if
it works as expected and no conflict with cascading deletion implemented
earlier.

Fixes #458
Part of #457

Diff: 453 lines (+453 / -0) across 6 files Reviewer: sophieliu15 Review duration: 4586m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.47) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.47 · 453 lines diff across 6 files
0.47
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.88 · 5 substantive comment(s)
0.88
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
90%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.366
Real PR Conversation Timeline
38 items
yiqigao217 yiqigao217 commented on Apr 03, 2020 16:16 UTC
Author

/assign @adrianludwin
/assign @sophieliu15
cc @adrianchung

sophieliu15 sophieliu15 commented on code on Apr 03, 2020 17:55 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)

Maybe use the full name instead of acronym? Or jut use "subnamespaces" as the first sentance.

sophieliu15 sophieliu15 commented on code on Apr 03, 2020 17:56 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)

Do we need to log the message here? IIUC, it will be logged in line 56?

adrianludwin adrianludwin commented on code on Apr 03, 2020 18:26 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)

+1

adrianludwin adrianludwin commented on code on Apr 03, 2020 18:29 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace_test.go:1
@@ -0,0 +1,63 @@
+package validators
+
+import (
+	"testing"
+
+	. "github.com/onsi/gomega"
+	"k8s.io/api/admission/v1beta1"
+	"sigs.k8s.io/controller-runtime/pkg/log/zap"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+func TestHNS(t *testing.T) {
+	f := forest.NewForest()
+
+	// Create two namespaces foo and bar.
+	createNS(f, "foo", nil)
+	createNS(f, "bar", nil)
+
+	// Create namespace baz with AllowCascadingDelete set to true.
+	baz := createNS(f, "baz", nil)
+	baz.UpdateAllowCascadingDelete(true)
+
+	h := &HierarchicalNamespace{
+		Log:    zap.Logger(false),
+		Forest: f,
+	}
+
+	tests := []struct {
+		name string
+		op   v1beta1.Operation
+		pnm  string
+		cnm  string
+		fail bool
+	}{
+		{name: "ok-create", op: v1beta1.Create, pnm: "foo", cnm: "brumpf"},
+		{name: "ok-delete", op: v1beta1.Delete, pnm: "foo", cnm: "baz"},

When did we make "baz" a child of "foo"? Or is that not necessary in the test? If not, maybe comment why we can delete baz from foo when it's not a child of foo.

adrianludwin adrianludwin commented on code on Apr 03, 2020 18:32 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,119 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(log logr.Logger, req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		log.V(1).Info(msg)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(log, req)
+}
+
+func (v *Namespace) checkForest(log logr.Logger, req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {
+		for _, cnm := range ns.ChildNames() {
+			cns := v.Forest.Get(cnm)
+			if cns.IsOwned {
+				msg := fmt.Sprintf("The namespace has owned namespace(s), e.g. %s. Please set allowCascadingDelete flag to true first.", cnm)

It would be more useful to give a full list here

adrianludwin adrianludwin commented on Apr 03, 2020 18:33 UTC
Reviewer

lgtm after a few minor comments

yiqigao217 yiqigao217 commented on code on Apr 03, 2020 18:34 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)

Ah right, good catch!

yiqigao217 yiqigao217 commented on code on Apr 03, 2020 18:36 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)

SG, yes since the creation of hns is masked by k hns create, users may not aware they are actually creating hns instances. Will update, thanks!

yiqigao217 yiqigao217 commented on code on Apr 03, 2020 18:55 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace_test.go:1
@@ -0,0 +1,63 @@
+package validators
+
+import (
+	"testing"
+
+	. "github.com/onsi/gomega"
+	"k8s.io/api/admission/v1beta1"
+	"sigs.k8s.io/controller-runtime/pkg/log/zap"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+func TestHNS(t *testing.T) {
+	f := forest.NewForest()
+
+	// Create two namespaces foo and bar.
+	createNS(f, "foo", nil)
+	createNS(f, "bar", nil)
+
+	// Create namespace baz with AllowCascadingDelete set to true.
+	baz := createNS(f, "baz", nil)
+	baz.UpdateAllowCascadingDelete(true)
+
+	h := &HierarchicalNamespace{
+		Log:    zap.Logger(false),
+		Forest: f,
+	}
+
+	tests := []struct {
+		name string
+		op   v1beta1.Operation
+		pnm  string
+		cnm  string
+		fail bool
+	}{
+		{name: "ok-create", op: v1beta1.Create, pnm: "foo", cnm: "brumpf"},
+		{name: "ok-delete", op: v1beta1.Delete, pnm: "foo", cnm: "baz"},

Thanks for pointing this one out! I was going to test deleting an hns as long as the namespace in the 'cnm' field doesn't have owner annotation and allowsCD.

After another look, I think I shouldn't use this case since this request would never get to handle(), it should return bad request in Handle() already. I will set a real hns relationship for them at the top.

yiqigao217 yiqigao217 commented on code on Apr 03, 2020 18:55 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,119 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(log logr.Logger, req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		log.V(1).Info(msg)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(log, req)
+}
+
+func (v *Namespace) checkForest(log logr.Logger, req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {
+		for _, cnm := range ns.ChildNames() {
+			cns := v.Forest.Get(cnm)
+			if cns.IsOwned {
+				msg := fmt.Sprintf("The namespace has owned namespace(s), e.g. %s. Please set allowCascadingDelete flag to true first.", cnm)

sure, will update!

adrianchung adrianchung commented on code on Apr 03, 2020 19:33 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonConflict, msg)
+		}
+	}
+
+	if req.op == v1beta1.Delete {
+		if cns.Exists() && !cns.AllowsCascadingDelete() {
+			msg := fmt.Sprintf("The subnamespace %s doesn't allow cascading deletion. Please set allowCascadingDelete flag first.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+	}
+
+	return allow("")
+}
+
+// decodeRequest gets the information we care about into a simple struct that's easy to both a) use
+// and b) factor out in unit tests.
+func (v *HierarchicalNamespace) decodeRequest(log logr.Logger, in admission.Request) (*hnsRequest, error) {
+	hns := &api.HierarchicalNamespace{}
+	var err error
+	// For DELETE request, use DecodeRaw() from req.OldObject, since Decode() only uses req.Object,
+	// which will be empty for a DELETE request.
+	if in.Operation == v1beta1.Delete {
+		log.V(1).Info("Decoding a delete request.")
+		err = v.decoder.DecodeRaw(in.OldObject, hns)
+	} else {
+		err = v.decoder.Decode(in, hns)
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	return &hnsRequest{
+		hns: hns,
+		op:  in.Operation,
+	}, nil
+}
+
+func (v *HierarchicalNamespace) InjectDecoder(d *admission.Decoder) error {

Is this function used in this PR? I'd expect to see a test for something like this, but don't see anything associated with it -- either that or as a part of an interface definition. Am I missing some understanding here?

adrianludwin adrianludwin commented on code on Apr 03, 2020 20:22 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonConflict, msg)
+		}
+	}
+
+	if req.op == v1beta1.Delete {
+		if cns.Exists() && !cns.AllowsCascadingDelete() {
+			msg := fmt.Sprintf("The subnamespace %s doesn't allow cascading deletion. Please set allowCascadingDelete flag first.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+	}
+
+	return allow("")
+}
+
+// decodeRequest gets the information we care about into a simple struct that's easy to both a) use
+// and b) factor out in unit tests.
+func (v *HierarchicalNamespace) decodeRequest(log logr.Logger, in admission.Request) (*hnsRequest, error) {
+	hns := &api.HierarchicalNamespace{}
+	var err error
+	// For DELETE request, use DecodeRaw() from req.OldObject, since Decode() only uses req.Object,
+	// which will be empty for a DELETE request.
+	if in.Operation == v1beta1.Delete {
+		log.V(1).Info("Decoding a delete request.")
+		err = v.decoder.DecodeRaw(in.OldObject, hns)
+	} else {
+		err = v.decoder.Decode(in, hns)
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	return &hnsRequest{
+		hns: hns,
+		op:  in.Operation,
+	}, nil
+}
+
+func (v *HierarchicalNamespace) InjectDecoder(d *admission.Decoder) error {

You mean InjectDecoder? It's part of the boilerplate code that's called by controller-runtime, I'm pretty sure nothing will compile if it's not there.

adrianludwin adrianludwin commented on code on Apr 03, 2020 20:26 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,121 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(req)
+}
+
+func (v *Namespace) checkForest(req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {

This might be a bit easier to read if you had more early exits:

if req.op != v1beta1.Delete {
  return allow("") // we only care about deletions
}

if ns.AllowsCascadingDelete {
  return allow("") // go ahead, make my day
}

// Check to see if there are any HNSes that can't be deleted
...

```

adrianludwin adrianludwin commented on code on Apr 03, 2020 20:28 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,121 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(req)
+}
+
+func (v *Namespace) checkForest(req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {
+		hnses := []string{}
+		for _, cnm := range ns.ChildNames() {
+			cns := v.Forest.Get(cnm)
+			if cns.IsOwned {
+				hnses = append(hnses, cnm)
+			}

Shouldn't this be if cns.IsOwned && !cns.AllowsCascadingDelete()? If so, maybe change hnses to cantDelete or something like that, to make it clear why things get added to that list.

If I'm correct, and this is a bug, maybe add a unit test for this too?

adrianludwin adrianludwin commented on code on Apr 03, 2020 20:28 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,121 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(req)
+}
+
+func (v *Namespace) checkForest(req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {
+		hnses := []string{}
+		for _, cnm := range ns.ChildNames() {
+			cns := v.Forest.Get(cnm)
+			if cns.IsOwned {
+				hnses = append(hnses, cnm)
+			}
+		}
+		if len(hnses) != 0 {
+			msg := fmt.Sprintf("The namespace has owned namespace(s): %s. Please set allowCascadingDelete flag to true first.", hnses)

Maybe Please set allowCascadingDelete first either in the parent namespace or in all the owned children?

yiqigao217 yiqigao217 commented on code on Apr 03, 2020 20:32 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace_test.go:1
@@ -0,0 +1,63 @@
+package validators
+
+import (
+	"testing"
+
+	. "github.com/onsi/gomega"
+	"k8s.io/api/admission/v1beta1"
+	"sigs.k8s.io/controller-runtime/pkg/log/zap"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+func TestHNS(t *testing.T) {
+	f := forest.NewForest()
+
+	// Create two namespaces foo and bar.
+	createNS(f, "foo", nil)
+	createNS(f, "bar", nil)
+
+	// Create namespace baz with AllowCascadingDelete set to true.
+	baz := createNS(f, "baz", nil)
+	baz.UpdateAllowCascadingDelete(true)
+
+	h := &HierarchicalNamespace{
+		Log:    zap.Logger(false),
+		Forest: f,
+	}
+
+	tests := []struct {
+		name string
+		op   v1beta1.Operation
+		pnm  string
+		cnm  string
+		fail bool
+	}{
+		{name: "ok-create", op: v1beta1.Create, pnm: "foo", cnm: "brumpf"},
+		{name: "ok-delete", op: v1beta1.Delete, pnm: "foo", cnm: "baz"},

FYI updated in line 21 by createOwnedNamespace().

yiqigao217 yiqigao217 commented on code on Apr 03, 2020 20:34 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonConflict, msg)
+		}
+	}
+
+	if req.op == v1beta1.Delete {
+		if cns.Exists() && !cns.AllowsCascadingDelete() {
+			msg := fmt.Sprintf("The subnamespace %s doesn't allow cascading deletion. Please set allowCascadingDelete flag first.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+	}
+
+	return allow("")
+}
+
+// decodeRequest gets the information we care about into a simple struct that's easy to both a) use
+// and b) factor out in unit tests.
+func (v *HierarchicalNamespace) decodeRequest(log logr.Logger, in admission.Request) (*hnsRequest, error) {
+	hns := &api.HierarchicalNamespace{}
+	var err error
+	// For DELETE request, use DecodeRaw() from req.OldObject, since Decode() only uses req.Object,
+	// which will be empty for a DELETE request.
+	if in.Operation == v1beta1.Delete {
+		log.V(1).Info("Decoding a delete request.")
+		err = v.decoder.DecodeRaw(in.OldObject, hns)
+	} else {
+		err = v.decoder.Decode(in, hns)
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	return &hnsRequest{
+		hns: hns,
+		op:  in.Operation,
+	}, nil
+}
+
+func (v *HierarchicalNamespace) InjectDecoder(d *admission.Decoder) error {

The documentation of the interface DecoderInjector is here: https://godoc.org/sigs.k8s.io/controller-runtime/pkg/webhook/admission#DecoderInjector. It only says it will be used by ControllerManager to inject decoder though.

yiqigao217 yiqigao217 commented on code on Apr 03, 2020 20:41 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,121 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(req)
+}
+
+func (v *Namespace) checkForest(req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {
+		hnses := []string{}
+		for _, cnm := range ns.ChildNames() {
+			cns := v.Forest.Get(cnm)
+			if cns.IsOwned {
+				hnses = append(hnses, cnm)
+			}

Yes good catch it's a bug. Say the owner doesn't allowCD but all its owned NS allows, then it should return allow(). Good catch on this corner case, will add the unit test on that and manual test it too.

adrianchung adrianchung commented on code on Apr 04, 2020 00:47 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonConflict, msg)
+		}
+	}
+
+	if req.op == v1beta1.Delete {
+		if cns.Exists() && !cns.AllowsCascadingDelete() {
+			msg := fmt.Sprintf("The subnamespace %s doesn't allow cascading deletion. Please set allowCascadingDelete flag first.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+	}
+
+	return allow("")
+}
+
+// decodeRequest gets the information we care about into a simple struct that's easy to both a) use
+// and b) factor out in unit tests.
+func (v *HierarchicalNamespace) decodeRequest(log logr.Logger, in admission.Request) (*hnsRequest, error) {
+	hns := &api.HierarchicalNamespace{}
+	var err error
+	// For DELETE request, use DecodeRaw() from req.OldObject, since Decode() only uses req.Object,
+	// which will be empty for a DELETE request.
+	if in.Operation == v1beta1.Delete {
+		log.V(1).Info("Decoding a delete request.")
+		err = v.decoder.DecodeRaw(in.OldObject, hns)
+	} else {
+		err = v.decoder.Decode(in, hns)
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	return &hnsRequest{
+		hns: hns,
+		op:  in.Operation,
+	}, nil
+}
+
+func (v *HierarchicalNamespace) InjectDecoder(d *admission.Decoder) error {

I tried just deleting InjectDecoder and InjectClient methods out of .pkg/validators/hierarchy.go as a test and the binary still compiles and deploys. I'm not one to argue with the compiler. As an experiment can you see what'd happen if we took this out and see if there's any side effects? I don't want to block the review or anything -- you're just likely closest to trying this out!

adrianludwin adrianludwin commented on code on Apr 04, 2020 02:34 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonConflict, msg)
+		}
+	}
+
+	if req.op == v1beta1.Delete {
+		if cns.Exists() && !cns.AllowsCascadingDelete() {
+			msg := fmt.Sprintf("The subnamespace %s doesn't allow cascading deletion. Please set allowCascadingDelete flag first.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+	}
+
+	return allow("")
+}
+
+// decodeRequest gets the information we care about into a simple struct that's easy to both a) use
+// and b) factor out in unit tests.
+func (v *HierarchicalNamespace) decodeRequest(log logr.Logger, in admission.Request) (*hnsRequest, error) {
+	hns := &api.HierarchicalNamespace{}
+	var err error
+	// For DELETE request, use DecodeRaw() from req.OldObject, since Decode() only uses req.Object,
+	// which will be empty for a DELETE request.
+	if in.Operation == v1beta1.Delete {
+		log.V(1).Info("Decoding a delete request.")
+		err = v.decoder.DecodeRaw(in.OldObject, hns)
+	} else {
+		err = v.decoder.Decode(in, hns)
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	return &hnsRequest{
+		hns: hns,
+		op:  in.Operation,
+	}, nil
+}
+
+func (v *HierarchicalNamespace) InjectDecoder(d *admission.Decoder) error {

Hmm. Are you sure the webhook is running correctly after this? Without InjectDecoder, I'm not sure how the decoder field is set, which means it should cause a nil pointer exception the first time we try to decode something. Perhaps it just looks fine because you never created a HierarchicalNamespace object, but as soon as you do, HNC will crash?

I would have _thought_ that InjectDecoder was checked at compile time, but perhaps it's only checked at runtime with a type switch.

jiachengxu jiachengxu commented on code on Apr 06, 2020 06:20 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,119 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io

why the update is needed? In your Handle method, it only handles create and delete operations.

adrianludwin adrianludwin commented on code on Apr 06, 2020 11:41 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,119 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io

Nice catch! We should probably reject any updates to HNSes (it doesn't have any real fields anyway), or else take update out of this list.

yiqigao217 yiqigao217 commented on code on Apr 06, 2020 15:28 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,122 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(log, decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(log logr.Logger, req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Create {
+		if reconcilers.EX[pnm] {
+			msg := fmt.Sprintf("The namespace %s is not allowed to create subnamespaces. Please create hns in a different namespace.", pnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+
+		if cns.Exists() {
+			msg := fmt.Sprintf("The requested namespace %s already exists. Please use a different name.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonConflict, msg)
+		}
+	}
+
+	if req.op == v1beta1.Delete {
+		if cns.Exists() && !cns.AllowsCascadingDelete() {
+			msg := fmt.Sprintf("The subnamespace %s doesn't allow cascading deletion. Please set allowCascadingDelete flag first.", cnm)
+			log.V(1).Info(msg)
+			return deny(metav1.StatusReasonForbidden, msg)
+		}
+	}
+
+	return allow("")
+}
+
+// decodeRequest gets the information we care about into a simple struct that's easy to both a) use
+// and b) factor out in unit tests.
+func (v *HierarchicalNamespace) decodeRequest(log logr.Logger, in admission.Request) (*hnsRequest, error) {
+	hns := &api.HierarchicalNamespace{}
+	var err error
+	// For DELETE request, use DecodeRaw() from req.OldObject, since Decode() only uses req.Object,
+	// which will be empty for a DELETE request.
+	if in.Operation == v1beta1.Delete {
+		log.V(1).Info("Decoding a delete request.")
+		err = v.decoder.DecodeRaw(in.OldObject, hns)
+	} else {
+		err = v.decoder.Decode(in, hns)
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	return &hnsRequest{
+		hns: hns,
+		op:  in.Operation,
+	}, nil
+}
+
+func (v *HierarchicalNamespace) InjectDecoder(d *admission.Decoder) error {

Thanks for bringing this up! I am also curious so I tested with removing the InjectDecoder in namespace webhook and make deploy. I got errors when trying to delete a namespace. The errors was the same as when I had dereference of an nil pointer similar to #603 .

yiqigao217 yiqigao217 commented on code on Apr 06, 2020 15:29 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,121 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(req)
+}
+
+func (v *Namespace) checkForest(req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {

Done, I put first two ifs into one.

yiqigao217 yiqigao217 commented on code on Apr 06, 2020 15:31 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,121 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(req)
+}
+
+func (v *Namespace) checkForest(req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {
+		hnses := []string{}
+		for _, cnm := range ns.ChildNames() {
+			cns := v.Forest.Get(cnm)
+			if cns.IsOwned {
+				hnses = append(hnses, cnm)
+			}

Added new unit tests and manually tested with setting allowCascadingDeletes (the webhook and cascading deletion all worked as expected).

yiqigao217 yiqigao217 commented on code on Apr 06, 2020 15:31 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,119 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io

Good catch, thanks! Removed.

yiqigao217 yiqigao217 commented on code on Apr 06, 2020 15:32 UTC
Code Review
incubator/hnc/pkg/validators/namespace.go:1
@@ -0,0 +1,121 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+)
+
+// NamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	NamespaceServingPath = "/validate-v1-namespace"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-v1-namespace,mutating=false,failurePolicy=fail,groups="",resources=namespaces,verbs=create;update;delete,versions=v1,name=vnamespace.k8s.io
+
+type Namespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// nsRequest defines the aspects of the admission.Request that we care about.
+type nsRequest struct {
+	ns *corev1.Namespace
+	op v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *Namespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("NamespaceName", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request).
+func (v *Namespace) handle(req *nsRequest) admission.Response {
+	owner := req.ns.Annotations[api.AnnotationOwner]
+	if owner != "" && req.op == v1beta1.Delete {
+		msg := fmt.Sprintf("The namespace %s is an owned namespace. Please delete the HNS instance from the owner namespace %s instead.", req.ns.Name, owner)
+		return deny(metav1.StatusReasonForbidden, msg)
+	}
+
+	return v.checkForest(req)
+}
+
+func (v *Namespace) checkForest(req *nsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	ns := v.Forest.Get(req.ns.Name)
+
+	// Check whether the deleting namespace has owned namespaces if it doesn't allow cascading deletion.
+	if req.op == v1beta1.Delete && !ns.AllowsCascadingDelete() {
+		hnses := []string{}
+		for _, cnm := range ns.ChildNames() {
+			cns := v.Forest.Get(cnm)
+			if cns.IsOwned {
+				hnses = append(hnses, cnm)
+			}
+		}
+		if len(hnses) != 0 {
+			msg := fmt.Sprintf("The namespace has owned namespace(s): %s. Please set allowCascadingDelete flag to true first.", hnses)

Done, I also added a list of owned namespaces with allowCascadingDelete unset.

yiqigao217 yiqigao217 commented on code on Apr 06, 2020 15:56 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,119 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io

I manually tested with update removed. Seems to reject all update requests, we need to have it listed here and in Handle reject all update requests.

adrianludwin adrianludwin commented on code on Apr 06, 2020 16:43 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,119 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io

How did you try to update it? You mean with labels and stuff? Yeah, perhaps we should allow those.

I'm surprised that an action that we _didn't_ list as part of the validator would be blocked. What was the error message with update removed from the webhook config?

yiqigao217 yiqigao217 commented on Apr 06, 2020 16:43 UTC
Author

PTAL, I updated the namespace webhook to check if all owned namespaces allowCD and added the new unit tests. I also updated the HNS webhook to deny all update requests and added one unit test case. @adrianludwin , @jiachengxu

adrianludwin adrianludwin commented on code on Apr 06, 2020 16:44 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,119 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io

Note that update is still present here.

adrianludwin adrianludwin commented on code on Apr 06, 2020 16:46 UTC
Code Review
incubator/hnc/pkg/validators/hierarchical_namespace.go:1
@@ -0,0 +1,123 @@
+package validators
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-logr/logr"
+	"k8s.io/api/admission/v1beta1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
+
+	api "github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/api/v1alpha1"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/forest"
+	"github.com/kubernetes-sigs/multi-tenancy/incubator/hnc/pkg/reconcilers"
+)
+
+// HierarchicalNamespaceServingPath is where the validator will run. Must be kept in sync with the
+// kubebuilder markers below.
+const (
+	HierarchicalNamespaceServingPath = "/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces"
+)
+
+// Note: the validating webhook FAILS CLOSE. This means that if the webhook goes down, all further
+// changes are forbidden.
+//
+// +kubebuilder:webhook:path=/validate-hnc-x-k8s-io-v1alpha1-hierarchicalnamespaces,mutating=false,failurePolicy=fail,groups="hnc.x-k8s.io",resources=hierarchicalnamespaces,verbs=create;update;delete,versions=v1alpha1,name=hierarchicalnamespaces.hnc.x-k8s.io
+
+type HierarchicalNamespace struct {
+	Log     logr.Logger
+	Forest  *forest.Forest
+	decoder *admission.Decoder
+}
+
+// req defines the aspects of the admission.Request that we care about.
+type hnsRequest struct {
+	hns *api.HierarchicalNamespace
+	op  v1beta1.Operation
+}
+
+// Handle implements the validation webhook.
+func (v *HierarchicalNamespace) Handle(ctx context.Context, req admission.Request) admission.Response {
+	log := v.Log.WithValues("Namespace", req.Namespace, "Name", req.Name)
+	// Early exit since the HNC SA can do whatever it wants.
+	if isHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
+		log.V(1).Info("Allowed change by HNC SA")
+		return allow("HNC SA")
+	}
+
+	decoded, err := v.decodeRequest(log, req)
+	if err != nil {
+		v.Log.Error(err, "Couldn't decode request")
+		return deny(metav1.StatusReasonBadRequest, err.Error())
+	}
+
+	resp := v.handle(decoded)
+	log.V(1).Info("Handled", "allowed", resp.Allowed, "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
+	return resp
+}
+
+// handle implements the non-boilerplate logic of this validator, allowing it to be more easily unit
+// tested (ie without constructing a full admission.Request). It validates that the request is allowed
+// based on the current in-memory state of the forest.
+func (v *HierarchicalNamespace) handle(req *hnsRequest) admission.Response {
+	v.Forest.Lock()
+	defer v.Forest.Unlock()
+
+	pnm := req.hns.Namespace
+	cnm := req.hns.Name
+	cns := v.Forest.Get(cnm)
+
+	if req.op == v1beta1.Update {

Maybe restructure this as a switch statement, with any unexpected op resulting in log.Error? We should let unexpected ops through though, since it's probably just a webhook misconfiguration.

I'm thinking we _should_ allow Update though in case people want to put labels or annotations onto them. You can't change the namespace or name, which are the only properties we care about anyway.

yiqigao217 yiqigao217 commented on Apr 06, 2020 17:37 UTC
Author

update verb is removed in HNS webhook and the update request handling and the unit test are all removed. @adrianludwin

adrianludwin adrianludwin commented on Apr 06, 2020 17:39 UTC
Contributor

/lgtm
/approve
/hold
/assign @rjbez17

rjbez17 rjbez17 commented on Apr 06, 2020 20:37 UTC
Contributor

/lgtm
/approve
/hold cancel

k8s-ci-robot k8s-ci-robot commented on Apr 06, 2020 20:37 UTC
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: <a href="https://github.com/kubernetes-sigs/multi-tenancy/pull/602#issuecomment-609936784" title="Approved">adrianludwin</a>, <a href="https://github.com/kubernetes-sigs/multi-tenancy/pull/602#issuecomment-610023772" title="Approved">rjbez17</a>, <a href="https://github.com/kubernetes-sigs/multi-tenancy/pull/602#" title="Author self-approved">yiqigao217</a>

The full list of commands accepted by this bot can be found here.

The pull request process is described here

<details >
Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [adrianludwin,rjbez17]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    Reviewers
    Assignees
    yiqigao217 yiqigao217
    Labels
    risk: low confidence: 90% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 46.9% (MEDIUM) · Higher = larger blast radius
    46.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90% · Lower = rushed or shallow review
    90%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.7% · Safe to merge
    4.7%