Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix keycloak-configure secrets drift #506

Merged
merged 2 commits into from
Dec 4, 2024
Merged

Conversation

klinch0
Copy link
Contributor

@klinch0 klinch0 commented Dec 4, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced management of Kubernetes secrets for k8s-client, kubeapps-client, and kubeapps-auth-config.
    • Improved handling of client secrets by reusing existing configurations when available.
  • Bug Fixes

    • Addressed issues with static secret definitions, streamlining the configuration process.
  • Chores

    • Removed outdated secret and Keycloak client definitions for cleaner configuration management.

@klinch0 klinch0 requested a review from kvaps as a code owner December 4, 2024 15:17
@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Dec 4, 2024
Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

Walkthrough

The pull request modifies the configure-kk.yaml file, enhancing the management of Kubernetes secrets and Keycloak client configurations. The implementation now checks for existing secrets in the Kubernetes namespace, decoding them if present, instead of generating new random values. New Kubernetes secrets for k8s-client, kubeapps-client, and kubeapps-auth-config have been added, while previous static definitions have been removed to streamline the configuration.

Changes

File Path Change Summary
packages/system/keycloak-configure/templates/configure-kk.yaml - Added new Kubernetes secrets for k8s-client, kubeapps-client, and kubeapps-auth-config with base64-encoded values.
- Removed old secrets and Keycloak client definitions.

Possibly related PRs

  • Refactor Keycloak #502: The changes in this PR involve modifications to Keycloak configurations, which may relate to the management of Keycloak clients and secrets, similar to the enhancements made in the main PR regarding the handling of Kubernetes secrets and Keycloak client configurations.

Suggested labels

enhancement, size:L

Poem

Hop hop hooray, secrets stored with care,
In Kubernetes' arms, they’re safe everywhere.
Old values removed, new paths we tread,
Keycloak's clients now dance, no worries ahead!
With base64 hugs, our secrets are bright,
In the world of config, everything feels right! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 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.

@klinch0 klinch0 closed this Dec 4, 2024
@dosubot dosubot bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Dec 4, 2024
Copy link
Contributor

@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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
packages/system/keycloak-configure/templates/configure-kk.yaml (2)

33-62: Enhance secret security configuration

Consider adding the following security improvements to the secret definitions:

  1. Add immutable: true to prevent accidental updates
  2. Add labels for secret rotation management
  3. Consider using a more specific secret type than Opaque

Example enhancement:

 apiVersion: v1
 kind: Secret
 metadata:
   name: k8s-client
   namespace: {{ .Release.Namespace }}
+  labels:
+    secret-rotation: enabled
+    secret-rotation-period: "30d"
 type: Opaque
+immutable: true
 data:
   client-secret-key: {{ $k8sClient | b64enc }}

Line range hint 154-161: Security: Address insecure configuration settings

Several security concerns in the auth configuration:

  1. --ssl-insecure-skip-verify disables SSL certificate verification, which is unsafe
  2. --cookie-secure=false allows cookies over non-HTTPS connections
  3. Sensitive auth configuration in ConfigMap instead of Secret

Recommendations:

  1. Remove --ssl-insecure-skip-verify and properly configure SSL certificates
  2. Enable secure cookies unless there's a specific requirement for HTTP
  3. Consider moving sensitive auth configuration to a Secret
       extraFlags:
-        - --ssl-insecure-skip-verify
-        - --cookie-secure=false
+        - --cookie-secure=true
         - --scope=openid email groups
🛑 Comments failed to post (1)
packages/system/keycloak-configure/templates/configure-kk.yaml (1)

10-29: ⚠️ Potential issue

Critical: Fix variable assignment in secret generation logic

The current implementation has a serious issue with variable scoping that will result in empty secrets. The := operator creates new variables in the if/else blocks instead of assigning values to the outer variables.

Apply this fix to all three secret blocks:

-{{ $k8sClient := "" }}
+{{ $k8sClient := "" -}}
 {{- if $existingK8sSecret }}
-  {{- $k8sClient := index $existingK8sSecret.data "client-secret-key" | b64dec }}
+  {{- $k8sClient = index $existingK8sSecret.data "client-secret-key" | b64dec }}
 {{- else }}
