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

fix(auth-delegations): Fix missing domains for legal representative delegations #17304

Merged
merged 4 commits into from
Dec 20, 2024

Conversation

GunnlaugurG
Copy link
Member

@GunnlaugurG GunnlaugurG commented Dec 19, 2024

What

  • Fixing a bug where /domain route was getting a 403 when trying to create a delegation as a Legal representative.
  • Fix a bug where general mandate users could open access control when they do not have access to change anything there.

Why

  • So legal representative actors can create delegations
  • So general mandate actos cannot open access control

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 a new utility function for filtering custom scope rules.
    • Expanded delegation handling to include the LegalRepresentative delegation type.
  • Bug Fixes

    • Enhanced logic to ensure only valid delegation scopes are returned based on custom rules.
  • Documentation

    • Updated method signatures to reflect new filtering logic.
  • Chores

    • Added new model to the module for improved database interactions.

@GunnlaugurG GunnlaugurG requested review from a team as code owners December 19, 2024 23:13
Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

Walkthrough

This pull request introduces enhancements to the delegation management system across multiple services. The changes focus on improving scope filtering for delegations, introducing a new utility function filterByCustomScopeRule, and expanding support for different delegation types. The modifications primarily affect the delegation-related services, adding more flexible and granular control over scope and delegation type management.

Changes

File Change Summary
libs/auth-api-lib/src/lib/delegations/delegation-scope.service.ts Added imports for ApiScopeInfo and filterByCustomScopeRule. Updated findValidGeneralMandateScopesTo method to filter scopes based on custom rules.
libs/auth-api-lib/src/lib/delegations/delegations-incoming-custom.service.ts Removed local filterByCustomScopeRule method. Updated findAllAvailableGeneralMandate to use imported utility function.
libs/auth-api-lib/src/lib/delegations/utils/filterByScopeCustomScopeRule.ts Added new utility function to filter scopes based on custom delegation type rules.
libs/auth-api-lib/src/lib/resources/delegation-resources.service.ts Added ApiScopeDelegationType model. Updated delegationTypeFilter to support LegalRepresentative delegation type.
libs/auth-api-lib/src/lib/resources/resources.module.ts Imported ApiScopeDelegationType and added to Sequelize module features.

Sequence Diagram

sequenceDiagram
    participant Service as DelegationScopeService
    participant Utility as filterByCustomScopeRule
    participant Model as ApiScopeInfo

    Service->>Utility: Filter scopes
    Utility-->>Model: Check scope rules
    Utility-->>Service: Return filtered scopes
    Service->>Service: Map valid scopes
Loading

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • saevarma

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6bfd414 and 4a275ae.

📒 Files selected for processing (3)
  • libs/auth-api-lib/src/lib/delegations/delegation-scope.service.ts (2 hunks)
  • libs/auth-api-lib/src/lib/delegations/delegations-incoming-custom.service.ts (2 hunks)
  • libs/auth-api-lib/src/lib/delegations/utils/filterByScopeCustomScopeRule.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • libs/auth-api-lib/src/lib/delegations/utils/filterByScopeCustomScopeRule.ts
  • libs/auth-api-lib/src/lib/delegations/delegations-incoming-custom.service.ts
  • libs/auth-api-lib/src/lib/delegations/delegation-scope.service.ts

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.

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

🧹 Nitpick comments (1)
libs/auth-api-lib/src/lib/resources/delegation-resources.service.ts (1)

317-317: Update comment to reflect new logic.
This revised comment clarifies that delegations for individuals are now allowed under certain circumstances. Good improvement for maintainability.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b76b7dd and 6bfd414.

📒 Files selected for processing (5)
  • libs/auth-api-lib/src/lib/delegations/delegation-scope.service.ts (2 hunks)
  • libs/auth-api-lib/src/lib/delegations/delegations-incoming-custom.service.ts (2 hunks)
  • libs/auth-api-lib/src/lib/delegations/utils/filterByScopeCustomScopeRule.ts (1 hunks)
  • libs/auth-api-lib/src/lib/resources/delegation-resources.service.ts (3 hunks)
  • libs/auth-api-lib/src/lib/resources/resources.module.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
libs/auth-api-lib/src/lib/resources/resources.module.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."
libs/auth-api-lib/src/lib/delegations/utils/filterByScopeCustomScopeRule.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."
libs/auth-api-lib/src/lib/resources/delegation-resources.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."
libs/auth-api-lib/src/lib/delegations/delegations-incoming-custom.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."
libs/auth-api-lib/src/lib/delegations/delegation-scope.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."
🔇 Additional comments (13)
libs/auth-api-lib/src/lib/resources/delegation-resources.service.ts (4)

28-28: No issues with the newly imported model.
The import of ApiScopeDelegationType aligns with the expanded functionality for supporting legal representative delegations.


46-47: Constructor injection of ApiScopeDelegationType model is consistent.
Injecting apiScopeDelegationTypeModel here extends the service’s domain logic for new delegation types. Ensure that naming remains consistent and descriptive to minimize confusion.


319-340: New logic for handling LegalRepresentative delegation.

  1. The fallback to a ForbiddenException is correctly placed to enforce restricted access for non-authorized individuals.
  2. Additional condition to fetch scopes from apiScopeDelegationTypeModel is appropriate, ensuring only valid scopes are returned.
  3. The or-clause properly merges multiple delegation type conditions.

Consider verifying test coverage for these changes to ensure all legal representative use cases are tested.

✅ Verification successful

Test coverage for LegalRepresentative delegation is comprehensive

The test files show adequate coverage for LegalRepresentative delegation scenarios:

  • delegations-filters.spec.ts includes specific test cases for LegalRepresentative delegations, including:

    • Verification of legal representative access
    • Filtering of delegations based on legal representative type
    • Both positive and negative test cases for verification endpoints
  • Test cases cover:

    • Proper authorization checks
    • Scope filtering for legal representatives
    • Verification of delegation types
    • Integration with necessary services (National Registry, RSK)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Checking test coverage for delegationTypeFilter
rg -A 4 'delegationTypeFilter' | rg 'test'

Length of output: 40


Script:

#!/bin/bash
# Let's search for test files related to delegation resources
fd "delegation.*test" --type f

# Let's also check for test files containing LegalRepresentative
rg -l "LegalRepresentative.*test|test.*LegalRepresentative"

# Let's look for actual test cases involving legal representatives
rg -B 2 -A 4 "LegalRepresentative" "**/*test*"

Length of output: 702


Script:

#!/bin/bash
# Let's examine the test cases in the identified files
cat apps/services/auth/ids-api/src/app/delegations/test/delegations-filters.spec.ts

# Let's also check the delegation test cases
cat apps/services/auth/delegation-api/src/app/delegations/test/delegation-index/delegation-index-test-cases.ts
cat apps/services/auth/delegation-api/src/app/delegations/test/delegations-controller/delegations.controller.test-cases.ts

Length of output: 21347


310-310: Delegation type check for user.delegationType usage.
Reusing user.delegationType ensures that the filter logic is consistent. Make sure all calling methods provide user objects with the delegationType property assigned.

Run this script to confirm all code paths properly instantiate user.delegationType:

✅ Verification successful

Based on the code analysis, I can now provide a final response:

The delegationType property is a critical part of the User interface and is properly handled in the codebase.

The check for user.delegationType is valid as:

  1. The User interface in multiple locations (libs/shared/types/src/lib/user.ts, libs/auth-nest-tools/src/lib/auth.ts) defines delegationType as an optional array of AuthDelegationType.
  2. The delegationTypeFilter method in delegation-resources.service.ts properly handles the case when delegationType is undefined.
  3. The property is consistently used across the codebase for authorization and delegation type checks.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
rg -A 6 $'new User\\('

Length of output: 22


Script:

#!/bin/bash
# Search for User type definitions and interfaces
ast-grep --pattern 'interface User {
  $$$
}'

# Search for User class definitions
ast-grep --pattern 'class User {
  $$$
}'

# Search for delegationType assignments or checks
rg -A 3 "delegationType"

Length of output: 65653

libs/auth-api-lib/src/lib/delegations/utils/filterByScopeCustomScopeRule.ts (2)

1-2: Import statements align with usage.
The imports used (AuthDelegationType, ApiScopeInfo) are relevant for custom scope rule checks and properly typed.


4-20: New function for scope filtering.

  1. Exported as a default function, which is consistent for a small utility.
  2. The logic returns “true” when no matching rule is found, preserving existing default functionality.
  3. Appropriately checks onlyForDelegationType array for the GeneralMandate. If future needs arise, consider a more flexible or dynamic approach, e.g. passing in the required delegation type at runtime.

No issues found with correctness or clarity.

libs/auth-api-lib/src/lib/resources/resources.module.ts (2)

29-29: New import of ApiScopeDelegationType model is consistent.
This import ensures that the tracking of delegation types is unified within the ORM context.


43-43: Adding ApiScopeDelegationType to SequelizeModule.forFeature.
Including ApiScopeDelegationType in forFeature ensures the model is recognized by Sequelize. Good step for legal representative delegations.

libs/auth-api-lib/src/lib/delegations/delegation-scope.service.ts (2)

30-30: ApiScopeInfo import is valid for referencing scope details.
Importing this type clarifies the scope structure and contributes to type safety.


33-33: Introduced filterByCustomScopeRule.
Centralizing scope filtering logic in a dedicated utility function makes the code more maintainable and testable.

libs/auth-api-lib/src/lib/delegations/delegations-incoming-custom.service.ts (3)

29-29: LGTM! Good modularization.

Moving the scope rule filtering logic to a separate utility function improves code reusability and maintainability.


Line range hint 1-450: Compliant with coding guidelines.

The service implementation follows the required guidelines for libs/**/* files:

  • Uses TypeScript effectively with proper type definitions
  • Maintains modularity for reuse across different apps
  • Follows import/export patterns that support tree-shaking

223-223: Verify the impact on existing general mandate delegations.

The change looks correct and aligns with the PR objectives to fix permission issues. However, let's verify that existing general mandate delegations continue to work as expected.

✅ Verification successful

Let me gather more information about the implementation and tests.


The changes to filterByCustomScopeRule are safe and well-tested

The implementation is correct and the tests demonstrate that general mandate delegations work as expected:

  • The function correctly filters scopes based on delegation types
  • Comprehensive test coverage exists for general mandate scenarios including:
    • Valid general mandate delegations
    • Expired delegations
    • Multiple delegation type support
    • Scope filtering based on delegation types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for other usages of filterByCustomScopeRule to ensure consistent implementation

# Check for all usages of the function
rg -A 5 "filterByCustomScopeRule"

# Check for tests covering general mandate functionality
fd -e spec.ts -e test.ts | xargs rg -l "GeneralMandate"

Length of output: 3631


Script:

#!/bin/bash
# Check the implementation of filterByCustomScopeRule
cat libs/auth-api-lib/src/lib/delegations/utils/filterByScopeCustomScopeRule.ts

# Check general mandate related tests
rg -A 5 "GeneralMandate" apps/services/auth/ids-api/src/app/delegations/test/delegations.controller.spec.ts

Length of output: 3595

Copy link

codecov bot commented Dec 19, 2024

Codecov Report

Attention: Patch coverage is 78.26087% with 5 lines in your changes missing coverage. Please review.

Project coverage is 35.67%. Comparing base (95f602a) to head (339f87a).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
.../src/lib/resources/delegation-resources.service.ts 44.44% 5 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #17304      +/-   ##
==========================================
- Coverage   35.69%   35.67%   -0.02%     
==========================================
  Files        6927     6927              
  Lines      148705   148646      -59     
  Branches    42493    42472      -21     
==========================================
- Hits        53080    53033      -47     
+ Misses      95625    95613      -12     
Flag Coverage Δ
air-discount-scheme-web 0.00% <ø> (ø)
api 3.33% <ø> (ø)
api-domains-auth-admin 48.49% <ø> (ø)
application-api-files 61.90% <ø> (ø)
application-core 75.72% <ø> (ø)
application-system-api 38.74% <ø> (+0.01%) ⬆️
application-template-api-modules 27.68% <ø> (-0.02%) ⬇️
application-templates-accident-notification 27.61% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 25.74% <ø> (ø)
application-templates-driving-license 18.15% <ø> (ø)
application-templates-estate 13.69% <ø> (ø)
application-templates-example-payment 24.69% <ø> (ø)
application-templates-financial-aid 14.45% <ø> (ø)
application-templates-general-petition 23.12% <ø> (ø)
application-templates-inheritance-report 6.59% <ø> (ø)
application-templates-marriage-conditions 15.18% <ø> (ø)
application-templates-mortgage-certificate 43.62% <ø> (ø)
application-templates-parental-leave 29.93% <ø> (ø)
application-types 6.51% <ø> (ø)
application-ui-components 1.22% <ø> (ø)
application-ui-shell 22.31% <ø> (ø)
clients-charge-fjs-v2 28.35% <ø> (ø)
contentful-apps 4.71% <ø> (ø)
financial-aid-backend 51.42% <ø> (ø)
financial-aid-shared 17.88% <ø> (ø)
island-ui-core 30.40% <ø> (ø)
judicial-system-web 27.72% <ø> (ø)
portals-admin-regulations-admin 1.80% <ø> (ø)
portals-core 19.61% <ø> (ø)
services-auth-admin-api 52.55% <26.08%> (-0.01%) ⬇️
services-auth-delegation-api 58.53% <34.78%> (-0.01%) ⬇️
services-auth-ids-api 52.55% <60.86%> (+<0.01%) ⬆️
services-auth-public-api 49.40% <56.52%> (-0.01%) ⬇️
services-user-notification 46.53% <ø> (ø)
services-user-profile 56.88% <ø> (ø)
shared-components 29.64% <ø> (ø)
shared-form-fields 33.36% <ø> (ø)
web 2.40% <ø> (ø)

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

Files with missing lines Coverage Δ
...ib/src/lib/delegations/delegation-scope.service.ts 91.52% <100.00%> (+0.22%) ⬆️
...delegations/delegations-incoming-custom.service.ts 91.46% <100.00%> (-0.26%) ⬇️
.../delegations/utils/filterByScopeCustomScopeRule.ts 100.00% <100.00%> (ø)
...auth-api-lib/src/lib/resources/resources.module.ts 100.00% <100.00%> (ø)
.../src/lib/resources/delegation-resources.service.ts 95.27% <44.44%> (-3.06%) ⬇️

... and 13 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 95f602a...339f87a. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Dec 19, 2024

Datadog Report

All test runs 81ff844 🔗

10 Total Test Services: 0 Failed, 10 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.01%), 166 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
air-discount-scheme-web 0 0 0 2 0 6.59s 1 no change Link
api 0 0 0 4 0 2.44s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 10.13s 1 no change Link
application-api-files 0 0 0 2 0 4.32s 1 no change Link
application-core 0 0 0 97 0 15.28s 1 no change Link
application-system-api 0 0 0 46 0 2m 10.49s 1 no change Link
application-template-api-modules 0 0 0 118 0 2m 4.98s 1 decreased (-0.01%) Link
application-templates-accident-notification 0 0 0 140 0 13.65s 1 no change Link
application-templates-criminal-record 0 0 0 2 0 9.55s 1 no change Link
application-templates-driving-license 0 0 0 13 0 12.87s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (1)

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

@GunnlaugurG GunnlaugurG added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Dec 20, 2024
@kodiakhq kodiakhq bot merged commit 9364323 into main Dec 20, 2024
137 checks passed
@kodiakhq kodiakhq bot deleted the fix/delegation-bugs branch December 20, 2024 11:18
GunnlaugurG added a commit that referenced this pull request Dec 20, 2024
…elegations (#17304)

* attempt to fix delegation bugs

* add filterOutForDelegationType to utils func

* Utils func changes

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants