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): Security&Integrity #16863

Merged
merged 54 commits into from
Dec 3, 2024
Merged

chore(j-s): Security&Integrity #16863

merged 54 commits into from
Dec 3, 2024

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Nov 14, 2024

Security&Integrity

Öryggishola - notandi sem hefur aðgang að einhverju máli getur sótt stöðu birtingar fyrir hvaða varnaraðlia sem er í hvaða máli sem er
Ekki sækja stöðu fyrirkalls til RLS ef staða fyrirkalls er til í gagnagrunni

What

  • Rewrites client subpoena refreshes. If the subpoena has been delivered to the police system, but does. not yet have a service status, then the client simple asks the server to retieve the current subpona. If needed, the backend ask the police system for an update. The current user can only retrieve subpoenas belonging to cases she has read access to.
  • Rewrites digital mailbox subpoena refresh in a similar way.
  • Makes various improvements, such as:
    • cleaner backend endpoint routing,
    • adding and rewriting backend endpoint guards,
    • applying consistent ordering of database query conditions,
    • throwing more appropriate exceptions,
    • adding a number of unit tests,
    • applying concistent directives ordering, and
    • improving error messages.

Why

  • It was possible to retrieve subpoena info from the police system for a subpoena the user was not supposed to have access to.
  • Code cleanup.

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 SubpoenaModule for enhanced subpoena management.
    • Added getSubpoena method to retrieve subpoena details using case and defendant IDs.
    • New GraphQL query for fetching detailed subpoena information.
    • Added defendantId field to GraphQL queries for case and limited access case.
  • Bug Fixes

    • Improved error handling for missing or invalid subpoena IDs.
    • Updated service status checks for subpoenas.
    • Enhanced error handling in the LawyersService for when a lawyer is not found.
  • Documentation

    • Enhanced API documentation for various endpoints, including clearer error messages and response structures.
  • Refactor

    • Streamlined state management in the ServiceAnnouncement component.
    • Simplified mapping logic in the IndictmentOverview and Overview components.
    • Updated method signatures for clarity in the CaseController and CaseService.
  • Tests

    • Expanded test coverage for new guards and methods in the InternalSubpoenaController and SubpoenaController.
  • Chores

    • Removed unused GraphQL queries and updated imports across several files.

Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Walkthrough

The changes in this pull request primarily focus on the integration and management of a new SubpoenaModule within the judicial system API. Key modifications include the addition of methods for retrieving and managing subpoenas, updates to existing service and controller logic, and adjustments to error handling. Several guards are introduced or modified to enhance security, while some existing methods and entities related to subpoena status have been removed or refactored. The overall structure of the application remains intact, with an emphasis on improving functionality related to subpoenas.

Changes

File Change Summary
apps/judicial-system/api/src/app/app.module.ts Added SubpoenaModule to the imports array.
apps/judicial-system/api/src/app/modules/backend/backend.service.ts Removed getSubpoenaStatus, added getSubpoena method.
apps/judicial-system/api/src/app/modules/defendant/index.ts Removed export for Subpoena.
apps/judicial-system/api/src/app/modules/defendant/models/defendant.model.ts Updated import path for Subpoena.
apps/judicial-system/api/src/app/modules/index.ts Added export for SubpoenaModule.
apps/judicial-system/api/src/app/modules/police/index.ts Removed export for SubpoenaStatus.
apps/judicial-system/api/src/app/modules/police/models/subpoenaStatus.model.ts Removed SubpoenaStatus class.
apps/judicial-system/api/src/app/modules/police/police.resolver.ts Removed subpoenaStatus query method.
apps/judicial-system/api/src/app/modules/subpoena/dto/subpoena.input.ts Renamed SubpoenaStatusQueryInput to SubpoenaQueryInput, added defendantId field.
apps/judicial-system/api/src/app/modules/subpoena/index.ts Added export for Subpoena.
apps/judicial-system/api/src/app/modules/subpoena/subpoena.module.ts Added new SubpoenaModule.
apps/judicial-system/api/src/app/modules/subpoena/subpoena.resolver.ts Added SubpoenaResolver class and subpoena query method.
apps/judicial-system/backend/src/app/modules/case/case.controller.ts Updated API response description in getById method.
apps/judicial-system/backend/src/app/modules/case/dto/internalCases.dto.ts Removed InternalCasesDto class.
apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts Modified filter functions to include CaseState.ACCEPTED.
apps/judicial-system/backend/src/app/modules/case/guards/indictmentCaseExistsForDefendant.guard.ts Added IndictmentCaseExistsForDefendantGuard class.
apps/judicial-system/backend/src/app/modules/case/guards/mergedCaseExists.guard.ts Updated error handling in MergedCaseExistsGuard.
apps/judicial-system/backend/src/app/modules/case/internalCase.controller.ts Changed HTTP methods for retrieving indictment cases to GET.
apps/judicial-system/backend/src/app/modules/case/internalCase.service.ts Added SubpoenaService as a dependency, updated methods.
apps/judicial-system/backend/src/app/modules/defendant/civilClaimant.controller.ts Added CivilClaimantExistsGuard for update and delete methods.
apps/judicial-system/backend/src/app/modules/defendant/civilClaimant.service.ts Updated method signatures and error handling.
apps/judicial-system/backend/src/app/modules/defendant/defendant.controller.ts Added class-level guards for all routes.
apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts Refactored DefendantService class.
apps/judicial-system/backend/src/app/modules/event-log/eventLog.controller.ts Added @ApiTags decorator to EventLogController.
apps/judicial-system/backend/src/app/modules/file/file.controller.ts Added class-level @UseGuards(JwtAuthGuard).
apps/judicial-system/backend/src/app/modules/notification/internalNotification.controller.ts Added class-level @UseGuards(TokenGuard).
apps/judicial-system/backend/src/app/modules/police/police.controller.ts Removed getSubpoenaStatus method.
apps/judicial-system/backend/src/app/modules/police/police.service.ts Updated getSubpoenaStatus return type to Promise<SubpoenaInfo>.
apps/judicial-system/backend/src/app/modules/subpoena/dto/updateSubpoena.dto.ts Updated serviceDate property type to Date.
apps/judicial-system/backend/src/app/modules/subpoena/guards/policeSubpoenaExists.guard.ts Added PoliceSubpoenaExistsGuard class.
apps/judicial-system/backend/src/app/modules/subpoena/guards/subpoenaExists.guard.ts Modified logic and error handling in SubpoenaExistsGuard.
apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts Removed getSubpoena method, updated guards.
apps/judicial-system/backend/src/app/modules/subpoena/limitedAccessSubpoena.controller.ts Updated guard for getSubpoenaPdf method.
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.controller.ts Added getSubpoena method and updated import statements.
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts Updated findBySubpoenaId method to findById and added getSubpoena method.
apps/judicial-system/web/src/components/FormProvider/case.graphql Added defendantId field to subpoenas object.
apps/judicial-system/web/src/components/FormProvider/limitedAccessCase.graphql Added defendantId field to subpoenas object.
apps/judicial-system/web/src/utils/hooks/useSubpoena/getSubpoenaStatus.graphql Removed getSubpoenaStatus query.
apps/judicial-system/web/src/utils/hooks/useSubpoena/index.ts Updated hook signature to accept a single subpoena parameter.
apps/judicial-system/web/src/utils/hooks/useSubpoena/subpoena.graphql Added new Subpoena query.
libs/judicial-system/audit-trail/src/lib/auditTrail.service.ts Removed GET_SUBPOENA_STATUS from AuditedAction enum.
libs/judicial-system/lawyers/src/lib/lawyers.service.ts Updated error handling in getLawyer method.
apps/judicial-system/backend/src/app/modules/police/index.ts Added new export for SubpoenaInfo.

Possibly related PRs

Suggested reviewers

  • oddsson

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

codecov bot commented Nov 14, 2024

Codecov Report

Attention: Patch coverage is 37.50000% with 140 lines in your changes missing coverage. Please review.

Project coverage is 35.72%. Comparing base (04edebb) to head (ccef389).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ckend/src/app/modules/subpoena/subpoena.service.ts 18.00% 41 Missing ⚠️
.../api/src/app/modules/subpoena/subpoena.resolver.ts 0.00% 18 Missing ⚠️
...m/backend/src/app/modules/police/police.service.ts 6.25% 15 Missing ⚠️
...rc/app/modules/police/models/subpoenaInfo.model.ts 0.00% 14 Missing ⚠️
...ckend/src/app/modules/case/internalCase.service.ts 50.00% 9 Missing ⚠️
...al-system/web/src/utils/hooks/useSubpoena/index.ts 11.11% 8 Missing ⚠️
...onents/ServiceAnnouncement/ServiceAnnouncement.tsx 0.00% 6 Missing ⚠️
...nd/src/app/modules/case/internalCase.controller.ts 44.44% 5 Missing ⚠️
...api/src/app/modules/subpoena/dto/subpoena.input.ts 0.00% 3 Missing ⚠️
...em/api/src/app/modules/subpoena/subpoena.module.ts 0.00% 3 Missing ⚠️
... and 11 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16863      +/-   ##
==========================================
+ Coverage   35.68%   35.72%   +0.03%     
==========================================
  Files        6917     6920       +3     
  Lines      147445   147486      +41     
  Branches    41976    41988      +12     
==========================================
+ Hits        52618    52686      +68     
+ Misses      94827    94800      -27     
Flag Coverage Δ
air-discount-scheme-web 0.00% <ø> (ø)
api 3.34% <ø> (ø)
application-api-files 62.01% <ø> (ø)
application-core 76.01% <ø> (ø)
application-system-api 38.75% <ø> (ø)
application-template-api-modules 27.77% <ø> (ø)
application-templates-accident-notification 29.01% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 25.93% <ø> (ø)
application-templates-driving-license 18.18% <ø> (ø)
application-templates-estate 13.83% <ø> (ø)
application-templates-example-payment 24.85% <ø> (ø)
application-templates-financial-aid 14.42% <ø> (ø)
application-templates-general-petition 23.13% <ø> (ø)
application-templates-inheritance-report 6.54% <ø> (ø)
application-templates-marriage-conditions 15.11% <ø> (ø)
application-templates-mortgage-certificate 43.24% <ø> (ø)
application-templates-parental-leave 29.95% <ø> (ø)
application-ui-components 1.24% <ø> (ø)
application-ui-shell 22.48% <ø> (ø)
clients-charge-fjs-v2 24.11% <ø> (ø)
web 2.43% <ø> (ø)

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

Files with missing lines Coverage Δ
apps/judicial-system/api/src/app/app.module.ts 0.00% <ø> (ø)
...cial-system/api/src/app/modules/defendant/index.ts 0.00% <ø> (ø)
...udicial-system/api/src/app/modules/police/index.ts 0.00% <ø> (ø)
...stem/api/src/app/modules/police/police.resolver.ts 0.00% <ø> (ø)
.../src/app/modules/subpoena/models/subpoena.model.ts 0.00% <ø> (ø)
...em/backend/src/app/modules/case/case.controller.ts 86.95% <ø> (ø)
...ckend/src/app/modules/case/filters/cases.filter.ts 97.91% <ø> (ø)
...e/guards/indictmentCaseExistsForDefendant.guard.ts 100.00% <100.00%> (ø)
.../app/modules/case/guards/mergedCaseExists.guard.ts 100.00% <100.00%> (+80.00%) ⬆️
...c/app/modules/case/test/createTestingCaseModule.ts 100.00% <100.00%> (ø)
... and 37 more

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 04edebb...ccef389. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 14, 2024

Datadog Report

All test runs c10c648 🔗

21 Total Test Services: 0 Failed, 20 Passed
➡️ Test Sessions change in coverage: 92 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 7.25s 1 no change Link
api 0 0 0 4 0 2.41s 1 no change Link
application-api-files 0 0 0 2 0 4.3s 1 no change Link
application-core 0 0 0 97 0 14.7s 1 no change Link
application-system-api 0 0 0 46 0 2m 20.66s 1 no change Link
application-template-api-modules 0 0 0 118 0 2m 1.67s 1 no change Link
application-templates-accident-notification 0 0 0 148 0 15.23s 1 no change Link
application-templates-criminal-record 0 0 0 2 0 10.02s 1 no change Link
application-templates-driving-license 0 0 0 13 0 13.3s 1 no change Link
application-templates-example-payment 0 0 0 2 0 10.42s 1 no change Link

@gudjong gudjong dismissed coderabbitai[bot]’s stale review November 27, 2024 15:31

All requests have been handled

@gudjong gudjong requested a review from unakb December 2, 2024 17:22
Copy link
Member

@oddsson oddsson left a comment

Choose a reason for hiding this comment

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

Nice! Just a couple of comments :)

@unakb unakb added the automerge Merge this PR as soon as all checks pass label Dec 3, 2024
@gudjong gudjong requested a review from oddsson December 3, 2024 12:03
@oddsson oddsson removed the automerge Merge this PR as soon as all checks pass label Dec 3, 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

🧹 Outside diff range and nitpick comments (2)
apps/judicial-system/backend/src/app/modules/police/models/subpoenaInfo.model.ts (2)

5-13: Consider reordering type definitions to avoid potential circular dependencies.

The SubpoenaUpdate interface extends from SubpoenaInfo before the class is defined. While TypeScript's declaration hoisting might handle this, it's better to define types in a clear dependency order.

Consider moving the interface after the class definition or extracting the shared types to a separate interface.


15-21: Consider deriving keys dynamically to prevent maintenance issues.

Maintaining a separate array of keys could lead to inconsistencies if the SubpoenaUpdate interface changes. Consider using TypeScript's type system to derive the keys automatically.

-const subpoenaUpdateKeys: Array<keyof SubpoenaUpdate> = [
-  'serviceStatus',
-  'comment',
-  'servedBy',
-  'defenderNationalId',
-  'serviceDate',
-]
+const subpoenaUpdateKeys: Array<keyof SubpoenaUpdate> = Object.keys(
+  SubpoenaInfo.prototype
+).filter((key) => key !== 'isNewValueSetAndDifferent' && key !== 'isSubpoenaInfoChanged') as Array<keyof SubpoenaUpdate>
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2d2cfde and a92bd7f.

📒 Files selected for processing (2)
  • apps/judicial-system/backend/src/app/modules/police/models/subpoenaInfo.model.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/police/models/subpoenaInfo.model.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."
📓 Learnings (1)
apps/judicial-system/backend/src/app/modules/police/models/subpoenaInfo.model.ts (1)
Learnt from: unakb
PR: island-is/island.is#16393
File: apps/judicial-system/digital-mailbox-api/src/app/modules/cases/models/subpoena.response.ts:164-169
Timestamp: 2024-11-12T15:15:11.835Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
🔇 Additional comments (3)
apps/judicial-system/backend/src/app/modules/police/models/subpoenaInfo.model.ts (3)

1-3: LGTM! Dependencies are properly imported.

The imports are well-organized and appropriate for the model's requirements.


35-49: LGTM! Properties are well-documented with Swagger decorators.

The class properties are properly defined and documented. The optional nature of the properties aligns with the subpoena update requirements.


24-33: Consider handling complex object comparisons.

The isNewValueSetAndDifferent method might not handle deep equality checks for objects or arrays correctly. This could lead to false positives when comparing complex values.

Consider using a deep equality comparison for object types:

private isNewValueSetAndDifferent = (
  newValue: unknown,
  oldValue: unknown,
): boolean => {
  if (!newValue) return false;
  if (typeof newValue === 'object' && newValue !== null) {
    return JSON.stringify(newValue) !== JSON.stringify(oldValue);
  }
  return newValue !== oldValue;
}

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 and nitpick comments (5)
apps/judicial-system/backend/src/app/modules/police/police.service.ts (2)

369-370: Address TODO comment for expired status handling

The TODO comment indicates that expired status handling is missing. This could affect the completeness of the subpoena status tracking.

Would you like me to help implement the expired status handling or create a GitHub issue to track this task?


361-370: Simplify complex service status determination

The nested ternary operations make the code harder to read and maintain.

Consider using a more readable approach:

-            serviceStatus: response.deliveredToLawyer
-              ? ServiceStatus.DEFENDER
-              : response.prosecutedConfirmedSubpoenaThroughIslandis
-              ? ServiceStatus.ELECTRONICALLY
-              : response.deliveredOnPaper || response.delivered === true
-              ? ServiceStatus.IN_PERSON
-              : response.acknowledged === false && response.delivered === false
-              ? ServiceStatus.FAILED
-              : undefined,
+            serviceStatus: getServiceStatus(response),

Add a helper function:

function getServiceStatus(response: SubpoenaResponse): ServiceStatus | undefined {
  if (response.deliveredToLawyer) {
    return ServiceStatus.DEFENDER;
  }
  if (response.prosecutedConfirmedSubpoenaThroughIslandis) {
    return ServiceStatus.ELECTRONICALLY;
  }
  if (response.deliveredOnPaper || response.delivered === true) {
    return ServiceStatus.IN_PERSON;
  }
  if (response.acknowledged === false && response.delivered === false) {
    return ServiceStatus.FAILED;
  }
  return undefined;
}
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)

62-81: Consider enhancing type safety and readability of utility functions.

The utility functions are well-structured, but could benefit from some improvements:

-const isNewValueSetAndDifferent = (
-  newValue: unknown,
-  oldValue: unknown,
-): boolean => Boolean(newValue) && newValue !== oldValue
+const hasChanged = <T>(newValue: T | null | undefined, oldValue: T): boolean => 
+  newValue != null && newValue !== oldValue

-export const isSubpoenaInfoChanged = (
+export const hasSubpoenaInfoChanges = (
   newSubpoenaInfo: SubpoenaInfo,
   oldSubpoenaInfo: SubpoenaInfo,
-) =>
-  subpoenaInfoKeys.some((key) =>
-    isNewValueSetAndDifferent(newSubpoenaInfo[key], oldSubpoenaInfo[key]),
-  )
+): boolean => subpoenaInfoKeys.some((key) =>
+  hasChanged(newSubpoenaInfo[key], oldSubpoenaInfo[key])
+)

219-219: Translate comment to English.

The comment "Færa message handling í defendant service" should be in English for consistency.

-// Færa message handling í defendant service
+// TODO: Move message handling to defendant service

198-236: Consider extracting defender choice reset logic.

The defender choice update logic is complex and could benefit from being extracted into a separate method for better readability.

+private shouldResetDefenderChoice(
+  defendant: Defendant,
+  defenderChoice?: string,
+  defenderNationalId?: string,
+): boolean {
+  return (
+    defendant.isDefenderChoiceConfirmed &&
+    ((defenderChoice && defendant.defenderChoice !== defenderChoice) ||
+     (defenderNationalId && defendant.defenderNationalId !== defenderNationalId))
+  )
+}

 if (
   subpoena.case &&
   subpoena.defendant &&
   (defenderChoice ||
     defenderNationalId ||
     defenderName ||
     defenderEmail ||
     defenderPhoneNumber ||
     requestedDefenderChoice ||
     requestedDefenderNationalId ||
     requestedDefenderName)
 ) {
-  const resetDefenderChoiceConfirmed =
-    subpoena.defendant?.isDefenderChoiceConfirmed &&
-    ((defenderChoice &&
-      subpoena.defendant?.defenderChoice !== defenderChoice) ||
-      (defenderNationalId &&
-        subpoena.defendant?.defenderNationalId !== defenderNationalId))
+  const resetDefenderChoiceConfirmed = this.shouldResetDefenderChoice(
+    subpoena.defendant,
+    defenderChoice,
+    defenderNationalId
+  )
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a92bd7f and 7b92849.

📒 Files selected for processing (3)
  • apps/judicial-system/backend/src/app/modules/police/index.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/police/police.service.ts (5 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
apps/judicial-system/backend/src/app/modules/police/index.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/subpoena/subpoena.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/police/police.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."
📓 Learnings (3)
apps/judicial-system/backend/src/app/modules/police/index.ts (1)
Learnt from: unakb
PR: island-is/island.is#16393
File: apps/judicial-system/digital-mailbox-api/src/app/modules/cases/models/subpoena.response.ts:164-169
Timestamp: 2024-11-12T15:15:11.835Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)
Learnt from: gudjong
PR: island-is/island.is#16863
File: apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts:173-174
Timestamp: 2024-11-27T14:24:01.943Z
Learning: When updating records in the `SubpoenaService` class (`apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts`), prefer to log errors when multiple rows are affected instead of throwing an exception.
Learnt from: gudjong
PR: island-is/island.is#16863
File: apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts:163-216
Timestamp: 2024-11-27T14:25:48.464Z
Learning: When using Sequelize transactions in the backend services, exceptions thrown within the transaction callback are sufficient for rollback, and additional exception handling within the transaction is not necessary.
Learnt from: oddsson
PR: island-is/island.is#16329
File: apps/judicial-system/backend/src/app/modules/notification/subpoenaNotification.service.ts:0-0
Timestamp: 2024-11-12T15:15:26.274Z
Learning: In `apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts`, the method `findBySubpoenaId` throws an error if the subpoena is not found. Therefore, downstream code does not need to check if the result is undefined.
apps/judicial-system/backend/src/app/modules/police/police.service.ts (1)
Learnt from: unakb
PR: island-is/island.is#16393
File: apps/judicial-system/digital-mailbox-api/src/app/modules/cases/models/subpoena.response.ts:164-169
Timestamp: 2024-11-12T15:15:11.835Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
🔇 Additional comments (6)
apps/judicial-system/backend/src/app/modules/police/index.ts (1)

4-4: LGTM! Export of SubpoenaInfo interface

The addition of the SubpoenaInfo export aligns with the PR's objective to enhance the subpoena handling process.

apps/judicial-system/backend/src/app/modules/police/police.service.ts (2)

61-67: LGTM! Well-structured SubpoenaInfo interface

The interface properly encapsulates all necessary fields for subpoena status information with appropriate optionality.


Line range hint 395-402: LGTM! Robust error handling

The error handling follows the service's pattern with proper logging and clear error messages. The comment explains the behavior when the service is unavailable.

apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (3)

86-86: LGTM: Sequelize injection properly implemented.

The Sequelize connection is correctly injected using the @InjectConnection() decorator.


258-280: LGTM: Finder methods properly implemented with improved error handling.

The finder methods are well-implemented with:

  • Clear error messages
  • Proper use of NotFoundException
  • Consistent include patterns

359-383: LGTM with verification: Comprehensive subpoena status handling.

The implementation properly handles subpoena status updates with appropriate checks and authorization. However, let's verify that this method is properly guarded at the controller/resolver level.

✅ Verification successful

Properly guarded endpoint with role-based access and existence checks

The implementation is properly secured at the controller level with:

  • @UseGuards(SubpoenaExistsGuard) for validating subpoena existence
  • Role-based access control through @RolesRules decorator with multiple roles (districtCourtJudge, districtCourtAssistant, districtCourtRegistrar)
  • User context through @CurrentHttpUser() decorator
  • Subpoena context through @CurrentSubpoena() decorator
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the getSubpoena method is properly guarded in controllers/resolvers
ast-grep --pattern 'class $_ {
  $$$
  @$_Guard()
  $$$
  getSubpoena($_, $_) {
    $$$
  }
  $$$
}'

Length of output: 102


Script:

#!/bin/bash
# Let's search for files that might contain the controller/resolver using this service
rg -l "SubpoenaService" --type ts

# Then let's look for any endpoint or resolver that calls getSubpoena
rg "getSubpoena\(" --type ts -A 5 -B 5

Length of output: 11718


Script:

#!/bin/bash
# Let's check the guards on the controller endpoint
rg -B 10 "getSubpoena\(" apps/judicial-system/backend/src/app/modules/subpoena/subpoena.controller.ts

# Also check what SubpoenaExistsGuard does
cat apps/judicial-system/backend/src/app/modules/subpoena/guards/SubpoenaExistsGuard.ts

Length of output: 986

@oddsson oddsson added the automerge Merge this PR as soon as all checks pass label Dec 3, 2024
@kodiakhq kodiakhq bot merged commit 9f4f9ae into main Dec 3, 2024
89 checks passed
@kodiakhq kodiakhq bot deleted the j-s/improved-security branch December 3, 2024 22:32
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.

3 participants