Repository navigation
Move source-ip validation from cilium to kube-ovn side - #687
Conversation
WalkthroughA 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
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)
Poem
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
5313e31 to
4cae7a7
Compare
2527864 to
0a50479
Compare
There was a problem hiding this comment.
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 thegolang:1.23image to compile a statically linked binary usingCGO_ENABLED=0andGOOS=linux, and the runtime stage uses analpine:3.21.3image 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 viayqto update thevalues.yamlfile. 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 ofio/ioutil.
"io/ioutil"is deprecated in Go ≥ 1.19. Switch to theioorospackages.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 rungo mod tidyto 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 issueFix 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 issueTypo 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.
b920ca3 to
8c981a6
Compare
There was a problem hiding this comment.
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 forkubeovn-webhookis 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 deprecatedio/ioutilpackage.The
io/ioutilpackage has been deprecated since Go 1.19. Use equivalent functions from theioorospackages 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: 10Note: Make sure your webhook server implements a
/healthzendpoint 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
⛔ Files ignored due to path filters (1)
packages/system/kubeovn-webhook/images/kubeovn-webhook/go.sumis 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 newenableSourceIPVerificationflag under thedaemonsection 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 commandmake -C packages/system/kubeovn-webhook imageextends 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
PortSecurityGlobalvariable is properly defined.The code references a global variable
PortSecurityGlobalthat 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
PortSecurityGlobalvariable is already defined inpackages/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.goremain consistent with its consumption inadmission.go.
83-87:Details
✅ Verification successful
Verify
RoutesGlobalvariable is properly defined.The code references a global variable
RoutesGlobalthat 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
RoutesGlobalis defined in bothadmission.goandmain.go. As it is declared inmain.go, there’s no need to add it toadmission.go. Just ensure that its initialization logic inmain.goguarantees a non-nil and appropriate value for safe usage.
| spec: | ||
| serviceAccountName: {{ include "namespace-annotation-webhook.fullname" . }} | ||
| securityContext: | ||
| runAsNonRoot: false |
There was a problem hiding this comment.
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: trueAnd 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.
| runAsNonRoot: false | |
| runAsNonRoot: true | |
| securityContext: | |
| allowPrivilegeEscalation: false | |
| runAsUser: 1000 | |
| capabilities: |
8bccef9 to
a60cd75
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
packages/system/kubeovn-webhook/templates/mutatingwebhookconfiguration.yaml (1)
6-6:⚠️ Potential issueFix 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 issueFix 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/ioutilpackage has been deprecated since Go 1.19. As noted by the static analysis tool, it should be replaced with either theioorospackage.-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 = truewhen 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
⛔ Files ignored due to path filters (1)
packages/system/kubeovn-webhook/images/kubeovn-webhook/go.sumis 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.goLength of output: 1266
Clarification on Global Variable Reference
The variablePortSecurityGlobalis correctly defined and initialized inpackages/system/kubeovn-webhook/images/kubeovn-webhook/main.go(inside the global variable declaration and flag initialization). The usage inadmission.gois 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.goLength of output: 1260
Verification Complete: Global variable
RoutesGlobalis properly defined.After reviewing the code, it’s confirmed that
RoutesGlobalis defined as a global package-level variable inpackages/system/kubeovn-webhook/images/kubeovn-webhook/main.goand is accessible within the same package, including inadmission.go.No change is required in the code at lines 83-87.
Signed-off-by: Andrei Kvapil <[email protected]>
a60cd75 to
750e452
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
🔭 Outside diff range comments (1)
packages/system/kubeovn-webhook/templates/certmanager.yaml (1)
31-46: 🛠️ Refactor suggestionQuote 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 issueFix 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 issueFix 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 suggestionQuote 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 suggestionQuote 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
⛔ Files ignored due to path filters (1)
packages/system/kubeovn-webhook/images/kubeovn-webhook/go.sumis 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.
Co-authored-by: Timofei Larkin <[email protected]> Signed-off-by: Andrei Kvapil <[email protected]>
a317ed6 to
478a3f5
Compare
There was a problem hiding this comment.
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
📒 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—settingrunAsNonRoot: trueand addingrunAsUser: 65534andfsGroup: 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 to64Miprovides 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-securtyto--port-security), ensuring that the expected parameter is correctly passed.
64-64: Secured TLS Secret Permissions.
AddingdefaultMode: 0400to 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 deprecatedio/ioutilpackage.
This package has been deprecated since Go 1.19; please switch toio.ReadAllinstead.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 likereflect.DeepEqualto confirm the content is genuinely unchanged.
| if err != nil { | ||
| log.Printf("Failed to get namespace %q: %v", ns, err) | ||
| admissionResponse.Allowed = true | ||
| writeResponse(w, admissionReviewResp) | ||
| return | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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 | |
| } |
| admissionResponse.Allowed = true | ||
| writeResponse(w, admissionReviewResp) | ||
| return |
There was a problem hiding this comment.
🛠️ 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.
| admissionResponse.Allowed = true | |
| writeResponse(w, admissionReviewResp) | |
| return | |
| admissionResponse.Allowed = false | |
| writeResponse(w, admissionReviewResp) | |
| return |
Needed for cozystack/website#102
Upstream issues:
Summary by CodeRabbit
Summary by CodeRabbit
New Features
Configuration
kubeovn-webhookadded.portSecurity,routes, andimageinvalues.yaml.kubeovn-webhookin thepaas-full.yamlconfiguration file.