Skip to content

Fix missing methods in interfaces - #13

Merged
evgenyk merged 3 commits into
mainfrom
ev/fixing_interfaces
Jul 24, 2025
Merged

Fix missing methods in interfaces#13
evgenyk merged 3 commits into
mainfrom
ev/fixing_interfaces

Conversation

@evgenyk

@evgenyk evgenyk commented Jul 24, 2025

Copy link
Copy Markdown
Contributor

Add necessary methods to the IAuthorizationCodeFlow and IDeviceAuthorizationFlow interfaces, ensuring proper functionality for device authorization and token management. Clean up redundant code and improve overall structure.

@coderabbitai

coderabbitai Bot commented Jul 24, 2025

Copy link
Copy Markdown

Walkthrough

The changes refactor option configuration patterns in both the authorization_code and client_credentials OAuth2 flows. Option functions are moved to dedicated files, and a consistent Option type alias is introduced. Interfaces and structs in the authorization code flow are expanded with new methods for device authorization and HTTP callback handling, while duplicated or misplaced methods are removed or consolidated. Additionally, a spelling correction is applied to a JWT token validation function and its test usages.

Changes

File(s) Change Summary
oauth2/authorization_code/authorization_code.go Added new methods to AuthorizationCodeFlow for device auth, HTTP callback handling, and HTTP client retrieval. Updated interfaces. Removed redundant methods and option type alias.
oauth2/authorization_code/options.go Added Option type alias and updated all option functions to use it. Removed HTTP handler and flow methods, focusing file on configuration only. Removed unused imports.
oauth2/client_credentials/client_credentials.go Removed all option-related functions and the Option type alias. Removed related imports. Option logic moved to a new file.
oauth2/client_credentials/options.go New file. Introduced Option type alias and defined option functions for configuring client credentials flow, including audience and token validation options.
jwt/jwt_options.go Corrected spelling of function name from WillValidateAlgorythm to WillValidateAlgorithm.
jwt/jwt_test.go Updated test code to use corrected WillValidateAlgorithm function name.
oauth2/authorization_code/authorization_code_test.go Updated test code to use corrected WillValidateAlgorithm function name.
oauth2/client_credentials/client_credentials_test.go Updated test code to use corrected WillValidateAlgorithm function name.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Browser
    participant AuthorizationCodeFlow
    participant OAuth2Provider

    User->>Browser: Initiate login
    Browser->>AuthorizationCodeFlow: Request Auth URL
    AuthorizationCodeFlow->>Browser: Respond with Auth URL
    Browser->>OAuth2Provider: Redirect with Auth URL
    OAuth2Provider->>Browser: Redirect with Auth Code
    Browser->>AuthorizationCodeFlow: Send Auth Code (callback)
    AuthorizationCodeFlow->>AuthorizationCodeFlow: AuthorizationCodeReceivedHandler
    AuthorizationCodeFlow->>OAuth2Provider: Exchange code for token
    OAuth2Provider->>AuthorizationCodeFlow: Return token
    AuthorizationCodeFlow->>AuthorizationCodeFlow: Parse/validate token, store in session
Loading
sequenceDiagram
    participant Device
    participant AuthorizationCodeFlow
    participant OAuth2Provider

    Device->>AuthorizationCodeFlow: StartDeviceAuth
    AuthorizationCodeFlow->>OAuth2Provider: DeviceAuth request
    OAuth2Provider->>AuthorizationCodeFlow: DeviceAuth response
    AuthorizationCodeFlow->>Device: Respond with device code info
    Device->>OAuth2Provider: Poll for token
    OAuth2Provider->>Device: Return token (after user authorizes)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–25 minutes

Possibly related PRs

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ev/fixing_interfaces

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 generate unit tests to generate unit tests for 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (8)
oauth2/client_credentials/options.go (2)

11-13: Remove unnecessary parentheses around single type definition

The parentheses are not needed when defining a single type.

-type (
-	Option func(*ClientCredentialsFlow)
-)
+type Option func(*ClientCredentialsFlow)

26-31: Fix incorrect comment

The comment is copied from WithAuthParameter and doesn't accurately describe this function.

-// Adds an arbitrary parameter to the list of parameters to request.
+// Adds an audience to the list of audiences to request.
func WithAudience(audience string) Option {
oauth2/authorization_code/authorization_code.go (2)

34-51: Consider extracting common methods into a base interface

Both IAuthorizationCodeFlow and IDeviceAuthorizationFlow share several methods. Consider creating a base interface to reduce duplication and ensure consistency.

+type IBaseFlow interface {
+	GetHttpClient(ctx context.Context, tokenSource oauth2.TokenSource) *http.Client
+	GetToken() (*jwt.Token, error)
+	IsAuthenticated() bool
+	Logout() error
+}
+
 type IAuthorizationCodeFlow interface {
+	IBaseFlow
 	GetAuthURL() string
 	ExchangeCode(ctx context.Context, authorizationCode string, receivedState string) error
-	GetHttpClient(ctx context.Context, tokenSource oauth2.TokenSource) *http.Client
-	GetToken() (*jwt.Token, error)
-	IsAuthenticated() bool
-	Logout() error
 	AuthorizationCodeReceivedHandler(w http.ResponseWriter, r *http.Request)
 }

 type IDeviceAuthorizationFlow interface {
+	IBaseFlow
 	StartDeviceAuth(ctx context.Context) (*oauth2.DeviceAuthResponse, error)
 	ExchangeDeviceAccessToken(ctx context.Context, da *oauth2.DeviceAuthResponse, opts ...oauth2.AuthCodeOption) error
-	GetHttpClient(ctx context.Context, tokenSource oauth2.TokenSource) *http.Client
-	GetToken() (*jwt.Token, error)
-	IsAuthenticated() bool
-	Logout() error
 }

259-259: Fix typo in comment

-// Returns the client to make requests to the backend, will refreesh token if offline is requested.
+// Returns the client to make requests to the backend, will refresh token if offline is requested.
oauth2/authorization_code/options.go (4)

9-11: Remove unnecessary parentheses around single type definition

For consistency with Go conventions and the suggestion in client_credentials/options.go.

-type (
-	Option func(*AuthorizationCodeFlow)
-)
+type Option func(*AuthorizationCodeFlow)

34-34: Fix incorrect comment

The comment doesn't match the function purpose.

-// Adds an audience to the list of audiences to request.
+// Sets the prompt parameter for the authorization request.

48-48: Fix incorrect comment

The comment doesn't match the function purpose.

-// Adds the offline scope to the list of scopes to request.
+// Sets a custom state generator function.

62-62: Fix incorrect comments

These comments are copied from WithSessionHooks and don't describe the actual functions.

-// Integrates with the session management
+// Sets the client ID for the OAuth2 configuration.
 func WithClientID(clientID string) Option {

-// Integrates with the session management
+// Sets the client secret for the OAuth2 configuration.
 func WithClientSecret(clientSecret string) Option {

Also applies to: 69-69

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d65de7c and 191503a.

📒 Files selected for processing (4)
  • oauth2/authorization_code/authorization_code.go (3 hunks)
  • oauth2/authorization_code/options.go (2 hunks)
  • oauth2/client_credentials/client_credentials.go (0 hunks)
  • oauth2/client_credentials/options.go (1 hunks)
💤 Files with no reviewable changes (1)
  • oauth2/client_credentials/client_credentials.go
🔇 Additional comments (3)
oauth2/client_credentials/options.go (2)

15-24: LGTM!

The implementation correctly handles both existing and new parameters in the EndpointParams map.


59-69: LGTM!

The token validation configuration is implemented correctly with proper conditional JWKS validation.

oauth2/authorization_code/authorization_code.go (1)

123-128: LGTM!

The device authorization implementation is clean and follows the OAuth2 pattern correctly.

Comment thread oauth2/authorization_code/authorization_code.go
Comment thread oauth2/authorization_code/authorization_code.go
Comment thread oauth2/client_credentials/options.go
Comment thread oauth2/client_credentials/options.go Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
oauth2/authorization_code/authorization_code.go (2)

134-134: Handle potential URL parsing error

The error from url.Parse is ignored, which could lead to runtime issues.

 state := flow.stateGenerator(flow)
-url, _ := url.Parse(flow.config.AuthCodeURL(state))
+parsedURL, err := url.Parse(flow.config.AuthCodeURL(state))
+if err != nil {
+	// AuthCodeURL should always return a valid URL, but handle error defensively
+	return flow.config.AuthCodeURL(state)
+}
+url := parsedURL

145-166: Fix remaining critical issues in authorization callback handler

While the authorization code extraction has been fixed, critical issues remain:

  1. Missing return statements after error responses (lines 151, 161)
  2. No handling of invalid state parameter case
  3. Potential for continued execution after errors
func (flow *AuthorizationCodeFlow) AuthorizationCodeReceivedHandler(w http.ResponseWriter, r *http.Request) {
	receivedState := r.URL.Query().Get("state")
	if flow.stateVerifier(flow, receivedState) {
		token, err := flow.config.Exchange(r.Context(), r.URL.Query().Get("code"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
+			return
		}
		parsedToken, err := jwt.ParseOAuth2Token(token, flow.tokenOptions...)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if parsedToken.IsValid() {
			stringToken, err := parsedToken.AsString()
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
+				return
			}
			flow.sessionHooks.SetToken(RawToken, stringToken)
		}
+	} else {
+		http.Error(w, "Invalid state parameter", http.StatusBadRequest)
	}
}
🧹 Nitpick comments (1)
oauth2/authorization_code/authorization_code.go (1)

34-51: Consider interface composition to reduce duplication.

Both IAuthorizationCodeFlow and IDeviceAuthorizationFlow share several identical methods (GetHttpClient, GetToken, IsAuthenticated, Logout). Consider extracting these common methods into a base interface to improve maintainability and reduce duplication.

+type ITokenFlow interface {
+	GetHttpClient(ctx context.Context, tokenSource oauth2.TokenSource) *http.Client
+	GetToken() (*jwt.Token, error)
+	IsAuthenticated() bool
+	Logout() error
+}

type IAuthorizationCodeFlow interface {
+	ITokenFlow
	GetAuthURL() string
	ExchangeCode(ctx context.Context, authorizationCode string, receivedState string) error
-	GetHttpClient(ctx context.Context, tokenSource oauth2.TokenSource) *http.Client
-	GetToken() (*jwt.Token, error)
-	IsAuthenticated() bool
-	Logout() error
	AuthorizationCodeReceivedHandler(w http.ResponseWriter, r *http.Request)
}

type IDeviceAuthorizationFlow interface {
+	ITokenFlow
	StartDeviceAuth(ctx context.Context) (*oauth2.DeviceAuthResponse, error)
	ExchangeDeviceAccessToken(ctx context.Context, da *oauth2.DeviceAuthResponse, opts ...oauth2.AuthCodeOption) error
-	GetHttpClient(ctx context.Context, tokenSource oauth2.TokenSource) *http.Client
-	GetToken() (*jwt.Token, error)
-	IsAuthenticated() bool
-	Logout() error
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 191503a and 81cde9f.

📒 Files selected for processing (6)
  • jwt/jwt_options.go (1 hunks)
  • jwt/jwt_test.go (2 hunks)
  • oauth2/authorization_code/authorization_code.go (3 hunks)
  • oauth2/authorization_code/authorization_code_test.go (2 hunks)
  • oauth2/client_credentials/client_credentials_test.go (1 hunks)
  • oauth2/client_credentials/options.go (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • jwt/jwt_test.go
  • oauth2/client_credentials/client_credentials_test.go
  • jwt/jwt_options.go
  • oauth2/authorization_code/authorization_code_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • oauth2/client_credentials/options.go
🔇 Additional comments (2)
oauth2/authorization_code/authorization_code.go (2)

123-128: LGTM!

Clean implementation that properly delegates to the OAuth2 config's DeviceAuth method with appropriate error handling.


259-262: LGTM!

Clean wrapper implementation that properly delegates to the OAuth2 library's NewClient function.

@evgenyk
evgenyk merged commit b255588 into main Jul 24, 2025
4 checks passed
@evgenyk
evgenyk deleted the ev/fixing_interfaces branch August 1, 2025 13:11
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.

1 participant