-  {{- $k8sClient := randAlphaNum 32 }}
+  {{- $k8sClient = randAlphaNum 32 }}
 {{- end }}

Similar changes needed for $kubeappsClient and $cookieSecret blocks. Use = for assignment instead of := to modify the existing variables.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 yamllint (1.35.1)

[warning] 14-14: wrong indentation: expected 0 but found 2

(indentation)


[warning] 19-19: wrong indentation: expected 0 but found 2

(indentation)


[warning] 21-21: wrong indentation: expected 0 but found 2

(indentation)


[warning] 26-26: wrong indentation: expected 0 but found 2

(indentation)


[warning] 28-28: wrong indentation: expected 0 but found 2

(indentation)

@klinch0 klinch0 reopened this Dec 4, 2024
@dosubot dosubot bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Dec 4, 2024
Copy link
Contributor

@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: 2

🧹 Outside diff range and nitpick comments (2)
packages/system/keycloak-configure/templates/configure-kk.yaml (2)

10-29: Consider refactoring duplicated secret handling logic

The secret handling logic is duplicated three times with slight variations. Consider creating a template helper function to reduce duplication and standardize the approach.

Example helper function:

{{- define "getOrGenerateSecret" }}
{{- $existing := index . 0 }}
{{- $length := index . 1 }}
{{- $result := "" }}
{{- if $existing }}
  {{- $result = index $existing.data "client-secret-key" | b64dec }}
{{- else }}
  {{- $result = randAlphaNum $length }}
{{- end }}
{{- $result }}
{{- end }}

Then use it like:

{{- $k8sClient := include "getOrGenerateSecret" (list $existingK8sSecret 32) }}
🧰 Tools
🪛 yamllint (1.35.1)

[warning] 14-14: wrong indentation: expected 0 but found 2

(indentation)


[warning] 19-19: wrong indentation: expected 0 but found 2

(indentation)


[warning] 21-21: wrong indentation: expected 0 but found 2

(indentation)


[warning] 26-26: wrong indentation: expected 0 but found 2

(indentation)


[warning] 28-28: wrong indentation: expected 0 but found 2

(indentation)


33-63: Enhance secret management with metadata and immutability

Consider adding the following improvements to the Secret resources:

  1. Add labels for better resource management
  2. Consider setting immutable: true to prevent accidental updates
  3. Add annotations to document the purpose of each secret

Example enhancement for k8s-client secret:

 apiVersion: v1
 kind: Secret
 metadata:
   name: k8s-client
   namespace: {{ .Release.Namespace }}
+  labels:
+    app.kubernetes.io/name: keycloak
+    app.kubernetes.io/component: client-secret
+  annotations:
+    description: "Secret for Kubernetes client authentication with Keycloak"
 type: Opaque
+immutable: true
 data:
   client-secret-key: {{ $k8sClient | b64enc }}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9ea2b25 and 13d01c6.

📒 Files selected for processing (1)
  • packages/system/keycloak-configure/templates/configure-kk.yaml (2 hunks)
🧰 Additional context used
🪛 yamllint (1.35.1)
packages/system/keycloak-configure/templates/configure-kk.yaml

[warning] 14-14: wrong indentation: expected 0 but found 2

(indentation)


[warning] 19-19: wrong indentation: expected 0 but found 2

(indentation)


[warning] 21-21: wrong indentation: expected 0 but found 2

(indentation)


[warning] 26-26: wrong indentation: expected 0 but found 2

(indentation)


[warning] 28-28: wrong indentation: expected 0 but found 2

(indentation)

🔇 Additional comments (1)
packages/system/keycloak-configure/templates/configure-kk.yaml (1)

6-8: Verify impact on existing deployments

The new secret lookup logic changes how secrets are managed. Please ensure this change doesn't affect existing deployments during upgrades.

✅ Verification successful

Based on the search results, I can now provide a final response about the secret lookup changes:

Secret lookups are used safely with proper fallback handling

The code changes are safe for existing deployments because:

  • The lookups are used in a read-only manner to check for existing secrets
  • The code has proper conditional logic after the lookups ({{- if $existingK8sSecret }})
  • These secrets are referenced consistently across the codebase in packages/apps/tenant/templates/kubeconfig.yaml and packages/system/keycloak-configure/templates/configure-kk.yaml
  • The namespaces are explicitly specified, preventing any unintended cross-namespace access
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing secrets in the cluster that might be affected
kubectl get secrets -A | grep -E 'k8s-client|kubeapps-client|kubeapps-auth-config'

# Check if any pods are using these secrets
kubectl get pods -A -o json | jq '.items[] | select(.spec.volumes[]?.secret?.secretName | select(. == "k8s-client" or . == "kubeapps-client" or . == "kubeapps-auth-config")) | {namespace: .metadata.namespace, pod: .metadata.name, secret: .spec.volumes[].secret.secretName}'

Length of output: 556


Script:

#!/bin/bash
# Let's analyze the Helm chart to understand the impact of these secret lookups
# First, check if these secrets are referenced in other templates
fd -e yaml -e tpl | xargs rg -l "k8s-client|kubeapps-client|kubeapps-auth-config"

# Check for any conditional logic or default values related to these secrets
fd -e yaml -e tpl | xargs rg -A 5 -B 5 "lookup.*Secret.*k8s-client|lookup.*Secret.*kubeapps-client|lookup.*Secret.*kubeapps-auth-config"

# Check values.yaml for any related configurations
fd "values.yaml" | xargs cat

Length of output: 65817

@@ -168,7 +208,7 @@ data:
provider: "oidc"
clientID: "kubeapps"
clientSecret: {{ $kubeappsClient }}
cookieSecret: {{ randAlphaNum 16 | b64enc | quote }}
cookieSecret: {{ $cookieSecret }}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security concern: Plain text secrets in ConfigMap

The cookieSecret is stored as plain text in the ConfigMap. Consider using a Secret resource or a secure external secret management solution for sensitive values.

Consider using one of these approaches:

  1. Use Kubernetes Secrets and mount them as environment variables
  2. Implement HashiCorp Vault integration
  3. Use Sealed Secrets for encrypted secret management

Would you like me to provide an example implementation for any of these approaches?

{{- $rootSaConfigMap := lookup "v1" "ConfigMap" "kube-system" "kube-root-ca.crt" }}
{{- $k8sCa := index $rootSaConfigMap.data "ca.crt" | b64enc }}
{{- $k8sCa := index $rootSaConfigMap.data "ca.crt" | b64enc }}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add null check for CA certificate

The code assumes $rootSaConfigMap exists and contains ca.crt. Add a null check to handle cases where the ConfigMap might not exist.

-{{- $k8sCa := index $rootSaConfigMap.data "ca.crt" | b64enc }}
+{{- $k8sCa := "" }}
+{{- if and $rootSaConfigMap (hasKey $rootSaConfigMap.data "ca.crt") }}
+  {{- $k8sCa = index $rootSaConfigMap.data "ca.crt" | b64enc }}
+{{- end }}
📝 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
{{- $k8sCa := index $rootSaConfigMap.data "ca.crt" | b64enc }}
{{- $k8sCa := "" }}
{{- if and $rootSaConfigMap (hasKey $rootSaConfigMap.data "ca.crt") }}
{{- $k8sCa = index $rootSaConfigMap.data "ca.crt" | b64enc }}
{{- end }}

Copy link
Member

@kvaps kvaps left a comment

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot bot added the lgtm This PR has been approved by a maintainer label Dec 4, 2024
@kvaps kvaps changed the title fix secrets draft fix keycloak-configure secrets drift Dec 4, 2024
@kvaps kvaps merged commit 3aa5f88 into aenix-io:main Dec 4, 2024
1 check passed
klinch0 added a commit to klinch0/cozystack that referenced this pull request Dec 5, 2024
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Enhanced management of Kubernetes secrets for `k8s-client`,
`kubeapps-client`, and `kubeapps-auth-config`.
- Improved handling of client secrets by reusing existing configurations
when available.
  
- **Bug Fixes**
- Addressed issues with static secret definitions, streamlining the
configuration process.

- **Chores**
- Removed outdated secret and Keycloak client definitions for cleaner
configuration management.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This was referenced Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lgtm This PR has been approved by a maintainer size:M This PR changes 30-99 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants