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

chore(j-s): Prison users access to appeal case files #15844

Merged
merged 15 commits into from
Sep 5, 2024

Conversation

oddsson
Copy link
Member

@oddsson oddsson commented Sep 2, 2024

Prison users access to appeal case files

Asana

What

This PR implements access for prison users to appeal case files. The following rules apply

  1. Prison admins (FMST) should only see the appeal ruling and only if the appeal case is completed
  2. Prison staff should not see any appeal case files

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 enhanced access control mechanisms for case retrieval based on user roles.
    • Added a new interceptor for managing case file responses according to user roles and appeal states.
    • Implemented functions to identify prison staff and admin users for improved role management.
    • Expanded case file categorization for prison administration cases.
  • Bug Fixes

    • Improved access permissions logic for prison system users in case file guards.

@oddsson oddsson requested a review from a team as a code owner September 2, 2024 13:49
Copy link
Contributor

coderabbitai bot commented Sep 2, 2024

Walkthrough

The changes involve significant modifications to various components within the judicial system's backend. Key updates include the replacement of interceptors in the CaseController and LimitedAccessCaseController, the introduction of new interceptors and guards, and enhancements to user role verification functions. Additionally, new constants for case file categories have been added, improving the access control mechanisms based on user roles.

Changes

Files Change Summary
apps/judicial-system/backend/src/app/modules/case/case.controller.ts, apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts Interceptors in the getById method of CaseController and LimitedAccessCaseController were replaced or updated. The CaseInterceptor was removed and replaced with CompletedAppealAccessedInterceptor and CaseFileInterceptor.
apps/judicial-system/backend/src/app/modules/case/interceptors/caseFile.interceptor.ts Introduced CaseFileInterceptor, which modifies response data based on user roles and case appeal states.
apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts Introduced a new constant prisonAdminCaseFileCategories, an array containing CaseFileCategory.APPEAL_RULING.
apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts Refined access logic for prison admin users to include checks against the new prisonAdminCaseFileCategories array.
libs/judicial-system/types/src/index.ts, libs/judicial-system/types/src/lib/user.ts Added new functions isPrisonStaffUser and isPrisonAdminUser to enhance user role validation within the judicial system.
apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts Updated test suite for LimitedAccessViewCaseFileGuard to focus exclusively on prisonAdminUser, removing references to prisonUser.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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: 0

Outside diff range, codebase verification and nitpick comments (3)
apps/judicial-system/backend/src/app/modules/case/interceptors/completedAppealAccessed.interceptor.ts (1)

Line range hint 23-50: Consider enhancing type safety and code organization.

While the implementation is correct, there are opportunities to improve type safety and code organization:

  1. Consider extracting the condition for logging the event into a separate method for better readability.
  2. Use type guards to narrow down the user type and avoid type assertions.
  3. Consider using an enum for user roles instead of string literals.

Here's a suggested refactoring:

import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common'
import {
  CaseAppealState,
  EventType,
  InstitutionType,
  User,
  UserRole,
} from '@island.is/judicial-system/types'
import { EventLogService } from '../../event-log'
import { Case } from '../models/case.model'

@Injectable()
export class CompletedAppealAccessedInterceptor implements NestInterceptor {
  constructor(private readonly eventLogService: EventLogService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<Case> {
    const request = context.switchToHttp().getRequest()
    const user = request.user as User

    return next.handle().pipe(
      map((data: Case) => {
        if (this.shouldLogEvent(data, user)) {
          this.logEvent(data, user)
        }
        return data
      }),
    )
  }

  private shouldLogEvent(data: Case, user: User): boolean {
    return (
      data.appealState === CaseAppealState.COMPLETED &&
      (this.isLegalUser(user) || this.isPrisonStaff(user))
    )
  }

  private isLegalUser(user: User): boolean {
    return [UserRole.PROSECUTOR, UserRole.DEFENDER].includes(user.role)
  }

  private isPrisonStaff(user: User): boolean {
    return (
      user.role === UserRole.PRISON_SYSTEM_STAFF &&
      user.institution?.type === InstitutionType.PRISON
    )
  }

  private logEvent(data: Case, user: User): void {
    this.eventLogService.create({
      eventType: EventType.APPEAL_RESULT_ACCESSED,
      caseId: data.id,
      nationalId: user.nationalId,
      userRole: user.role,
    })
  }
}

This refactoring improves readability, maintainability, and type safety while preserving the original functionality.

apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (2)

69-73: Approved with suggestion: Prison system user access condition

The updated condition for prison system users is more flexible and robust. It now checks against multiple categories and ensures caseFile.category is defined before the inclusion check.

Consider reordering the conditions for better performance:

 if (isPrisonSystemUser(user) && caseFile.category) {
   if (
-    isCompletedCase(theCase.state) &&
-    prisonSystemCaseFileCategories.includes(caseFile.category)
+    prisonSystemCaseFileCategories.includes(caseFile.category) &&
+    isCompletedCase(theCase.state)
   ) {
     return true
   }
 }

This change puts the more specific condition first, potentially avoiding unnecessary checks of isCompletedCase when the category doesn't match.


Line range hint 1-80: Suggestions for improving code organization and testability

The LimitedAccessViewCaseFileGuard is well-structured, but consider the following improvements:

  1. Extract the role-specific logic into separate methods for better readability and testability.
  2. Use dependency injection for the imported constants to make the guard more flexible and easier to test.
  3. Consider adding unit tests for this guard to ensure all conditions are correctly handled.

Here's an example of how you could refactor the canActivate method:

@Injectable()
export class LimitedAccessViewCaseFileGuard implements CanActivate {
  constructor(
    @Inject('DEFENDER_CATEGORIES_RESTRICTION')
    private defenderCategoriesRestriction: CaseFileCategory[],
    @Inject('DEFENDER_CATEGORIES_INDICTMENT')
    private defenderCategoriesIndictment: CaseFileCategory[],
    @Inject('PRISON_SYSTEM_CATEGORIES')
    private prisonSystemCategories: CaseFileCategory[],
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const { user, theCase, caseFile } = this.extractRequestData(context);

    if (isDefenceUser(user) && caseFile.category) {
      return this.checkDefenceUserAccess(user, theCase, caseFile);
    }

    if (isPrisonSystemUser(user) && caseFile.category) {
      return this.checkPrisonSystemUserAccess(user, theCase, caseFile);
    }

    throw new ForbiddenException(`Forbidden for ${user.role}`);
  }

  private extractRequestData(context: ExecutionContext): { user: User; theCase: Case; caseFile: CaseFile } {
    const request = context.switchToHttp().getRequest();
    const user: User = request.user;
    const theCase: Case = request.case;
    const caseFile: CaseFile = request.caseFile;

    if (!user) throw new InternalServerErrorException('Missing user');
    if (!theCase) throw new InternalServerErrorException('Missing case');
    if (!caseFile) throw new InternalServerErrorException('Missing case file');

    return { user, theCase, caseFile };
  }

  private checkDefenceUserAccess(user: User, theCase: Case, caseFile: CaseFile): boolean {
    if (
      isRequestCase(theCase.type) &&
      isCompletedCase(theCase.state) &&
      this.defenderCategoriesRestriction.includes(caseFile.category)
    ) {
      return true;
    }

    if (
      isIndictmentCase(theCase.type) &&
      this.defenderCategoriesIndictment.includes(caseFile.category)
    ) {
      return true;
    }

    return false;
  }

  private checkPrisonSystemUserAccess(user: User, theCase: Case, caseFile: CaseFile): boolean {
    return (
      this.prisonSystemCategories.includes(caseFile.category) &&
      isCompletedCase(theCase.state)
    );
  }
}

This refactoring improves readability, testability, and maintainability of the guard.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ed805ae and 583bbbd.

Files selected for processing (11)
  • apps/judicial-system/backend/src/app/modules/case/case.controller.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/guards/limitedAccessCaseExists.guard.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/interceptors/caseFile.interceptor.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/interceptors/completedAppealAccessed.interceptor.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (2 hunks)
  • libs/judicial-system/types/src/index.ts (1 hunks)
  • libs/judicial-system/types/src/lib/file.ts (1 hunks)
  • libs/judicial-system/types/src/lib/user.ts (1 hunks)
Files skipped from review due to trivial changes (3)
  • apps/judicial-system/backend/src/app/modules/case/guards/limitedAccessCaseExists.guard.ts
  • libs/judicial-system/types/src/index.ts
  • libs/judicial-system/types/src/lib/file.ts
Additional context used
Path-based instructions (8)
apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/case/interceptors/completedAppealAccessed.interceptor.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/case/interceptors/caseFile.interceptor.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
libs/judicial-system/types/src/lib/user.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."
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/judicial-system/backend/src/app/modules/case/case.controller.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
Additional comments not posted (12)
apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (1)

26-26: LGTM! Consider minor formatting adjustment.

The addition of prisonSystemCaseFileCategories aligns well with the PR objectives. It correctly restricts prison system access to only the appeal ruling, as specified in the requirements.

For consistency with other constants in this file, consider adding a line break after the opening bracket:

-export const prisonSystemCaseFileCategories = [CaseFileCategory.APPEAL_RULING]
+export const prisonSystemCaseFileCategories = [
+  CaseFileCategory.APPEAL_RULING,
+]

Let's verify the usage of this new constant in other parts of the codebase:

Verification successful

Usage of prisonSystemCaseFileCategories verified successfully.

The constant prisonSystemCaseFileCategories is correctly utilized in the codebase, aligning with the PR objectives. It is used in:

  • apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts for conditional logic.
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts as an import.

These usages confirm its role in managing access to appeal rulings as intended.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of prisonSystemCaseFileCategories in the codebase

# Test: Search for imports or usage of prisonSystemCaseFileCategories
# Expect: At least one occurrence in a file other than the current one
rg --type typescript -g '!**/caseFileCategory.ts' 'prisonSystemCaseFileCategories'

Length of output: 117


Script:

#!/bin/bash
# Description: Check for usage of prisonSystemCaseFileCategories in the codebase

# Test: Search for imports or usage of prisonSystemCaseFileCategories
# Expect: At least one occurrence in a file other than the current one
rg --type-add 'ts:*.ts' -g '!**/caseFileCategory.ts' 'prisonSystemCaseFileCategories'

Length of output: 530

apps/judicial-system/backend/src/app/modules/case/interceptors/completedAppealAccessed.interceptor.ts (1)

23-23: Improved class name for better clarity.

The change from CaseInterceptor to CompletedAppealAccessedInterceptor better reflects the specific purpose of this interceptor. This naming convention aligns well with the Single Responsibility Principle.

apps/judicial-system/backend/src/app/modules/case/interceptors/caseFile.interceptor.ts (3)

1-19: Imports look good.

The necessary imports for RxJS, NestJS, and custom types are present and appropriate for the interceptor's functionality.


1-53: Overall, the interceptor implements the required functionality with room for improvement.

The CaseFileInterceptor successfully filters case files based on user roles and appeal state, aligning with the PR objectives. The implementation ensures that prison admins (FMST) can access appeal rulings for completed appeals, while prison staff have no access to appeal case files.

However, the suggested refactoring would improve code quality, readability, and maintainability. It's important to implement these changes carefully and verify that they don't introduce any regressions in the existing functionality.

After implementing the suggested changes, please run comprehensive tests to ensure that the access control logic works as expected for all user roles and appeal states.


21-53: Interceptor logic aligns with PR objectives, but consider some improvements.

The interceptor successfully filters case files based on user roles and appeal state. However, there are a few points to consider:

  1. The logic for filtering case files could be simplified for better readability.
  2. Modifying the original data object directly might have unintended side effects.
  3. The returnData variable is not consistently used throughout the method.
  4. There's no error handling for potential undefined values.

Consider refactoring the interceptor logic as follows:

@Injectable()
export class CaseFileInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Case> {
    const request = context.switchToHttp().getRequest()
    const user: User = request.user

    return next.handle().pipe(
      map((data: Case) => {
        if (!data.caseFiles) {
          return data
        }

        if (isPrisonStaffUser(user) || data.appealState !== CaseAppealState.COMPLETED) {
          return { ...data, caseFiles: [] }
        }

        if (isPrisonSystemUser(user)) {
          return {
            ...data,
            caseFiles: data.caseFiles.filter(
              (cf) => cf.category === CaseFileCategory.APPEAL_RULING
            ),
          }
        }

        return data
      })
    )
  }
}

This refactored version:

  1. Simplifies the logic and improves readability.
  2. Creates a new object instead of modifying the original data.
  3. Consistently returns a new or modified object.
  4. Adds a check for undefined caseFiles.

To ensure this refactoring doesn't break existing functionality, please run the following test:

This will help us understand how the interceptor is used and ensure our changes don't introduce any regressions.

apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (1)

24-24: LGTM: Import of prisonSystemCaseFileCategories

The addition of prisonSystemCaseFileCategories import is appropriate and consistent with the existing import pattern for case file categories.

libs/judicial-system/types/src/lib/user.ts (1)

117-122: LGTM! Consider adding a clarifying comment.

The implementation of isPrisonStaffUser looks good and is consistent with other user role check functions in the file. It's correctly exported and uses TypeScript for parameter typing, making it reusable across different NextJS apps.

Consider adding a comment to clarify the difference between isPrisonStaffUser and isPrisonSystemUser. For example:

// Checks if the user is a prison staff member (excludes prison admin)
export const isPrisonStaffUser = (user: InstitutionUser): boolean =>
  Boolean(
    user.role &&
      prisonSystemRoles.includes(user.role) &&
      user.institution?.type === InstitutionType.PRISON,
  )

Let's verify the usage of this new function in the codebase:

Verification successful

Function isPrisonStaffUser is actively used in the codebase.

The isPrisonStaffUser function is integrated and utilized in multiple parts of the codebase, confirming its role in determining user roles related to prison staff. It is used in the following locations:

  • libs/judicial-system/types/src/index.ts
  • apps/judicial-system/backend/src/app/modules/case/interceptors/caseFile.interceptor.ts
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of isPrisonStaffUser function
# Expected: No results if the function is not yet used

rg --type typescript "isPrisonStaffUser"

Length of output: 75


Script:

#!/bin/bash
# Description: Check for usage of isPrisonStaffUser function
# Expected: No results if the function is not yet used

rg --type ts "isPrisonStaffUser"

Length of output: 537

apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (2)

56-57: New interceptors imported: Verify implementations

The addition of CaseFileInterceptor and CompletedAppealAccessedInterceptor aligns with the changes in the @UseInterceptors decorator. These custom interceptors likely enhance the access control for case files and completed appeals.

Please ensure that the implementations of these interceptors in their respective files (caseFile.interceptor.ts and completedAppealAccessed.interceptor.ts) align with the PR objectives, particularly regarding access rules for prison admins and staff.

Verification successful

Interceptors Implementations Verified

The implementations of CaseFileInterceptor and CompletedAppealAccessedInterceptor align with the PR objectives. They effectively manage access control and event logging for case files and completed appeals, supporting the access rules for prison admins and staff.

  • CaseFileInterceptor clears or filters case files based on user roles and appeal states.
  • CompletedAppealAccessedInterceptor logs access events for completed appeals for specific user roles.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of the new interceptors

# Test: Check the content of the new interceptor files
echo "Checking CaseFileInterceptor implementation:"
cat $(fd --type f --glob '**/caseFile.interceptor.ts')

echo "\nChecking CompletedAppealAccessedInterceptor implementation:"
cat $(fd --type f --glob '**/completedAppealAccessed.interceptor.ts')

Length of output: 3154


89-89: Updated interceptors: Verify access control implementation

The @UseInterceptors decorator has been updated to use CompletedAppealAccessedInterceptor and CaseFileInterceptor instead of the previous CaseInterceptor. This change appears to implement more specific access control mechanisms.

Please verify that this change correctly implements the access rules described in the PR objectives:

  1. Prison admins (FMST) should have access to view appeal rulings only for completed appeals.
  2. Prison staff should not have access to any appeal case files.

Run the following test to check the implementation:

If the test doesn't return any results, consider implementing explicit role checks in the getById method or ensure that the interceptors handle this logic appropriately.

Verification successful

Interceptors Implement Access Control Correctly

The CompletedAppealAccessedInterceptor and CaseFileInterceptor effectively enforce the access control rules as intended. The interceptors ensure that:

  • Prison admins (FMST) can view appeal rulings only for completed appeals.
  • Prison staff do not have access to any appeal case files.

These implementations align with the PR objectives and correctly handle the specified access control logic.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of access control in the getById method

# Test: Check for role-based access control in the getById method
echo "Checking role-based access control in getById method:"
ast-grep --lang typescript --pattern 'getById($$$) {
  $$$
  if ($user.role === "PRISON_ADMIN") {
    $$$
  } else if ($user.role === "PRISON_STAFF") {
    $$$
  }
  $$$
}' apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts

Length of output: 929


Script:

#!/bin/bash
# Description: Verify the implementation of access control in the getById method by checking for individual role checks

# Test: Check for PRISON_ADMIN role access control in the getById method
echo "Checking for PRISON_ADMIN role access control in getById method:"
ast-grep --lang typescript --pattern 'if ($user.role === "PRISON_ADMIN") { $$$ }' apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts

# Test: Check for PRISON_STAFF role access control in the getById method
echo "Checking for PRISON_STAFF role access control in getById method:"
ast-grep --lang typescript --pattern 'if ($user.role === "PRISON_STAFF") { $$$ }' apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts

Length of output: 609


Script:

#!/bin/bash
# Description: Locate and examine the implementation of CompletedAppealAccessedInterceptor and CaseFileInterceptor

# Find the implementation of CompletedAppealAccessedInterceptor
echo "Searching for CompletedAppealAccessedInterceptor implementation:"
ast-grep --lang typescript --pattern 'class CompletedAppealAccessedInterceptor { $$$ }'

# Find the implementation of CaseFileInterceptor
echo "Searching for CaseFileInterceptor implementation:"
ast-grep --lang typescript --pattern 'class CaseFileInterceptor { $$$ }'

Length of output: 412


Script:

#!/bin/bash
# Description: Search for any files related to interceptors in the codebase

# Find files that might contain interceptor implementations
echo "Searching for interceptor-related files:"
fd interceptor --type f

Length of output: 1654


Script:

#!/bin/bash
# Description: Display the contents of the interceptors to verify access control logic

# Display the contents of completedAppealAccessed.interceptor.ts
echo "Contents of completedAppealAccessed.interceptor.ts:"
cat apps/judicial-system/backend/src/app/modules/case/interceptors/completedAppealAccessed.interceptor.ts

# Display the contents of caseFile.interceptor.ts
echo "Contents of caseFile.interceptor.ts:"
cat apps/judicial-system/backend/src/app/modules/case/interceptors/caseFile.interceptor.ts

Length of output: 3001

apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts (1)

19-22: Verify usage of new imports and consider adding comments.

New imports have been added for prison-related user checks and case file categories:

  1. isPrisonStaffUser and isPrisonSystemUser from '@island.is/judicial-system/types'
  2. prisonSystemCaseFileCategories from '../file/guards/caseFileCategory'

These imports suggest new functionality related to prison system users and case file categories. However, they are not used in the visible part of this file.

To ensure these imports are necessary and used correctly, please run the following script:

If these imports are used in this file or closely related files, consider adding comments to explain their purpose and how they relate to the changes in prison user access to appeal case files mentioned in the PR objectives.

Also applies to: 43-43

Verification successful

Imports are used correctly across the codebase.

The imports isPrisonStaffUser, isPrisonSystemUser, and prisonSystemCaseFileCategories are utilized in multiple files, confirming their necessity and relevance to the functionality related to prison system users and case file categories.

  • isPrisonStaffUser and isPrisonSystemUser are used in:

    • limitedAccessCase.service.ts
    • viewCaseFile.guard.ts
    • limitedAccessViewCaseFile.guard.ts
    • case.filter.ts
    • cases.filter.ts
    • caseFile.interceptor.ts
  • prisonSystemCaseFileCategories is used in:

    • limitedAccessViewCaseFile.guard.ts
    • Defined in caseFileCategory.ts

Consider adding comments to these imports to clarify their purpose and how they relate to the changes in prison user access to appeal case files.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new imports in the codebase

# Test 1: Check for usage of isPrisonStaffUser and isPrisonSystemUser
echo "Checking usage of isPrisonStaffUser and isPrisonSystemUser:"
rg --type typescript "isPrisonStaffUser|isPrisonSystemUser" apps/judicial-system/backend/src

# Test 2: Check for usage of prisonSystemCaseFileCategories
echo "Checking usage of prisonSystemCaseFileCategories:"
rg --type typescript "prisonSystemCaseFileCategories" apps/judicial-system/backend/src

Length of output: 489


Script:

#!/bin/bash
# Description: Verify the usage of new imports in the codebase with corrected file type

# Test 1: Check for usage of isPrisonStaffUser and isPrisonSystemUser
echo "Checking usage of isPrisonStaffUser and isPrisonSystemUser:"
rg --type ts "isPrisonStaffUser|isPrisonSystemUser" apps/judicial-system/backend/src

# Test 2: Check for usage of prisonSystemCaseFileCategories
echo "Checking usage of prisonSystemCaseFileCategories:"
rg --type ts "prisonSystemCaseFileCategories" apps/judicial-system/backend/src

Length of output: 2563

apps/judicial-system/backend/src/app/modules/case/case.controller.ts (2)

103-103: New import added for CompletedAppealAccessedInterceptor.

The import statement for CompletedAppealAccessedInterceptor has been added, which aligns with the changes in the getById method.


471-471: Interceptor changed for getById method.

The CaseInterceptor has been replaced with CompletedAppealAccessedInterceptor for the getById method. This change appears to be related to the new functionality for allowing prison users to access appeal case files under specific conditions.

To ensure that the new interceptor correctly implements the access rules described in the PR objectives, we need to review its implementation. Let's check the contents of the CompletedAppealAccessedInterceptor:

Verification successful

Interceptor Implementation Verified

The CompletedAppealAccessedInterceptor class is implemented in the codebase and includes logic related to handling completed appeal cases. This aligns with the review comment's description of its purpose. The interceptor checks if the appealState of a Case is COMPLETED, which suggests it is implementing the intended access rules.

  • Location: apps/judicial-system/backend/src/app/modules/case/interceptors/completedAppealAccessed.interceptor.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the CompletedAppealAccessedInterceptor implementation
ast-grep --lang typescript --pattern 'class CompletedAppealAccessedInterceptor {
  $$$
}'

Length of output: 91


Script:

#!/bin/bash
# Search for the CompletedAppealAccessedInterceptor class definition in the codebase
rg 'class CompletedAppealAccessedInterceptor' --type=ts -A 10

Length of output: 1634

Copy link

codecov bot commented Sep 2, 2024

Codecov Report

Attention: Patch coverage is 64.15094% with 19 lines in your changes missing coverage. Please review.

Project coverage is 36.93%. Comparing base (e0f0050) to head (101531e).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
.../modules/case/interceptors/caseFile.interceptor.ts 21.05% 15 Missing ⚠️
libs/judicial-system/types/src/lib/user.ts 60.00% 4 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #15844   +/-   ##
=======================================
  Coverage   36.93%   36.93%           
=======================================
  Files        6681     6682    +1     
  Lines      136472   136505   +33     
  Branches    38756    38769   +13     
=======================================
+ Hits        50401    50415   +14     
- Misses      86071    86090   +19     
Flag Coverage Δ
judicial-system-api 18.32% <63.63%> (+0.06%) ⬆️
judicial-system-backend 56.11% <64.15%> (-0.03%) ⬇️
judicial-system-formatters 80.11% <63.63%> (-0.68%) ⬇️
judicial-system-message 66.79% <ø> (ø)
judicial-system-message-handler 47.61% <ø> (ø)
judicial-system-scheduler 69.16% <63.63%> (-0.39%) ⬇️
judicial-system-types 48.07% <45.45%> (-1.04%) ⬇️
judicial-system-web 28.77% <20.00%> (-0.01%) ⬇️

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

Files with missing lines Coverage Δ
...em/backend/src/app/modules/case/case.controller.ts 84.36% <100.00%> (ø)
...dules/case/guards/limitedAccessCaseExists.guard.ts 100.00% <100.00%> (ø)
...nterceptors/completedAppealAccessed.interceptor.ts 33.33% <100.00%> (ø)
...c/app/modules/case/limitedAccessCase.controller.ts 97.58% <100.00%> (+0.01%) ⬆️
...nd/src/app/modules/file/guards/caseFileCategory.ts 100.00% <100.00%> (ø)
...les/file/guards/limitedAccessViewCaseFile.guard.ts 100.00% <100.00%> (ø)
libs/judicial-system/types/src/index.ts 100.00% <100.00%> (ø)
libs/judicial-system/types/src/lib/file.ts 100.00% <100.00%> (ø)
libs/judicial-system/types/src/lib/user.ts 86.48% <60.00%> (-4.14%) ⬇️
.../modules/case/interceptors/caseFile.interceptor.ts 21.05% <21.05%> (ø)

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 e0f0050...101531e. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Sep 2, 2024

Datadog Report

All test runs 3654b0a 🔗

14 Total Test Services: 1 Failed, 13 Passed
🔻 Test Sessions change in coverage: 5 decreased, 2 increased, 13 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
judicial-system-backend 16 0 0 20033 0 17m 19.66s 1 decreased (-0.02%) Link
api 0 0 0 4 0 2.59s 1 no change Link
application-system-api 0 0 0 111 2 3m 3.56s 1 no change Link
application-template-api-modules 0 0 0 109 0 1m 43.14s 1 no change Link
application-templates-driving-license 0 0 0 13 0 15.2s 1 no change Link
application-ui-shell 0 0 0 74 0 31.99s 1 no change Link
judicial-system-api 0 0 0 54 0 5.95s 1 increased (+0.11%) Link
judicial-system-formatters 0 0 0 36 0 5.33s 1 decreased (-0.18%) Link
judicial-system-message 0 0 0 31 0 11.26s 1 no change Link
judicial-system-message-handler 0 0 0 4 0 3.67s 1 no change Link

❌ Failed Tests (16)

This report shows up to 5 failed tests.

  • Limited Access View Case File Guard prison system users for ADMISSION_TO_FACILITY cases in state ACCEPTED prison system users can view APPEAL_RULING should activate - apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts - Details

    Expand for error
     expect(received).toBe(expected) // Object.is equality
     
     Expected: true
     Received: undefined
    
  • Limited Access View Case File Guard prison system users for ADMISSION_TO_FACILITY cases in state COMPLETED prison system users can view APPEAL_RULING should activate - apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts - Details

    Expand for error
     expect(received).toBe(expected) // Object.is equality
     
     Expected: true
     Received: undefined
    
  • Limited Access View Case File Guard prison system users for ADMISSION_TO_FACILITY cases in state DISMISSED prison system users can view APPEAL_RULING should activate - apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts - Details

    Expand for error
     expect(received).toBe(expected) // Object.is equality
     
     Expected: true
     Received: undefined
    
  • Limited Access View Case File Guard prison system users for ADMISSION_TO_FACILITY cases in state REJECTED prison system users can view APPEAL_RULING should activate - apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts - Details

    Expand for error
     expect(received).toBe(expected) // Object.is equality
     
     Expected: true
     Received: undefined
    
  • Limited Access View Case File Guard prison system users for CUSTODY cases in state ACCEPTED prison system users can view APPEAL_RULING should activate - apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts - Details

    Expand for error
     expect(received).toBe(expected) // Object.is equality
     
     Expected: true
     Received: undefined
    

🔻 Code Coverage Decreases vs Default Branch (5)

  • judicial-system-types - jest 51.9% (-0.6%) - Details
  • judicial-system-formatters - jest 88.48% (-0.18%) - Details
  • judicial-system-scheduler - jest 75.17% (-0.05%) - Details
  • judicial-system-xrd-api - jest 76% (-0.05%) - Details
  • judicial-system-backend - jest 59.64% (-0.02%) - Details

Copy link
Member

@gudjong gudjong left a comment

Choose a reason for hiding this comment

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

Two suggested changes.

@oddsson oddsson requested a review from gudjong September 4, 2024 10:15
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: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 583bbbd and 339048d.

Files selected for processing (7)
  • apps/judicial-system/backend/src/app/modules/case/case.controller.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/interceptors/caseFile.interceptor.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (3 hunks)
  • libs/judicial-system/types/src/index.ts (1 hunks)
  • libs/judicial-system/types/src/lib/user.ts (1 hunks)
Files skipped from review as they are similar to previous changes (5)
  • apps/judicial-system/backend/src/app/modules/case/case.controller.ts
  • apps/judicial-system/backend/src/app/modules/case/interceptors/caseFile.interceptor.ts
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts
  • apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts
  • libs/judicial-system/types/src/index.ts
Additional context used
Path-based instructions (2)
apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
libs/judicial-system/types/src/lib/user.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 not posted (3)
apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (1)

68-74: LGTM!

The code changes implement the access control logic for prison admin users correctly, addressing the suggestions from the previous review.

libs/judicial-system/types/src/lib/user.ts (2)

117-122: LGTM!

The code changes are approved. The isPrisonAdminUser function follows the existing pattern of user role validation functions and correctly checks if a user is a prison admin.


124-129: LGTM!

The code changes are approved. The isPrisonStaffUser function follows the existing pattern of user role validation functions and correctly checks if a user is a prison staff.

Copy link
Member

@gudjong gudjong left a comment

Choose a reason for hiding this comment

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

Nice

@gudjong gudjong added the automerge Merge this PR as soon as all checks pass label Sep 5, 2024
@oddsson oddsson removed the automerge Merge this PR as soon as all checks pass label Sep 5, 2024
@oddsson oddsson requested a review from gudjong September 5, 2024 13:11
@oddsson oddsson added the automerge Merge this PR as soon as all checks pass label Sep 5, 2024
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: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 339048d and 101531e.

Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (1 hunks)
Additional context used
Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
Additional comments not posted (5)
apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (5)

Line range hint 1-1: Overall structure and setup are appropriate for the test suite.

The use of Jest for mocking and the givenWhenThen pattern are well-suited for testing the guard functionality. The setup is clean and follows good practices in behavior-driven development (BDD).


Line range hint 1-1: Comprehensive test coverage for defence users.

The parameterized tests for defence users are thorough, covering both allowed and disallowed case file categories across various case types and states. This ensures robust testing of guard conditions.


Line range hint 1-1: Test case for prison system users aligns with PR objectives.

The focus on testing access rights for prison admins, specifically for the APPEAL_RULING category, is crucial and aligns with the PR's goal of restricting access to sensitive information. The tests are well-structured to ensure that security measures are correctly enforced.


Line range hint 1-1: Robust test coverage for remaining users.

The tests comprehensively cover various roles and institutions, ensuring that access controls are strictly enforced. This is crucial for the security and integrity of the system.


Line range hint 1-1: Important tests for error handling in cases of missing data.

The tests for scenarios where critical information is missing are crucial. They ensure that the system throws appropriate exceptions, which is vital for robust error handling and security.

@kodiakhq kodiakhq bot merged commit 0815408 into main Sep 5, 2024
46 of 47 checks passed
@kodiakhq kodiakhq bot deleted the j-s/limited-access-files branch September 5, 2024 13:43
jonnigs pushed a commit that referenced this pull request Sep 12, 2024
* Create CaseFileInterceptor

* Filter case files in interceptor

* Only send appeal ruling for completed appeals

* Refactor

* Remove unused code

* Refactor

* Allow defence users to see all files

* Refactor

* Fix tests

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
@coderabbitai coderabbitai bot mentioned this pull request Oct 21, 2024
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants