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

feat(ids-api): Default scopes for clients #16476

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open

Conversation

magnearun
Copy link
Contributor

@magnearun magnearun commented Oct 18, 2024

What

Adds phone, email and address as default scopes when creating clients

Adds migration that inserts these default scopes for existing clients

Why

These scopes should be granted by default

Screenshots / Gifs

Attach Screenshots / Gifs to help reviewers understand the scope of the pull request

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features
    • Introduced default scopes ('email', 'address', 'phone') for specific client types, enhancing client scope management.
    • Expanded scope assignments for web and native client types in the admin service.

@magnearun magnearun marked this pull request as ready for review October 18, 2024 15:55
@magnearun magnearun requested a review from a team as a code owner October 18, 2024 15:55
@magnearun magnearun requested a review from a team as a code owner October 18, 2024 15:55
Copy link
Contributor

coderabbitai bot commented Oct 18, 2024

Walkthrough

This pull request introduces a migration that adds default scopes to the client_allowed_scope table for specific client types in the database. The migration checks for existing client scopes and performs a bulk insert of new default scopes if necessary. Additionally, it modifies the defaultClientScopes method in the AdminClientsService class to include additional scopes ('email', 'phone', 'address') for web and native client types.

Changes

File Change Summary
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js Added up and down methods for migration, implementing logic to insert default scopes for specific client types.
libs/auth-api-lib/src/lib/clients/admin/admin-clients.service.ts Updated defaultClientScopes method to include additional scopes ('email', 'phone', 'address') for web and native clients.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • Herdismaria
  • oskarjs

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 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.

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

🧹 Outside diff range and nitpick comments (2)
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js (2)

1-1: Remove redundant 'use strict' directive

The 'use strict' directive is unnecessary in JavaScript modules as they are automatically in strict mode. Consider removing this line to adhere to modern JavaScript best practices.

Apply this change:

-'use strict';
🧰 Tools
🪛 Biome

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


35-40: Consider implementing a rollback method

While it may not be necessary to remove the default scopes, it's generally a good practice to provide rollback functionality in migrations. This allows for more flexibility in managing database states and can be crucial for testing or recovering from failed deployments.

Consider implementing a down method that removes the default scopes added by this migration. Here's a potential implementation:

async down (queryInterface, Sequelize) {
  const defaultScopes = ['email', 'address', 'phone'];
  const clients = await queryInterface.sequelize.query(
    'SELECT "client_id" FROM "client" WHERE "client_type" IN (:clientTypes);',
    {
      type: queryInterface.sequelize.QueryTypes.SELECT,
      replacements: { clientTypes: ['web', 'native', 'spa'] }
    }
  );
  const clientIds = clients.map(client => client.client_id);

  if (clientIds.length) {
    await queryInterface.sequelize.query(
      'DELETE FROM "client_allowed_scope" WHERE "client_id" IN (:clientIds) AND "scope_name" IN (:scopes)',
      {
        replacements: { clientIds, scopes: defaultScopes }
      }
    );
  }
}

This implementation would remove the default scopes added by the up method, providing a way to revert the changes if necessary.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 52288e6 and a2ea02c.

📒 Files selected for processing (2)
  • libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js (1 hunks)
  • libs/auth-api-lib/src/lib/clients/admin/admin-clients.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/auth-api-lib/src/lib/clients/admin/admin-clients.service.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (3)
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js (2)

12-17: LGTM: Efficient retrieval of existing scopes

The query to fetch existing scopes is well-structured and uses parameterized input. The use of a Set for lookup is an efficient approach for checking existing scopes.


32-32: LGTM: Efficient bulk insert of new scopes

The use of bulkInsert is an efficient way to insert multiple rows at once. This approach is suitable for potentially large datasets and helps minimize database round-trips.

libs/auth-api-lib/src/lib/clients/admin/admin-clients.service.ts (1)

634-646: Approve changes with suggestions for improvement

The implementation correctly adds the new default scopes (email, phone, and address) for web and native client types, aligning with the PR objectives. However, consider the following improvements:

  1. Fix the indentation of the new code block to match the rest of the file.
  2. Add a comment explaining the rationale behind adding these specific scopes by default.

Here's a suggested revision with improved formatting and a comment:

 switch (client.clientType) {
   case ClientType.web:
   case ClientType.native:
-        scopes.push(...[{
-          clientId: client.clientId,
-          scopeName: 'profile',
-        }, {
-          clientId: client.clientId,
-          scopeName: 'email',
-        }, {
-          clientId: client.clientId,
-          scopeName: 'phone',
-        }, {
-          clientId: client.clientId,
-          scopeName: 'address',
-        }])
+        // Add default scopes for web and native clients to ensure
+        // access to essential user information
+        scopes.push(
+          ...[
+            { clientId: client.clientId, scopeName: 'profile' },
+            { clientId: client.clientId, scopeName: 'email' },
+            { clientId: client.clientId, scopeName: 'phone' },
+            { clientId: client.clientId, scopeName: 'address' },
+          ]
+        )
 }

Is a database migration planned to add these new default scopes for existing web and native clients? If not, consider creating one to ensure consistency across all clients.

Comment on lines 5 to 10
const clients = await queryInterface.sequelize.query(`SELECT "client_id" FROM "client" WHERE "client_type" IN ('web', 'native', 'spa');`, { type: queryInterface.sequelize.QueryTypes.SELECT });
const clientIds = clients.map(client => client.client_id);

if (!clientIds.length) {
return;
}
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

Consider using parameterized query for better security

While the current query is not directly vulnerable to SQL injection (as it doesn't use user input), it's a good practice to use parameterized queries consistently. Consider refactoring to use query parameters.

Here's a suggested refactoring:

const clients = await queryInterface.sequelize.query(
  'SELECT "client_id" FROM "client" WHERE "client_type" IN (:clientTypes);',
  {
    type: queryInterface.sequelize.QueryTypes.SELECT,
    replacements: { clientTypes: ['web', 'native', 'spa'] }
  }
);

This approach is more secure and consistent with best practices for database queries.

Comment on lines 19 to 30
const rows = [];
const defaultScopes = ['email', 'address', 'phone']

for (const clientId of clientIds) {
rows.push(...defaultScopes.filter((scope => {
return !existingScopesLookup.has(`${clientId}-${scope}`);
})).map(scope => ({ client_id: clientId, scope_name: scope })));
}

if (!rows.length) {
return;
}
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

Consider extracting default scopes to a constant

The default scopes array is defined within the method. For better maintainability and potential reuse, consider extracting it to a constant at the module level.

Apply this change at the top of the file:

const DEFAULT_SCOPES = ['email', 'address', 'phone'];

module.exports = {
  async up(queryInterface, Sequelize) {
    // ... existing code ...
    
    // Replace line 20 with:
    // const defaultScopes = DEFAULT_SCOPES;
    
    // ... rest of the code ...
  },
  // ... down method ...
};

This change improves code readability and makes it easier to update default scopes in the future if needed.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 18, 2024

Datadog Report

All test runs 4f8823e 🔗

9 Total Test Services: 0 Failed, 9 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.01%), 1 increased (+0.19%), 16 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.95s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 13.3s 1 no change Link
application-system-api 0 0 0 120 2 3m 21.53s 1 no change Link
application-template-api-modules 0 0 0 123 0 2m 41.61s 1 decreased (-0.01%) Link
auth-api-lib 0 0 0 20 0 28.81s 1 no change Link
services-auth-admin-api 0 0 0 130 0 3m 47.85s 1 no change Link
services-auth-delegation-api 0 0 0 256 0 3m 19.35s 1 increased (+0.19%) Link
services-auth-ids-api 0 0 0 121 0 0s N/A Link
services-auth-personal-representative 0 0 0 59 0 1m 28.06s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • application-template-api-modules - jest 30.04% (-0.01%) - Details

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

🧹 Outside diff range and nitpick comments (1)
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js (1)

1-3: Remove redundant 'use strict' directive

The 'use strict' directive on line 1 is redundant in ES modules, as they are always in strict mode. Consider removing this line to improve code cleanliness.

Apply this change:

-'use strict'

 module.exports = {
🧰 Tools
🪛 Biome

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a2ea02c and 6431c0b.

📒 Files selected for processing (2)
  • libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js (1 hunks)
  • libs/auth-api-lib/src/lib/clients/admin/admin-clients.service.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/auth-api-lib/src/lib/clients/admin/admin-clients.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (2)
libs/auth-api-lib/migrations/20241018150418-add-default-scopes-to-client-allowed-scope-table.js (2)

4-45: LGTM: Well-implemented migration logic

The up method is well-structured and follows good practices:

  • It uses parameterized queries for security.
  • It efficiently retrieves and processes data.
  • It includes early returns to avoid unnecessary processing.

Good job on the implementation!


47-52: LGTM: Appropriate handling of down migration

The down method is intentionally left empty with a clear comment explaining that no rollback is needed. This is an acceptable approach when the migration doesn't require reversal.

)

const rows = []
const defaultScopes = ['email', 'address', 'phone']
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

Consider extracting default scopes to a constant

For better maintainability and potential reuse, consider extracting the default scopes array to a constant at the module level.

Apply this change at the top of the file:

const DEFAULT_SCOPES = ['email', 'address', 'phone'];

module.exports = {
  async up(queryInterface, Sequelize) {
    // ... existing code ...
    
    // Replace line 28 with:
    const defaultScopes = DEFAULT_SCOPES;
    
    // ... rest of the code ...
  },
  // ... down method ...
};

This change improves code readability and makes it easier to update default scopes in the future if needed.

Copy link

codecov bot commented Oct 18, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 36.80%. Comparing base (6ea4498) to head (1c78899).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16476      +/-   ##
==========================================
+ Coverage   36.77%   36.80%   +0.03%     
==========================================
  Files        6847     6839       -8     
  Lines      141873   141440     -433     
  Branches    40424    40257     -167     
==========================================
- Hits        52167    52051     -116     
+ Misses      89706    89389     -317     
Flag Coverage Δ
api 3.37% <ø> (ø)
api-domains-auth-admin 48.48% <ø> (ø)
application-system-api 41.34% <ø> (ø)
application-template-api-modules 27.79% <ø> (-0.02%) ⬇️
nest-core ?
services-auth-delegation-api 57.36% <0.00%> (+0.06%) ⬆️
services-auth-personal-representative 45.11% <0.00%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...lib/src/lib/clients/admin/admin-clients.service.ts 86.86% <100.00%> (ø)

... and 44 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 6ea4498...1c78899. Read the comment docs.

@magnearun magnearun removed the request for review from saevarma October 22, 2024 12:49
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