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

implemented OAuth client credentials flow #2690

Merged
merged 5 commits into from
Nov 3, 2024

Conversation

imolorhe
Copy link
Collaborator

@imolorhe imolorhe commented Nov 2, 2024

Fixes

Closes #2680

Checks

  • Ran yarn test-build
  • Updated relevant documentations
  • Updated matching config options in altair-static

Changes proposed in this pull request:

Summary by Sourcery

Implement the OAuth2 client credentials flow in the OAuth2Client class, enabling access token retrieval using client credentials. Enhance the client to support various authentication and request formats, and add tests to ensure functionality across different scenarios.

New Features:

  • Implement OAuth2 client credentials flow in the OAuth2Client class, allowing retrieval of access tokens using client credentials.

Enhancements:

  • Add support for different authentication and request formats in the OAuth2Client, including basic auth and JSON or form-encoded requests.

Tests:

  • Introduce comprehensive tests for the OAuth2 client credentials flow, including scenarios for different authentication and request formats.

Copy link

sourcery-ai bot commented Nov 2, 2024

Reviewer's Guide by Sourcery

This PR implements the OAuth2 Client Credentials flow, adding support for this authentication method alongside the existing Authorization Code flow. The implementation includes new configuration options for authentication and request formats, with comprehensive test coverage.

Sequence diagram for OAuth2 Client Credentials flow

sequenceDiagram
    participant Client as OAuth2Client
    participant AuthServer as Authorization Server
    Client->>AuthServer: POST /oauth/token (grant_type: client_credentials)
    AuthServer-->>Client: 200 OK (access_token, refresh_token, expires_in, token_type)
Loading

Updated class diagram for OAuth2Client

classDiagram
    class OAuth2Client {
        -OAuth2ClientOptions options
        +getAuthorizationUrl() Promise~string~
        +getAuthorizationRedirectResponse() Promise~AuthorizationRedirectResponse|AuthorizationRedirectErrorResponse|undefined~
        +getAccessTokenFromCode(code: string) Promise~AccessTokenResponse|AccessTokenErrorResponse~
        +getAccessTokenFromClientCredentials() Promise~AccessTokenResponse|AccessTokenErrorResponse~
        -getAccessTokenRequestHeaders() HeadersInit
        -getAccessTokenRequestBody(params: AccessTokenRequest) BodyInit
        -makeAccessTokenRequest(params: AccessTokenRequest) Promise~AccessTokenResponse|AccessTokenErrorResponse~
    }
    class OAuth2ClientOptions {
        <<interface>>
        +string[] scopes
        +AuthFormat authFormat
        +RequestFormat requestFormat
    }
    class AuthorizationCode_OAuth2ClientOptions {
        <<interface>>
        +OAuth2Type type
        +string clientId
        +string clientSecret
        +string redirectUri
        +string state
        +string authorizationEndpoint
        +string tokenEndpoint
    }
    class AuthorizationCodePKCE_OAuth2ClientOptions {
        <<interface>>
        +OAuth2Type type
        +string codeVerifier
    }
    class ClientCredentials_OAuth2ClientOptions {
        <<interface>>
        +OAuth2Type type
        +string clientId
        +string clientSecret
        +string tokenEndpoint
    }
    OAuth2ClientOptions <|-- AuthorizationCode_OAuth2ClientOptions
    OAuth2ClientOptions <|-- AuthorizationCodePKCE_OAuth2ClientOptions
    OAuth2ClientOptions <|-- ClientCredentials_OAuth2ClientOptions
    OAuth2Client o-- OAuth2ClientOptions
Loading

File-Level Changes

Change Details Files
Added OAuth2 Client Credentials flow implementation
  • Added new OAuth2Type enum value for CLIENT_CREDENTIALS
  • Implemented getAccessTokenFromClientCredentials method
  • Added validation to prevent using authorization-specific methods with client credentials flow
  • Updated UI to conditionally show relevant fields based on selected OAuth2 type
packages/altair-core/src/oauth2/client.ts
packages/altair-core/src/oauth2/types.ts
packages/altair-app/src/app/modules/altair/components/authorization/authorization-oauth2/authorization-oauth2.component.ts
packages/altair-app/src/app/modules/altair/components/authorization/authorization-oauth2/authorization-oauth2.component.html
Added configurable authentication and request format options
  • Added AuthFormat enum for Basic Auth and Body authentication methods
  • Added RequestFormat enum for JSON and Form encoded request formats
  • Implemented dynamic header and body generation based on format settings
  • Added UI controls for selecting auth and request formats
packages/altair-core/src/oauth2/types.ts
packages/altair-core/src/oauth2/client.ts
packages/altair-app/src/app/modules/altair/components/authorization/authorization-oauth2/authorization-oauth2.component.html
Enhanced test infrastructure and coverage
  • Added MswMockRequestHandler for testing HTTP requests
  • Added tests for different auth and request format combinations
  • Added tests for client credentials flow
  • Set up test environment with location mock
packages/altair-core/src/test-helpers.ts
packages/altair-core/src/oauth2/client.spec.ts
packages/altair-core/jest.setup.js

Assessment against linked issues

Issue Objective Addressed Explanation
#2680 Add support for OAuth 2.0 Client Credentials flow authentication
#2680 Allow configuration of Client ID, Client Secret, Token URL and Scope for Client Credentials flow

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @imolorhe - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Use a more secure base64 encoding method for handling non-ASCII characters in credentials (link)
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🔴 Security: 1 blocking issue
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

const headers: HeadersInit = {};
switch (this.options.authFormat) {
case AuthFormat.BASIC_AUTH: {
headers.Authorization = `Basic ${btoa(
Copy link

Choose a reason for hiding this comment

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

🚨 issue (security): Use a more secure base64 encoding method for handling non-ASCII characters in credentials

btoa() fails with non-ASCII characters. Consider using TextEncoder and Buffer.from().toString('base64') or a similar UTF-8 safe approach.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@sourcery-ai review


private async makeAccessTokenRequest(
params: AccessTokenRequest
): Promise<AccessTokenResponse | AccessTokenErrorResponse> {
const response = await fetch(this.options.tokenEndpoint, {
Copy link

Choose a reason for hiding this comment

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

issue: Add explicit error handling for network failures in token requests

Wrap the fetch call in a try-catch block and provide specific error handling for network failures, timeouts, and non-JSON responses.

}

private getAccessTokenRequestBody(params: AccessTokenRequest): BodyInit {
let bodyParams: Partial<AccessTokenRequest> = structuredClone(params);
Copy link

Choose a reason for hiding this comment

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

suggestion (performance): Replace structuredClone with Object.assign for better performance

Since we're only dealing with a shallow object structure, using Object.assign({}, params) would be more efficient than a deep clone.

Suggested change
let bodyParams: Partial<AccessTokenRequest> = structuredClone(params);
let bodyParams: Partial<AccessTokenRequest> = Object.assign({}, params);

Copy link

github-actions bot commented Nov 2, 2024

Visit the preview URL for this PR (updated for commit 60bcbeb):

https://altair-gql--pr2690-imolorhe-oauth2-clie-ayj24hxn.web.app

(expires Sun, 10 Nov 2024 07:29:05 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 02d6323d75a99e532a38922862e269d63351a6cf

@imolorhe imolorhe added this pull request to the merge queue Nov 3, 2024
Merged via the queue into master with commit 58948c0 Nov 3, 2024
14 checks passed
@imolorhe imolorhe deleted the imolorhe/oauth2-client-credentials-flow branch November 3, 2024 09:01
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.

Add support for Client Credentials flow
1 participant