Skip to content

Conversation

@sgayangi
Copy link
Contributor

@sgayangi sgayangi commented Nov 21, 2025

Purpose

$subject

Summary by CodeRabbit

  • New Features

    • Added certificate validation that accepts JWKS or inline certificates, including base64-encoded PEM/X.509 handling and robust validation with clear errors.
  • Chores

    • Reduced log verbosity for Key Manager and related message processing to debug-level to declutter operational logs.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Nov 21, 2025

Walkthrough

Adds robust certificate handling to signature validation (base64 decoding, PEM/X.509 parsing and validation, error-aware marshal flow) and reduces logging verbosity by changing several Info logs to Debug.

Changes

Cohort / File(s) Summary
k8s client — signature validation & CR update
apim-apk-agent/internal/k8sClient/k8s_client.go
Adds imports (crypto/x509, encoding/base64, encoding/pem); changes marshalSignatureValidation signature to return (dpv1alpha2.SignatureValidation, error); new error-aware creation/update paths call marshalSignatureValidation, handle errors, and assign the returned SignatureValidation to tokenIssuer.Spec.SignatureValidation. Adds debug/error logging around these flows.
k8s client — certificate parsing & validation
apim-apk-agent/internal/k8sClient/k8s_client.go
marshalSignatureValidation now: preserves JWKS path; for non-JWKS attempts base64-decode CertificateValue (uses decoded if successful), validates PEM format via pem.Decode and parses X.509 with x509.ParseCertificate; returns error on invalid PEM/X.509; on success returns SignatureValidation with CertificateInline. Adds logging for JWKS, decode results, validation errors and fallbacks.
Logging verbosity reductions
apim-apk-agent/internal/messaging/km_listener.go, apim-apk-agent/internal/synchronizer/keymanagers_fetcher.go
Downgrades several Infof log statements to Debugf (decoded stream, Key Managers received, Resolved Key Managers received). No control-flow changes.

Sequence Diagram(s)

sequenceDiagram
    participant Sync as Synchronizer / Caller
    participant K8s as k8s_client.marshalSignatureValidation
    participant CR as TokenIssuer CR (create/update)
    Sync->>K8s: request marshalSignatureValidation(config)
    alt CertificateType == JWKS
        K8s-->>Sync: SignatureValidation{JWKS} (nil error)
    else CertificateType != JWKS
        K8s->>K8s: try base64.Decode(value)
        alt decode success
            K8s->>K8s: pem.Decode -> x509.ParseCertificate
            alt valid PEM/X.509
                K8s-->>Sync: SignatureValidation{CertificateInline} (nil error)
            else invalid PEM/X.509
                K8s-->>Sync: error (invalid certificate)
            end
        else decode fail
            K8s->>K8s: attempt pem.Decode on original value -> x509.ParseCertificate
            alt valid PEM/X.509
                K8s-->>Sync: SignatureValidation{CertificateInline} (nil error)
            else invalid PEM/X.509
                K8s-->>Sync: error (invalid certificate)
            end
        end
    end
    alt no error
        Sync->>CR: assign SignatureValidation to tokenIssuer.Spec and create/update CR
        CR-->>Sync: success / log
    else error
        Sync-->>CR: abort create/update, log error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

  • Attention areas:
    • marshalSignatureValidation: correctness of base64 fallback logic, PEM decode and x509 parsing, and clear error messages.
    • Call sites in create/update flows: proper handling of returned error and ensuring tokenIssuer.Spec.SignatureValidation is assigned only on success.
    • Logging changes: confirm reduced verbosity is intended and no important Info logs were removed.

Poem

🐰 I hopped through bytes both plain and base64,
Sniffed PEM leaves and checked each X.509 trace.
I nudged logs quieter, now debug softly sings,
Tokens wear clean certs and validation springs —
A tiny rabbit cheers these tidy things! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings, 1 inconclusive)
Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is largely incomplete, containing only a placeholder 'Purpose: $subject' instead of actual content addressing the required template sections. Complete the description by filling in all required sections: Purpose with issue links, Goals, Approach, User stories, Release notes, Documentation, and other relevant sections from the template.
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'Use correct Key Manager value' is somewhat vague and doesn't clearly convey the specific technical change being made, such as certificate validation or signature validation handling. Consider a more descriptive title like 'Add X.509 certificate validation for Key Manager signature validation' or 'Enhance signature validation with certificate decoding and validation'.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3527f4 and 5ec659f.

📒 Files selected for processing (3)
  • apim-apk-agent/internal/k8sClient/k8s_client.go (2 hunks)
  • apim-apk-agent/internal/messaging/km_listener.go (2 hunks)
  • apim-apk-agent/internal/synchronizer/keymanagers_fetcher.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
apim-apk-agent/internal/synchronizer/keymanagers_fetcher.go (1)
apim-apk-agent/internal/loggers/logger.go (1)
  • LoggerSynchronizer (51-51)
apim-apk-agent/internal/messaging/km_listener.go (2)
apim-apk-agent/internal/loggers/logger.go (1)
  • LoggerMessaging (50-50)
apim-apk-agent/internal/eventhub/marshaller.go (1)
  • MarshalKeyManager (271-281)
apim-apk-agent/internal/k8sClient/k8s_client.go (1)
apim-apk-agent/internal/loggers/logger.go (1)
  • LoggerK8sClient (48-48)
🔇 Additional comments (4)
apim-apk-agent/internal/synchronizer/keymanagers_fetcher.go (1)

131-131: LGTM: Appropriate log level adjustment.

Reducing verbosity by moving detailed key manager data to debug level is appropriate for production environments.

apim-apk-agent/internal/messaging/km_listener.go (1)

83-83: LGTM: Consistent log level adjustments.

All three logging statements appropriately moved to debug level, reducing operational log verbosity while preserving diagnostic information.

Also applies to: 95-95, 97-97

apim-apk-agent/internal/k8sClient/k8s_client.go (2)

24-24: LGTM: Import addition.

The encoding/base64 import is correctly added to support certificate value decoding.


799-802: LGTM: Debug logging additions.

The debug logs provide useful diagnostic information for signature validation configuration.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apim-apk-agent/internal/k8sClient/k8s_client.go (1)

808-838: Certificate validation implementation is robust and addresses past review concerns.

The validation chain properly ensures certificate integrity:

  1. Base64 detection (lines 817-822): Attempts decoding and uses the result if successful. While this could theoretically produce false positives, the subsequent validations prevent invalid certificates from being accepted.

  2. PEM validation (lines 824-828): Ensures the certificate (decoded or original) is in valid PEM format. This catches any incorrectly decoded values.

  3. X.509 validation (lines 830-833): Parses and validates the certificate structure, providing the final safety check.

The error propagation ensures invalid certificates are rejected at TokenIssuer creation/update time.

Optional optimization: Consider checking for PEM format markers (-----BEGIN CERTIFICATE-----) before attempting base64 decode to avoid unnecessary processing. However, this is not critical since PEM format contains characters (dashes, newlines) that should cause base64 decode to fail naturally.

Example optimization:

 certValue := keyManagerConfig.CertificateValue
 // Check if the certificate value is base64 encoded and decode it
-if decodedCert, err := base64.StdEncoding.DecodeString(certValue); err == nil {
+if !strings.Contains(certValue, "-----BEGIN") {
+  if decodedCert, err := base64.StdEncoding.DecodeString(certValue); err == nil {
     // Successfully decoded, use the decoded value
     decodedCertStr := string(decodedCert)
     loggers.LoggerK8sClient.Debugf("Certificate value was base64 encoded, using decoded value")
     certValue = decodedCertStr
+  }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ec659f and 57cd03a.

📒 Files selected for processing (1)
  • apim-apk-agent/internal/k8sClient/k8s_client.go (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apim-apk-agent/internal/k8sClient/k8s_client.go (3)
apim-apk-agent/pkg/eventhub/types/types.go (1)
  • KeyManagerConfig (261-283)
apim-apk-agent/internal/constants/constants.go (3)
  • GatewayGroup (23-23)
  • GatewayKind (24-24)
  • GatewayName (22-22)
apim-apk-agent/internal/loggers/logger.go (1)
  • LoggerK8sClient (48-48)
🔇 Additional comments (4)
apim-apk-agent/internal/k8sClient/k8s_client.go (4)

24-27: LGTM! Appropriate imports for certificate validation.

The added standard library imports (crypto/x509, encoding/base64, encoding/pem) are necessary and appropriate for implementing robust certificate validation.


645-650: LGTM! Proper error handling for signature validation.

The error-aware flow correctly handles validation failures by logging and returning the error, preventing invalid TokenIssuer CRs from being created with malformed certificates.


786-791: LGTM! Consistent error handling in update path.

The update flow mirrors the create path with proper error handling, ensuring consistency across TokenIssuer lifecycle operations.


811-834: LGTM! Appropriate log level adjustments.

The log level changes correctly reduce verbosity for successful operations (Debug level) while preserving error visibility (Error level for validation failures at lines 826 and 831). This aligns with the PR objective of reducing logging verbosity.

@Tharsanan1 Tharsanan1 merged commit 4346fea into wso2:master Nov 21, 2025
3 of 4 checks passed
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