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

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

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

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/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/:zendeskId endpoint.
apps/services/auth/admin-api/src/main.ts Introduced middleware for JSON request body parsing.
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/zendeskAuth.guard.ts Added ZendeskAuthGuard for validating Zendesk webhook requests.
libs/shared/utils/src/lib/errorCodes.ts Added new error code: INVALID_DATE_FORMAT.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • Herdismaria
  • saevarma

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.

apps/services/auth/admin-api/src/main.ts Outdated Show resolved Hide resolved
Comment on lines +17 to +19
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const body = request.rawBody?.toString() ?? ''
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid suppressing TypeScript and ESLint errors; properly type request.rawBody

The code disables ESLint and uses @ts-expect-error to ignore TypeScript errors for request.rawBody. To maintain type safety and code quality, consider extending the Request interface to include rawBody instead of suppressing errors.

Here's how you can extend the Request interface:

import { Request } from 'express'

interface RawBodyRequest extends Request {
  rawBody: Buffer
}

const request = context.switchToHttp().getRequest<RawBodyRequest>()
const body = request.rawBody?.toString() ?? ''

Copy link

codecov bot commented Oct 3, 2024

Codecov Report

Attention: Patch coverage is 22.85714% with 54 lines in your changes missing coverage. Please review.

Project coverage is 36.94%. Comparing base (9ef986b) to head (eeb80b0).
Report is 33 commits behind head on main.

Files with missing lines Patch % Lines
...legations/admin/delegation-admin-custom.service.ts 0.00% 36 Missing ⚠️
libs/auth-nest-tools/src/lib/zendeskAuth.guard.ts 25.00% 12 Missing ⚠️
...ra-nest-server/src/lib/includeRawBodyMiddleware.ts 33.33% 4 Missing ⚠️
libs/infra-nest-server/src/lib/bootstrap.ts 50.00% 1 Missing ⚠️
libs/testing/nest/src/lib/testServer.ts 50.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16257      +/-   ##
==========================================
+ Coverage   36.76%   36.94%   +0.18%     
==========================================
  Files        6785     6782       -3     
  Lines      139900   140013     +113     
  Branches    39772    39817      +45     
==========================================
+ Hits        51435    51730     +295     
+ Misses      88465    88283     -182     
Flag Coverage Δ
air-discount-scheme-backend 54.03% <31.03%> (-0.20%) ⬇️
air-discount-scheme-web 0.00% <ø> (ø)
api 3.37% <ø> (-0.03%) ⬇️
api-domains-air-discount-scheme 36.89% <29.41%> (-0.03%) ⬇️
api-domains-assets 26.71% <ø> (ø)
api-domains-auth-admin 48.77% <ø> (ø)
api-domains-communications 39.90% <29.41%> (-0.03%) ⬇️
api-domains-criminal-record 47.93% <ø> (+0.07%) ⬆️
api-domains-driving-license 44.41% <29.41%> (-0.07%) ⬇️
api-domains-education 31.74% <ø> (+0.06%) ⬆️
api-domains-health-insurance 34.78% <ø> (+0.09%) ⬆️
api-domains-mortgage-certificate 35.66% <29.41%> (-0.04%) ⬇️
api-domains-payment-schedule 41.13% <29.41%> (-0.08%) ⬇️
application-api-files 57.91% <ø> (+0.05%) ⬆️
application-core 71.62% <ø> (ø)
application-system-api 41.62% <31.03%> (+<0.01%) ⬆️
application-template-api-modules 24.38% <29.41%> (+0.64%) ⬆️
application-templates-accident-notification 29.44% <ø> (+7.30%) ⬆️
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 26.63% <ø> (ø)
application-templates-driving-license 18.63% <ø> (-0.08%) ⬇️
application-templates-estate 12.33% <ø> (-0.01%) ⬇️
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.15% <ø> (ø)
application-types 6.71% <ø> (ø)
application-ui-components 1.28% <ø> (ø)
application-ui-shell 21.29% <ø> (-0.01%) ⬇️
auth-nest-tools 29.92% <0.00%> (-1.11%) ⬇️
auth-react 22.80% <ø> (ø)
clients-charge-fjs-v2 24.11% <ø> (ø)
clients-driving-license 40.73% <ø> (+0.08%) ⬆️
clients-driving-license-book 43.77% <29.41%> (-0.14%) ⬇️
clients-financial-statements-inao 49.25% <ø> (+0.07%) ⬆️
clients-license-client 1.83% <ø> (ø)
clients-middlewares 73.11% <ø> (+0.33%) ⬆️
clients-regulations 42.71% <ø> (+0.08%) ⬆️
clients-rsk-company-registry 29.76% <ø> (ø)
clients-syslumenn 49.49% <29.41%> (-0.18%) ⬇️
cms 0.43% <ø> (-0.01%) ⬇️
cms-translations 39.02% <29.41%> (-0.03%) ⬇️
download-service 43.99% <31.03%> (-0.77%) ⬇️
financial-aid-backend 56.39% <29.41%> (-0.16%) ⬇️
icelandic-names-registry-backend 54.01% <31.03%> (-0.64%) ⬇️
infra-nest-server 48.23% <34.48%> (-0.72%) ⬇️
judicial-system-api 18.30% <ø> (-0.01%) ⬇️
license-api 42.63% <31.03%> (-0.04%) ⬇️
nest-audit 68.20% <ø> (ø)
nest-feature-flags 51.46% <29.41%> (-0.57%) ⬇️
nest-problem 45.90% <31.03%> (-0.59%) ⬇️
nest-swagger 51.71% <ø> (ø)
portals-admin-regulations-admin 1.88% <ø> (ø)
portals-core 16.17% <ø> (ø)
reference-backend 49.84% <31.03%> (-0.73%) ⬇️
services-auth-delegation-api 57.76% <21.42%> (-0.18%) ⬇️
services-auth-personal-representative 45.41% <20.00%> (-0.12%) ⬇️
services-sessions 65.28% <34.48%> (-0.51%) ⬇️
services-university-gateway 48.30% <31.03%> (-0.13%) ⬇️
services-user-notification 47.03% <34.48%> (-0.04%) ⬇️
services-user-profile 62.16% <34.48%> (-0.22%) ⬇️
shared-components 27.68% <ø> (ø)
shared-form-fields 31.63% <ø> (+0.02%) ⬆️
skilavottord-ws 24.24% <ø> (ø)
web 1.83% <ø> (ø)

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

Files with missing lines Coverage Δ
.../app/v2/delegations/delegation-admin.controller.ts 96.77% <ø> (-0.11%) ⬇️
apps/services/auth/admin-api/src/main.ts 0.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%> (ø)
libs/testing/nest/src/lib/setup.ts 94.11% <100.00%> (+0.36%) ⬆️
libs/infra-nest-server/src/lib/bootstrap.ts 76.11% <50.00%> (-0.81%) ⬇️
libs/testing/nest/src/lib/testServer.ts 96.00% <50.00%> (-4.00%) ⬇️
... and 3 more

... and 51 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 9ef986b...eeb80b0. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 3, 2024

Datadog Report

All test runs 392bbdd 🔗

75 Total Test Services: 1 Failed, 72 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
services-auth-admin-api 1 0 0 127 0 3m 16.79s 1 increased (+0.1%) Link
air-discount-scheme-backend 0 0 0 81 0 31.55s N/A Link
air-discount-scheme-web 0 0 0 2 0 9.23s N/A Link
api 0 0 0 4 0 3.04s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 19.55s N/A Link
api-domains-assets 0 0 0 3 0 12.47s N/A Link
api-domains-auth-admin 0 0 0 18 0 12.87s N/A Link
api-domains-communications 0 0 0 5 0 27.17s N/A Link
api-domains-criminal-record 0 0 0 5 0 8.77s 1 no change Link
api-domains-driving-license 0 0 0 23 0 31.81s N/A Link

❌ Failed Tests (1)

  • withoutAuth and permissions POST /delegation-admin/:zendeskId POST /delegation-admin/zendesk should return 201 when signature is valid - apps/services/auth/admin-api/src/app/v2/delegations/test/delegation-admin.auth.spec.ts - Details

    Expand for error
     expect(received).toEqual(expected) // deep equality
     
     Expected: 200
     Received: 403
    

🔻 Code Coverage Decreases vs Default Branch (20)

This report shows up to 5 code coverage decreases.

  • auth-nest-tools - jest 32.44% (-1.51%) - Details
  • infra-nest-server - jest 55.5% (-0.61%) - Details
  • reference-backend - jest 54.63% (-0.58%) - Details
  • nest-feature-flags - jest 57.29% (-0.57%) - Details
  • icelandic-names-registry-backend - jest 59.48% (-0.55%) - 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)

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.

Comment on lines +149 to +154
beforeServerStart: async (app) => {
await new Promise((resolve) =>
resolve(app.use(includeRawBodyMiddleware())),
)
},
})
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify the beforeServerStart function.

The beforeServerStart function can be simplified. The current implementation wraps the synchronous app.use call in an unnecessary Promise. Consider refactoring it as follows:

beforeServerStart: async (app) => {
  app.use(includeRawBodyMiddleware())
},

This change maintains the same functionality while making the code more straightforward and easier to read.

Comment on lines +194 to +211
it('POST /delegation-admin/zendesk should return 201 when signature is valid', async () => {
// Act
const res = await getRequestMethod(
server,
'POST',
)('/delegation-admin/zendesk')
.send({
id: 'test',
})
.set(
'x-zendesk-webhook-signature',
'ntgS06VGgd4z73lHjIpC2sk9azhRNi4u1xkXF/KPKTs=',
)
.set('x-zendesk-webhook-signature-timestamp', '2024-10-02T14:21:04Z')

// Assert
expect(res.status).toEqual(200)
})
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test assertions for valid signature scenario.

While the test case correctly checks for a 200 OK response when the signature is valid, it could be improved:

  1. Add an assertion to verify that delegationAdminService.createDelegationByZendeskId was called with the correct parameters.
  2. Include an assertion for the response body structure.

Consider enhancing the test with these additional assertions:

// Assert
expect(res.status).toEqual(200)
expect(delegationAdminService.createDelegationByZendeskId).toHaveBeenCalledWith('test')
expect(res.body).toEqual({}) // Adjust this based on the expected response structure

These additions will make the test more robust by ensuring that the service method is called correctly and that the response body matches the expected structure.

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

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

if (!createdByNationalId) {
Copy link
Member

Choose a reason for hiding this comment

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

We should verify that the createdByNationalId is valid National Id by using the kennitala package.

})
}

this.verifyZendeskTicket(zendeskCase, fromReferenceId, toReferenceId)
Copy link
Member

Choose a reason for hiding this comment

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

This doesn't quite make sense in this context its comparing the values with it self as we pulled it from the ticket.

We should instead verify that these are valid person national IDs and it is not the same national IDs.

That is also a valid check in the admin portal create flow so maybe a new utility that does it. And this function can be used in the admin portal create flow to compare the details with the ticket, then do the data validation that these are valid national IDs of persons and not the same, and the date is also valid if present.

@@ -127,6 +127,10 @@ export const bootstrap = async (
})
}

if (options.beforeServerStart) {
await options.beforeServerStart(app)
Copy link
Member

Choose a reason for hiding this comment

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

We talked about making beforeServerStart synchronous?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants