Skip to content

Conversation

NickCao
Copy link
Collaborator

@NickCao NickCao commented Feb 6, 2025

Summary by CodeRabbit

  • New Features

    • Introduced support for customizable authorization configurations, including a new authorization section in Helm charts.
    • Enabled CEL-based rules for more granular access control.
  • Refactor

    • Separated authentication and authorization flows for improved modularity.
    • Enhanced configuration loading to incorporate the new authorization settings.

Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

Walkthrough

This pull request introduces a new authorization configuration mechanism to the project. It adds new API types and their deepcopy methods, updates configuration loading to support both authentication and authorization, and refactors the main initialization flow accordingly. The PR also extends helm chart configurations by adding authorization settings and implements a new CEL-based authorizer along with its configuration loader.

Changes

File(s) Change Summary
api/v1alpha1/authorizationconfiguration_types.go
api/v1alpha1/zz_generated.deepcopy.go
Added new types AuthorizationConfiguration and CELConfiguration and corresponding deepcopy methods for Kubernetes API serialization/deserialization.
cmd/main.go
internal/config/config.go
Refactored initialization: replaced a single authenticator with distinct authn and authz variables and updated the configuration loading logic to return both authentication and authorization components.
deploy/helm/jumpstarter/.../controller-cm.yaml
deploy/helm/jumpstarter/values.yaml
Introduced a new authorization entry in the ConfigMap and a corresponding authorizationConfig section in values, specifying CEL-based authorization parameters.
internal/authorization/cel.go
internal/authorization/config.go
Implemented a new CEL authorizer (CELAuthorizer) with its authorization logic and added a configuration loader (LoadAuthorizationConfiguration) to instantiate an authorizer based on the configuration type.

Sequence Diagram(s)

sequenceDiagram
    participant Main
    participant ConfigLoader as LoadConfiguration
    participant AuthConfigLoader as LoadAuthorizationConfiguration
    participant CEL as NewCELAuthorizer
    Main->>ConfigLoader: Request configuration load
    ConfigLoader->>ConfigMap: Retrieve auth & authorization data
    ConfigLoader->>AuthConfigLoader: Load authorization configuration
    AuthConfigLoader->>CEL: If type == "CEL", compile expression and create CELAuthorizer
    CEL-->>AuthConfigLoader: Return CELAuthorizer instance
    AuthConfigLoader-->>ConfigLoader: Return authorizer instance
    ConfigLoader-->>Main: Return authenticator and authorizer
Loading

Possibly related PRs

Suggested reviewers

  • mangelajo

Poem

I'm a bunny, hopping with glee today,
New types and functions pave a brand new way.
From CEL expressions to configs so neat,
Our code hops forward with each fresh beat.
Cheers to changes—may the bugs stay at bay!
🐰 Happy coding and carrot-filled days!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

@NickCao NickCao changed the base branch from main to oidc-design February 6, 2025 20:11
@NickCao NickCao changed the base branch from oidc-design to main February 6, 2025 20:18
@NickCao NickCao changed the base branch from main to oidc-design February 6, 2025 20:19
Base automatically changed from oidc-design to main February 12, 2025 16:59
@NickCao NickCao changed the title Cel authorization Customizable client authorization Feb 17, 2025
@NickCao NickCao marked this pull request as ready for review February 17, 2025 21:34
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

🧹 Nitpick comments (6)
internal/config/config.go (2)

23-23: Refactored function signature to return authentication.ContextAuthenticator, authorizer.Authorizer, and error.

This change correctly aligns the function's outputs with the new approach of loading both authentication and authorization from the config. Consider whether returning multiple values might be better encapsulated in a struct for improved maintainability, although it's optional.


31-31: Enhanced error message for missing authentication configuration.

This message helps clarify which section is missing, but for consistency, ensure the style matches other error messages (e.g., beginning with "missing 'xyz' section").

internal/authorization/cel.go (2)

21-23: Expression struct straightforwardly wraps the CEL expression string.

Consider renaming Expression field to something like Code or Rule to avoid shadowing the struct name, although it's not critical.


33-47: Environment initialization for CEL is well-structured.

The usage of environment.MustBaseEnvSet and extension points for variables is appropriate. Consider logging or handling advanced environment features for debugging complex rules if needed.

internal/authorization/config.go (1)

21-29: Consider adding validation for empty configuration.

While the function handles decoding errors, it might be worth adding explicit validation for empty configuration bytes.

 func LoadAuthorizationConfiguration(
 	ctx context.Context,
 	scheme *runtime.Scheme,
 	configuration []byte,
 	reader client.Reader,
 	prefix string,
 ) (authorizer.Authorizer, error) {
+	if len(configuration) == 0 {
+		return nil, fmt.Errorf("empty authorization configuration")
+	}
 	var authorizationConfiguration jumpstarterdevv1alpha1.AuthorizationConfiguration
deploy/helm/jumpstarter/values.yaml (1)

97-103: Authorization Configuration Block is Well-Structured!

The new authorizationConfig block is clearly defined and mirrors the style of the existing authenticationConfig section. The multi-line YAML string is appropriately used to encapsulate the authorization configuration details. In particular, the declaration of the API version, kind, type, and CEL-based expression is consistent with the intended design.

A couple of suggestions:

  • Validation of the CEL Expression: Ensure that downstream components (e.g., the configuration loader and the CEL-based authorizer) validate the expression "self.spec.username == user.username" correctly. Consider adding tests or inline documentation that specifies any constraints or expected format for these expressions.
  • Documentation: It may be beneficial to enhance inline comments or update the documentation for jumpstarter-controller parameters, explaining the purpose and usage of authorizationConfig to aid users in customizing client authorization.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e1423e5 and ce035dc.

📒 Files selected for processing (8)
  • api/v1alpha1/authorizationconfiguration_types.go (1 hunks)
  • api/v1alpha1/zz_generated.deepcopy.go (1 hunks)
  • cmd/main.go (2 hunks)
  • deploy/helm/jumpstarter/charts/jumpstarter-controller/templates/cms/controller-cm.yaml (1 hunks)
  • deploy/helm/jumpstarter/values.yaml (1 hunks)
  • internal/authorization/cel.go (1 hunks)
  • internal/authorization/config.go (1 hunks)
  • internal/config/config.go (2 hunks)
🔇 Additional comments (23)
internal/config/config.go (7)

7-8: Imports for new authentication and authorization functionality look valid.

No issues observed. The addition of these imports is consistent with the new requirement to load both authentication and authorization within this module.


12-12: Import for the authorizer interface is appropriate.

This aligns with the newly introduced return type requiring an authorizer.Authorizer.


26-26: Updated return statement to (nil, nil, err) is correct.

Returning three values here is now mandatory due to the new signature.


34-43: OIDC-based authentication loading appears well-structured.

The code consistently handles decoding and error scenarios. Ensure you have sufficient test coverage for potential parsing errors from OIDC, especially if the configuration is malformed.


45-48: Authorization configuration check is properly mirrored from the authentication check.

This symmetry helps maintain consistency. Keep the error message uniform with the authentication check for better clarity.


50-59: Calls LoadAuthorizationConfiguration to parse the new authorization config.

The approach is consistent with the separation of concerns: OIDC config is in oidc, while authorization config is in authorization. Looks good.


61-61: Returns a bearer token authenticator and the loaded authorizer.

This final return effectively ties together authentication and authorization. Good job linking the dependencies.

internal/authorization/cel.go (6)

1-2: Package declaration for the new authorization logic is appropriately structured.

No concerns at this top level.


3-5: Import statements are aligned with CEL-based authorization.

The external dependencies (cel-go, k8s.io/apiserver, etc.) are relevant and correctly scoped for this implementation.

Also applies to: 7-14


16-20: CELAuthorizer struct introduces a clear, minimal set of fields.

Storing the compiled CEL program is efficient. The reader and prefix fields look well-defined for resource fetching and user prefixing.


25-27: Getter method simply returns the expression string.

Clean and concise.


29-31: ReturnTypes() indicates a boolean return type for CEL expressions.

This is properly aligned with typical authorization decisions.


49-50: Compilation of the CEL expression and creation of CELAuthorizer.

Compiling the expression once avoids repeated overhead at runtime. Error handling is clear. Good job.

Also applies to: 51-56, 58-63

api/v1alpha1/authorizationconfiguration_types.go (6)

1-2: New package v1alpha1 introduced for authorization configuration is well-scoped.

This versioned approach aligns with Kubernetes API best practices.


3-5: Imports are minimal and fit the CRD style.

No further concerns.


7-8: Deepcopy generation annotation is standard for CRD definitions.

This is necessary to ensure proper CRD behavior in Kubernetes.


9-14: AuthorizationConfiguration structure is well-defined.

The Type field and a pointer to CELConfiguration allow flexible extension for future authorization types.


16-18: CELConfiguration struct uses a single Expression for CEL rules.

Straightforward and sufficiently descriptive.


20-22: init() properly registers AuthorizationConfiguration with the SchemeBuilder.

Ensures the Kubernetes API can recognize and manage these objects.

internal/authorization/config.go (1)

14-20: LGTM! Well-structured function signature with comprehensive parameters.

The function signature is well-designed, accepting all necessary dependencies for configuration loading and authorization setup.

cmd/main.go (1)

154-154: LGTM! Clean separation of authentication and authorization concerns.

The refactoring to separate authentication and authorization is a good practice, improving modularity and maintainability.

api/v1alpha1/zz_generated.deepcopy.go (1)

61-104: LGTM! Generated deepcopy methods are consistent with existing patterns.

The auto-generated deepcopy methods for AuthorizationConfiguration and CELConfiguration follow the same patterns as other types in the codebase.

deploy/helm/jumpstarter/charts/jumpstarter-controller/templates/cms/controller-cm.yaml (1)

14-14: LGTM! Consistent configuration structure.

The authorization configuration follows the same pattern as the existing authentication configuration, maintaining consistency in the ConfigMap structure.

Comment on lines +65 to +71
func (b *CELAuthorizer) Authorize(
ctx context.Context,
attributes authorizer.Attributes,
) (authorizer.Decision, string, error) {
var self map[string]interface{}
var err error

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Authorize() method handles resource fetching and CEL evaluation logically.

  1. The logic for retrieving Exporter or Client is correct, but consider gracefully handling the case where spec doesn't exist before using .(map[string]any), to avoid potential runtime panics.
  2. The CEL evaluation and final decision returning DecisionAllow or DecisionDeny is consistent with standard authorizer patterns.

Apply a safer approach for type assertions on self["spec"] to prevent panics, for example:

- self["spec"].(map[string]any)["username"] = e.Username(b.prefix)
+ spec, ok := self["spec"].(map[string]any)
+ if !ok {
+   return authorizer.DecisionDeny, "missing spec in resource", fmt.Errorf("spec field not found or invalid")
+ }
+ spec["username"] = e.Username(b.prefix)

Also applies to: 72-85, 87-99, 100-101, 103-116, 118-127

Comment on lines +31 to +42
switch authorizationConfiguration.Type {
case "Basic":
return NewBasicAuthorizer(reader, prefix), nil
case "CEL":
if authorizationConfiguration.CEL == nil {
return nil, fmt.Errorf("CEL authorizer configuration missing")
}
return NewCELAuthorizer(reader, prefix, authorizationConfiguration.CEL.Expression)
default:
return nil, fmt.Errorf("unsupported authorizer type: %s", authorizationConfiguration.Type)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify CEL expression validity during initialization.

For the CEL authorizer type, it would be beneficial to validate the expression syntax during initialization to fail fast on invalid expressions.


🏁 Script executed:

#!/bin/bash
# Description: Search for CEL expression validation in the codebase.

# Test: Look for CEL expression validation in NewCELAuthorizer.
ast-grep --pattern $'func NewCELAuthorizer($_, $_, $expr string) ($_, error) {
  $$$
}'

# Test: Look for CEL expression validation in cel.go.
rg -A 5 'NewCELAuthorizer'

Length of output: 966


CEL expression validation: Additional check required during initialization

The current implementation calls NewCELAuthorizer with the provided CEL expression without performing any syntax checks. The verification confirms that neither the caller in internal/authorization/config.go nor the implementation in internal/authorization/cel.go includes an explicit validation step for the expression. To improve reliability and fail fast on misconfigurations, please add a validation routine (for example, leveraging the CEL parser) within NewCELAuthorizer before extending the environment.

  • File: internal/authorization/cel.go
    • Suggestion: Add a step to validate the expression parameter, ensuring it adheres to the expected CEL syntax.
  • File: internal/authorization/config.go
    • Observation: The switch case for the "CEL" type currently only checks for missing configuration (authorizationConfiguration.CEL == nil).

@NickCao NickCao closed this Mar 7, 2025
@mangelajo mangelajo added this to the 0.6.0 milestone May 8, 2025
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