Skip to content

Move source-ip validation from cilium to kube-ovn side - #687

Merged
Andrei Kvapil (kvaps) merged 2 commits into
mainfrom
kube-ovn-webhook
Mar 11, 2025
Merged

Andrei Kvapil (kvaps) merged 2 commits into
mainfrom
kube-ovn-webhook

Conversation

@kvaps

@kvaps Andrei Kvapil (kvaps) commented Mar 10, 2025 •

Copy link
Copy Markdown
Member

Needed for cozystack/website#102

Upstream issues:

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a mutating admission webhook that automatically updates pod annotations based on namespace settings.
    • Streamlined deployment with a dedicated Helm chart offering dynamic naming, secure TLS with automated certificate management, and configurable port security.
    • Enhanced container image builds and overall Kubernetes resource setups for improved security and performance.
    • Added a new configuration option for Cilium to disable source IP verification.
  • Configuration

    • New Helm chart for kubeovn-webhook added.
    • New configuration entries for portSecurity, routes, and image in values.yaml.
    • New release entry for kubeovn-webhook in the paas-full.yaml configuration file.
    • Introduced a new ClusterRole and ClusterRoleBinding to manage permissions for the webhook service.

@coderabbitai

coderabbitai Bot commented Mar 10, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

A new Helm chart is introduced to deploy the kube-ovn-webhook, a Kubernetes mutating admission webhook that copies namespace annotations into pods. The changes include a Helm chart file, helper templates, and default values; a Makefile that builds and updates the Docker image; and source code for the webhook including a multi-stage Dockerfile, Go module, admission handler, and main server. Additionally, the pull request adds Kubernetes manifests for certificate management, RBAC, deployment, webhook configuration, service, and service account.

Changes

File(s) Change Summary
packages/system/kubeovn-webhook/Chart.yaml, packages/system/kubeovn-webhook/templates/_helpers.tpl, packages/system/kubeovn-webhook/values.yaml Added new Helm chart metadata, helper functions, and configuration values for the webhook deployment.
packages/system/kubeovn-webhook/Makefile Introduced a Makefile with variables and targets to build the Docker image, update image digest, and handle push/load actions.
packages/system/kubeovn-webhook/images/kubeovn-webhook/{Dockerfile, admission.go, go.mod, main.go} Added the Dockerfile (multi-stage build), Go module, admission webhook logic for processing pod mutations, and main server to run the webhook.
packages/system/kubeovn-webhook/templates/{certmanager.yaml, clusterrole.yaml, crb.yaml, deployment.yaml, mutatingwebhookconfiguration.yaml, service.yaml, serviceaccount.yaml} Added Kubernetes manifests for certificate management (Issuers and Certificates), RBAC (ClusterRole and ClusterRoleBinding), deployment configuration, mutating webhook setup, service exposure, and service account.
packages/core/platform/bundles/paas-full.yaml Introduced a new release entry for kubeovn-webhook in the deployment configuration.
packages/system/cilium/values-kubeovn.yaml Added a new configuration option for disabling source IP verification in Cilium.

Sequence Diagram(s)

sequenceDiagram
    participant API as Kubernetes API Server
    participant WH as kube-ovn-webhook
    participant NS as Namespace API

    API->>WH: Send AdmissionReview for Pod creation
    WH->>NS: Retrieve namespace annotations
    NS-->>WH: Return annotations
    WH->>API: Return AdmissionReview response (allow or patch)
Loading

Poem

In a garden of charts and code so new,
I hop with joy at each deployment cue.
With webhooks and YAMLs blooming set just right,
I nibble on changes from morning till night.
Carrots and code both make my heart race,
Celebrating each line with a merry embrace.
Hop on, dear coder, to innovation's bright space! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kvaps Andrei Kvapil (kvaps) changed the title Enable tenant isolation by default Move source-ip validation to kube-ovn side Mar 10, 2025
@kvaps Andrei Kvapil (kvaps) changed the title Move source-ip validation to kube-ovn side Move source-ip validation from cilium to kube-ovn side Mar 10, 2025
@kvaps
Andrei Kvapil (kvaps) force-pushed the kube-ovn-webhook branch 2 times, most recently from 2527864 to 0a50479 Compare March 10, 2025 20:22

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 2

🧹 Nitpick comments (7)
packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go (2)

28-47: Consider adding graceful shutdown and health endpoints.

The current server implementation lacks graceful shutdown handling and health/readiness endpoints, which are beneficial for Kubernetes deployments.

Here's a suggested implementation with context handling for graceful shutdown:

-	mux := http.NewServeMux()
-	mux.HandleFunc("/mutate-pods", HandleMutatePods)
-
-	tlsCert, err := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile)
-	if err != nil {
-		log.Fatalf("Failed to load key pair: %v", err)
-	}
-
-	server := &http.Server{
-		Addr: ":8443",
-		TLSConfig: &tls.Config{
-			Certificates: []tls.Certificate{tlsCert},
-		},
-		Handler: mux,
-	}
-
-	log.Printf("Starting webhook server on %s", server.Addr)
-	if err := server.ListenAndServeTLS("", ""); err != nil {
-		log.Fatalf("Failed to start server: %v", err)
-	}
+	mux := http.NewServeMux()
+	mux.HandleFunc("/mutate-pods", HandleMutatePods)
+	mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
+		w.WriteHeader(http.StatusOK)
+	})
+	mux.HandleFunc("/ready", func(w http.ResponseWriter, r *http.Request) {
+		w.WriteHeader(http.StatusOK)
+	})
+
+	tlsCert, err := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile)
+	if err != nil {
+		log.Fatalf("Failed to load key pair: %v", err)
+	}
+
+	server := &http.Server{
+		Addr: ":8443",
+		TLSConfig: &tls.Config{
+			Certificates: []tls.Certificate{tlsCert},
+		},
+		Handler: mux,
+	}
+
+	// Handle graceful shutdown
+	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+	defer stop()
+
+	go func() {
+		<-ctx.Done()
+		log.Println("Shutting down server...")
+		
+		shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+		defer cancel()
+		
+		if err := server.Shutdown(shutdownCtx); err != nil {
+			log.Fatalf("Server shutdown failed: %v", err)
+		}
+	}()
+
+	log.Printf("Starting webhook server on %s", server.Addr)
+	if err := server.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
+		log.Fatalf("Failed to start server: %v", err)
+	}

Don't forget to add required imports:

import (
	"context"
	"crypto/tls"
	"flag"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

3-8: Consider adding timeouts to HTTP server.

The HTTP server configuration lacks timeout settings, which could lead to resource leaks or denial-of-service vulnerabilities.

 import (
 	"crypto/tls"
 	"flag"
 	"log"
 	"net/http"
+	"time"
 )

And update the server configuration:

 	server := &http.Server{
 		Addr: ":8443",
 		TLSConfig: &tls.Config{
 			Certificates: []tls.Certificate{tlsCert},
 		},
 		Handler: mux,
+		ReadTimeout:    10 * time.Second,
+		WriteTimeout:   10 * time.Second,
+		MaxHeaderBytes: 1 << 20, // 1 MB
 	}
packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile (1)

1-17: Multi-stage Dockerfile Implementation
This Dockerfile correctly implements a multi-stage build. The builder stage uses the golang:1.23 image to compile a statically linked binary using CGO_ENABLED=0 and GOOS=linux, and the runtime stage uses an alpine:3.21.3 image to keep the final image minimal.

Consider adding a non-root user in the runtime stage for enhanced container security in production environments.

packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml (1)

5-6: Resolving YAML Linter Syntax Issue
The static analysis tool flagged a potential YAML syntax issue on line 6 due to the Helm templating. This is a common false positive when using unquoted templated values. To improve YAML parsing reliability, consider quoting the value as shown below:

-    cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/{{ include "namespace-annotation-webhook.fullname" . }}-cert
+    cert-manager.io/inject-ca-from: '{{ .Release.Namespace }}/{{ include "namespace-annotation-webhook.fullname" . }}-cert'
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 6-6: syntax error: expected , but found ''

(syntax)

packages/system/kubeovn-webhook/Makefile (1)

9-20: Docker Image Build Process
The build target uses Docker Buildx with provenance disabled and leverages caching features as well as metadata extraction via yq to update the values.yaml file. This strategy helps ensure that the Docker image is correctly tagged with its digest.

It may be beneficial to confirm that $(REGISTRY) and $(TAG) are properly defined in the environment and to add error handling in case the metadata file generation or digest extraction fails.

packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (1)

7-7: Use modern I/O packages instead of io/ioutil.
"io/ioutil" is deprecated in Go ≥ 1.19. Switch to the io or os packages.

Proposed fix:

-import (
-       "io/ioutil"
-       ...
-)
+import (
+       "io"
+       ...
+)

...

- body, err := ioutil.ReadAll(r.Body)
+ body, err := io.ReadAll(r.Body)

Also applies to: 26-26

🧰 Tools
🪛 golangci-lint (1.62.2)

7-7: SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details.

(staticcheck)

packages/system/kubeovn-webhook/images/kubeovn-webhook/go.mod (1)

12-47: Indirect Dependencies Management
The indirect dependency block appears to be automatically generated. It is good practice to periodically run go mod tidy to ensure these dependencies stay updated and consistent with your codebase.

🛑 Comments failed to post (2)
packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go (1)

23-23: ⚠️ Potential issue

Fix typo in flag name "port-securty".

There's a typo in the flag name for port security.

-	flag.BoolVar(&PortSecurityGlobal, "port-securty", true, "If false, skip adding port_security unless specified by the Namespace.")
+	flag.BoolVar(&PortSecurityGlobal, "port-security", true, "If false, skip adding port_security unless specified by the Namespace.")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	flag.BoolVar(&PortSecurityGlobal, "port-security", true, "If false, skip adding port_security unless specified by the Namespace.")
packages/system/kubeovn-webhook/templates/deployment.yaml (1)

49-49: ⚠️ Potential issue

Typo in Argument Flag
The CLI argument flag is written as --port-securty={{ .Values.portSecurity }}. This appears to be a typo; it should likely be --port-security={{ .Values.portSecurity }} to ensure that the flag is correctly parsed and applied.

@kvaps
Andrei Kvapil (kvaps) force-pushed the kube-ovn-webhook branch 2 times, most recently from b920ca3 to 8c981a6 Compare March 10, 2025 20:40

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (8)
packages/core/platform/bundles/paas-full.yaml (1)

53-59: New Release Entry for kubeovn-webhook Integrated.
The new release entry for kubeovn-webhook is defined with the proper attributes and dependencies. For improved readability—and to comply with YAML linting suggestions—consider adding spaces after commas in the inline list. For example:

-  dependsOn: [cilium,kubeovn,cert-manager]
+  dependsOn: [cilium, kubeovn, cert-manager]
🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 58-58: too few spaces after comma

(commas)


[warning] 58-58: too few spaces after comma

(commas)

packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (4)

7-7: Replace deprecated io/ioutil package.

The io/ioutil package has been deprecated since Go 1.19. Use equivalent functions from the io or os packages instead.

-	"io/ioutil"
+	"io"

And then update the corresponding function call:

-	body, err := ioutil.ReadAll(r.Body)
+	body, err := io.ReadAll(r.Body)
🧰 Tools
🪛 golangci-lint (1.62.2)

7-7: SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details.

(staticcheck)


103-107: Improve annotation change detection logic.

The current approach only compares the length of annotation maps, which might incorrectly identify changes if a key is replaced with another one of the same length. Consider implementing a deeper comparison of the annotation contents.

-	if len(mergedAnnotations) == len(pod.Annotations) {
+	hasChanges := false
+	if len(mergedAnnotations) != len(pod.Annotations) {
+		hasChanges = true
+	} else {
+		for k, v := range mergedAnnotations {
+			if origValue, exists := pod.Annotations[k]; !exists || origValue != v {
+				hasChanges = true
+				break
+			}
+		}
+	}
+
+	if !hasChanges {

146-146: Add timeout to the context for Kubernetes API calls.

Using context.Background() without a timeout could lead to hanging requests if the Kubernetes API server is unresponsive. Add a reasonable timeout to prevent this issue.

-	ns, err := clientset.CoreV1().Namespaces().Get(context.Background(), namespace, metav1.GetOptions{})
+	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+	defer cancel()
+	ns, err := clientset.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})

Remember to add the missing import:

+	"time"

160-160: Handle potential write error.

The write operation error is being discarded with _, _. Consider logging this error as it might indicate connectivity issues with the client.

-	_, _ = w.Write(resp)
+	if _, err := w.Write(resp); err != nil {
+		log.Printf("Error writing response: %v", err)
+	}
packages/system/kubeovn-webhook/templates/deployment.yaml (3)

32-38: Consider increasing resource limits for production deployments.

The current resource limits (100m CPU, 128Mi memory) might be sufficient for testing but could be inadequate for production deployments in large clusters with high pod creation rates. Consider adjusting these based on observed usage patterns.


23-46: Add health probes for better container lifecycle management.

The deployment lacks liveness and readiness probes, which are important for Kubernetes to properly manage the container lifecycle. Consider adding health probes to ensure proper detection of container health status.

          volumeMounts:
            - name: webhook-certs
              mountPath: /etc/webhook/certs
              readOnly: true
+          livenessProbe:
+            httpGet:
+              path: /healthz
+              port: 8443
+              scheme: HTTPS
+            initialDelaySeconds: 15
+            periodSeconds: 20
+          readinessProbe:
+            httpGet:
+              path: /healthz
+              port: 8443
+              scheme: HTTPS
+            initialDelaySeconds: 5
+            periodSeconds: 10

Note: Make sure your webhook server implements a /healthz endpoint or adjust the path accordingly.


8-9: Define a rolling update strategy for controlled updates.

The deployment doesn't specify a rolling update strategy, so it will use the default. Consider defining a specific strategy to ensure minimal disruption during updates.

spec:
  replicas: 2
+  strategy:
+    type: RollingUpdate
+    rollingUpdate:
+      maxUnavailable: 0
+      maxSurge: 1
  selector:
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2527864 and 8c981a6.

⛔ Files ignored due to path filters (1)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.sum is excluded by !**/*.sum
📒 Files selected for processing (18)
  • Makefile (1 hunks)
  • packages/core/platform/bundles/paas-full.yaml (1 hunks)
  • packages/system/cilium/values-kubeovn.yaml (1 hunks)
  • packages/system/kubeovn-webhook/Chart.yaml (1 hunks)
  • packages/system/kubeovn-webhook/Makefile (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.mod (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go (1 hunks)
  • packages/system/kubeovn-webhook/templates/_helpers.tpl (1 hunks)
  • packages/system/kubeovn-webhook/templates/certmanager.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/clusterrole.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/crb.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/deployment.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/service.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/serviceaccount.yaml (1 hunks)
  • packages/system/kubeovn-webhook/values.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (11)
  • packages/system/kubeovn-webhook/templates/clusterrole.yaml
  • packages/system/kubeovn-webhook/templates/serviceaccount.yaml
  • packages/system/kubeovn-webhook/templates/crb.yaml
  • packages/system/kubeovn-webhook/templates/_helpers.tpl
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go
  • packages/system/kubeovn-webhook/Chart.yaml
  • packages/system/kubeovn-webhook/Makefile
  • packages/system/kubeovn-webhook/templates/service.yaml
  • packages/system/kubeovn-webhook/values.yaml
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.mod
🧰 Additional context used
🪛 YAMLlint (1.35.1)
packages/core/platform/bundles/paas-full.yaml

[warning] 58-58: too few spaces after comma

(commas)


[warning] 58-58: too few spaces after comma

(commas)

packages/system/kubeovn-webhook/templates/certmanager.yaml

[error] 4-4: syntax error: expected , but found ''

(syntax)

packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml

[error] 6-6: syntax error: expected , but found ''

(syntax)

🪛 golangci-lint (1.62.2)
packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go

7-7: SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details.

(staticcheck)

🔇 Additional comments (4)
packages/system/cilium/values-kubeovn.yaml (1)

2-3: New Source IP Verification Flag Added.
The new enableSourceIPVerification flag under the daemon section will allow disabling source IP checks in Cilium. Ensure that downstream components (or the integrated kube-ovn logic) correctly observe and honor this configuration.

Makefile (1)

13-15: Added Build Command for kubeovn-webhook Image.
The inclusion of the command make -C packages/system/kubeovn-webhook image extends the build target to cover the new webhook component. This is an appropriate addition to support the new deployment.

packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (2)

93-95:

Details

✅ Verification successful

Verify PortSecurityGlobal variable is properly defined.

The code references a global variable PortSecurityGlobal that is not defined in this file. Ensure it's properly defined and initialized in another file or add it to this file to avoid potential nil reference issues.


🏁 Script executed:

#!/bin/bash
# Check if PortSecurityGlobal is defined in the main.go or other related files
find packages/system/kubeovn-webhook/images/kubeovn-webhook/ -type f -name "*.go" | xargs grep -l "PortSecurityGlobal"

Length of output: 249


Action Required: Confirm Global Definition in Main File

The PortSecurityGlobal variable is already defined in packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go (as verified by the grep output). Please ensure that its initialization in that file is as intended and that there’s no risk of a nil or uninitialized reference during runtime.

  • Confirm that the variable is appropriately assigned during startup.
  • Revalidate that any changes to its initialization or usage in main.go remain consistent with its consumption in admission.go.

83-87:

Details

✅ Verification successful

Verify RoutesGlobal variable is properly defined.

The code references a global variable RoutesGlobal that is not defined in this file. Ensure it's properly defined and initialized in another file or add it to this file to avoid potential nil reference issues.


🏁 Script executed:

#!/bin/bash
# Check if RoutesGlobal is defined in the main.go or other related files
find packages/system/kubeovn-webhook/images/kubeovn-webhook/ -type f -name "*.go" | xargs grep -l "RoutesGlobal"

Length of output: 243


Global variable RoutesGlobal is properly defined

The shell script output confirms that RoutesGlobal is defined in both admission.go and main.go. As it is declared in main.go, there’s no need to add it to admission.go. Just ensure that its initialization logic in main.go guarantees a non-nil and appropriate value for safe usage.

Comment thread packages/system/kubeovn-webhook/templates/certmanager.yaml
Comment thread packages/system/kubeovn-webhook/templates/deployment.yaml Outdated
spec:
serviceAccountName: {{ include "namespace-annotation-webhook.fullname" . }}
securityContext:
runAsNonRoot: false

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security risk: Container runs as root.

Setting runAsNonRoot: false allows the container to run as root, which is a security risk. Consider changing this to true and specify a non-root user ID in the container configuration.

-        runAsNonRoot: false
+        runAsNonRoot: true

And add a user ID to the security context:

          securityContext:
            allowPrivilegeEscalation: false
+           runAsUser: 1000
            capabilities:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
runAsNonRoot: false
runAsNonRoot: true
securityContext:
allowPrivilegeEscalation: false
runAsUser: 1000
capabilities:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (2)
packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml (1)

6-6: ⚠️ Potential issue

Fix YAML syntax by quoting template expression.

The static analysis tool detected a YAML syntax error. To prevent parsing issues, enclose the templated value in quotes.

-    cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/{{ include "namespace-annotation-webhook.fullname" . }}-cert
+    cert-manager.io/inject-ca-from: "{{ .Release.Namespace }}/{{ include \"namespace-annotation-webhook.fullname\" . }}-cert"
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 6-6: syntax error: expected , but found ''

(syntax)

packages/system/kubeovn-webhook/templates/certmanager.yaml (1)

4-4: ⚠️ Potential issue

Fix YAML syntax by quoting template expressions.

The static analysis tool detected a YAML syntax error. To prevent parsing issues, enclose the templated value in quotes.

-  name: {{ include "namespace-annotation-webhook.fullname" . }}-selfsigned-issuer
+  name: "{{ include \"namespace-annotation-webhook.fullname\" . }}-selfsigned-issuer"

Apply similar changes to all other template expressions in this file (lines 12, 15, 17, 19, 25, 29, 34, 41, 42, 44, 45).

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 4-4: syntax error: expected , but found ''

(syntax)

🧹 Nitpick comments (5)
packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (4)

7-7: Update deprecated import.

The io/ioutil package has been deprecated since Go 1.19. As noted by the static analysis tool, it should be replaced with either the io or os package.

-import (
-	"context"
-	"encoding/json"
-	"fmt"
-	"io/ioutil"
-	"log"
-	"net/http"
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"log"
+	"net/http"

Additionally, replace the function call on line 26:

-	body, err := ioutil.ReadAll(r.Body)
+	body, err := io.ReadAll(r.Body)
🧰 Tools
🪛 golangci-lint (1.62.2)

7-7: SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details.

(staticcheck)


136-151: Optimize Kubernetes client initialization.

A new Kubernetes client is created for every request, which can be inefficient. Consider initializing the client once during startup and reusing it for subsequent requests.

Create a global client variable and initialize it once:

var (
    k8sClient *kubernetes.Clientset
)

func init() {
    config, err := rest.InClusterConfig()
    if err != nil {
        log.Fatalf("Failed to get in-cluster config: %v", err)
    }
    
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        log.Fatalf("Failed to create Kubernetes client: %v", err)
    }
    
    k8sClient = clientset
}

func getNamespaceAnnotations(namespace string) (map[string]string, error) {
    ns, err := k8sClient.CoreV1().Namespaces().Get(context.Background(), namespace, metav1.GetOptions{})
    if err != nil {
        return nil, err
    }
    return ns.Annotations, nil
}

47-60: Early return could hide errors.

The code returns early with admissionResponse.Allowed = true when an error occurs, which could lead to silent failures. Consider adding more detailed logging or rejecting the request when critical errors occur.

For example, unmarshal errors could indicate malformed requests that should be rejected rather than allowed:

 	if err := json.Unmarshal(raw, &pod); err != nil {
+		log.Printf("Failed to unmarshal pod object: %v", err)
 		admissionResponse.Allowed = true
 		writeResponse(w, admissionReviewResp)
 		return
 	}

160-161: Improve error handling in writeResponse.

The write operation ignores potential errors. Consider adding error logging for better debuggability.

-	_, _ = w.Write(resp)
+	if _, err := w.Write(resp); err != nil {
+		log.Printf("Error writing response: %v", err)
+	}
packages/core/platform/bundles/paas-full.yaml (1)

53-58: LGTM! Addition of the kubeovn-webhook component.

The kubeovn-webhook component is properly integrated into the release pipeline with appropriate dependencies.

Fix the spacing after commas in the dependsOn list for improved readability:

-  dependsOn: [cilium,kubeovn,cert-manager]
+  dependsOn: [cilium, kubeovn, cert-manager]
🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 58-58: too few spaces after comma

(commas)


[warning] 58-58: too few spaces after comma

(commas)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8c981a6 and a60cd75.

⛔ Files ignored due to path filters (1)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.sum is excluded by !**/*.sum
📒 Files selected for processing (18)
  • Makefile (1 hunks)
  • packages/core/platform/bundles/paas-full.yaml (1 hunks)
  • packages/system/cilium/values-kubeovn.yaml (1 hunks)
  • packages/system/kubeovn-webhook/Chart.yaml (1 hunks)
  • packages/system/kubeovn-webhook/Makefile (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.mod (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go (1 hunks)
  • packages/system/kubeovn-webhook/templates/_helpers.tpl (1 hunks)
  • packages/system/kubeovn-webhook/templates/certmanager.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/clusterrole.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/crb.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/deployment.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/service.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/serviceaccount.yaml (1 hunks)
  • packages/system/kubeovn-webhook/values.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (14)
  • packages/system/kubeovn-webhook/Chart.yaml
  • packages/system/cilium/values-kubeovn.yaml
  • packages/system/kubeovn-webhook/templates/clusterrole.yaml
  • Makefile
  • packages/system/kubeovn-webhook/templates/_helpers.tpl
  • packages/system/kubeovn-webhook/templates/crb.yaml
  • packages/system/kubeovn-webhook/templates/serviceaccount.yaml
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile
  • packages/system/kubeovn-webhook/Makefile
  • packages/system/kubeovn-webhook/templates/service.yaml
  • packages/system/kubeovn-webhook/templates/deployment.yaml
  • packages/system/kubeovn-webhook/values.yaml
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.mod
🧰 Additional context used
🪛 YAMLlint (1.35.1)
packages/core/platform/bundles/paas-full.yaml

[warning] 58-58: too few spaces after comma

(commas)


[warning] 58-58: too few spaces after comma

(commas)

packages/system/kubeovn-webhook/templates/certmanager.yaml

[error] 4-4: syntax error: expected , but found ''

(syntax)

packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml

[error] 6-6: syntax error: expected , but found ''

(syntax)

🪛 golangci-lint (1.62.2)
packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go

7-7: SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details.

(staticcheck)

🔇 Additional comments (2)
packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (2)

93-95:

Details

❌ Incorrect review comment

Undefined global variable reference.

The code references an undefined variable PortSecurityGlobal. This variable isn't defined in this file.


🏁 Script executed:

#!/bin/bash
# Check for PortSecurityGlobal definition in the codebase
rg "var\s+PortSecurityGlobal" --type go
# Look for defined flags in the main.go file
cat packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go

Length of output: 1266


Clarification on Global Variable Reference
The variable PortSecurityGlobal is correctly defined and initialized in packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go (inside the global variable declaration and flag initialization). The usage in admission.go is therefore valid. You can disregard the previous warning regarding an undefined variable.

Likely an incorrect or invalid review comment.


83-87:

Details

✅ Verification successful

Undefined global variable reference.

The code references an undefined variable RoutesGlobal. This variable isn't defined in this file, which suggests it's either missing or intended to be defined elsewhere.


🏁 Script executed:

#!/bin/bash
# Check for RoutesGlobal definition in the codebase
rg "var\s+RoutesGlobal" --type go
# Look for defined constants in the main.go file
cat packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go

Length of output: 1260


Verification Complete: Global variable RoutesGlobal is properly defined.

After reviewing the code, it’s confirmed that RoutesGlobal is defined as a global package-level variable in packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go and is accessible within the same package, including in admission.go.

No change is required in the code at lines 83-87.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🔭 Outside diff range comments (1)
packages/system/kubeovn-webhook/templates/certmanager.yaml (1)

31-46: 🛠️ Refactor suggestion

Quote template expressions in TLS certificate configuration.

Ensure all template expressions in the certificate configuration are properly quoted.

-  name: {{ include "namespace-annotation-webhook.fullname" . }}-cert
+  name: "{{ include "namespace-annotation-webhook.fullname" . }}-cert"
-  secretName: {{ include "namespace-annotation-webhook.fullname" . }}-tls
+  secretName: "{{ include "namespace-annotation-webhook.fullname" . }}-tls"
-    name: {{ include "namespace-annotation-webhook.fullname" . }}-ca-issuer
+    name: "{{ include "namespace-annotation-webhook.fullname" . }}-ca-issuer"
-  commonName: {{ include "namespace-annotation-webhook.fullname" . }}-tls
+  commonName: "{{ include "namespace-annotation-webhook.fullname" . }}-tls"
-    - {{ include "namespace-annotation-webhook.fullname" . }}
-    - {{ include "namespace-annotation-webhook.fullname" . }}.{{ .Release.Namespace }}.svc
+    - "{{ include "namespace-annotation-webhook.fullname" . }}"
+    - "{{ include "namespace-annotation-webhook.fullname" . }}.{{ .Release.Namespace }}.svc"
♻️ Duplicate comments (4)
packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml (1)

5-6: ⚠️ Potential issue

Fix potential YAML parsing error by quoting template expression.

The annotation value contains template expressions that need to be quoted to prevent YAML parsing errors.

-    cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/{{ include "namespace-annotation-webhook.fullname" . }}-cert
+    cert-manager.io/inject-ca-from: "{{ .Release.Namespace }}/{{ include "namespace-annotation-webhook.fullname" . }}-cert"
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 6-6: syntax error: expected , but found ''

(syntax)

packages/system/kubeovn-webhook/templates/certmanager.yaml (3)

3-4: ⚠️ Potential issue

Fix YAML syntax error by quoting template expression.

The template expression in the name field needs to be quoted to prevent YAML parsing errors.

-  name: {{ include "namespace-annotation-webhook.fullname" . }}-selfsigned-issuer
+  name: "{{ include "namespace-annotation-webhook.fullname" . }}-selfsigned-issuer"
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 4-4: syntax error: expected , but found ''

(syntax)


23-30: 🛠️ Refactor suggestion

Quote template expressions in CA issuer configuration.

Template expressions should be quoted to ensure proper YAML parsing.

-  name: {{ include "namespace-annotation-webhook.fullname" . }}-ca-issuer
+  name: "{{ include "namespace-annotation-webhook.fullname" . }}-ca-issuer"
-    secretName: {{ include "namespace-annotation-webhook.fullname" . }}-root-ca
+    secretName: "{{ include "namespace-annotation-webhook.fullname" . }}-root-ca"

11-21: 🛠️ Refactor suggestion

Quote all template expressions in certificate configuration.

Similar to the previous issue, all template expressions in the certificate configuration should be quoted.

-  name: {{ include "namespace-annotation-webhook.fullname" . }}-root-ca
+  name: "{{ include "namespace-annotation-webhook.fullname" . }}-root-ca"
-  secretName: {{ include "namespace-annotation-webhook.fullname" . }}-root-ca
+  secretName: "{{ include "namespace-annotation-webhook.fullname" . }}-root-ca"
-  commonName: {{ include "namespace-annotation-webhook.fullname" . }}-root-ca
+  commonName: "{{ include "namespace-annotation-webhook.fullname" . }}-root-ca"
-    name: {{ include "namespace-annotation-webhook.fullname" . }}-selfsigned-issuer
+    name: "{{ include "namespace-annotation-webhook.fullname" . }}-selfsigned-issuer"
🧹 Nitpick comments (2)
packages/core/platform/bundles/paas-full.yaml (1)

53-58: Integration looks good, but fix spacing in dependsOn array.

The kubeovn-webhook is properly integrated into the platform bundle with correct namespace and dependencies.

-  dependsOn: [cilium,kubeovn,cert-manager]
+  dependsOn: [cilium, kubeovn, cert-manager]
🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 58-58: too few spaces after comma

(commas)


[warning] 58-58: too few spaces after comma

(commas)

packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (1)

136-151: Consider caching namespace annotations.

The webhook creates a new Kubernetes client and fetches namespace information for every single pod creation. This could impact performance at scale. Consider implementing a caching mechanism for namespace annotations to reduce API server load.

// Add a simple time-based cache
type namespaceCache struct {
    annotations map[string]map[string]string
    expiry      map[string]time.Time
    mu          sync.RWMutex
}

var nsCache = &namespaceCache{
    annotations: make(map[string]map[string]string),
    expiry:      make(map[string]time.Time),
}

func (c *namespaceCache) get(namespace string) (map[string]string, bool) {
    c.mu.RLock()
    defer c.mu.RUnlock()
    
    annotations, exists := c.annotations[namespace]
    if !exists {
        return nil, false
    }
    
    expiry, _ := c.expiry[namespace]
    if time.Now().After(expiry) {
        return nil, false
    }
    
    return annotations, true
}

func (c *namespaceCache) set(namespace string, annotations map[string]string) {
    c.mu.Lock()
    defer c.mu.Unlock()
    
    c.annotations[namespace] = annotations
    c.expiry[namespace] = time.Now().Add(5 * time.Minute) // Cache for 5 minutes
}

func getNamespaceAnnotations(namespace string) (map[string]string, error) {
    // Check cache first
    if annotations, found := nsCache.get(namespace); found {
        return annotations, nil
    }

    // If not in cache, proceed with API call
    config, err := rest.InClusterConfig()
    if err != nil {
        return nil, err
    }
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, err
    }

    ns, err := clientset.CoreV1().Namespaces().Get(context.Background(), namespace, metav1.GetOptions{})
    if err != nil {
        return nil, err
    }
    
    // Update cache
    nsCache.set(namespace, ns.Annotations)
    
    return ns.Annotations, nil
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a60cd75 and 750e452.

⛔ Files ignored due to path filters (1)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.sum is excluded by !**/*.sum
📒 Files selected for processing (18)
  • Makefile (1 hunks)
  • packages/core/platform/bundles/paas-full.yaml (1 hunks)
  • packages/system/cilium/values-kubeovn.yaml (1 hunks)
  • packages/system/kubeovn-webhook/Chart.yaml (1 hunks)
  • packages/system/kubeovn-webhook/Makefile (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.mod (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go (1 hunks)
  • packages/system/kubeovn-webhook/templates/_helpers.tpl (1 hunks)
  • packages/system/kubeovn-webhook/templates/certmanager.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/clusterrole.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/crb.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/deployment.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/service.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/serviceaccount.yaml (1 hunks)
  • packages/system/kubeovn-webhook/values.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (13)
  • packages/system/cilium/values-kubeovn.yaml
  • packages/system/kubeovn-webhook/templates/serviceaccount.yaml
  • packages/system/kubeovn-webhook/templates/clusterrole.yaml
  • Makefile
  • packages/system/kubeovn-webhook/templates/_helpers.tpl
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/main.go
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile
  • packages/system/kubeovn-webhook/templates/crb.yaml
  • packages/system/kubeovn-webhook/values.yaml
  • packages/system/kubeovn-webhook/templates/deployment.yaml
  • packages/system/kubeovn-webhook/Makefile
  • packages/system/kubeovn-webhook/templates/service.yaml
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/go.mod
🧰 Additional context used
🪛 golangci-lint (1.62.2)
packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go

7-7: SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details.

(staticcheck)

🪛 YAMLlint (1.35.1)
packages/core/platform/bundles/paas-full.yaml

[warning] 58-58: too few spaces after comma

(commas)


[warning] 58-58: too few spaces after comma

(commas)

packages/system/kubeovn-webhook/templates/certmanager.yaml

[error] 4-4: syntax error: expected , but found ''

(syntax)

packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml

[error] 6-6: syntax error: expected , but found ''

(syntax)

🔇 Additional comments (2)
packages/system/kubeovn-webhook/Chart.yaml (1)

1-6: LGTM: Well-structured Helm chart definition.

The Helm chart definition for the Kube-OVN webhook is clear and follows best practices, with appropriate specification of API version, name, description, type, and versioning.

packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml (1)

9-34: LGTM: Webhook configuration is properly structured.

The webhook configuration contains appropriate settings for admission review, failure policy, and namespace selection. The rules are correctly set to only intercept Pod creation operations.

Comment thread packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go
Comment thread packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go
Comment thread packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go
Comment thread packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go Outdated
Comment thread packages/system/kubeovn-webhook/templates/certmanager.yaml Outdated
Comment thread packages/system/kubeovn-webhook/templates/deployment.yaml Outdated
Comment thread packages/system/kubeovn-webhook/templates/deployment.yaml Outdated
Comment thread packages/system/kubeovn-webhook/templates/deployment.yaml
Co-authored-by: Timofei Larkin <[email protected]>
Signed-off-by: Andrei Kvapil <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
packages/system/kubeovn-webhook/templates/certmanager.yaml (5)

1-7: Ensure templating consistency in metadata.

In this first document (lines 1–7), verify that all template expressions within metadata (including namespace values) are properly quoted when needed. Consistent quoting helps avoid subtle YAML linting issues in CI/CD pipelines.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 4-4: syntax error: expected , but found ''

(syntax)


9-20: Quote template values in Certificate metadata fields.

This Certificate resource (lines 9–20) uses template expressions in fields such as the resource name (line 12) and issuer reference (line 19). To ensure reliable YAML parsing, review and consider quoting these expressions as needed.


24-26: Wrap template output in quotes for CA Issuer.

In the CA Issuer definition (lines 22–30), the metadata name on line 25 is generated with a template expression. Please consider quoting it to prevent YAML parsing errors.


33-45: Apply quoting to templated values in Certificate resource.

Within this Certificate (lines 31–45), multiple metadata fields—such as the name (line 34), secret references, commonName, and dnsNames list items—use template expressions. Enclosing these in quotes can help avoid YAML linting problems and improve consistency.


16-16: Standardize inline comment language.

The inline comment on line 16 uses non-English text ("5 лет"). For consistency with the rest of the configuration (and to aid international collaborators), consider using English (e.g., "5 years").

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 750e452 and 478a3f5.

📒 Files selected for processing (8)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (1 hunks)
  • packages/system/kubeovn-webhook/templates/certmanager.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/deployment.yaml (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile (1 hunks)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (2 hunks)
  • packages/system/kubeovn-webhook/templates/certmanager.yaml (1 hunks)
  • packages/system/kubeovn-webhook/templates/deployment.yaml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go
  • packages/system/kubeovn-webhook/images/kubeovn-webhook/Dockerfile
  • packages/system/kubeovn-webhook/templates/certmanager.yaml
  • packages/system/kubeovn-webhook/templates/deployment.yaml
🧰 Additional context used
🪛 YAMLlint (1.35.1)
packages/system/kubeovn-webhook/templates/certmanager.yaml

[error] 4-4: syntax error: expected , but found ''

(syntax)

🔇 Additional comments (9)
packages/system/kubeovn-webhook/templates/deployment.yaml (4)

22-24: Security Context Enhancement Approved.
The security context update—setting runAsNonRoot: true and adding runAsUser: 65534 and fsGroup: 65534—aligns well with container best practices by ensuring the container runs with restricted privileges.


37-37: Updated Memory Request.
Increasing the memory resource request to 64Mi provides a more reliable allocation for the container. Verify that this value is appropriate for the container’s performance requirements based on your load testing.


51-51: Corrected Port Security Argument.
The typo in the command-line argument has been fixed (from --port-securty to --port-security), ensuring that the expected parameter is correctly passed.


64-64: Secured TLS Secret Permissions.
Adding defaultMode: 0400 to the secret volume ensures that the TLS certificate files are read-only and accessible only by the owner, which is a strong security measure.

packages/system/kubeovn-webhook/templates/certmanager.yaml (1)

3-5: Quote templated expression for proper YAML parsing.

Line 4 defines the Issuer’s name using a template expression that is not wrapped in quotes. This can trigger YAML parsing errors (as noted by YAMLlint). Please enclose the template output in quotes. For example:

-  name: {{ include "namespace-annotation-webhook.fullname" . }}-selfsigned-issuer
+  name: "{{ include \"namespace-annotation-webhook.fullname\" . }}-selfsigned-issuer"
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 4-4: syntax error: expected , but found ''

(syntax)

packages/system/kubeovn-webhook/images/kubeovn-webhook/admission.go (4)

7-7: Replace deprecated io/ioutil package.
This package has been deprecated since Go 1.19; please switch to io.ReadAll instead.

Also applies to: 26-26


83-87: Undefined variable reference: RoutesGlobal.
This global variable is not declared and will cause a compilation error or undefined reference.


93-95: Undefined variable reference: PortSecurityGlobal.
This variable is referenced as a boolean but is never declared or imported, resulting in a compile-time error.


103-107: Fix incorrect equality check for annotations.
Relying on identical lengths to confirm no change is insufficient because a removed annotation plus a newly added annotation could preserve length but still differ. Use something like reflect.DeepEqual to confirm the content is genuinely unchanged.

Comment on lines +64 to +69
if err != nil {
log.Printf("Failed to get namespace %q: %v", ns, err)
admissionResponse.Allowed = true
writeResponse(w, admissionReviewResp)
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider failing closed instead of defaulting to Allowed on namespace retrieval error.
If the webhook fails to retrieve the namespace annotations, allowing the admission might lead to missing or incorrect annotation configurations. Denying admission until the request can be reliably validated could be safer.

-    admissionResponse.Allowed = true
+    admissionResponse.Allowed = false
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err != nil {
log.Printf("Failed to get namespace %q: %v", ns, err)
admissionResponse.Allowed = true
writeResponse(w, admissionReviewResp)
return
}
if err != nil {
log.Printf("Failed to get namespace %q: %v", ns, err)
admissionResponse.Allowed = false
writeResponse(w, admissionReviewResp)
return
}

Comment on lines +57 to +59
admissionResponse.Allowed = true
writeResponse(w, admissionReviewResp)
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider failing closed instead of defaulting to Allowed on unmarshal error.
Currently, if the Pod unmarshalling fails, you allow the request. This can introduce a security risk, as failing to parse a Pod definition may skip essential validations. Failing closed (i.e., denying the admission) may be preferable to ensure invalid or malformed requests don’t bypass the webhook.

Here’s an example change:

-    admissionResponse.Allowed = true
+    admissionResponse.Allowed = false
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
admissionResponse.Allowed = true
writeResponse(w, admissionReviewResp)
return
admissionResponse.Allowed = false
writeResponse(w, admissionReviewResp)
return

@lllamnyp Timofei Larkin (lllamnyp) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@kvaps
Andrei Kvapil (kvaps) merged commit 0e10f95 into main Mar 11, 2025
@kvaps
Andrei Kvapil (kvaps) deleted the kube-ovn-webhook branch March 11, 2025 11:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants