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

🔨 Maintenance: Bringing openid-client lib to latest version #544

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

lelemm
Copy link
Contributor

@lelemm lelemm commented Jan 8, 2025

I MAY ( 🤭 ) have forgotten to update the library since ever. This brings it to the latest version of the library

@actual-github-bot actual-github-bot bot changed the title 🔨 Maintenance: Bringing openid-client lib to latest version [WIP] 🔨 Maintenance: Bringing openid-client lib to latest version Jan 8, 2025
@lelemm lelemm changed the title [WIP] 🔨 Maintenance: Bringing openid-client lib to latest version 🔨 Maintenance: Bringing openid-client lib to latest version Jan 8, 2025
Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

The pull request introduces a significant update to the OpenID client implementation in the project. The primary change involves upgrading the openid-client dependency from version 5.4.2 to 6.1.7 in the package.json file. Correspondingly, the src/accounts/openid.js file has undergone a comprehensive refactoring to align with the new library version.

The modifications include changing the import strategy for the OpenID client library, restructuring the client setup and authentication methods, and updating the approach to handling OpenID Connect flows. The changes impact how the OpenID client is instantiated, how authorization URLs are generated, how token exchanges are performed, and how user information is retrieved. The refactoring introduces a more modular and encapsulated approach to managing OpenID authentication, with updates to method signatures and the addition of utility functions for URL validation and server hostname detection.

Finishing Touches

  • 📝 Generate Docstrings

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.

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

🧹 Nitpick comments (1)
src/accounts/openid.js (1)

10-17: Unnecessary imports and global assignments in Node.js 18+

Since your package.json specifies Node.js version ">=18.0.0", the fetch API and the webcrypto module are globally available. Therefore, importing webcrypto from 'node:crypto' and fetch from 'node-fetch' is unnecessary. Additionally, the assignment of webcrypto to globalThis.crypto is redundant.

Apply this diff to remove the unnecessary imports and assignments:

- import { webcrypto } from 'node:crypto';
- import fetch from 'node-fetch';

  /* eslint-disable-next-line no-undef */
- if (!globalThis.crypto) {
-   /* eslint-disable-next-line no-undef */
-   globalThis.crypto = webcrypto;
- }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0637b1d and a460732.

⛔ Files ignored due to path filters (2)
  • upcoming-release-notes/544.md is excluded by !**/*.md
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (2)
  • package.json (1 hunks)
  • src/accounts/openid.js (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Docker image (alpine)
🔇 Additional comments (4)
src/accounts/openid.js (3)

Line range hint 263-268: Potential issue with user identification

The logic for determining the identity may fail if none of the user information fields are present. This could lead to authentication failures.

Please verify that the userinfo response will always contain at least one of the following fields: preferred_username, login, email, id, or name. If not, consider adding a default or handling this scenario appropriately.


127-138: Incorrect handling of GitHub user info

In the userinfo method, the condition checks for config.authMethod to determine whether to fetch user info from GitHub. Ensure that config.authMethod is set correctly and that this logic is intentional.

Please verify that config.authMethod can only be 'openid' or a value indicating GitHub authentication. If there are other authentication methods, the condition might skip necessary steps.


80-139: 🛠️ Refactor suggestion

Redundant custom client methods

The client object manually recreates methods (authorizationUrl, callback, grant, userinfo) that are already provided by the openid-client library's Client instance. This can lead to maintenance challenges and potential bugs.

Consider using the Client instance's built-in methods instead of defining custom ones. Here's how you can refactor the code:

- const client = {
-   redirect_uris: [
-     new URL('/openid/callback', config.server_hostname).toString(),
-   ],
-   authorizationUrl(params) {
-     const urlObj = openIdClient.buildAuthorizationUrl(discovered, {
-       ...params,
-       redirect_uri: this.redirect_uris[0],
-     });
-     return urlObj.href;
-   },
-   async callback(redirectUri, params, checks) {
-     // Custom implementation
-   },
-   async grant(grantParams) {
-     // Custom implementation
-   },
-   async userinfo(accessToken, sub = '') {
-     // Custom implementation
-   },
- };

- return client;

+ // With the Client instance returned from setupOpenIdClient, use its methods directly.
+ return client;

This refactor leverages the openid-client library's tested and maintained methods, reducing custom code and potential errors.

Likely invalid or redundant comment.

package.json (1)

41-41: ⚠️ Potential issue

Ensure compatibility with openid-client version 6

Upgrading openid-client from ^5.4.2 to ^6.1.7 introduces breaking changes. Version 6 includes significant updates and refactoring that may affect your codebase.

Please consult the openid-client migration guide to ensure all changes are appropriately addressed. Verify that all usages of openid-client methods in your code are updated to match the new API.

@@ -256,12 +329,11 @@ export async function loginWithOpenIdFinalize(body) {
} else if (error.message === 'openid-grant-failed') {
return { error: 'openid-grant-failed' };
} else {
throw error; // Re-throw other unexpected errors
throw error;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Unhandled exception may cause server crash

In the catch block, an error is re-thrown without proper handling. This could cause the server to crash if the exception is not caught elsewhere.

Consider handling the error gracefully and returning an appropriate response to the client.

          } else {
-           throw error;
+           console.error('An unexpected error occurred:', error);
+           return { error: 'unknown-error' };
          }
📝 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.

Suggested change
throw error;
} else {
console.error('An unexpected error occurred:', error);
return { error: 'unknown-error' };
}

Comment on lines +175 to +179
const state = openIdClient.randomState();
const code_verifier = openIdClient.randomPKCECodeVerifier();
const code_challenge = await openIdClient.calculatePKCECodeChallenge(
code_verifier,
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect usage of PKCE generation methods

The methods openIdClient.randomState(), openIdClient.randomPKCECodeVerifier(), and openIdClient.calculatePKCECodeChallenge() are not part of the openid-client library's public API in version 6.x. Instead, PKCE and state generation are handled using the generators module.

Update the code to use the generators provided by the library:

+ const { generators } = openIdClient;
+ const code_verifier = generators.codeVerifier();
+ const code_challenge = generators.codeChallenge(code_verifier);
+ const state = generators.state();

- const state = openIdClient.randomState();
- const code_verifier = openIdClient.randomPKCECodeVerifier();
- const code_challenge = await openIdClient.calculatePKCECodeChallenge(
-   code_verifier,
- );
📝 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.

Suggested change
const state = openIdClient.randomState();
const code_verifier = openIdClient.randomPKCECodeVerifier();
const code_challenge = await openIdClient.calculatePKCECodeChallenge(
code_verifier,
);
const { generators } = openIdClient;
const code_verifier = generators.codeVerifier();
const code_challenge = generators.codeChallenge(code_verifier);
const state = generators.state();

Comment on lines +258 to +261
state: body.state,
});
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect parameters in token exchange

When using the client.grant() method with the authorization_code grant type, the redirect_uri must be included in the parameters. Additionally, the state parameter is not typically included in this context.

Adjust the parameters as follows:

  tokenSet = await client.grant({
    grant_type: 'authorization_code',
    code: body.code,
+   redirect_uri: client.metadata.redirect_uris[0],
    code_verifier,
-   state: body.state,
  });

Ensure that the redirect_uri matches one of the registered URIs and that unnecessary parameters are removed.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +59 to +78
let discovered;
if (typeof config.issuer === 'string') {
discovered = await openIdClient.discovery(
new URL(config.issuer),
config.client_id,
config.client_secret,
);
} else {
const serverMetadata = {
issuer: config.issuer.name,
authorization_endpoint: config.issuer.authorization_endpoint,
token_endpoint: config.issuer.token_endpoint,
userinfo_endpoint: config.issuer.userinfo_endpoint,
};
discovered = new openIdClient.Configuration(
serverMetadata,
config.client_id,
config.client_secret,
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential misuse of openid-client methods

The methods openIdClient.discovery and new openIdClient.Configuration(...) do not align with the openid-client library's documented usage in version 6.x. Typically, you should use openIdClient.Issuer.discover() to discover the OpenID Provider's configuration and create a Client instance accordingly.

Consider revising the code to correctly utilize the openid-client library methods. Here's how you might adjust the implementation:

  async function setupOpenIdClient(config) {
-   let discovered;
-   if (typeof config.issuer === 'string') {
-     discovered = await openIdClient.discovery(
-       new URL(config.issuer),
-       config.client_id,
-       config.client_secret,
-     );
-   } else {
-     const serverMetadata = {
-       issuer: config.issuer.name,
-       authorization_endpoint: config.issuer.authorization_endpoint,
-       token_endpoint: config.issuer.token_endpoint,
-       userinfo_endpoint: config.issuer.userinfo_endpoint,
-     };
-     discovered = new openIdClient.Configuration(
-       serverMetadata,
-       config.client_id,
-       config.client_secret,
-     );
-   }

+   let issuer;
+   if (typeof config.issuer === 'string') {
+     issuer = await openIdClient.Issuer.discover(config.issuer);
+   } else {
+     issuer = new openIdClient.Issuer({
+       issuer: config.issuer.name,
+       authorization_endpoint: config.issuer.authorization_endpoint,
+       token_endpoint: config.issuer.token_endpoint,
+       userinfo_endpoint: config.issuer.userinfo_endpoint,
+     });
+   }

+   const client = new issuer.Client({
+     client_id: config.client_id,
+     client_secret: config.client_secret,
+     redirect_uris: [
+       new URL('/openid/callback', config.server_hostname).toString(),
+     ],
+     response_types: ['code'],
+   });

    // Replace the custom client object with the one provided by openid-client
+   return client;
  }

Committable suggestion skipped: line range outside the PR's diff.

if (!config.authMethod || config.authMethod === 'openid') {
return openIdClient.fetchUserInfo(discovered, accessToken, sub);
} else {
const response = await fetch('https://api.github.com/user', {
Copy link
Member

Choose a reason for hiding this comment

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

❓ question: ‏why are we connecting to GH api here? 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants