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

feat: k8s auth token instead of kube conffig #600

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

mojtaba-esk
Copy link
Contributor

@mojtaba-esk mojtaba-esk commented Jan 7, 2025

Closes #319

Summary by CodeRabbit

  • New Features

    • Enhanced Kubernetes client configuration with flexible options.
    • Added logging capabilities to test suites.
    • Introduced authentication token generation script for Kubernetes access.
  • Bug Fixes

    • Improved error handling for Kubernetes client initialization.
    • Added checks for cluster configuration before executing commands.
  • Chores

    • Refactored Kubernetes client setup across multiple test suites.
    • Added new utility functions for managing Kubernetes client options.

@mojtaba-esk mojtaba-esk requested a review from a team January 7, 2025 12:45
@mojtaba-esk mojtaba-esk self-assigned this Jan 7, 2025
Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Walkthrough

The pull request introduces a comprehensive enhancement to Kubernetes client authentication in the knuu project. The changes focus on providing more flexible authentication methods, particularly supporting token-based authentication. A new ClientOptions structure and associated methods have been added to the k8s package, allowing developers to configure Kubernetes clients using environment variables or programmatic options. The modifications span multiple files, including test suite setup, utility functions, and a new authentication token generation script.

Changes

File Change Summary
e2e/*/suite_setup_test.go Updated to use new K8s client initialization with logger and default options
e2e/suite.go Added K8sDefaultOptions() method to retrieve Kubernetes authentication options from environment variables
pkg/k8s/clinet_options.go Introduced new ClientOptions struct and functional options for client configuration
pkg/k8s/errors.go Added new error variables for cluster configuration validation
pkg/k8s/k8s.go Enhanced Client struct with clusterConfig and updated client initialization methods
pkg/k8s/utils.go Modified cluster configuration retrieval to support token-based authentication
scripts/auth_token.sh New script to generate Kubernetes service account token

Assessment against linked issues

Objective Addressed Explanation
Authentication with token [#319] Implemented token-based authentication through new ClientOptions and utility functions

Poem

🐰 In the realm of Kubernetes grand,
A token's power now takes its stand!
No config file, just pure delight,
Authentication shining bright! 🔐
Knuu's magic makes clusters align! 🚀


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@celestia-bot celestia-bot requested review from smuu and sysrex January 7, 2025 12:45
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: 8

🧹 Nitpick comments (5)
pkg/k8s/utils.go (1)

43-45: Improve error specificity in getClusterConfigWithToken

Currently, when any of opts.clusterHost, opts.authToken, or opts.cert is empty, the function returns a generic ErrEmptyClusterHostOrAuthTokenOrCert error. To enhance clarity, consider specifying which parameter is missing in the error message.

Apply this diff to improve error messages:

 func getClusterConfigWithToken(opts *ClientOptions) (*rest.Config, error) {
-	if opts.clusterHost == "" || opts.authToken == "" || opts.cert == "" {
-		return nil, ErrEmptyClusterHostOrAuthTokenOrCert
+	var missingFields []string
+	if opts.clusterHost == "" {
+		missingFields = append(missingFields, "clusterHost")
+	}
+	if opts.authToken == "" {
+		missingFields = append(missingFields, "authToken")
+	}
+	if opts.cert == "" {
+		missingFields = append(missingFields, "cert")
+	}
+	if len(missingFields) > 0 {
+		return nil, fmt.Errorf("missing required fields: %v", missingFields)
 	}
scripts/auth_token.sh (2)

1-6: Add prerequisite checks and documentation

The script needs better documentation and validation of prerequisites.

Add:

 #!/bin/bash
+set -euo pipefail
+
 # This script generates a bearer token for the knuu service account.
 # It is used to authenticate the knuu service account to the Kubernetes API server.
 # The token is used to test things manually. 
 # It requries ~/.kube/config to be set up.
+
+# Verify prerequisites
+command -v kubectl >/dev/null 2>&1 || { echo "kubectl is required but not installed. Aborting." >&2; exit 1; }
+
+# Verify current context
+CURRENT_CONTEXT=$(kubectl config current-context)
+echo "Using Kubernetes context: $CURRENT_CONTEXT"
+read -p "Continue? (y/N) " -n 1 -r
+echo
+if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+    exit 1
+fi

61-62: Improve example usage documentation

The example command should be more comprehensive.

Add more detailed examples and common use cases:

 # Example how to run the tests using the auth token:
-# . ./scripts/auth_token.sh && go test -v ./e2e/basic/
+# Generate token and run tests:
+#   source ./scripts/auth_token.sh && go test -v ./e2e/basic/
+#
+# Export variables for later use:
+#   source ./scripts/auth_token.sh
+#   export | grep K8S_  # verify exported variables
+#
+# Use with kubectl:
+#   source ./scripts/auth_token.sh
+#   kubectl --token="$K8S_AUTH_TOKEN" --server="$K8S_HOST" get pods
pkg/k8s/clinet_options.go (2)

5-11: Add field documentation and consider adding getter methods.

The struct fields are correctly made private, but consider:

  1. Adding documentation for each field to explain their purpose and requirements
  2. Implementing getter methods if these values need to be accessed after initialization

Example documentation:

 type ClientOptions struct {
+    // clusterDomain is the domain name of the Kubernetes cluster
     clusterDomain string
+    // clusterHost is the host address of the Kubernetes API server
     clusterHost   string
+    // authToken is the authentication token for API server access
     authToken     string
+    // cert is the certificate data for TLS verification
     cert          string
+    // clusterConfig is the raw rest.Config if direct configuration is needed
     clusterConfig *rest.Config
 }

5-11: Document security requirements for auth tokens.

Since this code handles authentication tokens, please add documentation about:

  1. Required token format and minimum length
  2. Token security requirements (e.g., entropy, expiration)
  3. Safe token handling practices

Example documentation:

// ClientOptions holds Kubernetes client configuration.
// Security Notice:
// - Auth tokens must be kept secure and not logged
// - Tokens should be rotated regularly
// - Minimum token length: 32 characters
// - Token should have sufficient entropy
type ClientOptions struct {
    // ... existing fields ...
}

Also applies to: 21-27

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 83a1a24 and 1a3bbcc.

📒 Files selected for processing (13)
  • e2e/basic/suite_setup_test.go (2 hunks)
  • e2e/netshaper/suite_setup_test.go (2 hunks)
  • e2e/sidecars/suite_setup_test.go (2 hunks)
  • e2e/suite.go (3 hunks)
  • e2e/system/suite_setup_test.go (2 hunks)
  • e2e/tshark/tshark_test.go (2 hunks)
  • pkg/k8s/clinet_options.go (1 hunks)
  • pkg/k8s/errors.go (1 hunks)
  • pkg/k8s/k8s.go (6 hunks)
  • pkg/k8s/namespace.go (2 hunks)
  • pkg/k8s/pod.go (3 hunks)
  • pkg/k8s/utils.go (1 hunks)
  • scripts/auth_token.sh (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test (./e2e/netshaper, 60m)
  • GitHub Check: test (./e2e/basic, 15m)
🔇 Additional comments (18)
e2e/netshaper/suite_setup_test.go (3)

24-27: Good practice in grouping variable declarations

Grouping the variable declarations for ctx and logger enhances readability and maintains clean code structure.


29-30: Proper error handling after Kubernetes client creation

The error from k8s.NewClient is correctly handled using s.Require().NoError(err), ensuring the test suite fails if the client cannot be created.


34-35: Enhanced configurability with new options

Passing K8sClient and Logger to knuu.New improves the configurability and observability of the Knuu instance.

e2e/basic/suite_setup_test.go (1)

38-38: LGTM!

The changes correctly integrate the new K8s auth token functionality and logger configuration.

Also applies to: 49-49

e2e/system/suite_setup_test.go (1)

Line range hint 39-50: LGTM! Good error messages.

The changes correctly integrate the new K8s auth token functionality. The descriptive error messages in s.Require().NoError() calls will help with debugging.

e2e/sidecars/suite_setup_test.go (1)

37-43: LGTM!

The changes correctly integrate the new K8s auth token functionality with clean error handling.

e2e/tshark/tshark_test.go (3)

16-16: LGTM: Import for e2e package added.

The import aligns with the new e2e.Suite integration.


36-40: LGTM: Clean variable block initialization.

Good practice to group related variable declarations in a single var block.


42-42: LGTM: Updated k8s client initialization with auth token support.

The change correctly integrates the new authentication method via K8sDefaultOptions.

pkg/k8s/k8s.go (4)

12-12: LGTM: Added rest package import.

Required for handling cluster configuration.


44-44: LGTM: Added clusterConfig field to Client struct.

Good design to store the cluster configuration for reuse, avoiding repeated config retrieval.


Line range hint 57-82: LGTM: Enhanced NewClient implementation.

The changes correctly:

  1. Use getAppliedOptions for configuration
  2. Set custom QPS and Burst
  3. Pass cluster config to NewClientCustom

Line range hint 94-110: LGTM: Updated NewClientCustom implementation.

The changes properly integrate cluster configuration while maintaining existing functionality.

pkg/k8s/errors.go (1)

150-151: LGTM: Added comprehensive error handling for cluster configuration.

The new error variables provide clear messages for configuration-related issues:

  • ErrEmptyClusterHostOrAuthTokenOrCert for missing credentials
  • ErrClusterConfigNotSet for missing configuration
pkg/k8s/pod.go (2)

213-214: LGTM: Added cluster config validation in RunCommandInPod.

Good defensive programming to check for cluster config before creating the SPDY executor.

Also applies to: 216-216


285-286: LGTM: Added cluster config validation in PortForwardPod.

Consistent error handling with RunCommandInPod for missing cluster config.

Also applies to: 296-296

pkg/k8s/clinet_options.go (2)

1-3: LGTM! Clean package structure.

The package name and import are appropriate for Kubernetes client configuration.


35-43: ⚠️ Potential issue

Fix undefined constant and consider function visibility.

  1. The defaultClusterDomain constant is undefined in this file
  2. Consider if this function should be exported if it's needed by other packages

Let's verify the constant definition:

pkg/k8s/utils.go Show resolved Hide resolved
e2e/suite.go Outdated Show resolved Hide resolved
pkg/k8s/namespace.go Outdated Show resolved Hide resolved
scripts/auth_token.sh Show resolved Hide resolved
scripts/auth_token.sh Show resolved Hide resolved
scripts/auth_token.sh Show resolved Hide resolved
scripts/auth_token.sh Show resolved Hide resolved
pkg/k8s/clinet_options.go Show resolved Hide resolved
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: 0

🧹 Nitpick comments (1)
e2e/suite.go (1)

27-29: Add documentation for the new environment variable constants.

Consider adding documentation comments to explain the purpose and expected values of these environment variables.

+// envK8sHost is the environment variable name for the Kubernetes API server host
 envK8sHost      = "K8S_HOST"
+// envK8sCACert is the environment variable name for the Kubernetes CA certificate
 envK8sCACert    = "K8S_CA_CERT"
+// envK8sAuthToken is the environment variable name for the Kubernetes authentication token
 envK8sAuthToken = "K8S_AUTH_TOKEN"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1a3bbcc and b81bf31.

📒 Files selected for processing (2)
  • e2e/suite.go (4 hunks)
  • pkg/k8s/namespace.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/k8s/namespace.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test (./e2e/netshaper, 60m)
🔇 Additional comments (1)
e2e/suite.go (1)

103-116: Implementation looks good and includes proper validation!

The method properly validates all required environment variables and provides a clear fallback mechanism to the default kubeconfig. The use of constants and descriptive logging enhances maintainability.

Let's verify that this method is consistently used across the codebase:

✅ Verification successful

K8sDefaultOptions is consistently used across the codebase

All e2e test files properly initialize the k8s client using s.K8sDefaultOptions(), and there are no direct environment variable accesses outside of the Suite implementation. The implementation is being used as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of K8sDefaultOptions across test files

# Find all test setup files that might need K8s client initialization
echo "Checking test files for K8s client initialization..."
rg -l "k8s\.NewClient" --type go

# Check for any direct usage of these environment variables outside of K8sDefaultOptions
echo -e "\nChecking for direct environment variable usage..."
rg -l "K8S_(HOST|CA_CERT|AUTH_TOKEN)" --type go | grep -v "suite.go"

Length of output: 600


Script:

#!/bin/bash
# Check how k8s.NewClient is being used in e2e tests
echo "Checking k8s.NewClient usage in e2e tests..."
rg -B 3 -A 3 "k8s\.NewClient" e2e/

# Check if test files are using the Suite type and its methods
echo -e "\nChecking Suite usage in test files..."
rg -B 2 -A 2 "type \*Suite" e2e/

Length of output: 2389

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.

feat: Authentication with token
1 participant