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(license-service): Barcode session #17541

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

Conversation

magnearun
Copy link
Contributor

@magnearun magnearun commented Jan 17, 2025

What

Store in Redis session id when user creates a barcode
Check when creating a barcode if there is a key in redis for this user, license type, if the session id is the same we create the barcode, else we do not.

Why

We do not want users to be able to request a barcode for a licence on different devices within a short amount of time.
This will prevent users from being able to for example request a barcode for their driving license to get into a bar and the immediately login to their island.is app on another persons phone and request a barcode again for that person to "scam" their way in.

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

Release Notes

  • New Features

    • Enhanced session management for barcode creation
    • Added session identifier (sid) to authentication flow
  • Improvements

    • Introduced configurable barcode and session expiration times
    • Improved error handling for concurrent barcode sessions
  • Configuration Changes

    • Added new configuration parameters for barcode and session expiration
    • Updated JWT payload and authentication interfaces
  • Bug Fixes

    • Prevented multiple active barcode sessions for the same user and license type

@magnearun magnearun requested review from a team as code owners January 17, 2025 10:19
Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Walkthrough

This pull request introduces comprehensive changes to session management and configuration across multiple libraries and services. The modifications primarily focus on enhancing barcode and license service functionality by adding session key generation, session verification, and configurable expiration times. New methods for session caching, additional configuration parameters, and improved error handling for session-related scenarios have been implemented. The changes span authentication tools, license services, and problem type definitions to support more robust session management.

Changes

File Change Summary
libs/api/domains/license-service/src/lib/licenseService.service.ts Added getBarcodeSessionKey and checkBarcodeSession methods for session management
libs/auth-nest-tools/src/lib/* Added optional sid (session ID) property to various interfaces and strategies
libs/services/license/src/lib/barcode.service.ts Added session cache methods, removed hardcoded expiration constant
libs/services/license/src/lib/license.config.ts Added new configuration properties for barcode and session expiration times
libs/shared/problem/src/* Introduced BAD_SESSION problem type and related interfaces

Sequence Diagram

sequenceDiagram
    participant User
    participant LicenseService
    participant BarcodeService
    participant CacheManager

    User->>LicenseService: Request Barcode
    LicenseService->>LicenseService: Generate Session Key
    LicenseService->>BarcodeService: Check Existing Session
    BarcodeService->>CacheManager: Verify Active Session
    alt Session Exists
        BarcodeService-->>LicenseService: Throw ProblemError
    else No Active Session
        LicenseService->>BarcodeService: Create Barcode
        BarcodeService->>CacheManager: Store Session
    end
Loading

Possibly related PRs

Suggested labels

automerge


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 240e522 and 9f6761f.

📒 Files selected for processing (1)
  • apps/services/license-api/src/app/modules/license/test/license.service.spec.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/services/license-api/src/app/modules/license/test/license.service.spec.ts

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (5)
libs/auth-nest-tools/src/lib/mock-auth.guard.ts (1)

15-16: Consider meaningful default values for required fields.

Empty strings for required fields sid and sub might not be ideal for testing scenarios. Consider using meaningful default values that better represent real authentication data.

-      sid: '',
-      sub: '',
+      sid: 'mock-session-id',
+      sub: 'mock-subject-id',
libs/services/license/src/lib/barcode.service.ts (2)

13-13: Consider making session expiry time configurable.

While 30 minutes is a reasonable default, consider moving this to the configuration to allow for environment-specific adjustments.

-export const BARCODE_SESSION_EXPIRE_TIME_IN_SEC = 1800 // 30 minutes
+export const DEFAULT_BARCODE_SESSION_EXPIRE_TIME_IN_SEC = 1800 // 30 minutes

15-15: Make the session key prefix more specific.

Consider using a more specific prefix to avoid potential key collisions in Redis.

-export const BARCODE_ACTIVE_SESSION_KEY = 'activeSession'
+export const BARCODE_ACTIVE_SESSION_KEY = 'barcode:activeSession'
libs/api/domains/license-service/src/lib/licenseService.service.ts (2)

474-476: Consider making getBarcodeSessionKey private

Since this utility method is only used internally within the service, consider making it private by adding the private modifier.

-  getBarcodeSessionKey(licenseType: LicenseType, sub: string) {
+  private getBarcodeSessionKey(licenseType: LicenseType, sub: string) {

Line range hint 474-541: Consider implementing session cleanup mechanism

The current implementation lacks a mechanism to clean up expired sessions. Consider implementing a background job or using Redis TTL to automatically remove expired sessions and prevent resource exhaustion.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a71289 and a979a1f.

📒 Files selected for processing (9)
  • libs/api/domains/license-service/src/lib/licenseService.service.ts (5 hunks)
  • libs/auth-nest-tools/src/lib/auth.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/current-actor.decorator.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/jwt.payload.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/jwt.strategy.spec.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/jwt.strategy.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/mock-auth.guard.ts (1 hunks)
  • libs/services/license/src/index.ts (1 hunks)
  • libs/services/license/src/lib/barcode.service.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
libs/services/license/src/index.ts (2)

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

  • Shared services and modules that can be utilized across NestJS apps.
  • Proper implementation of NestJS providers, including custom providers.
  • Adherence to NestJS module encapsulation and isolation principles."

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/jwt.strategy.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/auth.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/mock-auth.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/auth-nest-tools/src/lib/current-actor.decorator.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/jwt.payload.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/api/domains/license-service/src/lib/licenseService.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/jwt.strategy.spec.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/services/license/src/lib/barcode.service.ts (2)

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

  • Shared services and modules that can be utilized across NestJS apps.
  • Proper implementation of NestJS providers, including custom providers.
  • Adherence to NestJS module encapsulation and isolation principles."

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 (6)
libs/services/license/src/index.ts (1)

8-8: LGTM! Export addition follows module encapsulation principles.

The new export BARCODE_SESSION_EXPIRE_TIME_IN_SEC aligns with the session management feature and follows proper naming conventions.

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

9-10: Breaking change: Verify impact of required 'sub' property.

The change from optional to required sub property is a breaking change that could affect existing implementations.

Let's verify the impact:

Session ID property addition looks good.

The addition of sid property aligns with the session management feature requirements.

libs/auth-nest-tools/src/lib/current-actor.decorator.ts (1)

28-28: LGTM! Session ID integration looks good.

The addition of the sid property to the user object is well-implemented and maintains backward compatibility.

libs/auth-nest-tools/src/lib/jwt.strategy.ts (1)

58-58: LGTM! JWT strategy properly includes session ID.

The session ID is correctly propagated from the JWT payload to the authenticated user object.

libs/services/license/src/lib/barcode.service.ts (1)

102-111: LGTM! Session cache methods are well-implemented.

The new session cache methods follow existing patterns and properly handle key prefixing.

libs/auth-nest-tools/src/lib/jwt.strategy.spec.ts (1)

27-28: Add test cases for session ID handling.

While the test payload has been updated with sub and sid properties, there are no specific test cases verifying the session ID handling. Consider adding test cases to verify:

  1. Session ID propagation
  2. Missing session ID scenarios
  3. Invalid session ID handling

libs/auth-nest-tools/src/lib/jwt.payload.ts Outdated Show resolved Hide resolved
libs/services/license/src/lib/barcode.service.ts Outdated Show resolved Hide resolved
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

♻️ Duplicate comments (1)
libs/api/domains/license-service/src/lib/licenseService.service.ts (1)

541-541: ⚠️ Potential issue

Ensure asynchronous operation completes.

The call to this.barcodeService.setSessionCache should be awaited to ensure it completes before proceeding.

Apply this diff to await the asynchronous call:

 await Promise.all([
   // Other async operations...
-  this.barcodeService.setSessionCache(barcodeSessionKey, user.sid),
+  this.barcodeService.setSessionCache(barcodeSessionKey, user.sid),
 ])
🧹 Nitpick comments (2)
libs/api/domains/license-service/src/lib/licenseService.service.ts (2)

291-291: Unnecessary indentation change—maintain consistency.

The indentation change on line 291 seems unintended and does not affect functionality. Please ensure consistent code formatting throughout the file.

Apply this diff to correct the indentation:

   if (!client) {
     const msg = `Invalid license type. "${type}"`
     this.logger.warn(msg, { category: LOG_CATEGORY })

-    throw new InternalServerErrorException(msg)
+    throw new InternalServerErrorException(msg)
   }

496-499: Use appropriate HTTP status code in ProblemError.

When throwing a ProblemError for an active session, consider specifying an appropriate HTTP status code (e.g., 429 Too Many Requests or 409 Conflict) to accurately represent the error condition.

Apply this diff to include a status code:

 throw new ProblemError({
   type: ProblemType.BAD_SUBJECT,
+  status: 409,
   title: `User has an active session for license type: ${licenseType}`,
 })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a979a1f and 3024ecc.

📒 Files selected for processing (2)
  • libs/api/domains/license-service/src/lib/licenseService.service.ts (5 hunks)
  • libs/services/license/src/lib/barcode.service.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/api/domains/license-service/src/lib/licenseService.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/services/license/src/lib/barcode.service.ts (2)

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

  • Shared services and modules that can be utilized across NestJS apps.
  • Proper implementation of NestJS providers, including custom providers.
  • Adherence to NestJS module encapsulation and isolation principles."

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 (8)
libs/services/license/src/lib/barcode.service.ts (4)

13-13: Consistent constant naming and documentation.

The constant BARCODE_SESSION_EXPIRE_TIME_IN_SEC is correctly named and follows the existing naming conventions. The inline comment provides clarity on the duration.


15-15: Constant BARCODE_ACTIVE_SESSION_KEY correctly introduced.

The addition of BARCODE_ACTIVE_SESSION_KEY enhances the readability of cache key construction and prevents hardcoding the key prefix multiple times.


102-112: Ensure cache keys are unique and collision-free.

When constructing cache keys using BARCODE_ACTIVE_SESSION_KEY and key, consider potential key collisions. If key can contain colons or other separators, it might inadvertently overlap with other keys. Ensure that key is appropriately sanitized or structured to prevent this.


Line range hint 91-94: Clarify the type modification in setCache method.

The setCache method's value parameter type has been modified to include string. If the method is intended to handle both BarcodeData<Type> and string, please document the use case. If not, consider reverting to the original type for type safety.

libs/api/domains/license-service/src/lib/licenseService.service.ts (4)

51-52: Imports updated correctly for error handling.

The addition of ProblemError and ProblemType imports aligns with the new error handling strategies implemented below.


474-476: Method getBarcodeSessionKey appropriately added.

The getBarcodeSessionKey method provides a clear way to generate session keys based on license type and sub. This enhances code maintainability and readability.


487-500: 🛠️ Refactor suggestion

Add error handling for cache operations.

The calls to getSessionCache and setSessionCache should include error handling to manage potential cache failures gracefully.

Apply this diff to add try-catch blocks:

 const barcodeSessionKey = this.getBarcodeSessionKey(licenseType, user.sub)
-const activeBarcodeSession = await this.barcodeService.getSessionCache(barcodeSessionKey)

+let activeBarcodeSession: string | undefined
+try {
+  activeBarcodeSession = await this.barcodeService.getSessionCache(barcodeSessionKey)
+} catch (error) {
+  this.logger.error('Failed to get session cache', { error, category: LOG_CATEGORY })
+  // Decide whether to proceed or rethrow the error
+}

 if (activeBarcodeSession && activeBarcodeSession !== user.sid) {
   // Existing logic...
 }

 // Later in the code...
- this.barcodeService.setSessionCache(barcodeSessionKey, user.sid),
+ try {
+   await this.barcodeService.setSessionCache(barcodeSessionKey, user.sid)
+ } catch (error) {
+   this.logger.error('Failed to set session cache', { error, category: LOG_CATEGORY })
+   // Decide on fail-open or fail-closed strategy
+ }

Likely invalid or redundant comment.


487-500: Consider potential issues with user.sid being undefined.

When using user.sid in session management, ensure that sid is always defined. If sid can be undefined, additional checks or fallbacks may be necessary to prevent issues when setting or comparing session IDs.

Run the following script to identify any instances where user.sid might be undefined:

libs/services/license/src/lib/barcode.service.ts Outdated Show resolved Hide resolved
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

♻️ Duplicate comments (1)
libs/api/domains/license-service/src/lib/licenseService.service.ts (1)

489-490: ⚠️ Potential issue

Add error handling for Redis operations.

The Redis operations (getSessionCache and setSessionCache) should include error handling to gracefully handle cache failures.

-      const activeBarcodeSession = await this.barcodeService.getSessionCache(barcodeSessionKey)
+      try {
+        const activeBarcodeSession = await this.barcodeService.getSessionCache(barcodeSessionKey)
+      } catch (error) {
+        this.logger.error('Failed to get session cache', {
+          error,
+          category: LOG_CATEGORY,
+        });
+        // Fail open: allow barcode creation if we can't check the session
+      }

-      barcodeSessionKey && user.sid && this.barcodeService.setSessionCache(barcodeSessionKey, user.sid),
+      barcodeSessionKey && user.sid ? 
+        this.barcodeService.setSessionCache(barcodeSessionKey, user.sid)
+          .catch(error => {
+            this.logger.error('Failed to set session cache', {
+              error,
+              category: LOG_CATEGORY,
+            });
+          })
+        : undefined,

Also applies to: 544-544

🧹 Nitpick comments (1)
libs/api/domains/license-service/src/lib/licenseService.service.ts (1)

474-476: Consider using a constant for the key separator.

The key generation logic is correct, but using a string literal for the separator could lead to maintenance issues.

+  private readonly BARCODE_SESSION_KEY_SEPARATOR = '-';
+
   getBarcodeSessionKey(licenseType: LicenseType, sub: string) {
-    return `${licenseType}-${sub}`
+    return `${licenseType}${this.BARCODE_SESSION_KEY_SEPARATOR}${sub}`
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9587a64 and 25363b4.

📒 Files selected for processing (4)
  • libs/api/domains/license-service/src/lib/licenseService.service.ts (5 hunks)
  • libs/auth-nest-tools/src/lib/auth.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/jwt.payload.ts (1 hunks)
  • libs/auth-nest-tools/src/lib/jwt.strategy.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • libs/auth-nest-tools/src/lib/auth.ts
  • libs/auth-nest-tools/src/lib/jwt.payload.ts
  • libs/auth-nest-tools/src/lib/jwt.strategy.spec.ts
🧰 Additional context used
📓 Path-based instructions (1)
libs/api/domains/license-service/src/lib/licenseService.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (2)
libs/api/domains/license-service/src/lib/licenseService.service.ts (2)

51-52: LGTM! Improved error handling with problem details format.

The changes enhance error handling by using the standardized problem details format and maintaining consistent indentation.

Also applies to: 291-291


487-502: LGTM! Robust session management implementation.

The implementation effectively prevents users from generating barcodes for licenses on multiple devices in a short timeframe by:

  1. Checking for existing sessions
  2. Comparing session IDs
  3. Using appropriate error handling

@datadog-island-is
Copy link

datadog-island-is bot commented Jan 17, 2025

Datadog Report

All test runs 8cfbca7 🔗

10 Total Test Services: 1 Failed, 9 Passed
🔻 Test Sessions change in coverage: 5 decreased, 6 increased, 187 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-user-notification 11 0 0 40 0 1m 35.43s 1 decreased (-0.56%) Link
air-discount-scheme-backend 0 0 0 63 0 31.13s N/A Link
air-discount-scheme-web 0 0 0 2 0 7.5s N/A Link
api 0 0 0 4 0 3.77s N/A Link
api-catalogue-services 0 0 0 23 0 9.14s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 21.58s N/A Link
api-domains-assets 0 0 0 3 0 13.11s N/A Link
api-domains-auth-admin 0 0 0 18 0 11.21s N/A Link
api-domains-communications 0 0 0 5 0 32.53s N/A Link
services-auth-delegation-api 0 0 0 270 0 3m 23.1s 1 decreased (-0.04%) Link

❌ Failed Tests (11)

This report shows up to 5 failed tests.

  • NotificationsWorkerService should call company registry for companies - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    
  • NotificationsWorkerService should call national registry for persons - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    
  • NotificationsWorkerService should not send email if feature flag is turned off - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    
  • NotificationsWorkerService should not send email if user has email notifications disabled - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    
  • NotificationsWorkerService should not send email if user has no email registered - apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts - Details

    Expand for error
     expect(jest.fn()).toHaveBeenCalledTimes(expected)
     
     Expected number of calls: 1
     Received number of calls: 0
    

🔻 Code Coverage Decreases vs Default Branch (5)

  • message-queue - jest 67.46% (-0.8%) - Details
  • services-user-notification - jest 68.26% (-0.56%) - Details
  • services-auth-delegation-api - jest 50.41% (-0.04%) - Details
  • services-university-gateway - jest 45.22% (-0.02%) - Details
  • license-api - jest 34.11% (-0.02%) - Details

Copy link
Member

@eirikurn eirikurn left a comment

Choose a reason for hiding this comment

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

Approving with simple comments 👍

Great work!

move contants to env and refactor barcodeSession check to function
@magnearun magnearun requested a review from a team as a code owner January 20, 2025 15:08
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

♻️ Duplicate comments (2)
libs/services/license/src/lib/barcode.service.ts (1)

100-109: 🛠️ Refactor suggestion

Add error handling for cache operations.

The cache operations should include error handling to gracefully handle failures.

Apply this diff to add error handling:

 async setSessionCache(key: string, value: string) {
+  try {
     return this.cacheManager.set(
       `${BARCODE_ACTIVE_SESSION_KEY}:${key}`,
       value,
       this.config.barcodeSessionExpireTimeInSec * 1000,
     )
+  } catch (error) {
+    this.logger.error('Failed to set session cache', { error })
+    throw error
+  }
 }

 async getSessionCache(key: string): Promise<string | undefined> {
+  try {
     return this.cacheManager.get(`${BARCODE_ACTIVE_SESSION_KEY}:${key}`)
+  } catch (error) {
+    this.logger.error('Failed to get session cache', { error })
+    return undefined
+  }
 }
libs/api/domains/license-service/src/lib/licenseService.service.ts (1)

553-555: 🛠️ Refactor suggestion

Add error handling for session cache operation.

The session cache operation should include error handling.

Apply this diff to add error handling:

-      barcodeSessionKey &&
-        user.sid &&
-        this.barcodeService.setSessionCache(barcodeSessionKey, user.sid),
+      barcodeSessionKey && user.sid
+        ? this.barcodeService
+            .setSessionCache(barcodeSessionKey, user.sid)
+            .catch((error) => {
+              this.logger.error('Failed to set session cache', {
+                error,
+                category: LOG_CATEGORY,
+              })
+            })
+        : undefined,
🧹 Nitpick comments (4)
libs/services/license/src/lib/license.config.ts (2)

8-9: Add JSDoc comments for the new configuration properties.

Consider adding documentation to explain the purpose and impact of these timing configurations:

+ /** Time in seconds before a generated barcode expires */
  barcodeExpireTimeInSec: z.number(),
+ /** Time in seconds before a barcode session expires, preventing multiple device access */
  barcodeSessionExpireTimeInSec: z.number(),

22-23: Consider adding validation for minimum values.

To prevent potential issues with too short expiration times:

-    barcodeExpireTimeInSec: env.requiredJSON('BARCODE_EXPIRE_TIME_IN_SEC', 60),
-    barcodeSessionExpireTimeInSec: env.requiredJSON('BARCODE_SESSION_EXPIRE_TIME_IN_SEC', 1800),
+    barcodeExpireTimeInSec: Math.max(30, env.requiredJSON('BARCODE_EXPIRE_TIME_IN_SEC', 60)),
+    barcodeSessionExpireTimeInSec: Math.max(300, env.requiredJSON('BARCODE_SESSION_EXPIRE_TIME_IN_SEC', 1800)),
apps/services/license-api/infra/license-api.ts (1)

46-47: Consider using environment-specific configurations.

The barcode timing values are currently hardcoded. Consider making them environment-specific like other configurations:

-      BARCODE_EXPIRE_TIME_IN_SEC: '60',
-      BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800',
+      BARCODE_EXPIRE_TIME_IN_SEC: {
+        dev: '120',  // Longer timeout for development
+        staging: '60',
+        prod: '60',
+      },
+      BARCODE_SESSION_EXPIRE_TIME_IN_SEC: {
+        dev: '3600',  // Longer timeout for development
+        staging: '1800',
+        prod: '1800',
+      },
libs/api/domains/license-service/src/lib/licenseService.service.ts (1)

507-512: Combine session key generation and check into a single operation.

The session key generation and check could be combined into a single operation for better readability.

Apply this diff to refactor the code:

-    const barcodeSessionKey = user.sub
-      ? this.getBarcodeSessionKey(licenseType, user.sub)
-      : undefined
-
-    await this.checkBarcodeSession(barcodeSessionKey, user, licenseType)
+    if (user.sub) {
+      await this.checkBarcodeSession(
+        this.getBarcodeSessionKey(licenseType, user.sub),
+        user,
+        licenseType,
+      )
+    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0884202 and 32d4643.

📒 Files selected for processing (8)
  • apps/api/infra/api.ts (1 hunks)
  • apps/services/license-api/infra/license-api.ts (1 hunks)
  • libs/api/domains/license-service/src/lib/licenseService.service.ts (4 hunks)
  • libs/services/license/src/lib/barcode.service.ts (4 hunks)
  • libs/services/license/src/lib/license.config.ts (2 hunks)
  • libs/shared/problem/src/Problem.ts (2 hunks)
  • libs/shared/problem/src/ProblemType.ts (1 hunks)
  • libs/shared/problem/src/problems.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
libs/shared/problem/src/Problem.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."
libs/shared/problem/src/problems.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."
apps/services/license-api/infra/license-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."
libs/shared/problem/src/ProblemType.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."
apps/api/infra/api.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
libs/services/license/src/lib/license.config.ts (2)

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

  • Shared services and modules that can be utilized across NestJS apps.
  • Proper implementation of NestJS providers, including custom providers.
  • Adherence to NestJS module encapsulation and isolation principles."

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/api/domains/license-service/src/lib/licenseService.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/services/license/src/lib/barcode.service.ts (2)

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

  • Shared services and modules that can be utilized across NestJS apps.
  • Proper implementation of NestJS providers, including custom providers.
  • Adherence to NestJS module encapsulation and isolation principles."

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 (5)
libs/shared/problem/src/Problem.ts (1)

8-8: LGTM! Well-structured type definition.

The addition of BadSessionProblem to the Problem type union is clean and follows TypeScript best practices for shared types.

Also applies to: 18-18

libs/shared/problem/src/ProblemType.ts (1)

12-12: Verify documentation URL existence.

The URL pattern follows the established convention, but we should ensure the documentation exists at the specified path.

✅ Verification successful

Documentation URL verified and accessible

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the documentation exists for the new problem type
curl -I https://docs.devland.is/reference/problems/bad-session

Length of output: 2407

libs/shared/problem/src/problems.ts (1)

34-36: LGTM!

The BadSessionProblem interface follows the established pattern and correctly extends the BaseProblem interface.

libs/services/license/src/lib/barcode.service.ts (1)

13-13: LGTM!

The changes improve configurability by replacing hardcoded values with configuration-based values.

Also applies to: 69-69, 86-86, 97-97

libs/api/domains/license-service/src/lib/licenseService.service.ts (1)

474-476: LGTM!

The session key generation follows a consistent format and is well-encapsulated.

apps/api/infra/api.ts Outdated Show resolved Hide resolved
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

🧹 Nitpick comments (5)
charts/islandis/values.staging.yaml (1)

1440-1441: LGTM! Consider documenting the timeout values.

The timeout values look reasonable:

  • 60-second barcode expiration provides good security
  • 30-minute session duration allows adequate user interaction time

Consider adding comments in the YAML file to document:

  • The reasoning behind these specific timeout values
  • The impact of modifying these values
  • Any related configuration values in other services that should be kept in sync
charts/services/api/values.prod.yaml (2)

38-39: Consider moving timeout values to secrets management.

The timeout values look reasonable from a security perspective (60s for barcode, 30min for session). However, consider moving these configuration values to the secrets section for better flexibility in managing different environments.

 env:
-  BARCODE_EXPIRE_TIME_IN_SEC: '60'
-  BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
 secrets:
+  BARCODE_EXPIRE_TIME_IN_SEC: '/k8s/api/BARCODE_EXPIRE_TIME_IN_SEC'
+  BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '/k8s/api/BARCODE_SESSION_EXPIRE_TIME_IN_SEC'

38-39: Add documentation for timeout values.

Please add comments explaining the purpose and impact of these timeout values to help other developers understand their significance in the barcode session management feature.

 env:
+  # Maximum lifetime of a generated barcode in seconds
   BARCODE_EXPIRE_TIME_IN_SEC: '60'
+  # Maximum duration of a barcode creation session in seconds
   BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800'
charts/services/api/values.staging.yaml (1)

38-39: LGTM! Configuration maintains consistency across services and environments.

The timeout values are consistent with:

  • Other environments (dev, staging, prod)
  • The license-api service configuration

This ensures reliable behavior of the barcode session management feature throughout the system.

Consider documenting these timeout values in the service's technical documentation to help other developers understand the session management behavior.

charts/islandis/values.prod.yaml (1)

277-278: LGTM! Consider documenting timeout rationales.

The timeout values look reasonable:

  • 60 seconds for barcode expiration provides sufficient time for legitimate use
  • 30 minutes for session expiration balances usability with security

Consider adding comments to document why these specific timeout values were chosen, to help future maintainers understand the rationale.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 32d4643 and ce40b58.

📒 Files selected for processing (9)
  • charts/islandis/values.dev.yaml (2 hunks)
  • charts/islandis/values.prod.yaml (2 hunks)
  • charts/islandis/values.staging.yaml (2 hunks)
  • charts/services/api/values.dev.yaml (1 hunks)
  • charts/services/api/values.prod.yaml (1 hunks)
  • charts/services/api/values.staging.yaml (1 hunks)
  • charts/services/license-api/values.dev.yaml (1 hunks)
  • charts/services/license-api/values.prod.yaml (1 hunks)
  • charts/services/license-api/values.staging.yaml (1 hunks)
🔇 Additional comments (5)
charts/services/license-api/values.prod.yaml (1)

22-23: Verify the timeout values align with security requirements.

The timeout values look reasonable:

  • BARCODE_EXPIRE_TIME_IN_SEC: '60' provides a short window that helps prevent barcode reuse
  • BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800' (30 minutes) balances security with user experience

Please confirm these timeout values have been approved by the security team, especially for the production environment.

charts/services/license-api/values.dev.yaml (1)

22-23: LGTM! Configuration matches production environment.

Good practice to maintain consistent timeout values across environments. This helps catch timing-related issues during development.

charts/services/license-api/values.staging.yaml (1)

22-23: LGTM! Configuration matches other environments.

Maintaining consistent timeout values across all environments (dev, staging, prod) is a good practice.

charts/services/api/values.dev.yaml (1)

38-39: LGTM! Configuration aligns with license-api service.

Good practice to maintain consistent timeout values between the API and license-api services to ensure proper integration.

charts/islandis/values.dev.yaml (1)

289-290: LGTM! Environment parity maintained.

The timeout values match production, maintaining consistency across environments.

@magnearun magnearun added the deploy-feature Deploys features to dev label Jan 20, 2025
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

🧹 Nitpick comments (1)
apps/services/license-api/src/app/modules/license/test/license.service.spec.ts (1)

381-381: Consider adding validation for the expiration time.

While using the configured expiration time is good, consider adding an assertion to validate that config.barcodeExpireTimeInSec is positive before using it in the test. This would help catch configuration issues early.

+ expect(config.barcodeExpireTimeInSec).toBeGreaterThan(0)
jest.advanceTimersByTime(config.barcodeExpireTimeInSec * 1000)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce40b58 and 083bc13.

📒 Files selected for processing (2)
  • apps/services/license-api/src/app/modules/license/test/license.service.spec.ts (3 hunks)
  • libs/services/license/src/index.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • libs/services/license/src/index.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/services/license-api/src/app/modules/license/test/license.service.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."
🔇 Additional comments (2)
apps/services/license-api/src/app/modules/license/test/license.service.spec.ts (2)

228-228: LGTM! Config type is properly declared.

The config variable is correctly typed using NestJS's ConfigType utility.


297-298: LGTM! Config is properly initialized.

The config is correctly retrieved from the test module using the appropriate configuration key.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 083bc13 and 54fc13a.

📒 Files selected for processing (6)
  • charts/islandis-services/api/values.dev.yaml (1 hunks)
  • charts/islandis-services/api/values.prod.yaml (1 hunks)
  • charts/islandis-services/api/values.staging.yaml (1 hunks)
  • charts/islandis-services/license-api/values.dev.yaml (1 hunks)
  • charts/islandis-services/license-api/values.prod.yaml (1 hunks)
  • charts/islandis-services/license-api/values.staging.yaml (1 hunks)
🔇 Additional comments (7)
charts/islandis-services/license-api/values.prod.yaml (1)

22-23: LGTM! The timeout values are reasonable.

The barcode expiration (60s) and session expiration (1800s) times align well with the PR objectives. The barcode expires quickly to prevent reuse, while the session timeout provides a reasonable window for user interaction.

charts/islandis-services/api/values.prod.yaml (1)

38-39: LGTM! Values are consistent with license-api configuration.

The timeout values match those in the license-api service, ensuring consistent behavior across services.

charts/islandis-services/license-api/values.dev.yaml (3)

23-23: LGTM! Session expiration time is reasonable.

30-minute session duration is a good balance between security and user experience.


Line range hint 1-5: Important: This file is auto-generated.

As per the warning comment, this file should not be edited manually. Please ensure you're following the correct process by running yarn charts to generate these values.

Please confirm the source of these configurations and ensure they're being managed through the proper configuration pipeline.


22-22: Consider increasing the barcode expiration time.

60 seconds might be too short for users to successfully scan their barcode, potentially leading to a poor user experience. Consider increasing this value based on real-world usage patterns.

Run this script to check barcode expiration times across environments:

charts/islandis-services/api/values.staging.yaml (1)

38-39: Review the timeout values for business requirements alignment.

The new environment variables introduce timeouts for barcode management:

  • BARCODE_EXPIRE_TIME_IN_SEC: '60' - Barcodes expire after 1 minute
  • BARCODE_SESSION_EXPIRE_TIME_IN_SEC: '1800' - Sessions expire after 30 minutes

While these values seem reasonable (short-lived barcodes for security, comfortable session duration), please verify:

  1. Is 1 minute sufficient for users to use the barcode?
  2. Does the 30-minute session timeout align with other session timeouts in the system?
charts/islandis-services/license-api/values.staging.yaml (1)

22-23: Consider managing timeout values through secrets.

While hardcoded values are acceptable for staging, consider:

  1. Moving these values to secrets for better security and flexibility
  2. Adding documentation about the purpose and relationship between these timeouts
  3. Evaluating if different license types need different timeout configurations

Let's verify if any documentation exists about these timeouts:

✅ Verification successful

Hardcoded timeout values are appropriate, no changes needed.

The current implementation:

  • Uses short-lived tokens (60s) for security with proper error handling
  • Maintains good UX with reasonable session duration (30min)
  • Has consistent values across environments by design
  • Includes proper validation and type safety
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for documentation about the timeout configuration
rg -i "barcode.*expire.*time|session.*expire.*time" README.md docs/

Length of output: 115


Script:

#!/bin/bash
# Find all markdown files
echo "=== Markdown files ==="
fd -e md

# Search for related configuration files
echo -e "\n=== Related configuration files ==="
fd -e yaml -e yml | grep -i "license\|barcode"

# Search for usage of these environment variables
echo -e "\n=== Environment variable usage ==="
rg "BARCODE_.*EXPIRE.*TIME" --type-add 'yaml:*.{yaml,yml}' --type yaml

Length of output: 24073


Script:

#!/bin/bash
# Search for code using these environment variables
echo "=== TypeScript/JavaScript usage ==="
rg "BARCODE_.*EXPIRE.*TIME" --type ts --type js -A 2 -B 2

# Look for related barcode implementation
echo -e "\n=== Barcode related code ==="
rg "barcode.*expire|expire.*barcode" --type ts --type js -i -A 2 -B 2

Length of output: 12224

charts/islandis-services/api/values.dev.yaml Outdated Show resolved Hide resolved
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

🧹 Nitpick comments (2)
libs/services/license/src/lib/license.config.ts (1)

8-9: Add documentation for the new configuration properties.

Consider adding JSDoc comments to document:

  • The purpose of these timeouts
  • The units (seconds)
  • The implications of these values on the system behavior
+  /**
+   * Time in seconds before a generated barcode expires
+   * @default 60
+   */
   barcodeExpireTimeInSec: z.number(),
+  /**
+   * Time in seconds before a barcode session expires
+   * Used to prevent multiple active sessions for the same license type
+   * @default 1800
+   */
   barcodeSessionExpireTimeInSec: z.number(),
libs/api/domains/license-service/src/lib/licenseService.service.ts (1)

Line range hint 511-559: Consider grouping session-related methods together.

The session management methods (getBarcodeSessionKey, checkBarcodeSession) should be moved closer to where they are used in createBarcode.

Move the session management methods just above the createBarcode method for better code organization.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 54fc13a and 240e522.

📒 Files selected for processing (6)
  • apps/services/license-api/src/app/modules/license/test/license.service.spec.ts (3 hunks)
  • libs/api/domains/license-service/src/lib/licenseService.service.ts (4 hunks)
  • libs/services/license/src/lib/barcode.service.ts (4 hunks)
  • libs/services/license/src/lib/license.config.ts (2 hunks)
  • libs/shared/problem/src/Problem.ts (2 hunks)
  • libs/shared/problem/src/problems.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • libs/shared/problem/src/problems.ts
  • libs/shared/problem/src/Problem.ts
  • apps/services/license-api/src/app/modules/license/test/license.service.spec.ts
🧰 Additional context used
📓 Path-based instructions (3)
libs/services/license/src/lib/license.config.ts (2)

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

  • Shared services and modules that can be utilized across NestJS apps.
  • Proper implementation of NestJS providers, including custom providers.
  • Adherence to NestJS module encapsulation and isolation principles."

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/services/license/src/lib/barcode.service.ts (2)

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

  • Shared services and modules that can be utilized across NestJS apps.
  • Proper implementation of NestJS providers, including custom providers.
  • Adherence to NestJS module encapsulation and isolation principles."

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/api/domains/license-service/src/lib/licenseService.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (5)
libs/services/license/src/lib/barcode.service.ts (3)

13-13: LGTM! Well-defined constant for session key prefix.

The constant name is descriptive and follows the naming convention.


Line range hint 69-87: LGTM! Good refactor to use configuration values.

The change from hardcoded values to configuration-based values improves flexibility and maintainability.


105-114: 🛠️ Refactor suggestion

Add error handling for Redis operations.

The session cache methods should handle potential Redis failures gracefully.

 async setSessionCache(key: string, value: string) {
+  try {
     return this.cacheManager.set(
       `${BARCODE_ACTIVE_SESSION_KEY}:${key}`,
       value,
       this.config.barcodeSessionExpireTimeInSec * 1000,
     )
+  } catch (error) {
+    this.logger.error('Failed to set session cache', { error })
+    throw error
+  }
 }

 async getSessionCache(key: string): Promise<string | undefined> {
+  try {
     return this.cacheManager.get(`${BARCODE_ACTIVE_SESSION_KEY}:${key}`)
+  } catch (error) {
+    this.logger.error('Failed to get session cache', { error })
+    return undefined
+  }
 }

Likely invalid or redundant comment.

libs/api/domains/license-service/src/lib/licenseService.service.ts (2)

474-476: LGTM! Clear and concise key generation.

The method follows single responsibility principle and is well-implemented.


478-500: LGTM! Robust session validation with proper error handling.

The implementation:

  • Properly validates session ownership
  • Uses appropriate error type (ProblemError)
  • Includes helpful logging

Copy link
Contributor

github-actions bot commented Jan 21, 2025

Affected services are: air-discount-scheme-api,air-discount-scheme-backend,api,application-system-api,download-service,financial-aid-api,financial-aid-backend,financial-aid-open-api,icelandic-names-registry-backend,judicial-system-api,judicial-system-digital-mailbox-api,judicial-system-xrd-api,judicial-system-backend,license-api,reference-backend,regulations-admin-backend,services-auth-admin-api,services-auth-ids-api,services-auth-personal-representative-public,services-auth-public-api,services-bff,services-auth-delegation-api,services-auth-personal-representative,services-documents,services-endorsements-api,services-form-system,services-search-indexer,services-sessions,services-university-gateway,services-user-notification,services-user-profile,skilavottord-ws,air-discount-scheme-web,skilavottord-web,web,application-system-form,island-ui-storybook,portals-admin,service-portal,system-e2e,
Feature deployment of your services will begin shortly. Your feature will be accessible here:
https://featbarcode-session-api-catalogue.dev01.devland.is/api
https://featbarcode-session-api.dev01.devland.is/download
https://featbarcode-session-application-callback-xrd.internal.dev01.devland.is/application-payment
https://featbarcode-session-application-callback-xrd.internal.dev01.devland.is/applications
https://featbarcode-session-application-payment-callback-xrd.internal.dev01.devland.is/application-payment
https://featbarcode-session-application-payment-callback-xrd.internal.dev01.devland.is/applications
https://featbarcode-session-beta.dev01.devland.is/
https://featbarcode-session-beta.dev01.devland.is/api
https://featbarcode-session-beta.dev01.devland.is/app/skilavottord/
https://featbarcode-session-beta.dev01.devland.is/app/skilavottord/api/graphql
https://featbarcode-session-beta.dev01.devland.is/bff
https://featbarcode-session-beta.dev01.devland.is/minarsidur
https://featbarcode-session-beta.dev01.devland.is/samradsgatt
https://featbarcode-session-beta.dev01.devland.is/stjornbord
https://featbarcode-session-beta.dev01.devland.is/stjornbord/bff
https://featbarcode-session-beta.dev01.devland.is/umsoknir
https://featbarcode-session-license-api-xrd.internal.dev01.devland.is/
https://featbarcode-session-loftbru-cf.dev01.devland.is/
https://featbarcode-session-loftbru-cf.dev01.devland.is/api/graphql
https://featbarcode-session-loftbru-cf.dev01.devland.is/api/public
https://featbarcode-session-loftbru-cf.dev01.devland.is/api/swagger
https://featbarcode-session-loftbru.dev01.devland.is/
https://featbarcode-session-loftbru.dev01.devland.is/api/graphql
https://featbarcode-session-loftbru.dev01.devland.is/api/public
https://featbarcode-session-loftbru.dev01.devland.is/api/swagger
https://featbarcode-session-service-portal-api.internal.dev01.devland.is/
https://featbarcode-session-services-university-gateway.internal.dev01.devland.is/api
https://featbarcode-session-sessions-api.internal.dev01.devland.is/
https://featbarcode-session-ui.dev01.devland.is/

Deployed services: application-system-api,application-system-form,service-portal,service-portal-api,portals-admin,api,web,skilavottord-web,skilavottord-ws,services-documents,island-ui-storybook,download-service,icelandic-names-registry-backend,endorsement-system-api,air-discount-scheme-web,air-discount-scheme-backend,air-discount-scheme-api,regulations-admin-backend,application-system-api-worker,license-api,services-sessions,services-sessions-worker,services-sessions-cleanup,services-university-gateway,services-university-gateway-worker,services-bff-portals-admin,services-bff-portals-my-pages,consultation-portal.
Excluded services: search-indexer-service,user-notification,user-notification-worker,user-notification-cleanup-worker

Copy link

codecov bot commented Jan 21, 2025

Codecov Report

Attention: Patch coverage is 55.55556% with 4 lines in your changes missing coverage. Please review.

Project coverage is 35.57%. Comparing base (27c57ef) to head (9f6761f).

Files with missing lines Patch % Lines
libs/services/license/src/lib/barcode.service.ts 50.00% 4 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #17541      +/-   ##
==========================================
- Coverage   35.57%   35.57%   -0.01%     
==========================================
  Files        7031     7031              
  Lines      150481   150485       +4     
  Branches    42970    42970              
==========================================
- Hits        53536    53535       -1     
- Misses      96945    96950       +5     
Flag Coverage Δ
air-discount-scheme-backend 48.15% <ø> (ø)
air-discount-scheme-web 0.00% <ø> (ø)
api 3.33% <ø> (ø)
api-catalogue-services 75.81% <ø> (ø)
api-domains-air-discount-scheme 37.90% <ø> (ø)
api-domains-assets 26.71% <ø> (ø)
api-domains-auth-admin 48.49% <ø> (ø)
api-domains-communications 39.49% <100.00%> (+<0.01%) ⬆️
api-domains-criminal-record 47.81% <ø> (ø)
api-domains-driving-license 44.77% <ø> (ø)
api-domains-education 31.09% <ø> (ø)
api-domains-health-insurance 35.19% <ø> (ø)
api-domains-mortgage-certificate 34.96% <ø> (ø)
api-domains-payment-schedule 42.04% <ø> (ø)
application-api-files 61.80% <ø> (ø)
application-core 75.68% <ø> (ø)
application-system-api 38.68% <100.00%> (+<0.01%) ⬆️
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 25.79% <ø> (ø)
application-templates-driving-license 18.15% <ø> (ø)
application-templates-estate 13.58% <ø> (ø)
application-templates-example-payment 24.66% <ø> (ø)
application-templates-financial-aid 14.99% <ø> (ø)
application-templates-general-petition 23.11% <ø> (ø)
application-templates-inheritance-report 6.59% <ø> (ø)
application-templates-marriage-conditions 14.80% <ø> (ø)
application-templates-mortgage-certificate 43.73% <ø> (ø)
application-templates-new-primary-school 21.02% <ø> (ø)
application-templates-parental-leave 29.92% <ø> (ø)
application-types 6.47% <ø> (ø)
application-ui-components 1.17% <ø> (ø)
application-ui-shell 22.00% <ø> (ø)
auth-admin-web 2.43% <ø> (ø)
auth-nest-tools 31.69% <ø> (ø)
auth-shared 75.00% <ø> (ø)
clients-charge-fjs-v2 28.88% <ø> (ø)
clients-driving-license 40.68% <ø> (ø)
clients-driving-license-book 43.75% <ø> (ø)
clients-financial-statements-inao 49.48% <ø> (ø)
clients-license-client 1.26% <ø> (ø)
clients-middlewares 73.14% <ø> (+0.40%) ⬆️
clients-regulations 42.75% <ø> (ø)
clients-rsk-company-registry 31.18% <ø> (ø)
clients-rsk-personal-tax-return 38.32% <ø> (ø)
clients-smartsolutions 12.77% <ø> (ø)
clients-syslumenn 49.18% <ø> (ø)
clients-zendesk 49.88% <ø> (ø)
cms 0.39% <ø> (ø)
cms-translations 38.81% <ø> (ø)
content-search-index-manager 95.65% <ø> (ø)
content-search-toolkit 8.16% <ø> (ø)
contentful-apps 4.56% <ø> (ø)
dokobit-signing 61.66% <ø> (ø)
email-service 59.68% <ø> (ø)
feature-flags 90.40% <ø> (ø)
file-storage 45.32% <ø> (ø)
financial-aid-backend 51.38% <ø> (ø)
icelandic-names-registry-backend 54.44% <ø> (ø)
infra-nest-server 48.06% <ø> (ø)
infra-tracing 69.94% <ø> (ø)
island-ui-core 30.32% <ø> (ø)
judicial-system-api 20.07% <ø> (ø)
judicial-system-audit-trail 68.53% <ø> (ø)
judicial-system-backend 55.81% <ø> (ø)
judicial-system-formatters 78.86% <ø> (ø)
judicial-system-scheduler 71.24% <ø> (ø)
judicial-system-types 37.77% <ø> (ø)
judicial-system-web 27.97% <ø> (ø)
license-api 42.88% <55.55%> (-0.11%) ⬇️
localization 10.15% <ø> (ø)
logging 58.02% <ø> (ø)
message-queue 67.05% <ø> (-0.71%) ⬇️
nest-audit 65.78% <ø> (ø)
nest-aws 51.93% <ø> (ø)
nest-config 76.05% <ø> (ø)
nest-core 53.16% <ø> (ø)
nest-feature-flags 50.69% <ø> (ø)
nest-problem 45.70% <100.00%> (+0.05%) ⬆️
nest-sequelize 94.44% <ø> (ø)
nest-swagger 51.29% <100.00%> (+0.15%) ⬆️
nova-sms 60.96% <ø> (ø)
portals-admin-regulations-admin 1.80% <ø> (ø)
portals-core 19.60% <ø> (ø)
regulations 16.78% <ø> (ø)
residence-history 85.00% <ø> (ø)
services-auth-admin-api 52.48% <100.00%> (+0.01%) ⬆️
services-auth-delegation-api 58.39% <100.00%> (-0.09%) ⬇️
services-auth-ids-api 52.52% <100.00%> (+0.02%) ⬆️
services-auth-public-api 49.36% <100.00%> (+<0.01%) ⬆️
shared-components 29.47% <ø> (ø)
shared-form-fields 33.36% <ø> (ø)
shared-mocking 58.64% <ø> (ø)
shared-pii 92.85% <ø> (ø)
shared-problem 88.00% <100.00%> (+0.50%) ⬆️
shared-utils 28.67% <ø> (ø)
skilavottord-ws 23.97% <ø> (ø)
web 2.39% <ø> (ø)

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

Files with missing lines Coverage Δ
.../license-service/src/lib/licenseService.service.ts 0.00% <ø> (ø)
...auth-nest-tools/src/lib/current-actor.decorator.ts 80.00% <ø> (ø)
libs/auth-nest-tools/src/lib/jwt.strategy.ts 92.00% <ø> (ø)
libs/services/license/src/index.ts 100.00% <ø> (ø)
libs/shared/problem/src/ProblemType.ts 100.00% <100.00%> (ø)
libs/services/license/src/lib/barcode.service.ts 84.84% <50.00%> (-11.71%) ⬇️

... and 2 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 27c57ef...9f6761f. Read the comment docs.

@thoreyjona
Copy link
Contributor

@magnearun can we get this to main tomorrow? 🙏

@eirikurn eirikurn enabled auto-merge January 22, 2025 20:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deploy-feature Deploys features to dev
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants