Skip to content

Conversation

@NickCao
Copy link
Collaborator

@NickCao NickCao commented May 30, 2025

Summary by CodeRabbit

  • New Features

    • When a client resource is not found during authorization, it is now automatically created using the requesting user's name.
    • If a resource name is missing in metadata, a sanitized and hashed version of the user's name is used as a fallback to ensure uniqueness.
    • Added a provisioning mode toggle to control automatic client creation during authorization.
  • Bug Fixes

    • Improved error handling during client resource authorization to provide clearer authorization outcomes.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 30, 2025

Warning

Rate limit exceeded

@NickCao has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 16 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8972949 and 1ccc5ce.

📒 Files selected for processing (6)
  • cmd/main.go (2 hunks)
  • internal/authorization/basic.go (3 hunks)
  • internal/authorization/metadata.go (4 hunks)
  • internal/authorization/metadata_test.go (1 hunks)
  • internal/config/config.go (3 hunks)
  • internal/config/types.go (2 hunks)

"""

Walkthrough

The updates modify the authorization logic by upgrading the authorizer to use a full client interface, enhancing error handling and resource creation for missing Client resources. Additionally, the metadata attribute getter now constructs a sanitized and hashed username to ensure a non-empty name in the context attributes. Configuration loading was updated to support provisioning settings propagated to the authorizer.

Changes

File(s) Change Summary
internal/authorization/basic.go Changed BasicAuthorizer to use client.Client instead of client.Reader; enhanced error handling and resource creation for missing Client resources; updated constructor signature.
internal/authorization/metadata.go Modified ContextAttributes to generate a sanitized, truncated, and partially hashed username to ensure a non-empty name; added normalizeName function.
internal/authorization/metadata_test.go Added TestNormalizeName to validate normalizeName function output and DNS-1123 compliance.
internal/config/config.go Updated LoadConfiguration to return a new Provisioning struct indicating provisioning enabled state.
internal/config/types.go Added new Provisioning struct and added it as a field to Config struct.
cmd/main.go Updated main.go to receive provisioning info from config and pass it to BasicAuthorizer constructor.

Possibly related PRs

  • Minor cleanup for token handling #100: Adds Username methods to Client and Exporter structs and refactors authorization code, closely related to authorization logic and client handling in internal/authorization/basic.go.

Suggested reviewers

  • mangelajo

Poem

In the warren of code, things shift and grow,
Now clients are clever, with full power to show.
If a name is missing, a hash hops in place,
Authorization’s stronger, with a more secure face.
🐇✨
Hopping forward, we’re ready to race!
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

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: 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 ea0c554 and cbbcdf7.

📒 Files selected for processing (2)
  • internal/authorization/basic.go (3 hunks)
  • internal/authorization/metadata.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
internal/authorization/basic.go (1)
api/v1alpha1/client_types.go (2)
  • Client (44-50)
  • ClientSpec (28-30)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: lint-go
  • GitHub Check: tests
  • GitHub Check: e2e-tests (ubuntu-24.04-arm)
  • GitHub Check: e2e-tests-28d6b1cc3b49ab9ae176918ab9709a2e2522c97e
  • GitHub Check: e2e-tests (ubuntu-24.04)
  • GitHub Check: deploy-kind
🔇 Additional comments (6)
internal/authorization/metadata.go (2)

5-6: LGTM! Appropriate imports for hash generation.

The added imports support the SHA-256 hash generation logic for handling empty names.


57-60: Good fallback mechanism for empty names.

The SHA-256 hash generation provides a deterministic, non-empty identifier when the name metadata is missing. This creates a stable mapping from username to resource name that supports the client provisioning logic in basic.go.

internal/authorization/basic.go (4)

8-9: LGTM! Necessary imports for client provisioning.

The added imports support the enhanced error handling and client resource creation functionality.

Also applies to: 11-11


16-16: Good upgrade to full client interface.

Upgrading from client.Reader to client.Client enables the creation of missing client resources while maintaining all existing read capabilities.

Also applies to: 20-21


31-31: LGTM! Updated to use the new client interface.

The Exporter case correctly uses the upgraded client interface for the Get operation.


66-70: Authorization check logic is sound.

The authorization check correctly validates that the user's name is in the client's usernames list. This will work properly once the previous issue with the client object reference is 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.

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: 1

🛑 Comments failed to post (1)
internal/authorization/metadata.go (1)

59-76: 🛠️ Refactor suggestion

Improve edge case handling and Kubernetes naming compliance.

The naming logic has potential issues that could generate invalid Kubernetes resource names:

  1. Double hyphens: Empty usernames or usernames with only invalid characters result in names like "oidc--<hash>" or "oidc-----<hash>"
  2. Invalid start/end characters: Kubernetes names must start and end with alphanumeric characters, but this logic could generate names ending with hyphens
  3. Dots in resource names: The regex allows dots, but some Kubernetes resources don't permit dots in names

Consider this improved implementation:

 if name == "" {
 	hash := sha256.Sum256([]byte(userInfo.GetName()))
 
-	sanitized := regexp.MustCompile("[^a-z0-9-.]+").ReplaceAllString(
+	sanitized := regexp.MustCompile("[^a-z0-9-]+").ReplaceAllString(
 		strings.ToLower(userInfo.GetName()),
 		"-",
 	)
+	
+	// Remove leading/trailing hyphens and collapse multiple hyphens
+	sanitized = regexp.MustCompile("^-+|-+$").ReplaceAllString(sanitized, "")
+	sanitized = regexp.MustCompile("-+").ReplaceAllString(sanitized, "-")
+	
+	// Ensure we have a valid base name
+	if sanitized == "" {
+		sanitized = "user"
+	}
 
 	if len(sanitized) > 37 {
 		sanitized = sanitized[:37]
 	}
+	
+	// Ensure name doesn't end with hyphen after truncation
+	sanitized = strings.TrimRight(sanitized, "-")
+	if sanitized == "" {
+		sanitized = "user"
+	}
 
 	name = strings.Join([]string{
 		"oidc",
 		sanitized,
 		hex.EncodeToString(hash[:3]),
 	}, "-")
 }
📝 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 name == "" {
		hash := sha256.Sum256([]byte(userInfo.GetName()))

		// Sanitize: lowercase, allow only a–z, 0–9, and hyphens
		sanitized := regexp.MustCompile("[^a-z0-9-]+").ReplaceAllString(
			strings.ToLower(userInfo.GetName()),
			"-",
		)

		// Remove leading/trailing hyphens and collapse multiple hyphens
		sanitized = regexp.MustCompile("^-+|-+$").ReplaceAllString(sanitized, "")
		sanitized = regexp.MustCompile("-+").ReplaceAllString(sanitized, "-")

		// Ensure we have a non-empty base
		if sanitized == "" {
			sanitized = "user"
		}

		// Truncate to max length
		if len(sanitized) > 37 {
			sanitized = sanitized[:37]
		}

		// Trim any trailing hyphens after truncation
		sanitized = strings.TrimRight(sanitized, "-")
		if sanitized == "" {
			sanitized = "user"
		}

		name = strings.Join([]string{
			"oidc",
			sanitized,
			hex.EncodeToString(hash[:3]),
		}, "-")
	}
🤖 Prompt for AI Agents
In internal/authorization/metadata.go around lines 59 to 76, the current
username sanitization can produce invalid Kubernetes resource names due to
double hyphens, invalid start/end characters, and dots in names. To fix this,
update the regex to exclude dots, trim leading and trailing hyphens from the
sanitized string, and replace consecutive hyphens with a single hyphen. Also,
add a fallback to a default string if the sanitized username becomes empty after
cleanup to avoid double hyphens in the final name. Ensure the final constructed
name starts and ends with an alphanumeric character to comply with Kubernetes
naming rules.

@NickCao NickCao force-pushed the provisioning branch 2 times, most recently from bacede3 to ec2dfc3 Compare May 30, 2025 18:36
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)
internal/authorization/metadata_test.go (1)

39-42: Consider using require.NoError for cleaner test failure handling.

While the current error handling works, you could make the test slightly cleaner by using testify's require package:

-		if validation.IsDNS1123Subdomain(result) != nil {
-			t.Error(fmt.Sprintf("normalizing the name %s does not produce a valid RFC1123 subdomain, but %s",
-				testcase.input, result))
-		}
+		require.NoError(t, validation.IsDNS1123Subdomain(result), 
+			"normalizing %s should produce valid RFC1123 subdomain, got %s", testcase.input, result)

This would also stop the test immediately on validation failure rather than continuing to check the exact output.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ec2dfc3 and 8972949.

📒 Files selected for processing (2)
  • internal/authorization/metadata.go (4 hunks)
  • internal/authorization/metadata_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/authorization/metadata.go
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: lint-go
  • GitHub Check: deploy-kind
  • GitHub Check: e2e-tests (ubuntu-24.04)
  • GitHub Check: e2e-tests-28d6b1cc3b49ab9ae176918ab9709a2e2522c97e
  • GitHub Check: e2e-tests (ubuntu-24.04-arm)
  • GitHub Check: tests
🔇 Additional comments (1)
internal/authorization/metadata_test.go (1)

11-48: Excellent test implementation with comprehensive coverage.

This test function follows Go testing best practices with several strengths:

  • Table-driven approach: Clean structure with clear input/output pairs
  • Comprehensive edge cases: Covers simple names, email formats, multiple special characters, boundary characters, and length limits
  • Dual validation: Tests both Kubernetes DNS-1123 compliance and exact output matching
  • Clear error messages: Descriptive error reporting with context

The test cases effectively validate the normalization logic for usernames that will be used as Kubernetes identifiers.

@NickCao NickCao merged commit c56bf9b into main May 30, 2025
8 checks passed
@NickCao NickCao deleted the provisioning branch May 30, 2025 19:28
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.

3 participants