From 2e1c4b36d91185b0eaa7a5e72442a6426619f0e7 Mon Sep 17 00:00:00 2001
From: shuting <shuting@nirmata.com>
Date: Tue, 30 Apr 2019 18:54:08 -0700
Subject: [PATCH] parse regex from policyResourceName

---
 controller/controller.go | 12 +++++------
 webhooks/admission.go    | 46 ++++++++++++++++++++--------------------
 webhooks/mutation.go     |  3 ++-
 webhooks/utils.go        | 11 +++++++---
 4 files changed, 39 insertions(+), 33 deletions(-)

diff --git a/controller/controller.go b/controller/controller.go
index 7c8a24b169..f1215c4a76 100644
--- a/controller/controller.go
+++ b/controller/controller.go
@@ -80,7 +80,7 @@ func NewPolicyController(config *rest.Config, logger *log.Logger) (*PolicyContro
 func (c *PolicyController) Run(stopCh <-chan struct{}) {
 	c.policyInformerFactory.Start(stopCh)
 	// Un-comment to run the violation Builder
-	//	c.violationBuilder.Run(1, stopCh)
+	c.violationBuilder.Run(1, stopCh)
 }
 
 // GetPolicies retrieves all policy resources
@@ -135,12 +135,12 @@ func (c *PolicyController) addPolicyLog(name, text string) {
 
 	// Add new log record
 	text = time.Now().Format("2006 Jan 02 15:04:05.999 ") + text
-	policy.Status.Logs = append(policy.Status.Logs, text)
+	//policy.Status.Logs = append(policy.Status.Logs, text)
 	// Pop front extra log records
-	logsCount := len(policy.Status.Logs)
-	if logsCount > policyLogMaxRecords {
-		policy.Status.Logs = policy.Status.Logs[logsCount-policyLogMaxRecords:]
-	}
+	// logsCount := len(policy.Status.Logs)
+	// if logsCount > policyLogMaxRecords {
+	// 	policy.Status.Logs = policy.Status.Logs[logsCount-policyLogMaxRecords:]
+	// }
 	// Save logs to policy object
 	_, err = c.policiesInterface.UpdateStatus(policy)
 	if err != nil {
diff --git a/webhooks/admission.go b/webhooks/admission.go
index 0b500d3c47..6fcdcb4929 100644
--- a/webhooks/admission.go
+++ b/webhooks/admission.go
@@ -61,40 +61,40 @@ func IsRuleApplicableToResource(kind string, resourceRaw []byte, policyResource
 		meta := parseMetadataFromObject(resourceRaw)
 		name := parseNameFromMetadata(meta)
 
-		// if policyResource.Name != nil && *policyResource.Name != name {
-		// 	return false, false
-		// }
 		if policyResource.Name != nil {
-			fmt.Println("*policyResource.Name, name", *policyResource.Name, name)
+
+			policyResourceName, isRegex := parseRegexPolicyResourceName(*policyResource.Name)
+			fmt.Println("policyResourceName, name, isRegex", policyResourceName, name, isRegex)
 
 			// if no regex used, check if names are matched, return directly
-			if policyResource.Name != nil && *policyResource.Name == name {
-				return true, nil
+			if !isRegex && policyResourceName != name {
+				return false, nil
 			}
 
 			// validation of regex is peformed when validating the policyResource
 			// refer to policyResource.Validate()
-			parseRegexPolicyResourceName(*policyResource.Name)
-			match, _ := regexp.MatchString(*policyResource.Name, name)
-
-			if !match {
-				return false, nil
-			}
-
-			if policyResource.Selector != nil {
-				selector, err := metav1.LabelSelectorAsSelector(policyResource.Selector)
-
-				if err != nil {
-					return false, err
-				}
-
-				labelMap := parseLabelsFromMetadata(meta)
-
-				if !selector.Matches(labelMap) {
+			if isRegex {
+				match, _ := regexp.MatchString(policyResourceName, name)
+				if !match {
 					return false, nil
 				}
 			}
 		}
+
+		if policyResource.Selector != nil {
+			selector, err := metav1.LabelSelectorAsSelector(policyResource.Selector)
+
+			if err != nil {
+				return false, err
+			}
+
+			labelMap := parseLabelsFromMetadata(meta)
+
+			if !selector.Matches(labelMap) {
+				return false, nil
+			}
+
+		}
 	}
 	return true, nil
 }
diff --git a/webhooks/mutation.go b/webhooks/mutation.go
index 604e147f17..722bfc4799 100644
--- a/webhooks/mutation.go
+++ b/webhooks/mutation.go
@@ -78,6 +78,7 @@ func (mw *MutationWebhook) Mutate(request *v1beta1.AdmissionRequest) *v1beta1.Ad
 			namespace := parseNamespaceFromMetadata(meta)
 			name := parseNameFromMetadata(meta)
 			mw.controller.LogPolicyInfo(policy.Name, fmt.Sprintf("Applied to %s %s/%s", request.Kind.Kind, namespace, name))
+			mw.logger.Printf("%s applied to %s %s/%s", policy.Name, request.Kind.Kind, namespace, name)
 
 			allPatches = append(allPatches, policyPatches...)
 		}
@@ -123,7 +124,7 @@ func (mw *MutationWebhook) applyPolicyRulesOnResource(kind string, rawResource [
 		}
 
 		if ok, err := IsRuleApplicableToResource(kind, rawResource, rule.Resource); !ok {
-			// mw.logger.Printf("Rule %d of policy %s does not match the request %v", ruleIdx, policy.Name, request.UID)
+			mw.logger.Printf("Rule %d of policy %s does not match the request", ruleIdx, policy.Name)
 			violationCount++
 			return nil, violationCount, err
 		}
diff --git a/webhooks/utils.go b/webhooks/utils.go
index 8a0f8ef391..42a463681f 100644
--- a/webhooks/utils.go
+++ b/webhooks/utils.go
@@ -2,6 +2,7 @@ package webhooks
 
 import (
 	"encoding/json"
+	"strings"
 
 	"k8s.io/apimachinery/pkg/labels"
 )
@@ -39,7 +40,11 @@ func parseNamespaceFromMetadata(meta map[string]interface{}) string {
 	return ""
 }
 
-// TODO:
-func parseRegexPolicyResourceName(policyResourceName string) string {
-	return ""
+// returns true if policyResourceName is a regexp
+func parseRegexPolicyResourceName(policyResourceName string) (string, bool) {
+	regex := strings.Split(policyResourceName, "regex:")
+	if len(regex) == 1 {
+		return regex[0], false
+	}
+	return strings.Trim(regex[1], " "), true
 }