Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(auth-admin): Webhook for general mandate delegation #16257

Merged
merged 12 commits into from
Oct 8, 2024

Conversation

GunnlaugurG
Copy link
Member

@GunnlaugurG GunnlaugurG commented Oct 3, 2024

What

Webhook to create General mandate delegation on Zendesk event.

Why

So zendesk users can create the delegation throught zendesk and not our admin portal.

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 endpoint for creating delegations using Zendesk ticket IDs.
    • Added a custom authentication guard for validating incoming requests from Zendesk webhooks.
    • Enhanced secret management by adding a new webhook secret.
    • Implemented middleware to handle raw body data in requests.
    • Expanded data handling capabilities with the addition of a new data transfer object for Zendesk webhooks.
    • Added error handling for invalid date formats within the delegation administration module.
  • Bug Fixes

    • Updated health check paths for various services to ensure proper monitoring.
  • Documentation

    • Improved test coverage for delegation administration functionality, particularly regarding Zendesk interactions.
  • Chores

    • Updated service configurations for improved performance and security across various environments.

@GunnlaugurG GunnlaugurG requested review from a team as code owners October 3, 2024 14:23
Copy link
Contributor

coderabbitai bot commented Oct 3, 2024

Walkthrough

The changes in this pull request introduce a new webhook secret configuration for the authentication service, specifically ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE. The DelegationAdminController is enhanced with a new method for handling POST requests related to Zendesk ticket IDs, while the test suite is updated to validate this functionality. Additionally, middleware is added to support raw body parsing in incoming requests, and a new DTO for Zendesk webhook input is introduced. The DelegationAdminCustomService class is also modified to improve delegation handling based on Zendesk tickets.

Changes

File Change Summary
apps/services/auth/admin-api/infra/auth-admin-api.ts Added new secret: ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE.
apps/services/auth/admin-api/src/app/app.module.ts Removed import: DelegationApiUserSystemNotificationConfig.
apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts Added ZendeskAuthGuard, moved @Scopes decorator, added createByZendeskId method.
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts Added body-parser middleware, new tests for POST /delegation-admin/zendesk endpoint.
apps/services/auth/admin-api/src/environments/environment.ts Added property: zendeskGeneralMandateWebhookSecret in devConfig and prodConfig.
libs/auth-api-lib/src/index.ts Added export for zendesk-webhook-input.dto.
libs/auth-api-lib/src/lib/delegations/dto/zendesk-webhook-input.dto.ts Introduced ZendeskWebhookInputDto class with id property.
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts Updated methods for processing Zendesk tickets, added createDelegationByZendeskId method.
libs/auth-nest-tools/src/lib/rawBodyRequest.type.ts Introduced RawBodyRequest interface extending Request with rawBody property.
libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts Added ZendeskAuthGuard for validating Zendesk webhook requests.
libs/infra-nest-server/src/lib/bootstrap.ts Updated bootstrap function to include optional beforeServerStart parameter.
libs/infra-nest-server/src/lib/types.ts Added beforeServerStart property to RunServerOptions type.
libs/portals/admin/delegation-admin/src/constants/errors.ts Added error code ErrorCodes.INVALID_DATE_FORMAT to FORM_ERRORS.
libs/portals/admin/delegation-admin/src/lib/messages.ts Added message invalidDateFormatError for date format validation.

Possibly related PRs


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 12

🧹 Outside diff range and nitpick comments (11)
apps/services/auth/admin-api/src/main.ts (1)

18-28: Implementation looks good, with room for improvement.

The beforeServerStart function correctly adds the bodyParser.json() middleware, which aligns with NestJS best practices. The custom verify function to assign the raw body is a useful addition, especially for webhook processing.

However, consider the following improvements:

  1. Type safety: Use a more specific type for req instead of any.
  2. Error handling: Add try-catch block to handle potential errors during body parsing.
  3. Buffer handling: Consider using Buffer.isBuffer(buf) for more explicit buffer checking.

Here's a suggested refactoring:

import { Request, Response } from 'express';

beforeServerStart: async (app) => {
  app.use(
    bodyParser.json({
      verify: (req: Request, res: Response, buf: Buffer, encoding: string) => {
        try {
          if (Buffer.isBuffer(buf) && buf.length) {
            (req as any).rawBody = buf;
          }
        } catch (error) {
          console.error('Error processing request body:', error);
        }
      },
    }),
  )
},

This refactoring improves type safety, adds error handling, and makes the buffer check more explicit.

🧰 Tools
🪛 Biome

[error] 22-22: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

libs/testing/nest/src/lib/setup.ts (1)

44-51: LGTM! Consistent implementation of the new option.

The changes to setupAppWithoutAuth correctly implement the new beforeServerStart option, maintaining backward compatibility with the default undefined value. The implementation adheres to coding guidelines and is consistent with the interface update.

For improved clarity, consider adding a brief comment explaining the purpose of the beforeServerStart option:

// Allow custom logic execution before server start
beforeServerStart = undefined,
libs/testing/nest/src/lib/testServer.ts (2)

29-35: LGTM! Consider adding an example usage in the comment.

The addition of the beforeServerStart option enhances the flexibility of the test server setup, aligning well with the PR objectives. The TypeScript usage for defining the new property is correct and follows the coding guidelines.

To further improve reusability and ease of use across different NextJS apps, consider adding a brief example of how to use this new option in the comment.

Here's a suggested addition to the comment:

/**
 * Hook to run before server is started.
 * @param app The nest application instance.
 * @returns a promise that resolves when the hook is done.
 * @example
 * beforeServerStart: async (app) => {
 *   await app.get(SomeService).initializeData();
 * }
 */

44-44: LGTM! Consider adding error handling for the beforeServerStart hook.

The implementation of the beforeServerStart hook is correct and aligns with the PR objectives. It enhances the configurability of the test server while maintaining backwards compatibility.

To improve robustness, consider adding error handling for the beforeServerStart hook execution. This will help developers identify and debug issues more easily if the hook fails.

Here's a suggested improvement:

   if (beforeServerStart) {
-    await beforeServerStart(app)
+    try {
+      await beforeServerStart(app)
+    } catch (error) {
+      console.error('Error in beforeServerStart hook:', error)
+      throw error // or handle it as appropriate for your use case
+    }
   }

Also applies to: 73-75

libs/infra-nest-server/src/lib/bootstrap.ts (1)

130-132: LGTM! Consider adding error handling.

The implementation of the beforeServerStart hook is correct and enhances the reusability of the bootstrap function across different NextJS apps. It's properly typed and positioned logically in the bootstrap process.

Consider adding error handling to prevent potential issues if the beforeServerStart function throws an error:

 if (options.beforeServerStart) {
-  await options.beforeServerStart(app)
+  try {
+    await options.beforeServerStart(app)
+  } catch (error) {
+    logger.error('Error in beforeServerStart hook', { error })
+    throw error
+  }
 }

This will ensure that any errors in the beforeServerStart hook are properly logged before being rethrown, aiding in debugging and maintaining the expected behavior of stopping the bootstrap process if an error occurs.

apps/services/auth/admin-api/infra/auth-admin-api.ts (1)

77-78: LGTM! Consider adding a comment for clarity.

The addition of the ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE secret is appropriate and aligns with the PR objective of implementing a webhook for general mandate delegation. The naming convention and path structure are consistent with other secrets in the file.

Consider adding a brief comment above this new secret to explain its purpose, for example:

// Secret for authenticating Zendesk webhook requests for general mandate delegation
ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE:
  '/k8s/services-auth/ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE',

This would improve code readability and make it easier for other developers to understand the purpose of this secret.

apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.spec.ts (1)

342-361: New test case for incorrect Zendesk ticket status

The new test case is a valuable addition:

  1. It covers an important edge case: rejecting delegation creation when the Zendesk ticket status is incorrect.
  2. It demonstrates the improved flexibility of the mockZendeskService function.
  3. The test aligns with the PR objectives by ensuring proper handling of Zendesk-triggered events.

Consider adding an assertion to verify that no delegation was created in the database. This would provide a more comprehensive check of the system's behavior. For example:

// Assert no delegation was created
const createdDelegation = await delegationModel.findOne({
  where: { fromNationalId, toNationalId }
});
expect(createdDelegation).toBeNull();
charts/identity-server/values.prod.yaml (1)

Line range hint 1-1000: Overall improvements to identity server configuration. Monitor performance post-deployment.

The changes in this file encompass several improvements across multiple services:

  1. Addition of a new secret for Zendesk webhook integration
  2. Standardization of health check paths
  3. Introduction of init containers for database management
  4. Adjustments to replica counts and resource allocations

These changes align well with the PR objective and should enhance the system's reliability, scalability, and performance.

After deploying these changes, closely monitor the following:

  1. The performance of the new Zendesk webhook integration
  2. The effectiveness of the new health check endpoints
  3. The impact of the adjusted resource allocations on overall system performance
  4. The behavior of the services under varying load conditions with the new scaling configurations

Consider setting up alerts for any unexpected behavior in these areas to quickly identify and address any issues that may arise from these changes.

charts/identity-server/values.dev.yaml (1)

Line range hint 1-1000: Summary of changes and suggestions

The primary change related to the PR objectives is the addition of the ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE secret in the services-auth-admin-api configuration. This supports the implementation of the Zendesk webhook for general mandate delegation.

Other changes in the file are focused on improving system performance and reliability across multiple services. While these are beneficial, they are not directly related to the webhook implementation.

To fully review the webhook implementation, it would be necessary to examine other files, particularly:

  1. The source code for the services-auth-admin-api where the webhook endpoint is likely implemented.
  2. Any new or modified Kubernetes manifests that might be setting up additional resources for the webhook.
  3. Documentation updates explaining the new webhook functionality.

Consider adding comments or documentation within this configuration file to explain the purpose of the new secret and its relation to the Zendesk webhook. This would improve maintainability and make it easier for other developers to understand the system architecture.

apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (1)

98-117: Consider adding auditing to the createByZendeskId method

The new createByZendeskId method lacks an @Audit decorator, which is used in other methods to track actions for auditing purposes. Including auditing will enhance traceability and maintain consistency across endpoints.

Apply this diff to include the audit decorator:

+  @Audit<DelegationDTO>({
+    namespace,
+    action: 'createByZendeskId',
+    resources: (delegation) => delegation?.id ?? undefined,
+  })
   @BypassAuth()
   @UseGuards(ZendeskAuthGuard(ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE))
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (1)

49-53: Define an Interface for Return Type

To enhance readability and maintainability, consider defining an interface for the return type of getZendeskCustomFields.

You can define an interface like this:

interface ZendeskCustomFields {
  fromReferenceId: string
  toReferenceId: string
  validTo: string | null
  createdByNationalId: string | null
}

And update the method signature:

private getZendeskCustomFields(ticket: Ticket): ZendeskCustomFields {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7b20920 and 3ed8368.

📒 Files selected for processing (16)
  • apps/services/auth/admin-api/infra/auth-admin-api.ts (1 hunks)
  • apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (4 hunks)
  • apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (3 hunks)
  • apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.spec.ts (2 hunks)
  • apps/services/auth/admin-api/src/main.ts (2 hunks)
  • charts/identity-server/values.dev.yaml (1 hunks)
  • charts/identity-server/values.prod.yaml (1 hunks)
  • charts/identity-server/values.staging.yaml (1 hunks)
  • libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (5 hunks)
  • libs/auth-api-lib/src/lib/delegations/constants/zendesk.ts (1 hunks)
  • libs/auth-nest-tools/src/index.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts (1 hunks)
  • libs/infra-nest-server/src/lib/bootstrap.ts (1 hunks)
  • libs/infra-nest-server/src/lib/types.ts (1 hunks)
  • libs/testing/nest/src/lib/setup.ts (2 hunks)
  • libs/testing/nest/src/lib/testServer.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
apps/services/auth/admin-api/infra/auth-admin-api.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.spec.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/services/auth/admin-api/src/main.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/auth-api-lib/src/lib/delegations/admin/delegation-admin-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/constants/zendesk.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-nest-tools/src/index.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-nest-tools/src/lib/zendeskAuth.guard.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/infra-nest-server/src/lib/bootstrap.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/infra-nest-server/src/lib/types.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/testing/nest/src/lib/setup.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/testing/nest/src/lib/testServer.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts

[error] 154-154: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

apps/services/auth/admin-api/src/main.ts

[error] 22-22: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (29)
libs/auth-api-lib/src/lib/delegations/constants/zendesk.ts (1)

5-6: LGTM! The additions align with the PR objectives and existing structure.

The new constants DelegationValidToId and DelegationCreatedById are consistent with the existing naming convention and structure. They appear to be custom field IDs for Zendesk, which aligns with the PR's objective of implementing a webhook for general mandate delegation.

This change adheres to the coding guidelines for files in the libs directory:

  • It maintains reusability across different NextJS apps by keeping these constants in a shared location.
  • The file uses TypeScript, exporting the constants for use in other parts of the system.
  • The simple structure of this constants file supports effective tree-shaking and bundling.
apps/services/auth/admin-api/src/main.ts (2)

6-6: LGTM: Import statement is correct.

The import statement for bodyParser is correctly placed and uses the appropriate import syntax for the package.


18-28: Consider security implications of storing raw request bodies.

While storing the raw request body can be useful, it also presents some security considerations:

  1. Sensitive data exposure: Ensure that sensitive information in the raw body is properly handled and not logged or exposed unintentionally.
  2. Memory usage: Large payloads could consume significant memory. Consider adding a size limit to mitigate potential DoS attacks.

To address these concerns:

  1. Implement a size limit for incoming payloads.
  2. Ensure proper handling of sensitive data in the raw body.
🧰 Tools
🪛 Biome

[error] 22-22: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

libs/auth-nest-tools/src/index.ts (1)

16-16: LGTM: New export aligns with coding guidelines

The addition of export * from './lib/zendeskAuth.guard' is consistent with the existing export pattern and adheres to the coding guidelines for libs/**/* files:

  1. It enhances reusability by making zendeskAuth.guard available across different NextJS apps.
  2. The wildcard export ensures that all TypeScript types defined in zendeskAuth.guard are accessible.
  3. This export doesn't impede effective tree-shaking and bundling practices.

This change appropriately expands the module's public API to include the new zendeskAuth.guard functionality.

libs/testing/nest/src/lib/setup.ts (2)

17-17: LGTM! Enhances setup flexibility.

The addition of the beforeServerStart option to the SetupOptions interface is a well-implemented enhancement. It allows for custom logic execution before server start, increasing the flexibility of the testing setup process. The TypeScript type definition is correct and adheres to best practices.


17-17: Overall, excellent enhancement to the testing setup process.

The changes introduced in this file significantly improve the flexibility of the testing setup process by allowing custom logic execution before server start. The implementation is consistent, adheres to coding guidelines, and maintains backward compatibility. These enhancements will likely improve the testing capabilities for various NestJS applications using this library.

Also applies to: 44-51

libs/infra-nest-server/src/lib/types.ts (2)

51-57: Excellent addition of the beforeServerStart hook!

The new beforeServerStart property is a well-implemented and valuable addition to the RunServerOptions type. It enhances the flexibility of server initialization, allowing for custom logic to be executed before the server starts. The implementation adheres to TypeScript best practices and is well-documented.

Key points:

  1. Correct TypeScript usage for defining the optional function property.
  2. Clear and accurate JSDoc comment providing description, parameter, and return type information.
  3. Enhances reusability and customization options across different NextJS apps.
  4. Optional nature ensures effective tree-shaking.

This addition aligns well with the PR objectives and the existing structure of RunServerOptions.


Line range hint 1-57: Summary: Valuable enhancement to server initialization options

The addition of the beforeServerStart hook to the RunServerOptions type is a well-implemented and valuable enhancement. It provides greater flexibility in server initialization, allowing for custom logic to be executed before the server starts. This change:

  1. Adheres to TypeScript best practices and coding guidelines for libs/**/* files.
  2. Enhances reusability and customization options across different NextJS apps.
  3. Maintains backwards compatibility due to its optional nature.
  4. Is well-documented, ensuring clear usage for developers.

The implementation aligns well with the PR objectives of improving the server initialization process. Great job on this enhancement!

libs/testing/nest/src/lib/testServer.ts (1)

6-6: Verify the usage of the imported bodyParser.

The bodyParser import has been added, but its usage is not visible in the provided changes. To ensure effective tree-shaking and bundling practices:

  1. If bodyParser is used elsewhere in the file or in dependent modules, please add a comment explaining its purpose.
  2. If it's not used, consider removing this import to maintain clean and efficient code.

To check the usage of bodyParser in the codebase, run the following script:

✅ Verification successful

Remove the unused bodyParser import.

The bodyParser import in testServer.ts is not utilized in the current implementation. To maintain clean and efficient code:

  • Remove the following line from libs/testing/nest/src/lib/testServer.ts:
    import bodyParser from 'body-parser'
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

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

# Search for bodyParser usage
echo "Searching for bodyParser usage:"
rg --type typescript 'bodyParser' libs/testing/nest/src

# Check if bodyParser is used in other files that import from testServer.ts
echo "Checking files that import from testServer.ts:"
rg --type typescript 'from.*testServer' libs/testing/nest | xargs rg --type typescript 'bodyParser'

Length of output: 436


Script:

#!/bin/bash
# Description: Check usage of bodyParser in the codebase without relying on --type

# Search for bodyParser usage in .ts and .tsx files
echo "Searching for bodyParser usage in TypeScript files:"
rg 'bodyParser' --glob '**/*.ts' --glob '**/*.tsx' libs/testing/nest/src

# Check if bodyParser is used in other files that import from testServer.ts
echo "Checking files that import from testServer.ts for bodyParser usage:"
rg 'from\s+["'\''].*testServer["'\'']' --glob '**/*.ts' --glob '**/*.tsx' libs/testing/nest | xargs -I {} rg 'bodyParser' {}

Length of output: 928


Script:

#!/bin/bash
# Description: Check usage of bodyParser in the codebase without relying on --type

# Search for bodyParser usage in .ts and .tsx files
echo "Searching for bodyParser usage in TypeScript files:"
rg 'bodyParser' --glob '**/*.ts' --glob '**/*.tsx' libs/testing/nest/src

# Check if bodyParser is used in other files that import from testServer.ts
echo "Checking files that import from testServer.ts for bodyParser usage:"
rg 'from\s+["'\''].*testServer["'\'']' --glob '**/*.ts' --glob '**/*.tsx' libs/testing/nest | awk -F: '{print $1}' | sort -u | xargs -I {} rg 'bodyParser' {}

Length of output: 569

libs/infra-nest-server/src/lib/bootstrap.ts (1)

130-132: Update documentation and verify usage across the codebase.

The addition of the beforeServerStart option enhances the flexibility of the bootstrap function. To ensure proper adoption and usage:

  1. Please update the relevant documentation to include information about this new option, its purpose, and usage examples.

  2. It's important to verify that this change doesn't unintentionally affect other parts of the codebase that use the bootstrap function.

To verify the impact and usage of this change, run the following script:

This will help identify any areas that might benefit from using this new option or that might need adjustment due to this change.

✅ Verification successful

Documentation updated and usage verified across the codebase.

The beforeServerStart option has been properly integrated and documented. Extensive checks across the codebase confirm that this addition does not adversely affect existing functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing usage of the bootstrap function and potential impact areas.

# Test: Search for usage of the bootstrap function
echo "Searching for usage of the bootstrap function:"
rg --type typescript "bootstrap\(" -A 5

# Test: Check for any existing beforeServerStart-like functionality that might be replaced by this new option
echo "Checking for potential beforeServerStart-like functionality:"
rg --type typescript "before.*server.*start" -i

Length of output: 395


Script:

#!/bin/bash
# Description: Check for existing usage of the bootstrap function and potential impact areas.

# Test: Search for usage of the bootstrap function in .ts and .tsx files
echo "Searching for usage of the bootstrap function in TypeScript files:"
rg "bootstrap\(" -g "*.ts" -g "*.tsx" -A 5

# Test: Check for any existing beforeServerStart-like functionality in .ts and .tsx files
echo "Checking for potential beforeServerStart-like functionality in TypeScript files:"
rg "before.*server.*start" -i -g "*.ts" -g "*.tsx"

Length of output: 19023

apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.spec.ts (2)

227-237: Improved flexibility in mockZendeskService function

The changes to the mockZendeskService function enhance its flexibility and reusability:

  1. The new optional info parameter allows for dynamic configuration of tags and status.
  2. Default values are preserved, maintaining backward compatibility.
  3. The use of the object spread operator ensures that only provided values in info override the defaults.

These improvements allow for more diverse test scenarios without altering the core logic of the test suite.

Also applies to: 244-245


Line range hint 1-361: Overall improvements in test coverage and flexibility

The changes in this file significantly enhance the test suite:

  1. The mockZendeskService function now allows for more flexible and diverse test scenarios.
  2. The new test case for incorrect Zendesk ticket status improves coverage of edge cases.
  3. These modifications align well with the PR objectives of implementing a webhook for general mandate delegation triggered by Zendesk events.

The changes adhere to NestJS testing practices and contribute to a more robust test suite. They demonstrate a thoughtful approach to ensuring the reliability of the Zendesk integration.

charts/identity-server/values.prod.yaml (4)

Line range hint 391-394: Health check path standardized. Verify endpoint implementation.

The update of the readiness check path to '/health/check' for services-auth-delegation-api aligns with standard naming conventions, which is a good practice.

To ensure this endpoint is correctly implemented, run the following command:

#!/bin/bash
# Verify the existence and response of the new health check endpoint
kubectl get pods -n identity-server-delegation -l app=services-auth-delegation-api -o jsonpath='{.items[0].metadata.name}' | xargs -I {} kubectl exec -n identity-server-delegation {} -- curl -s http://localhost:3333/health/check

This command should return an appropriate response indicating the health status of the service.


Line range hint 458-515: Configuration improvements for services-auth-ids-api. Verify resource allocation and scaling.

The changes to services-auth-ids-api configuration are positive improvements:

  1. Addition of init containers for migrations and seeding
  2. Updated replica count (min: 2, max: 15) for better scalability
  3. Increased resource limits to support new features and load

These changes should enhance the service's reliability and performance.

To ensure these changes are correctly implemented, run the following commands:

#!/bin/bash
# Verify the existence of init containers
kubectl get pods -n identity-server -l app=services-auth-ids-api -o jsonpath='{.spec.initContainers[*].name}'

# Verify the HPA configuration
kubectl get hpa -n identity-server services-auth-ids-api -o jsonpath='{.spec.minReplicas} {.spec.maxReplicas}'

# Verify the resource limits
kubectl get deployment -n identity-server services-auth-ids-api -o jsonpath='{.spec.template.spec.containers[0].resources.limits}'

These commands should confirm the presence of init containers, the correct HPA settings, and the updated resource limits.


Line range hint 328-335: Health check paths updated. Verify endpoint implementation.

The changes to the health check paths for services-auth-admin-api are good improvements:

  1. Readiness check path updated to '/backend/health/check'
  2. Liveness check path changed to '/backend/liveness'

These more specific paths suggest enhanced health check mechanisms.

To ensure these endpoints are correctly implemented, run the following commands:

These commands should return appropriate responses indicating the health status of the service.


298-298: LGTM! Verify the secret's existence in the Kubernetes cluster.

The addition of the ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE secret is in line with the PR objective and follows good security practices by storing it as a Kubernetes secret.

To ensure the secret is properly set up, run the following command:

This command should return the secret value without exposing it in the logs. If it returns a non-empty value, the secret is correctly set up.

charts/identity-server/values.staging.yaml (5)

Line range hint 1-836: Summary: Changes align with PR objectives and follow best practices

The modifications in this file align well with the PR objective of implementing a webhook for general mandate delegation triggered by Zendesk events. Key changes include:

  1. Addition of a Zendesk webhook secret for general mandate delegation.
  2. Implementation of init containers for database migrations and seeding in the services-auth-ids-api service.
  3. Minor adjustments to NODE_OPTIONS and ingress configurations to support the new functionality.

These changes follow Kubernetes best practices and appear to enhance the system's capabilities as intended. Ensure to monitor the performance of the new components after deployment, particularly the init containers and the services-auth-public-api memory usage.


Line range hint 462-489: Approval: Init containers added for database management

The addition of init containers for database migrations and seeding is a good practice. This ensures that the database schema is up-to-date and properly seeded before the main application starts, which aligns with best practices for database management in Kubernetes deployments.

To ensure the resource allocations for these init containers are sufficient, please monitor their performance during the next deployment and adjust if necessary. You can use the following command to check the status and duration of the init containers after deployment:

#!/bin/bash
# Check the status and duration of init containers

kubectl get pods -n identity-server -l app=services-auth-ids-api -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{range .status.initContainerStatuses[*]}{.name}{": "}{.state.terminated.reason}{" ("}{.state.terminated.exitCode}{"), duration: "}{.state.terminated.finishedAt}{" - "}{.state.terminated.startedAt}{"\n"}{end}{"\n"}{end}'

If the init containers are consistently taking too long or failing, consider increasing the resource limits.


Line range hint 745-745: Minor adjustment to NODE_OPTIONS

The NODE_OPTIONS environment variable for services-auth-public-api has been adjusted to --max-old-space-size=345 -r dd-trace/init. This seems to be a minor change in memory allocation. Ensure that this adjustment is sufficient for the service's needs.

Monitor the memory usage of the services-auth-public-api pods after deployment to ensure this change doesn't negatively impact performance:

#!/bin/bash
# Monitor memory usage of services-auth-public-api pods

kubectl top pods -n identity-server-admin -l app=services-auth-public-api --containers

Line range hint 788-794: Ingress configuration updated for API rewrite

The ingress configuration for services-auth-public-api has been updated to include a rewrite target for API requests. This change adds the annotation nginx.ingress.kubernetes.io/rewrite-target: '/$2' and modifies the path to /api(/|$)(.*). This change appears to be related to the new webhook functionality and should properly route API requests.

After deployment, verify that API requests are being properly routed:

#!/bin/bash
# Test API routing

# Replace <your-test-endpoint> with an actual API endpoint
curl -I https://identity-server.staging01.devland.is/api/<your-test-endpoint>

# Check the logs of the ingress controller for any routing errors
kubectl logs -n nginx-ingress-external -l app=nginx-ingress-controller --tail=100 | grep error

301-301: New secret added for Zendesk webhook

A new secret ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE has been added to the services-auth-admin-api configuration. This aligns with the PR objective of implementing a webhook for general mandate delegation triggered by Zendesk events.

To ensure this secret is properly set up, please run the following verification script:

✅ Verification successful

Zendesk Webhook Secret Verified

The secret ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE is correctly defined across all relevant environments (dev, prod, and staging) in the Kubernetes configuration files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence of the Zendesk webhook secret in the Kubernetes secrets

# Check if the secret exists
kubectl get secret -n identity-server-admin $(kubectl get secret -n identity-server-admin | grep services-auth | awk '{print $1}') -o jsonpath='{.data.ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE}' | base64 --decode

# If the secret exists, this command will output its value (which we don't want to see in logs)
# If it doesn't exist, it will return an error

Length of output: 319


Script:

#!/bin/bash
# Search for the Zendesk webhook secret key in the codebase YAML files

rg 'ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE' --type yaml

Length of output: 489

charts/identity-server/values.dev.yaml (3)

Line range hint 265-268: Performance and reliability improvements

Several changes have been made to enhance the performance and reliability of the services-auth-admin-api:

  1. The healthCheck configuration has been updated with more specific paths and timeout settings.
  2. The Horizontal Pod Autoscaler (hpa) settings have been adjusted, allowing for a higher maximum number of replicas (from 3 to 10).
  3. Resource limits and requests have been increased, particularly the memory limit (from 512Mi to 768Mi).

These changes should improve the service's scalability and responsiveness, which is beneficial when implementing new features like the Zendesk webhook.

Also applies to: 276-281, 290-295


Line range hint 1-1000: System-wide performance enhancements

Similar performance and reliability improvements have been applied across multiple services in the identity server configuration:

  1. Standardized healthCheck configurations with specific paths and timeout settings.
  2. Adjusted Horizontal Pod Autoscaler (hpa) settings, generally allowing for higher maximum replicas.
  3. Increased resource limits and requests, particularly for memory.

These changes appear to be part of a broader initiative to improve the overall system performance and are not directly related to the Zendesk webhook implementation. However, they will support the system's ability to handle increased load, which may be beneficial when introducing new features like the webhook.

To ensure these changes are consistent across services, run the following command:

#!/bin/bash
# Check for consistency in healthCheck and hpa configurations across services
yq e '.[] | select(has("healthCheck") and has("hpa")) | [.healthCheck.liveness.path, .healthCheck.readiness.path, .hpa.scaling.replicas.max] | @csv' charts/identity-server/values.dev.yaml

301-301: New secret added for Zendesk webhook

A new secret ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE has been added to the services-auth-admin-api configuration. This aligns with the PR objective of implementing a webhook for general mandate delegation triggered by Zendesk events.

To ensure this secret is properly set in the environment, run the following command:

libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts (1)

7-36: Well-structured and reusable guard implementation

The ZendeskAuthGuard function is implemented as a factory, allowing you to pass in different signing secrets as needed. This promotes reusability across different modules and aligns with TypeScript best practices.

apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (3)

14-14: Imports are correctly updated to include authentication guards

The addition of BypassAuth and ZendeskAuthGuard to the imports is appropriate for implementing the custom authentication flow required for the new Zendesk webhook endpoint.

Also applies to: 20-20


48-48: Confirm the placement of the @Scopes decorator

Ensure that the @Scopes(DelegationAdminScopes.read) decorator is applied to the correct method and that it aligns with the desired access control for the getDelegationAdmin endpoint.

Would you like assistance verifying that the scope requirements are correctly enforced?


98-117: Ensure ZendeskAuthGuard provides adequate security

Verify that ZendeskAuthGuard securely validates incoming requests using the ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE. Confirm that the guard correctly handles authentication and that no security vulnerabilities are introduced by bypassing the default authentication.

Run the following script to check for usages and implementations of ZendeskAuthGuard in the codebase:

✅ Verification successful

ZendeskAuthGuard Security Verified

The implementation of ZendeskAuthGuard securely validates incoming requests using HMAC with SHA-256. Its usage in delegation-admin.controller.ts correctly applies the guard with the necessary secret, ensuring proper authentication without introducing security vulnerabilities.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all implementations and usages of ZendeskAuthGuard
# Expect: ZendeskAuthGuard is implemented correctly and used appropriately.

# Search for the implementation of ZendeskAuthGuard
rg --type typescript --files-with-matches 'class ZendeskAuthGuard' | xargs cat

# Search for all usages of ZendeskAuthGuard
rg --type typescript 'ZendeskAuthGuard'

Length of output: 190


Script:

#!/bin/bash
# Description: Find all implementations and usages of ZendeskAuthGuard with corrected file type
# Expect: ZendeskAuthGuard is implemented correctly and used appropriately.

# Search for the implementation of ZendeskAuthGuard
rg --type ts 'class ZendeskAuthGuard' && rg --type ts 'class ZendeskAuthGuard' | xargs cat

# Search for all usages of ZendeskAuthGuard
rg --type ts 'ZendeskAuthGuard'

Length of output: 1098


Script:

#!/bin/bash
# Description: Correctly find and display implementations and usages of ZendeskAuthGuard
# Expect: ZendeskAuthGuard is implemented correctly and used appropriately.

# Search for the implementation of ZendeskAuthGuard using the --files-with-matches flag to get only file paths
rg --type ts --files-with-matches 'class ZendeskAuthGuard' | xargs cat

# Search for all usages of ZendeskAuthGuard and display the matching lines with context
rg --type ts -A2 'ZendeskAuthGuard'

Length of output: 2685

libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (1)

283-316: Ensure Transaction Rollback on Failure

While using transactions, ensure that any errors within the transaction block properly trigger a rollback to maintain data integrity.

Confirm that Sequelize is correctly configured to roll back transactions on exceptions. Also, ensure that any asynchronous operations inside the transaction are awaited to prevent unintentional commits.

Copy link

codecov bot commented Oct 3, 2024

Codecov Report

Attention: Patch coverage is 75.55556% with 22 lines in your changes missing coverage. Please review.

Project coverage is 36.87%. Comparing base (0a169cb) to head (241cff7).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...legations/admin/delegation-admin-custom.service.ts 60.46% 17 Missing ⚠️
apps/services/auth/admin-api/src/main.ts 0.00% 3 Missing ⚠️
libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts 94.11% 1 Missing ⚠️
libs/infra-nest-server/src/lib/bootstrap.ts 50.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16257      +/-   ##
==========================================
+ Coverage   36.85%   36.87%   +0.02%     
==========================================
  Files        6798     6801       +3     
  Lines      140531   140655     +124     
  Branches    39957    40032      +75     
==========================================
+ Hits        51799    51873      +74     
- Misses      88732    88782      +50     
Flag Coverage Δ
air-discount-scheme-backend 54.04% <32.25%> (-0.19%) ⬇️
air-discount-scheme-web 0.00% <ø> (ø)
api 3.37% <ø> (ø)
api-catalogue-services 77.85% <ø> (ø)
api-domains-air-discount-scheme 36.90% <27.77%> (-0.09%) ⬇️
api-domains-assets 26.71% <ø> (ø)
api-domains-auth-admin 48.77% <ø> (ø)
api-domains-communications 39.90% <31.57%> (-0.02%) ⬇️
api-domains-criminal-record 47.96% <ø> (ø)
api-domains-driving-license 44.39% <31.57%> (-0.07%) ⬇️
api-domains-education 31.48% <100.00%> (+0.03%) ⬆️
api-domains-health-insurance 34.83% <ø> (ø)
api-domains-mortgage-certificate 35.67% <27.77%> (-0.07%) ⬇️
api-domains-payment-schedule 41.13% <27.77%> (-0.12%) ⬇️
application-api-files 57.97% <100.00%> (+0.02%) ⬆️
application-core 71.54% <ø> (-0.09%) ⬇️
application-system-api 41.66% <32.25%> (-0.01%) ⬇️
application-template-api-modules 24.27% <31.57%> (-0.02%) ⬇️
application-templates-accident-notification 29.44% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 26.63% <ø> (ø)
application-templates-driving-license 18.40% <ø> (ø)
application-templates-estate 12.32% <ø> (ø)
application-templates-example-payment 25.41% <ø> (ø)
application-templates-financial-aid 14.34% <ø> (ø)
application-templates-general-petition 23.68% <ø> (ø)
application-templates-health-insurance 26.62% <ø> (ø)
application-templates-inheritance-report 6.45% <ø> (ø)
application-templates-marriage-conditions 15.23% <ø> (ø)
application-templates-mortgage-certificate 43.96% <ø> (ø)
application-templates-parental-leave 30.03% <ø> (ø)
application-types 6.71% <ø> (ø)
application-ui-components 1.28% <ø> (ø)
application-ui-shell 21.27% <ø> (ø)
auth-admin-web 2.43% <ø> (ø)
auth-nest-tools 29.84% <0.00%> (-1.48%) ⬇️
auth-react 22.77% <ø> (ø)
auth-shared 75.00% <ø> (ø)
clients-charge-fjs-v2 24.11% <ø> (ø)
clients-driving-license 40.63% <ø> (ø)
clients-driving-license-book 43.77% <27.77%> (-0.16%) ⬇️
clients-financial-statements-inao 49.29% <ø> (ø)
clients-license-client 1.83% <ø> (ø)
clients-middlewares 73.38% <100.00%> (+0.61%) ⬆️
clients-regulations 42.76% <ø> (ø)
clients-rsk-company-registry 29.76% <ø> (ø)
clients-rsk-personal-tax-return 38.00% <ø> (ø)
clients-smartsolutions 12.77% <ø> (ø)
clients-syslumenn 49.49% <27.77%> (-0.18%) ⬇️
clients-zendesk 54.61% <ø> (ø)
cms 0.43% <ø> (ø)
cms-translations 39.03% <31.57%> (-0.02%) ⬇️
content-search-index-manager 95.65% <ø> (ø)
content-search-toolkit 8.16% <ø> (ø)
contentful-apps 5.57% <ø> (ø)
dokobit-signing 63.29% <ø> (ø)
download-service 44.01% <32.25%> (-0.10%) ⬇️
email-service 61.05% <ø> (ø)
feature-flags 91.04% <ø> (ø)
file-storage 53.59% <ø> (ø)
financial-aid-backend 56.39% <27.77%> (-0.16%) ⬇️
financial-aid-shared 19.03% <ø> (ø)
icelandic-names-registry-backend 53.97% <30.00%> (-0.58%) ⬇️
infra-nest-server 48.17% <33.33%> (-0.59%) ⬇️
infra-tracing 43.24% <ø> (ø)
island-ui-core 28.44% <ø> (ø)
judicial-system-api 18.29% <ø> (ø)
judicial-system-audit-trail 69.27% <ø> (ø)
judicial-system-backend 55.17% <31.57%> (-0.03%) ⬇️
judicial-system-formatters 79.90% <ø> (ø)
judicial-system-message 67.18% <ø> (ø)
judicial-system-message-handler 48.26% <ø> (ø)
judicial-system-scheduler 69.41% <ø> (ø)
judicial-system-types 47.44% <ø> (ø)
judicial-system-web 27.96% <ø> (ø)
license-api 42.45% <32.25%> (-0.14%) ⬇️
localization 10.15% <ø> (ø)
logging 48.43% <ø> (ø)
message-queue 67.71% <ø> (ø)
nest-audit 68.20% <ø> (ø)
nest-config 78.38% <ø> (ø)
nest-feature-flags 51.46% <27.77%> (-0.56%) ⬇️
nest-problem 45.85% <30.00%> (-0.49%) ⬇️
nest-sequelize 94.44% <ø> (ø)
nest-swagger 51.71% <ø> (ø)
nova-sms 62.65% <ø> (ø)
portals-admin-regulations-admin 1.88% <ø> (ø)
reference-backend 49.79% <30.00%> (-0.62%) ⬇️
regulations 16.78% <ø> (ø)
residence-history 85.00% <ø> (ø)
services-auth-admin-api 52.12% <74.44%> (+0.13%) ⬆️
services-auth-delegation-api 57.73% <20.25%> (-0.15%) ⬇️
services-auth-ids-api 51.71% <20.25%> (-0.18%) ⬇️
services-auth-personal-representative-public 41.48% <18.98%> (-0.17%) ⬇️
services-auth-public-api 49.21% <18.98%> (-0.18%) ⬇️
services-documents 60.58% <30.00%> (-0.60%) ⬇️
services-endorsements-api 55.03% <32.25%> (-0.21%) ⬇️
services-sessions 65.36% <33.33%> (-0.41%) ⬇️
services-university-gateway 48.35% <30.00%> (-0.19%) ⬇️
services-user-notification 47.04% <35.48%> (-0.01%) ⬇️
services-user-profile 62.17% <35.48%> (-0.13%) ⬇️
shared-form-fields 31.59% <ø> (ø)
shared-mocking 64.62% <ø> (ø)
shared-pii 92.85% <ø> (ø)
shared-problem 87.50% <ø> (ø)
shared-utils 27.90% <0.00%> (-0.11%) ⬇️
skilavottord-ws 24.24% <ø> (ø)
testing-e2e 66.66% <ø> (ø)
web 1.83% <ø> (ø)

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

Files with missing lines Coverage Δ
apps/services/auth/admin-api/src/app/app.module.ts 100.00% <ø> (ø)
.../app/v2/delegations/delegation-admin.controller.ts 97.29% <100.00%> (+0.42%) ⬆️
...ces/auth/admin-api/src/environments/environment.ts 100.00% <100.00%> (ø)
libs/auth-api-lib/src/index.ts 100.00% <100.00%> (ø)
...h-api-lib/src/lib/delegations/constants/zendesk.ts 100.00% <ø> (ø)
...c/lib/delegations/dto/zendesk-webhook-input.dto.ts 100.00% <100.00%> (ø)
libs/auth-nest-tools/src/index.ts 100.00% <100.00%> (ø)
libs/infra-nest-server/src/index.ts 100.00% <100.00%> (ø)
...ra-nest-server/src/lib/includeRawBodyMiddleware.ts 100.00% <100.00%> (ø)
libs/shared/utils/src/lib/errorCodes.ts 100.00% <100.00%> (ø)
... and 6 more

... and 10 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 0a169cb...241cff7. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 3, 2024

Datadog Report

All test runs d14bfa4 🔗

100 Total Test Services: 0 Failed, 98 Passed
🔻 Test Sessions change in coverage: 20 decreased, 3 increased, 177 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-backend 0 0 0 81 0 29.69s N/A Link
air-discount-scheme-web 0 0 0 2 0 8.16s N/A Link
api 0 0 0 4 0 2.61s N/A Link
api-catalogue-services 0 0 0 23 0 10.61s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 17.83s N/A Link
api-domains-assets 0 0 0 3 0 11.36s N/A Link
api-domains-auth-admin 0 0 0 18 0 12.22s N/A Link
api-domains-communications 0 0 0 5 0 29.44s N/A Link
api-domains-criminal-record 0 0 0 5 0 8.78s N/A Link
api-domains-driving-license 0 0 0 23 0 29.75s N/A Link

🔻 Code Coverage Decreases vs Default Branch (20)

This report shows up to 5 code coverage decreases.

  • auth-nest-tools - jest 32.34% (-1.61%) - Details
  • infra-nest-server - jest 55.42% (-0.69%) - Details
  • nest-feature-flags - jest 57.27% (-0.65%) - Details
  • reference-backend - jest 54.56% (-0.65%) - Details
  • icelandic-names-registry-backend - jest 59.43% (-0.6%) - Details

Copy link
Member

@saevarma saevarma left a comment

Choose a reason for hiding this comment

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

First part of review, I have the admin service and the auth guard left to review

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

🧹 Outside diff range and nitpick comments (3)
libs/auth-api-lib/src/lib/delegations/dto/zendesk-webhook-input.dto.ts (1)

4-8: LGTM: Well-structured DTO with proper decorators.

The ZendeskWebhookInputDto class is well-defined with appropriate use of decorators for validation (@IsString()) and API documentation (@ApiProperty()). The naming convention follows best practices, and the use of TypeScript for defining props aligns with the coding guidelines.

Suggestion for improvement:
Consider adding a description to the @ApiProperty() decorator to provide more context in the API documentation. For example:

@ApiProperty({ description: 'Unique identifier for the Zendesk webhook event' })

This addition would enhance the API documentation without affecting the runtime behavior.

libs/infra-nest-server/src/index.ts (1)

6-6: LGTM! Consider adding a comment for clarity.

The new export statement is consistent with the existing code style and adheres to the coding guidelines. It enhances the module's public API by including the includeRawBodyMiddleware functionality.

Consider adding a brief comment above the new export statement to explain the purpose of the includeRawBodyMiddleware module. This would improve code readability and maintainability. For example:

+// Export middleware for including raw body in the request
 export * from './lib/includeRawBodyMiddleware'
libs/infra-nest-server/src/lib/includeRawBodyMiddleware.ts (1)

3-5: Enhance function documentation

Consider expanding the function documentation to provide more details about its purpose, parameters, and return value. This will improve code maintainability and make it easier for other developers to understand and use the middleware.

Here's a suggested improvement:

/**
 * Middleware that includes the raw body in the request object.
 * This middleware parses JSON requests and adds the raw body buffer to the request object.
 * 
 * @returns {Function} Express middleware function
 */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3ed8368 and eeb80b0.

📒 Files selected for processing (7)
  • apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (3 hunks)
  • apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (3 hunks)
  • apps/services/auth/admin-api/src/main.ts (2 hunks)
  • libs/auth-api-lib/src/index.ts (1 hunks)
  • libs/auth-api-lib/src/lib/delegations/dto/zendesk-webhook-input.dto.ts (1 hunks)
  • libs/infra-nest-server/src/index.ts (1 hunks)
  • libs/infra-nest-server/src/lib/includeRawBodyMiddleware.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts
  • apps/services/auth/admin-api/src/main.ts
🧰 Additional context used
📓 Path-based instructions (5)
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/auth-api-lib/src/index.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/dto/zendesk-webhook-input.dto.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/infra-nest-server/src/index.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/infra-nest-server/src/lib/includeRawBodyMiddleware.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."
📓 Learnings (1)
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (1)
Learnt from: saevarma
PR: island-is/island.is#16257
File: apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts:178-201
Timestamp: 2024-10-04T07:46:37.013Z
Learning: In `apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts`, ensure that test case names accurately describe the scenario being tested, particularly in cases involving invalid request signatures.
🪛 Biome
libs/infra-nest-server/src/lib/includeRawBodyMiddleware.ts

[error] 9-9: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (8)
libs/auth-api-lib/src/lib/delegations/dto/zendesk-webhook-input.dto.ts (2)

1-2: LGTM: Appropriate imports for DTO validation and API documentation.

The imports from 'class-validator' and '@nestjs/swagger' are well-chosen for validating the DTO and generating API documentation, respectively. This aligns with best practices for NestJS applications.


1-8: Compliance with coding guidelines confirmed.

This file adheres to the coding guidelines for the libs/**/* pattern:

  1. The DTO structure supports reusability across different NextJS apps.
  2. TypeScript is effectively used for defining props and exporting types.
  3. The simple and focused nature of the DTO allows for effective tree-shaking and bundling.

Great job on maintaining consistency with the project's coding standards!

libs/infra-nest-server/src/lib/includeRawBodyMiddleware.ts (2)

1-1: LGTM: Import statement is correct and necessary.

The import of bodyParser from the 'body-parser' library is appropriate for the middleware implementation.


1-14: Good adherence to coding guidelines and alignment with PR objectives

The implementation generally adheres to the coding guidelines for libs/**/* files:

  1. The middleware is exported, making it reusable across different NextJS apps.
  2. TypeScript is used, although it could be improved as suggested in the previous comment.
  3. The implementation is simple and doesn't introduce unnecessary complexity that might affect tree-shaking or bundling.

The middleware aligns with the PR objectives by facilitating the handling of webhook requests, which is part of the general mandate delegation feature. It allows for accessing the raw body of incoming requests, which can be crucial for webhook processing.

🧰 Tools
🪛 Biome

[error] 9-9: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (3)

2-2: LGTM: New imports are appropriate for the changes.

The new imports (bodyParser, DelegationDTO, DelegationAdminCustomService, and includeRawBodyMiddleware) are relevant to the new test suite for POST /delegation-admin/:zendeskId and align with the changes made in the file.

Also applies to: 15-16, 19-19


139-167: LGTM: Test suite setup follows NestJS best practices.

The new test suite for POST /delegation-admin/:zendeskId is well-structured:

  • It uses dependency injection to get the DelegationAdminCustomService.
  • beforeEach and afterEach hooks ensure proper setup and cleanup for each test.
  • Mocking of the DelegationAdminCustomService is done correctly.

This setup adheres to NestJS testing practices and ensures isolated tests.


169-192: LGTM: Test case for invalid signature is well-implemented.

This test case effectively checks the API's response to an invalid request signature:

  • The test name accurately describes the scenario: "POST /delegation-admin/zendesk should return 403 Forbidden when request signature is invalid."
  • It correctly sets up the request with invalid signature headers.
  • The assertions properly check both the status code (403) and the response body structure.

The implementation adheres to NestJS testing practices and provides good coverage for this error scenario.

libs/auth-api-lib/src/index.ts (1)

50-50: LGTM! The new export aligns with coding guidelines and PR objectives.

The addition of export * from './lib/delegations/dto/zendesk-webhook-input.dto' is appropriate and aligns well with our coding guidelines:

  1. It enhances reusability by making the Zendesk webhook input DTO available across different NextJS apps.
  2. The export likely includes TypeScript types for the webhook input, promoting type safety.
  3. The wildcard export (*) supports efficient tree-shaking during bundling.

This change also directly supports the PR objective of implementing a webhook for general mandate delegation triggered by Zendesk events.

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 (6)
libs/shared/utils/src/lib/errorCodes.ts (1)

8-8: LGTM! Consider adding a brief comment for clarity.

The new error code INVALID_DATE_FORMAT adheres to the existing naming convention and is appropriate for a shared utility. It follows TypeScript best practices for enums.

Consider adding a brief comment above the new error code to explain when it should be used. For example:

// Used when a date string doesn't match the expected format
INVALID_DATE_FORMAT = 'INVALID_DATE_FORMAT',

This addition would enhance the documentation for library consumers.

apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (1)

106-116: LGTM: Zendesk webhook implementation

The createByZendeskId method is well-implemented and aligns with the PR objectives. It follows NestJS best practices and ensures proper authentication using ZendeskAuthGuard.

Consider adding error handling to provide meaningful responses in case of failures:

@Post('/zendesk')
async createByZendeskId(@Body() { id }: ZendeskWebhookInputDto): Promise<void> {
  try {
    await this.delegationAdminService.createDelegationByZendeskId(id);
  } catch (error) {
    // Log the error
    console.error('Failed to create delegation:', error);
    // Rethrow or handle as appropriate
    throw new HttpException('Failed to create delegation', HttpStatus.INTERNAL_SERVER_ERROR);
  }
}

This will improve the robustness of the webhook endpoint.

libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (4)

156-178: LGTM: New method aligns with PR objectives

The createDelegationByZendeskId method effectively implements the webhook functionality for creating general mandate delegations from Zendesk tickets. It follows a clear and logical flow, with proper error handling for missing custom fields.

Consider adding a try-catch block to handle potential errors from this.zendeskService.getTicket(zendeskId) for more robust error handling.

try {
  const zendeskCase = await this.zendeskService.getTicket(zendeskId)
  // ... rest of the method
} catch (error) {
  throw new BadRequestException({
    message: 'Failed to retrieve Zendesk ticket',
    error: ErrorCodes.ZENDESK_TICKET_RETRIEVAL_FAILED,
  })
}

281-314: LGTM: Well-structured delegation insertion logic

The insertDelegation method effectively encapsulates the logic for creating a new delegation record. The use of a sequelize transaction ensures data consistency, which is crucial for maintaining the integrity of the delegation data.

Consider adding a comment explaining the purpose of using uuid() for the delegation ID, as it might not be immediately clear why a UUID is used instead of an auto-incrementing ID.

Add a comment above the id field:

id: uuid(), // Using UUID to ensure unique identifiers across distributed systems

316-344: LGTM: Centralized Zendesk ticket verification

The verifyZendeskTicket method effectively centralizes the logic for verifying Zendesk tickets, improving code organization and reusability. It covers all necessary checks and provides clear error messages with specific error codes.

Regarding the past review comment about passing custom fields to avoid redundant calls, the current implementation still re-extracts the custom fields. Consider updating the method signature and implementation to use the already extracted values:

private verifyZendeskTicket(
  ticket: Ticket,
  fromNationalId: string,
  toNationalId: string,
  fromReferenceId: string,
  toReferenceId: string
) {
  // ... existing checks ...

  if (fromReferenceId !== fromNationalId || toReferenceId !== toNationalId) {
    // ... existing error handling ...
  }
}

Then update the call in createDelegationByZendeskId:

const { fromReferenceId, toReferenceId, validTo, createdByNationalId } =
  this.getZendeskCustomFields(zendeskCase)

this.verifyZendeskTicket(
  zendeskCase,
  fromReferenceId,
  toReferenceId,
  fromReferenceId,
  toReferenceId
)

346-361: LGTM: Robust Zendesk date formatting

The formatZendeskDate method provides a centralized and robust way to handle Zendesk date formatting. It correctly handles null input and performs thorough date component validation.

To address the static analysis hint and improve type safety, replace the global isNaN function with Number.isNaN:

if (!day || !month || !year || Number.isNaN(day) || Number.isNaN(month) || Number.isNaN(year)) {
  throw new BadRequestException({
    message: 'Invalid date format in Zendesk ticket',
    error: ErrorCodes.INVALID_DATE_FORMAT,
  })
}

This change ensures that the type coercion performed by the global isNaN function is avoided, making the code more predictable and type-safe.

🧰 Tools
🪛 Biome

[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between eeb80b0 and 3f5870f.

📒 Files selected for processing (4)
  • apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (3 hunks)
  • libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (5 hunks)
  • libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts (1 hunks)
  • libs/shared/utils/src/lib/errorCodes.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/auth-api-lib/src/lib/delegations/admin/delegation-admin-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/shared/utils/src/lib/errorCodes.ts (2)

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

  • Cross-application utility functions, types, and constants.
  • TypeScript best practices to ensure type safety and reusability.
  • Documentation and examples for library consumers."

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts

[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (8)
apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (5)

12-21: LGTM: New imports for Zendesk webhook functionality

The addition of BypassAuth and ZendeskAuthGuard imports aligns with the PR objectives and follows NestJS architecture. These imports are necessary for implementing the new Zendesk webhook functionality.


28-28: LGTM: Import ZendeskWebhookInputDto for type safety

The addition of ZendeskWebhookInputDto import enhances type safety for the incoming Zendesk webhook payload, adhering to TypeScript best practices.


37-44: Great job addressing the security concern

The implementation of ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE with an error check addresses the security concern raised in the past review. This approach ensures that the application won't start without the required secret, enhancing overall security.


57-57: LGTM: Granular scope control for getDelegationAdmin

Moving the @Scopes(DelegationAdminScopes.read) decorator to the getDelegationAdmin method provides more granular control over method-level authorization. This change aligns with the suggestion from the past review comment.


Line range hint 1-150: Overall assessment: Well-implemented Zendesk webhook functionality

The changes in this file successfully implement the Zendesk webhook for general mandate delegation, aligning with the PR objectives. The code adheres to NestJS architecture, follows TypeScript best practices, and addresses security concerns raised in past reviews. The implementation is clean, well-structured, and maintains good separation of concerns.

Great job on this implementation!

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

Line range hint 49-79: LGTM: Improved custom field extraction

The renaming of getNationalIdsFromZendeskTicket to getZendeskCustomFields and the expansion of its functionality to extract additional custom fields (validTo and createdByNationalId) enhance the method's utility. The changes maintain good TypeScript practices and improve the overall functionality of the service.


193-203: LGTM: Improved modularity in createDelegation

The refactoring of createDelegation enhances code organization by delegating Zendesk ticket verification to verifyZendeskTicket and delegation creation to insertDelegation. This change improves the method's readability and maintainability while preserving its core functionality.


Line range hint 1-361: Overall: Excellent implementation of webhook functionality

The changes in this file successfully implement the webhook functionality for creating general mandate delegations from Zendesk tickets. The code demonstrates good practices in terms of:

  1. Modularity: New methods like verifyZendeskTicket and insertDelegation improve code organization.
  2. Error handling: Specific error codes and messages are used throughout.
  3. TypeScript usage: Proper type definitions and return types are maintained.
  4. Reusability: The code is structured to be reusable across different NextJS apps.

The refactoring of existing methods and the addition of new ones have significantly enhanced the service's capabilities while maintaining good code quality. The suggested minor improvements in the previous comments will further refine the implementation.

Great job on this implementation!

🧰 Tools
🪛 Biome

[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 353-353: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@GunnlaugurG GunnlaugurG requested a review from saevarma October 4, 2024 14:03
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3f5870f and 3671462.

📒 Files selected for processing (1)
  • apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (1)
Learnt from: saevarma
PR: island-is/island.is#16257
File: apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts:178-201
Timestamp: 2024-10-04T07:46:37.013Z
Learning: In `apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts`, ensure that test case names accurately describe the scenario being tested, particularly in cases involving invalid request signatures.
🔇 Additional comments (5)
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (5)

2-2: LGTM: New imports are appropriate for the added functionality.

The new imports (bodyParser, DelegationDTO, SequelizeConfigService, DelegationAdminCustomService, and includeRawBodyMiddleware) are well-aligned with the new functionality for handling POST requests and including raw body in the request. These additions follow NestJS best practices for modular imports.

Also applies to: 15-16, 19-19


139-163: LGTM: Well-structured test suite setup.

The new test suite for POST /delegation-admin/:zendeskId is well-structured and follows NestJS testing best practices. The setup includes:

  1. Proper initialization of the test app and server.
  2. Mocking of the DelegationAdminCustomService, which is a good practice for unit testing.
  3. Use of beforeEach for setting up the test environment, ensuring a clean state for each test.

These practices contribute to more reliable and maintainable tests.


165-167: LGTM: Proper test cleanup implemented.

The addition of the afterEach hook to clean up the app after each test is a good practice. This ensures proper test isolation and prevents potential side effects between tests, contributing to more reliable test results.


169-192: LGTM: Well-structured test for invalid signature scenario.

This test case effectively verifies the behavior when an invalid signature is provided:

  1. The test name clearly describes the scenario being tested, addressing previous feedback.
  2. It correctly checks for a 403 Forbidden response.
  3. The response body is appropriately validated.

This test contributes to ensuring the security of the API by verifying proper handling of invalid signatures.


Line range hint 1-212: LGTM: Comprehensive test coverage.

The test suite demonstrates thorough coverage of the delegation admin API:

  1. It includes tests for GET, DELETE, and POST methods.
  2. Various scenarios are covered, including authentication, authorization, and signature validation.
  3. The tests align with NestJS testing best practices, contributing to code quality and reliability.

This comprehensive approach to testing helps ensure the robustness and security of the API.

Copy link
Member

@saevarma saevarma left a comment

Choose a reason for hiding this comment

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

Few more, I still have the guard left to read over

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (5)
libs/infra-nest-server/src/lib/types.ts (1)

51-56: LGTM! Consider adding an example usage in the documentation.

The addition of the beforeServerStart hook is a valuable feature that aligns well with the PR objectives. It provides flexibility for additional setup or configuration before the server starts. The type definition and documentation are clear and correct.

To further improve the documentation, consider adding a brief example of how this hook might be used. This could help developers quickly understand its practical application. For instance:

/**
 * Hook to run before server is started.
 * @param app The nest application instance.
 * @returns a promise that resolves when the hook is done.
 * @example
 * beforeServerStart: (app) => {
 *   app.useGlobalPipes(new ValidationPipe());
 *   // Other custom configurations...
 * }
 */
beforeServerStart?: (app: INestApplication) => void
apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (1)

110-120: LGTM: New createByZendeskId method with a suggestion

The new createByZendeskId method is well-implemented and follows NestJS controller patterns. Great job using the custom ZendeskAuthGuard for authentication and the @BypassAuth() decorator to bypass the default authentication. The method signature, return type, and documentation are all correct.

Suggestion for improvement:
Consider adding error handling for the createDelegationByZendeskId service method call. This would help manage potential errors and provide appropriate responses to the client.

Example:

async createByZendeskId(@Body() { id }: ZendeskWebhookInputDto): Promise<void> {
  try {
    await this.delegationAdminService.createDelegationByZendeskId(id);
  } catch (error) {
    // Log the error
    console.error('Error creating delegation by Zendesk ID:', error);
    // Throw an appropriate HTTP exception
    throw new HttpException('Failed to create delegation', HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (3)

Line range hint 49-80: Improved Zendesk custom field extraction

The renaming and expansion of this method to include validTo and createdByNationalId fields is a good improvement. It aligns well with the PR objectives for implementing general mandate delegation.

Consider adding specific error messages for each missing required field to provide more detailed feedback. For example:

if (!fromReferenceId || !toReferenceId) {
  const missingFields = [];
  if (!fromReferenceId) missingFields.push('fromReferenceId');
  if (!toReferenceId) missingFields.push('toReferenceId');
  throw new BadRequestException({
    message: `Zendesk ticket is missing required custom fields: ${missingFields.join(', ')}`,
    error: ErrorCodes.ZENDESK_CUSTOM_FIELDS_MISSING,
  });
}

156-196: Well-implemented delegation creation from Zendesk ticket

The createDelegationByZendeskId method effectively implements the core functionality for creating general mandate delegations from Zendesk tickets. It includes necessary validations for national IDs and aligns well with the PR objectives.

Consider wrapping the Zendesk ticket retrieval in a try-catch block to handle potential network errors or invalid ticket IDs more gracefully. For example:

let zendeskCase: Ticket;
try {
  zendeskCase = await this.zendeskService.getTicket(zendeskId);
} catch (error) {
  throw new BadRequestException({
    message: 'Failed to retrieve Zendesk ticket',
    error: ErrorCodes.ZENDESK_TICKET_RETRIEVAL_FAILED,
  });
}

299-332: Well-structured insertDelegation method

The insertDelegation method effectively encapsulates the logic for creating a new delegation record. The use of a transaction ensures data consistency, which is crucial for this operation.

Consider adding error handling for the name retrieval process. If the namesService.getPersonName calls fail, it could lead to an unhandled promise rejection. You could wrap these calls in a try-catch block:

try {
  const [fromDisplayName, toName] = await Promise.all([
    this.namesService.getPersonName(delegation.fromNationalId),
    this.namesService.getPersonName(delegation.toNationalId),
  ]);
  // ... rest of the method
} catch (error) {
  throw new BadRequestException({
    message: 'Failed to retrieve person names',
    error: ErrorCodes.NAME_RETRIEVAL_FAILED,
  });
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3671462 and 1c1d384.

📒 Files selected for processing (7)
  • apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (3 hunks)
  • apps/services/auth/admin-api/src/main.ts (2 hunks)
  • libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (4 hunks)
  • libs/auth-nest-tools/src/lib/rawBodyRequest.type.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts (1 hunks)
  • libs/infra-nest-server/src/lib/bootstrap.ts (1 hunks)
  • libs/infra-nest-server/src/lib/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/services/auth/admin-api/src/main.ts
  • libs/infra-nest-server/src/lib/bootstrap.ts
🧰 Additional context used
📓 Path-based instructions (5)
apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/auth-api-lib/src/lib/delegations/admin/delegation-admin-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-nest-tools/src/lib/rawBodyRequest.type.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-nest-tools/src/lib/zendeskAuth.guard.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/infra-nest-server/src/lib/types.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts

[error] 375-375: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 375-375: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 375-375: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (12)
libs/auth-nest-tools/src/lib/rawBodyRequest.type.ts (1)

1-5: LGTM! Well-structured type definition.

The RawBodyRequest interface is well-defined and follows TypeScript best practices. It extends the Request interface from 'express' and adds a rawBody property of type Buffer, which is appropriate for handling raw request body data.

This type definition adheres to the coding guidelines for libs/**/* pattern:

  • It's reusable across different NextJS apps.
  • It uses TypeScript for defining and exporting types.
  • It's a small, focused type definition that supports effective tree-shaking.
libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts (4)

1-7: LGTM: Imports and constants are well-defined

The imports are appropriate for the functionality, and the use of a constant for the signing algorithm is a good practice for maintainability.


8-18: LGTM: Class structure and constructor implementation

The class structure follows NestJS conventions, and the constructor's check for the signing secret is a good practice for fail-fast behavior. The suggestion from the past review to move the check to the constructor has been successfully implemented.


20-30: LGTM: canActivate method implementation

The canActivate method correctly implements the CanActivate interface and effectively retrieves the necessary information from the request. The use of the custom RawBodyRequest type addresses the past review comment about extending the Request interface, improving type safety.


32-41: LGTM: isValidSignature method implementation with security improvement

The isValidSignature method correctly implements the signature validation logic. The use of crypto.timingSafeEqual addresses the past review comment about using a constant-time comparison, which is crucial for preventing timing attacks.

Regarding the question about comparing buffer lengths: crypto.timingSafeEqual automatically compares the lengths of the buffers and returns false if they differ, so an explicit length check is not necessary. This approach is both secure and concise.

apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (4)

15-15: LGTM: New imports for Zendesk webhook functionality

The new imports (BypassAuth, ZendeskAuthGuard, and ZendeskWebhookInputDto) are correctly added and align with the NestJS architecture. They provide the necessary components for implementing the new Zendesk webhook feature.

Also applies to: 21-21, 28-28


37-44: Excellent: Environment variable check implemented

Great job implementing the environment variable check for ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE. This addresses the security concern raised in the previous review and ensures that the application won't start without the required secret being set.

The error message is clear and informative, which will help developers quickly identify and resolve any configuration issues.


46-48: LGTM: ZendeskAuthGuard instantiation

The ZendeskAuthGuardInstance is correctly instantiated using the ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE. This follows NestJS best practices for creating and using custom guards. Creating the instance outside the controller class is an efficient approach.


61-61: Great: @Scopes decorator moved as suggested

Excellent job moving the @Scopes(DelegationAdminScopes.read) decorator to the getDelegationAdmin method. This change addresses the previous review comment and ensures that the read scope is explicitly applied to this method. It follows the principle of least privilege, enhancing the overall security of the controller.

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

Line range hint 198-226: Improved createDelegation method structure

The refactoring of the createDelegation method has improved its readability and maintainability. The extraction of common logic into separate methods (validatePersonsNationalIds, verifyZendeskTicket, and insertDelegation) is a good practice that enhances code organization.


334-348: Well-implemented ticket completion verification

The verifyTicketCompletion method effectively encapsulates the logic for checking if a Zendesk ticket has the required tag and status. This abstraction improves code reusability and maintainability.


350-366: Effective Zendesk ticket verification

The verifyZendeskTicket method effectively combines ticket completion verification with national ID matching. This encapsulation improves code organization and readability, making the createDelegation method cleaner and more focused.

@GunnlaugurG GunnlaugurG added the automerge Merge this PR as soon as all checks pass label Oct 7, 2024
@GunnlaugurG GunnlaugurG requested a review from saevarma October 7, 2024 14:21
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
apps/services/auth/admin-api/src/environments/environment.ts (2)

15-17: LGTM! Consider adding a comment for clarity.

The addition of zendeskGeneralMandateWebhookSecret to the development configuration is well-implemented. It correctly uses an environment variable with a fallback value, which is a good practice for development environments.

Consider adding a brief comment explaining the purpose of this secret and noting that the fallback value should only be used for local development:

 zendeskGeneralMandateWebhookSecret:
+  // Secret for Zendesk general mandate webhook. Fallback is for local development only.
   process.env.ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE ??
   'dGhpc19zZWNyZXRfaXNfZm9yX3Rlc3Rpbmdfb25seQ==',

33-34: LGTM! Consider adding error handling for missing environment variable.

The addition of zendeskGeneralMandateWebhookSecret to the production configuration is well-implemented. Using only the environment variable without a fallback is appropriate for production environments and aligns with security best practices.

Consider adding error handling to ensure the application fails to start if the environment variable is not set in production:

 zendeskGeneralMandateWebhookSecret:
-  process.env.ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE,
+  process.env.ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE ?? (() => {
+    throw new Error('ZENDESK_WEBHOOK_SECRET_GENERAL_MANDATE must be set in production');
+  })(),

This change will cause the application to throw an error during initialization if the required environment variable is missing, preventing it from starting with an undefined secret.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1c1d384 and a813739.

📒 Files selected for processing (4)
  • apps/services/auth/admin-api/src/app/app.module.ts (0 hunks)
  • apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (3 hunks)
  • apps/services/auth/admin-api/src/environments/environment.ts (2 hunks)
  • libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/services/auth/admin-api/src/app/app.module.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/services/auth/admin-api/src/environments/environment.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/auth-nest-tools/src/lib/zendeskAuth.guard.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 (10)
apps/services/auth/admin-api/src/environments/environment.ts (1)

Line range hint 1-38: Overall structure and consistency look good.

The file maintains a clear and consistent structure for both development and production configurations. The new zendeskGeneralMandateWebhookSecret property is added consistently to both devConfig and prodConfig objects, adhering to the existing pattern of configuration management.

The export logic at the end of the file correctly switches between configurations based on the NODE_ENV, which is a good practice for environment-specific settings.

This implementation aligns well with NestJS best practices for configuration management and environment-specific settings.

libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts (5)

1-7: LGTM: Imports and constants are well-defined

The imports are appropriate for the functionality, and the use of a constant for the signing algorithm is a good practice. The custom type RawBodyRequest is imported, which addresses the previous review comment about properly typing request.rawBody.


8-14: LGTM: Class declaration and constructor are well-implemented

The class structure follows NestJS conventions, and the constructor properly checks for the presence of the secret, addressing a potential issue early. The error message is clear and helpful.


16-26: LGTM: canActivate method is well-implemented

The canActivate method correctly implements the CanActivate interface. It efficiently retrieves the necessary headers and body from the request, using the custom RawBodyRequest type. This addresses the previous review comment about properly typing request.rawBody. The method is concise and focused on its responsibility of validating the request.


28-40: LGTM: isValidSignature method implements secure signature verification

The isValidSignature method follows security best practices by using HMAC for signature generation. The use of crypto.timingSafeEqual for comparison addresses the previous review comment about implementing a secure constant-time comparison, which helps prevent timing attacks. The method is concise and focused on its responsibility of validating the signature.


1-41: Great implementation of ZendeskAuthGuard

The ZendeskAuthGuard is well-implemented, following NestJS conventions and security best practices. It addresses all previous review comments, including proper typing of request.rawBody and using a secure constant-time comparison for signature verification. The guard effectively validates incoming requests from Zendesk webhooks, ensuring only legitimate requests are processed.

Good job on creating a robust and secure authentication guard!

apps/services/auth/admin-api/src/app/v2/delegations/delegation-admin.controller.ts (4)

15-15: LGTM: New imports for Zendesk webhook functionality.

The added imports (BypassAuth, ZendeskAuthGuard, and ZendeskWebhookInputDto) are appropriate for implementing the new Zendesk webhook functionality. They align well with the PR objectives.

Also applies to: 21-21, 28-28


35-36: LGTM: Environment import for configuration.

The addition of the env import from the environment file is a good practice for managing configuration. This aligns with the new Zendesk webhook functionality and allows for easier management of environment-specific settings.


50-50: LGTM: Improved scope control for getDelegationAdmin method.

Moving the @Scopes(DelegationAdminScopes.read) decorator to the getDelegationAdmin method level is a good practice. It provides more granular control over access permissions and ensures that each method has explicit scope definitions. This change aligns with the previous review suggestion and improves overall security.


99-109: LGTM: New createByZendeskId method implements webhook functionality.

The new createByZendeskId method successfully implements the webhook functionality for creating general mandate delegations triggered by Zendesk events. It adheres to NestJS architecture and uses appropriate guards and DTOs.

However, could you please clarify the use of the @BypassAuth() decorator? While it might be necessary for webhook functionality, it's important to ensure this doesn't introduce any security vulnerabilities.

To verify the usage of @BypassAuth(), please run the following script:

✅ Verification successful

LGTM: Usage of @BypassAuth() is consistent with the codebase.

The new createByZendeskId method successfully implements the webhook functionality for creating general mandate delegations triggered by Zendesk events. It adheres to NestJS architecture and utilizes appropriate guards and DTOs.

The usage of the @BypassAuth() decorator is consistent with other implementations within the codebase and does not introduce any new security vulnerabilities.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other occurrences of @BypassAuth() in the codebase
rg --type typescript '@BypassAuth\(\)' -C 5

Length of output: 80


Script:

#!/bin/bash
# Search for other occurrences of @BypassAuth() in TypeScript files
rg '@BypassAuth\(\)' --glob '*.ts' --glob '*.tsx' -C 5

Length of output: 35040

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

🧹 Outside diff range and nitpick comments (3)
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (3)

Line range hint 49-80: Consider improving error handling for new custom fields

The getZendeskCustomFields method has been updated to include validTo and createdByNationalId fields, which is a good improvement. However, the error handling for these new fields could be enhanced.

Consider adding specific error messages for missing validTo or createdByNationalId fields if they are required in some scenarios. This would provide more detailed feedback when creating delegations. For example:

if (someConditionWhereCreatedByIsRequired && !createdById) {
  throw new BadRequestException({
    message: 'Zendesk ticket is missing required createdBy field',
    error: ErrorCodes.ZENDESK_CUSTOM_FIELDS_MISSING,
  })
}

Line range hint 198-226: Improve error handling for Zendesk ticket retrieval

The createDelegation method has been refactored to use the new verifyZendeskTicket and insertDelegation methods, which improves code organization. However, the Zendesk ticket retrieval could benefit from better error handling.

Consider wrapping the Zendesk ticket retrieval in a try-catch block to handle potential errors gracefully. For example:

let zendeskCase: Ticket;
try {
  zendeskCase = await this.zendeskService.getTicket(delegation.referenceId);
} catch (error) {
  throw new BadRequestException({
    message: 'Failed to retrieve Zendesk ticket',
    error: ErrorCodes.ZENDESK_TICKET_RETRIEVAL_FAILED,
  });
}

This change would provide more specific error information if the Zendesk ticket retrieval fails.


299-332: Enhance error handling for name retrieval

The insertDelegation method is a good addition that encapsulates the logic for creating a new delegation. However, the error handling for name retrieval could be improved.

Consider adding error handling for the getPersonName calls. If these calls fail, it could lead to unexpected behavior. Here's a suggestion:

private async insertDelegation(
  delegation: CreatePaperDelegationDto & {
    createdBy: string
  },
): Promise<Delegation> {
  let fromDisplayName: string, toName: string;
  try {
    [fromDisplayName, toName] = await Promise.all([
      this.namesService.getPersonName(delegation.fromNationalId),
      this.namesService.getPersonName(delegation.toNationalId),
    ]);
  } catch (error) {
    throw new BadRequestException({
      message: 'Failed to retrieve person names',
      error: ErrorCodes.NAME_RETRIEVAL_FAILED,
    });
  }

  // Rest of the method remains the same
}

This change would provide more robust error handling if name retrieval fails.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a813739 and f901c16.

📒 Files selected for processing (1)
  • libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-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."
🪛 Biome
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts

[error] 375-375: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 375-375: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 375-375: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (1)
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (1)

334-348: Well-implemented ticket verification method

The verifyTicketCompletion method is a good addition to the service. It clearly separates the concerns of ticket verification and provides appropriate error handling.

The method checks for the required tag and ticket status, throwing specific exceptions with clear error messages and codes. This implementation enhances the overall robustness of the delegation creation process.

GunnlaugurG and others added 3 commits October 7, 2024 15:17
Reuse validatePersonsNationalIds in createDeleagtionByZendeskId
Copy link
Member

@saevarma saevarma left a comment

Choose a reason for hiding this comment

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

🚀

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

🧹 Outside diff range and nitpick comments (5)
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (1)

139-167: LGTM: Well-structured test suite setup with a minor suggestion.

The test suite setup for the POST /delegation-admin/zendesk endpoint follows NestJS testing best practices. It properly initializes the app, server, and mocks the DelegationAdminCustomService.

Consider adding a type annotation for the delegationAdminService variable to enhance type safety:

let delegationAdminService: DelegationAdminCustomService;
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (4)

Line range hint 49-80: LGTM! Consider enhancing error handling for optional fields.

The renaming and expansion of this method improve its clarity and functionality. It now extracts additional relevant information from the Zendesk ticket.

Consider adding null checks for the optional fields validTo and createdById to ensure they exist before accessing their value property. This can prevent potential runtime errors if these fields are unexpectedly missing:

const validTo = ticket.custom_fields.find(
  (field) => field.id === ZENDESK_CUSTOM_FIELDS.DelegationValidToId,
)?.value ?? null

const createdByNationalId = ticket.custom_fields.find(
  (field) => field.id === ZENDESK_CUSTOM_FIELDS.DelegationCreatedById,
)?.value ?? null

return {
  fromReferenceId: fromReferenceId.value,
  toReferenceId: toReferenceId.value,
  createdByNationalId,
  validTo,
}

156-191: Excellent implementation. Consider enhancing error handling for Zendesk ticket retrieval.

The new createDelegationByZendeskId method effectively implements the creation of a delegation from a Zendesk ticket, including necessary validations and error handling.

Consider wrapping the Zendesk ticket retrieval in a try-catch block to handle potential network errors or invalid ticket IDs gracefully:

async createDelegationByZendeskId(zendeskId: string): Promise<void> {
  let zendeskCase: Ticket;
  try {
    zendeskCase = await this.zendeskService.getTicket(zendeskId);
  } catch (error) {
    throw new BadRequestException({
      message: 'Failed to retrieve Zendesk ticket',
      error: ErrorCodes.ZENDESK_TICKET_RETRIEVAL_FAILED,
    });
  }

  // Rest of the method remains the same
  // ...
}

This change will provide more specific error handling for Zendesk-related issues.


Line range hint 193-220: Great refactoring. Consider consistent error handling for Zendesk ticket retrieval.

The refactoring of createDelegation improves readability and maintainability by separating concerns and using new helper methods.

For consistency with the createDelegationByZendeskId method, consider wrapping the Zendesk ticket retrieval in a try-catch block:

async createDelegation(
  user: User,
  delegation: CreatePaperDelegationDto,
): Promise<DelegationDTO> {
  this.validatePersonsNationalIds(
    delegation.toNationalId,
    delegation.fromNationalId,
  );

  let zendeskCase: Ticket;
  try {
    zendeskCase = await this.zendeskService.getTicket(delegation.referenceId);
  } catch (error) {
    throw new BadRequestException({
      message: 'Failed to retrieve Zendesk ticket',
      error: ErrorCodes.ZENDESK_TICKET_RETRIEVAL_FAILED,
    });
  }

  // Rest of the method remains the same
  // ...
}

This change will provide consistent error handling for Zendesk-related issues across both methods.


363-378: Effective date formatting with room for improvement.

The formatZendeskDate method handles date formatting and validation well. However, there's a minor improvement we can make based on the static analysis suggestion.

Replace the global isNaN function with Number.isNaN for more precise type checking:

if (!day || !month || !year || Number.isNaN(day) || Number.isNaN(month) || Number.isNaN(year)) {
  throw new BadRequestException({
    message: 'Invalid date format in Zendesk ticket',
    error: ErrorCodes.INVALID_DATE_FORMAT,
  });
}

This change ensures that the type checking is more accurate and avoids potential issues with type coercion.

🧰 Tools
🪛 Biome

[error] 370-370: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 370-370: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 370-370: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dd31dd8 and ed9add0.

📒 Files selected for processing (3)
  • apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (3 hunks)
  • apps/services/auth/admin-api/src/environments/environment.ts (2 hunks)
  • libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/services/auth/admin-api/src/environments/environment.ts
🧰 Additional context used
📓 Path-based instructions (2)
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (2)

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

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

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/auth-api-lib/src/lib/delegations/admin/delegation-admin-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."
📓 Learnings (1)
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (1)
Learnt from: saevarma
PR: island-is/island.is#16257
File: apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts:178-201
Timestamp: 2024-10-04T07:46:37.013Z
Learning: In `apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts`, ensure that test case names accurately describe the scenario being tested, particularly in cases involving invalid request signatures.
🪛 Biome
libs/auth-api-lib/src/lib/delegations/admin/delegation-admin-custom.service.ts

[error] 370-370: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 370-370: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 370-370: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (5)
apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts (3)

2-2: LGTM: New imports for enhanced request handling and service testing.

The addition of bodyParser, includeRawBodyMiddleware, and DelegationAdminCustomService imports are appropriate for the new POST endpoint test. These imports will allow for proper handling of raw request bodies and testing of the custom delegation admin service.

Also applies to: 15-16, 19-19


169-192: LGTM: Well-structured test for invalid signature scenario.

This test case correctly verifies the behavior when an invalid signature is provided. The test name accurately describes the scenario being tested, which is an improvement based on previous feedback.

The test structure and assertions are appropriate for checking the 403 Forbidden response.


Line range hint 1-212: Overall, good improvements to test coverage with minor enhancement opportunities.

The changes to this file significantly improve the test coverage for the delegation admin API, particularly for the new POST /delegation-admin/zendesk endpoint. The additions adhere to NestJS testing best practices and provide good coverage for both valid and invalid scenarios.

Key points:

  1. Proper setup and teardown of the test environment.
  2. Mocking of the DelegationAdminCustomService.
  3. Comprehensive tests for different signature validation scenarios.

The suggested improvements, if implemented, will further enhance type safety, test reliability, and assertion coverage. These changes align well with the PR objectives of implementing a webhook for general mandate delegation.

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

294-327: Well-implemented delegation creation logic.

The insertDelegation method effectively encapsulates the logic for creating a new delegation record. The use of a transaction ensures data consistency, and the parallel retrieval of names using Promise.all is efficient.


329-343: Clear and effective ticket completion verification.

The verifyTicketCompletion method provides clear validation for Zendesk ticket completion. It checks for the required tag and 'Solved' status, throwing descriptive exceptions with specific error codes when validation fails.

@kodiakhq kodiakhq bot merged commit 6ce1b55 into main Oct 8, 2024
265 checks passed
@kodiakhq kodiakhq bot deleted the feat/general-mandate-webhook branch October 8, 2024 10:01
saevarma added a commit that referenced this pull request Oct 8, 2024
* gm-delegation-webhook

* chore: charts update dirty files

* pr comments fixes

* pr comments fixes

* fix broken test

* Pr comments

* Pr comments

* chore: nx format:write update dirty files

* fix translation string

* Add comment to signing secret dev value.
Reuse validatePersonsNationalIds in createDeleagtionByZendeskId

* Update test labels

---------

Co-authored-by: andes-it <[email protected]>
Co-authored-by: Sævar Már Atlason <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
kodiakhq bot added a commit that referenced this pull request Oct 8, 2024
…6313)

* gm-delegation-webhook

* chore: charts update dirty files

* pr comments fixes

* pr comments fixes

* fix broken test

* Pr comments

* Pr comments

* chore: nx format:write update dirty files

* fix translation string

* Add comment to signing secret dev value.
Reuse validatePersonsNationalIds in createDeleagtionByZendeskId

* Update test labels

---------

Co-authored-by: Gunnlaugur Guðmundsson <[email protected]>
Co-authored-by: andes-it <[email protected]>
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
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants