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

Ma/membercare fixes #1160

Merged
merged 2 commits into from
Dec 16, 2024
Merged

Ma/membercare fixes #1160

merged 2 commits into from
Dec 16, 2024

Conversation

markusahlstrand
Copy link

@markusahlstrand markusahlstrand commented Dec 16, 2024

Summary by CodeRabbit

  • New Features

    • Updated user identifier structure in responses from various authentication strategies (Apple, Facebook, Google OAuth2, Membercare).
    • Expanded OAuth2 authorization request scopes for Membercare.
    • Enhanced JWT parsing logic and user information handling in Membercare.
  • Bug Fixes

    • Improved error handling for invalid ID tokens across authentication strategies.
  • Documentation

    • Updated type signatures to reflect changes in user identification properties.

Copy link

coderabbitai bot commented Dec 16, 2024

Walkthrough

This pull request introduces a consistent change across multiple OAuth2 authentication strategy files, focusing on modifying the user information return structure. The primary modification involves replacing the id key with sub in the returned user object across different authentication providers (Apple, Facebook, Google OAuth2, and Membercare). Additionally, the Membercare strategy includes expanded OAuth2 scopes and more complex user information parsing. These changes aim to standardize the user identification representation across different authentication strategies.

Changes

File Change Summary
src/strategies/apple.ts Replaced id with sub in validateAuthorizationCodeAndGetUser return object
src/strategies/facebook.ts Renamed id property to sub in returned user object
src/strategies/google-oauth2.ts Changed return object from id: payload.sub to sub: payload.sub
src/strategies/index.ts Updated UserInfo type from id: string to sub: string
src/strategies/membercare.ts Significant changes including:
- Expanded OAuth2 scopes
- Modified JWT payload checks
- Updated user info retrieval
- Renamed id to sub
- Changed email handling

Sequence Diagram

sequenceDiagram
    participant Client
    participant AuthProvider
    participant Strategy
    participant UserService

    Client->>Strategy: Request Authorization
    Strategy->>AuthProvider: Get Authorization Code
    AuthProvider-->>Strategy: Return Authorization Code
    Strategy->>AuthProvider: Validate Code
    AuthProvider-->>Strategy: Return ID Token
    Strategy->>Strategy: Parse Token
    Strategy->>UserService: Return User Info with 'sub'
    UserService-->>Client: Authenticate User
Loading

Possibly related PRs

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request.


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

@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: 3

🔭 Outside diff range comments (1)
src/strategies/apple.ts (1)

All OAuth2 strategies consistently use sub for user identification, but test fixtures need updating

The verification shows that all OAuth2 strategies (Apple, Google, Facebook, Membercare) have been properly updated to use sub instead of id. However, there's one remaining instance of id usage in test fixtures that should be updated for consistency:

  • test/fixtures/oauth2Client.ts: The mock response still uses id instead of sub
🔗 Analysis chain

Line range hint 94-101: LGTM! The change standardizes user identification across OAuth2 providers.

The replacement of id with sub aligns with OAuth2/OIDC standards and maintains consistency with other authentication strategies.

Let's verify the consistency of this change across other OAuth2 strategies:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all OAuth2 strategies use 'sub' instead of 'id'

# Search for OAuth2-related files and check their return structures
echo "Checking OAuth2 strategy implementations..."
fd -e ts -e js --full-path "src/strategies" --exec rg -A 5 -B 5 "validateAuthorizationCodeAndGetUser|return \{|sub:|id:"

# Specifically check for any remaining uses of 'id:' in return objects
echo "Checking for any remaining 'id:' usage in return objects..."
ast-grep --pattern 'return {
  id: $_,
  $$$
}'

Length of output: 4551

🧹 Nitpick comments (1)
src/strategies/membercare.ts (1)

220-220: Sanitize 'DebtorAccountNumber' When Constructing URLs

When constructing userInfoUrl.pathname using accessToken.payload["Membercare.Security.DebtorAccountNumber"], ensure that the value is sanitized to prevent injection attacks or malformed URLs. Even if the value comes from a trusted source, it's good practice to validate and encode dynamic URL segments.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d9f072 and 0ae32ce.

📒 Files selected for processing (5)
  • src/strategies/apple.ts (1 hunks)
  • src/strategies/facebook.ts (1 hunks)
  • src/strategies/google-oauth2.ts (1 hunks)
  • src/strategies/index.ts (1 hunks)
  • src/strategies/membercare.ts (4 hunks)
🔇 Additional comments (4)
src/strategies/membercare.ts (1)

188-190: Validate Access to 'Membercare.Security.DebtorAccountNumber'

Ensure that the property Membercare.Security.DebtorAccountNumber reliably exists in accessToken.payload. Accessing properties with dots in their keys can be error-prone if the payload structure changes or if the property is missing. Consider adding a check to confirm this property is present and properly formatted.

src/strategies/index.ts (1)

10-10: Verify All References to 'UserInfo.id' Are Updated to 'sub'

The UserInfo type now uses sub instead of id. Ensure that all references to UserInfo.id in the codebase are updated to UserInfo.sub to prevent runtime errors or undefined property access.

Run the following script to identify any remaining references to UserInfo.id:

✅ Verification successful

No References to UserInfo.id Found - Change is Safe

The codebase scan shows that there are no occurrences of UserInfo.id. The only references to UserInfo are its type definition and usage as a return type, where it's correctly defined with sub as the identifier property. This confirms that no updates are needed elsewhere in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all occurrences of 'UserInfo.id'

rg --type=typescript 'UserInfo\.id' -A 3 -B 3

Length of output: 82


Script:

#!/bin/bash
# Search for UserInfo.id pattern in all files, focusing on common extensions for TypeScript/JavaScript
rg 'UserInfo\.id' -g '*.{ts,tsx,js,jsx}' -A 3 -B 3

# Also search for any usage of UserInfo type to understand the context
rg 'UserInfo' -g '*.{ts,tsx,js,jsx}' -A 3 -B 3

# Use ast-grep to find type definitions and interfaces related to UserInfo
ast-grep --pattern 'interface UserInfo {
  $$$
}'

ast-grep --pattern 'type UserInfo = {
  $$$
}'

Length of output: 1186

src/strategies/facebook.ts (1)

65-65: Ensure Consumers Expect 'sub' Instead of 'id'

The return value now uses sub instead of id. Confirm that all parts of the codebase consuming this function are updated to expect sub, avoiding potential issues with undefined properties.

Run the following script to find usages of id in relation to the Facebook strategy:

✅ Verification successful

No Issues Found - Consumers Already Expect 'sub' Property

The codebase analysis shows that the consumers are already using the sub property, not id. Specifically, in src/authentication-flows/oauth2.tsx, the code destructures sub from the userinfo object: const { sub, email, ...profileData } = userinfo. This indicates that the codebase is already aligned with the Facebook strategy's return value using sub.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find code that accesses 'id' from the Facebook strategy's return value

rg --type=typescript 'facebook\.validateAuthorizationCodeAndGetUser.*\.id' -A 3 -B 3

Length of output: 121


Script:

#!/bin/bash
# Search for files containing 'facebook' and 'validateAuthorizationCodeAndGetUser'
rg -l "validateAuthorizationCodeAndGetUser.*facebook" 

# Search for usage of the function and surrounding context
rg "validateAuthorizationCodeAndGetUser" -A 5 -B 5

# Look for any destructuring or usage of 'id' or 'sub' properties
ast-grep --pattern 'const { $$$, id, $$$} = $_' 
ast-grep --pattern 'const { $$$, sub, $$$} = $_'

Length of output: 3836

src/strategies/google-oauth2.ts (1)

69-69: Update Codebase to Use 'sub' Instead of 'id' for User Identification

The return object now includes sub instead of id. Ensure that all functions and components that use this user information are updated accordingly to prevent inconsistencies and errors.

Run the following script to locate any references to id from the Google OAuth2 strategy:

@@ -141,7 +141,7 @@ export async function getRedirect(
const authorizationUrl = oauth2.createAuthorizationURL(
options.authorization_endpoint,
code,
["openid"],
["openid profile usermc"],
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure Additional OAuth2 Scopes Are Necessary

The OAuth2 scopes have been expanded from ["openid"] to ["openid profile usermc"]. Verify that requesting the profile and usermc scopes is required for the application's functionality. Unnecessary scopes may lead to excessive permissions and potential privacy concerns.

Comment on lines +252 to +256
sub: debtor.debtorAccountNumber,
email: debtor.contacts[0].value,
given_name: debtor.firstname,
family_name: debtor.lastname,
name: debtor.name,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Safely Access 'contacts' When Retrieving Email

In the return statement, you're accessing debtor.contacts[0].value to get the email. Ensure that debtor.contacts is not empty to prevent errors. Consider providing a fallback or handling the case where no contacts are available.

Apply this diff to safely extract the email:

return {
  sub: debtor.debtorAccountNumber,
- email: debtor.contacts[0].value,
+ email: debtor.contacts.length > 0 ? debtor.contacts[0].value : undefined,
  given_name: debtor.firstname,
  family_name: debtor.lastname,
  name: debtor.name,
};
📝 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
sub: debtor.debtorAccountNumber,
email: debtor.contacts[0].value,
given_name: debtor.firstname,
family_name: debtor.lastname,
name: debtor.name,
sub: debtor.debtorAccountNumber,
email: debtor.contacts.length > 0 ? debtor.contacts[0].value : undefined,
given_name: debtor.firstname,
family_name: debtor.lastname,
name: debtor.name,

Comment on lines +241 to +247
name: z.string().optional(),
debtorAccountNumber: z.string(),
contacts: z.array(
z.object({
value: z.string(),
}),
),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle Empty 'contacts' Array to Prevent Runtime Errors

When parsing debtor.contacts, ensure that the array is not empty before accessing its elements. Attempting to access debtor.contacts[0] without checking can result in a runtime error if the array is empty.

Apply this diff to add validation:

const debtor = z
  .object({
    firstname: z.string().optional(),
    lastname: z.string().optional(),
    name: z.string().optional(),
    debtorAccountNumber: z.string(),
    contacts: z.array(
      z.object({
        value: z.string(),
      }),
    ),
  })
  .parse(debtorBody);

+ if (debtor.contacts.length === 0) {
+   throw new Error("No contacts available for debtor");
+ }

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

@markusahlstrand markusahlstrand merged commit 68aa440 into main Dec 16, 2024
2 checks passed
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