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(services-bff): BFF (Backend for Frontend) #15835

Merged
merged 190 commits into from
Oct 31, 2024
Merged

feat(services-bff): BFF (Backend for Frontend) #15835

merged 190 commits into from
Oct 31, 2024

Conversation

snaerseljan
Copy link
Contributor

@snaerseljan snaerseljan commented Aug 30, 2024

BFF (Backend for Frontend)

Pitch

Description

This PR introduces the BFF (Backend for Frontend) service, an intermediary layer for multiple clients. As a first step we will start with the admin portal but soon others will follow, like service-portal and others.
The service handles authentication through our Identity Server and securely proxies authenticated requests to our GraphQL server.

What this PR includes

  • BFF service handling authentication and proxying request .
  • react-spa/bff shared authentication library.
  • Admin portal authentication with BFF, using the new bff library.
  • Refactor of client shared components to support BFF and backward compatibility for clients who do not support BFF

Why

See pitch introduction

Things to consider

  • ~Test bff controllers

TODO

  • MUST DO! Update download service and other endpoints to use token from user object instead of passing __accestToken in post param
  • Move more fields from environment.ts to bff config.
  • Implement DX experience for clients when starting GraphQL API (support) (Create a sibling PR)
  • Add Client IDS secret to AWS on staging and production.
  • Implement GET api proxy with url query param
  • Exclude health/check from api global prefix. Update bootstrap options

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 AuthController for managing authentication routes, including login, logout, and callback endpoints.
    • Added BffProvider for handling user authentication states and interactions with the backend.
    • New service configuration for services-bff-portals-admin across different environments.
    • Introduced ExecuteStreamRequestArgs type for better request handling.
    • Added createMockedInitialState function for generating user mock states.
    • Enhanced module exports for easier access to BFF functionalities.
    • Added new environment variables for improved service configuration.
    • Introduced isMockMode constant for conditional mock logic.
    • Updated path mapping for easier imports from the BFF library.
    • Added GetUserDto for handling user data requests with optional refresh token.
    • Introduced UserController and UserService for managing user-related functionalities.
    • Added BffPoller component for real-time session management across tabs.
    • Introduced ProxyService for proxying HTTP requests and managing tokens.
  • Bug Fixes

    • Enhanced error handling and validation in service preparation functions.
  • Documentation

    • Updated environment variable configurations and service definitions for clarity.
  • Tests

    • Comprehensive testing suite added for AuthController and ProxyController, covering various authentication scenarios.
    • Added unit tests for BFF environment configuration serialization.
  • Chores

    • Updated .gitignore to exclude specific files and directories.
    • Enhanced logging in local setup functions for better tracking of service processing.
    • Added new scripts and dependencies in package.json for improved functionality.
    • Improved path mappings in TypeScript configuration for better module resolution.

@snaerseljan snaerseljan requested review from a team as code owners August 30, 2024 15:26
@snaerseljan snaerseljan marked this pull request as draft August 30, 2024 15:26
Copy link
Contributor

coderabbitai bot commented Aug 30, 2024

Walkthrough

The pull request introduces several modifications across multiple files, primarily focusing on enhancing the configuration and functionality of a Backend for Frontend (BFF) service. Key changes include updates to authentication routes in the AuthController, the addition of a new IdsService, and the introduction of a BffProvider for managing user authentication states. Additionally, configuration files have been updated to include new environment variables and service definitions, while test files have been enhanced to cover the new functionalities.

Changes

File Path Change Summary
.prettierrc Updated plugin path from sort-projects to sort-projects.js.
apps/services/bff/src/app/modules/auth/auth.controller.ts Added AuthController class with new authentication routes: login, callbacks/login, logout, callbacks/logout.
apps/services/bff/src/app/modules/auth/auth.controller.spec.ts Enhanced test suite for AuthController covering various authentication endpoints.
apps/services/bff/src/app/modules/proxy/proxy.controller.spec.ts Introduced test suite for ProxyController with various scenarios for API request handling.
apps/services/bff/src/app/modules/proxy/proxy.types.ts Added new type ExecuteStreamRequestArgs for stream request parameters.
apps/services/bff/test/sharedConstants.ts Introduced constants and a function related to session management and token generation.
apps/services/bff/src/app/modules/ids/ids.service.ts Added IdsService class with methods for managing identity service interactions.
apps/services/bff/src/app/modules/ids/ids.types.ts Introduced new types and interfaces related to API responses for the identity service.
apps/services/bff/test/setup.ts Added multiple new environment variables for BFF service configuration.
apps/services/bff/test/setupTestServer.ts Introduced setupTestServer function for configuring a test server.
libs/react-spa/bff/src/lib/BffProvider.tsx Added BffProvider component for managing authentication states and interactions with BFF service.
libs/react-spa/bff/src/lib/bff.mocks.ts Introduced createMockedInitialState function for generating a mocked initial state for a logged-in user.
infra/src/cli/cli.ts Updated command definitions to accept multiple services as positional arguments for render-local-env and run-local-env.
infra/src/dsl/bff.ts Added getScopes and bffConfig functions for handling BFF configurations.
infra/src/dsl/dsl.ts Introduced bff method in ServiceBuilder class for integrating BFF configurations.
infra/src/dsl/value-files-generators/local-setup.ts Updated service name mapping logic in mapServiceToNXname function.
.gitignore Added entries for mountebank-imposter-config.json and .zed/, and updated ignored files.
tsconfig.base.json Added path mapping for @island.is/react-spa/bff.
infra/package.json Added new script generate-nx-schema and dependencies json-refs and json-schema-to-zod.
charts/islandis/values.dev.yaml Added configuration for services-bff-portals-admin.
charts/islandis/values.prod.yaml Added configuration for services-bff-portals-admin.
charts/islandis/values.staging.yaml Added configuration for services-bff-portals-admin.
infra/src/uber-charts/islandis.ts Updated service integration for bffAdminPortalService.
apps/api/infra/api.ts Updated imports and service configuration for services-bff-portals-admin.
apps/services/bff/src/app/modules/user/dto/get-user.dto.ts Added new DTO class GetUserDto with optional refresh property.
apps/services/bff/src/app/modules/user/user.controller.ts Introduced UserController class with getUser method for user retrieval.
apps/services/bff/src/app/modules/user/user.service.ts Added UserService class with methods for managing user-related functionalities.
libs/react-spa/bff/src/lib/BffPoller.tsx Introduced BffPoller component for managing user session polling.
infra/src/dsl/adapters/get-ssm-params.ts Enhanced error handling for AWS credentials in getSsmParams function.
apps/services/bff/src/app/modules/proxy/proxy.service.ts Added ProxyService class for proxying HTTP requests.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AuthController
    participant AuthService

    User->>AuthController: Login request
    AuthController->>AuthService: Validate credentials
    AuthService-->>AuthController: Return user data
    AuthController-->>User: Return login response

    User->>AuthController: Logout request
    AuthController->>AuthService: Process logout
    AuthService-->>AuthController: Confirm logout
    AuthController-->>User: Return logout response
Loading

Possibly related PRs

  • chore(web): Add pdf worker file to web assets #16266: The changes in the main PR regarding the .prettierrc file and the addition of the sort-projects.js plugin path are related to the modifications in the .prettierignore file in this PR, which also involves file management and configuration for Prettier.
  • fix(infra): CLI fixes for {run,render}-local-env #16575: This PR includes updates to the CLI commands that involve environment configurations, which may indirectly relate to the changes in the .prettierrc file as both involve configuration management within the project.
  • chore(infra): Comments, and linting #16578: The introduction of a new method for validating environment variables in this PR aligns with the configuration changes in the main PR, as both involve ensuring proper setup and management of project configurations.

Suggested reviewers

  • thordurhhh
  • svanaeinars
  • Toti91
  • eirikurn
  • RunarVestmann

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0b01e9e and f2a9f8a.

Files selected for processing (34)
  • apps/portals/admin/project.json (5 hunks)
  • apps/portals/admin/proxy.config.json (1 hunks)
  • apps/services/bff/.eslintrc.json (1 hunks)
  • apps/services/bff/README.md (1 hunks)
  • apps/services/bff/docker-compose.yml (1 hunks)
  • apps/services/bff/esbuild.json (1 hunks)
  • apps/services/bff/infra/admin-portal.infra.ts (1 hunks)
  • apps/services/bff/jest.config.ts (1 hunks)
  • apps/services/bff/project.json (1 hunks)
  • apps/services/bff/src/app/app.module.ts (1 hunks)
  • apps/services/bff/src/app/bff.config.ts (1 hunks)
  • apps/services/bff/src/app/modules/auth/auth.controller.ts (1 hunks)
  • apps/services/bff/src/app/modules/auth/auth.module.ts (1 hunks)
  • apps/services/bff/src/app/modules/auth/auth.service.ts (1 hunks)
  • apps/services/bff/src/app/modules/auth/auth.types.ts (1 hunks)
  • apps/services/bff/src/app/modules/auth/dto/callback-login-query.dto.ts (1 hunks)
  • apps/services/bff/src/app/modules/auth/dto/login-query.dto.ts (1 hunks)
  • apps/services/bff/src/app/modules/auth/pkce.service.spec.ts (1 hunks)
  • apps/services/bff/src/app/modules/auth/pkce.service.ts (1 hunks)
  • apps/services/bff/src/app/modules/cache/cache.module.ts (1 hunks)
  • apps/services/bff/src/app/modules/cache/cache.service.ts (1 hunks)
  • apps/services/bff/src/app/modules/user/user.controller.ts (1 hunks)
  • apps/services/bff/src/app/modules/user/user.module.ts (1 hunks)
  • apps/services/bff/src/app/modules/user/user.service.ts (1 hunks)
  • apps/services/bff/src/environment/environment.schema.ts (1 hunks)
  • apps/services/bff/src/environment/environment.ts (1 hunks)
  • apps/services/bff/src/environment/index.ts (1 hunks)
  • apps/services/bff/src/main.ts (1 hunks)
  • apps/services/bff/src/utils/env.ts (1 hunks)
  • apps/services/bff/tsconfig.app.json (1 hunks)
  • apps/services/bff/tsconfig.json (1 hunks)
  • apps/services/bff/tsconfig.spec.json (1 hunks)
  • libs/shared/utils/src/index.ts (1 hunks)
  • libs/shared/utils/src/lib/isString.ts (1 hunks)
Files skipped from review due to trivial changes (11)
  • apps/portals/admin/project.json
  • apps/portals/admin/proxy.config.json
  • apps/services/bff/.eslintrc.json
  • apps/services/bff/README.md
  • apps/services/bff/docker-compose.yml
  • apps/services/bff/jest.config.ts
  • apps/services/bff/src/environment/index.ts
  • apps/services/bff/tsconfig.json
  • apps/services/bff/tsconfig.spec.json
  • libs/shared/utils/src/index.ts
  • libs/shared/utils/src/lib/isString.ts
Additional context used
Path-based instructions (23)
apps/services/bff/src/app/modules/auth/auth.types.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/bff/src/app/modules/auth/dto/login-query.dto.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/bff/tsconfig.app.json (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/bff/src/app/modules/auth/dto/callback-login-query.dto.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/bff/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."
apps/services/bff/src/app/modules/user/user.module.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/bff/src/app/modules/user/user.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/bff/src/app/modules/auth/auth.module.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/bff/src/environment/environment.schema.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/bff/src/app/app.module.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/bff/src/app/bff.config.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/bff/src/app/modules/cache/cache.module.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/bff/src/app/modules/user/user.service.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/bff/src/environment/environment.ts (2)

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

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

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/services/bff/src/utils/env.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/bff/src/app/modules/auth/auth.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/bff/esbuild.json (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/bff/src/app/modules/cache/cache.service.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/bff/project.json (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/bff/src/app/modules/auth/pkce.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."
apps/services/bff/infra/admin-portal.infra.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/bff/src/app/modules/auth/pkce.service.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/bff/src/app/modules/auth/auth.service.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 not posted (45)
apps/services/bff/src/app/modules/auth/auth.types.ts (1)

1-7: Type definition for TokenResponse is correct and complete.

The TokenResponse type correctly defines all standard fields expected in an OAuth2 token response. This will facilitate secure handling of authentication tokens within the BFF service.

apps/services/bff/src/app/modules/auth/dto/login-query.dto.ts (1)

1-11: DTO definition for LoginQueryDto is robust and well-validated.

The LoginQueryDto class is well-defined with appropriate validation rules using class-validator. This ensures that the data received in login queries is correctly typed and optional, which is crucial for security and functionality.

apps/services/bff/src/app/modules/auth/dto/callback-login-query.dto.ts (1)

1-15: Well-structured DTO for callback login queries.

The use of class-validator decorators ensures that the data integrity is maintained, and the non-null assertion operator is appropriately used for required fields.

The code changes are approved.

apps/services/bff/src/main.ts (1)

1-14: Proper application setup and configuration.

The bootstrap configuration is well-structured, utilizing environment variables for flexibility. Consider expanding the health check configuration for more comprehensive monitoring in the future.

The code changes are approved.

apps/services/bff/src/app/modules/user/user.module.ts (1)

1-12: Well-organized User module with caching integration.

The module is structured according to NestJS best practices, with a clear separation of concerns and integration of caching for performance optimization. Ensure that the cache service is properly configured and tested.

The code changes are approved.

apps/services/bff/src/app/modules/user/user.controller.ts (1)

5-16: Well-structured UserController class.

The class is correctly set up with dependency injection and versioning. The getUser method is well-implemented, making good use of the UserService to fetch user data.

apps/services/bff/src/app/modules/auth/auth.module.ts (1)

8-12: Well-configured AuthModule.

The module is correctly set up with essential services for authentication, including PKCE support and caching mechanisms. This setup enhances security and performance.

apps/services/bff/src/environment/environment.schema.ts (1)

3-34: Comprehensive and well-documented environment configuration schemas.

The use of z.strictObject ensures robust validation. The schemas are well-structured and cover essential configurations for the application, enhancing maintainability and preventing configuration errors.

apps/services/bff/src/app/app.module.ts (1)

1-23: Comprehensive review of AppModule configuration.

The AppModule is well-structured and integrates various configurations and modules effectively. The use of @nestjs/common, @island.is/nest, and environment-specific configurations aligns with NestJS best practices. The module setup with AuditModule, BaseAuthModule, and ConfigModule is correctly implemented, ensuring a robust configuration for the BFF service.

  • AuditModule: Configured with environment-specific settings, which is a good practice for maintaining different configurations across environments.
  • BaseAuthModule: Properly registered with environment settings, ensuring that authentication configurations are centralized and manageable.
  • ConfigModule: The global flag and the inclusion of multiple configuration schemas (FeatureFlagConfig, IdsClientConfig, BffConfig) enhance the modularity and reusability of the configuration.

Overall, the AppModule setup supports maintainability and scalability, adhering to the principles of good software architecture in a microservices environment.

apps/services/bff/src/app/bff.config.ts (1)

1-34: Thorough review of BffConfig setup.

The BffConfig is well-defined using Zod for schema validation, which ensures that the configuration adheres to expected types and structures. The separation of Redis and authentication configurations into a single schema promotes modularity and reusability.

  • Redis Configuration: The dynamic loading of Redis nodes from the environment and the conditional SSL based on production status are best practices for secure and flexible configuration.
  • Authentication Configuration: Leveraging existing authSchema ensures consistency across different parts of the application that deal with authentication.

This configuration file is a good example of how to manage application settings securely and efficiently, adhering to best practices in software development.

apps/services/bff/src/app/modules/cache/cache.module.ts (1)

1-29: Detailed review of CacheModule configuration.

The CacheModule is configured to adapt to different environments effectively, using NestJS's dynamic module capabilities. The conditional registration based on environment variables (NODE_ENV and INIT_SCHEMA) is a smart way to handle different testing and deployment scenarios.

  • Testing and Initialization Conditions: The simple cache registration for testing or schema initialization scenarios is a practical approach to ensure that the service remains lightweight and manageable during these operations.
  • Production Configuration: The detailed setup for Redis using redisInsStore and createRedisCluster ensures that the caching mechanism is robust and scalable. The use of SSL configuration based on the production environment enhances security.

This module exemplifies how to configure caching in a service-oriented architecture effectively, considering both development convenience and production robustness.

apps/services/bff/src/app/modules/user/user.service.ts (1)

1-40: Comprehensive Review of UserService

  1. Imports and Decorators:

    • The use of @Injectable() and @Inject() decorators aligns with NestJS's dependency injection pattern, which is correctly implemented here.
  2. Constructor:

    • The constructor correctly injects Logger and CacheService. This encapsulation ensures that the service can log errors and interact with the cache without directly managing these dependencies.
  3. getUser Method:

    • Error Handling: The method throws an UnauthorizedException if no session ID (sid) is found in the cookies, which is a standard practice for handling missing authentication credentials.
    • Cache Interaction: The method retrieves a user object from the cache using a session key. The use of a helper method createSessionKeyType for key generation is a good practice as it abstracts key creation logic.
    • Logging: Proper error logging is implemented, which aids in debugging and monitoring.
    • Exception Rethrowing: The method rethrows an UnauthorizedException if any error occurs during the cache retrieval process, which simplifies error handling in upstream code.
  4. Suggestions:

    • Custom Error Message: The generic Error thrown when the user is not found in the cache could be replaced with a more descriptive error message or a specific exception type to improve error handling clarity.
    • Test Coverage: Ensure that unit tests cover scenarios such as missing sid, cache retrieval failures, and successful user retrieval.

Overall, the implementation adheres to NestJS best practices, with robust error handling and dependency management. Minor improvements could be made in error messaging.

apps/services/bff/src/environment/environment.ts (1)

1-27: Comprehensive Review of environment.ts

  1. Utility Functions Usage:

    • The use of requiredString and requiredStringArray for environment variable validation is a robust approach to ensure that all necessary configurations are present before the application starts. This pattern helps prevent runtime errors related to configuration issues.
  2. Configuration Object:

    • The structure of the environment object is clear and well-organized, separating concerns such as authentication and auditing into nested objects. This makes the configuration easy to read and maintain.
    • The use of TypeScript types for the environment configuration enhances type safety and reduces the risk of assigning incorrect values to the configuration properties.
  3. Suggestions:

    • Validation Enhancement: Consider adding more detailed validation for environment variables, such as URL format validation for the issuer and redirect URIs, to catch configuration errors early.
    • Documentation: Adding comments to the configuration object properties could improve maintainability by making it easier for new developers to understand the purpose of each configuration item.

The implementation of environment configuration in this file follows best practices for robustness and maintainability. Enhancements in validation and documentation could further improve the quality.

apps/services/bff/src/utils/env.ts (1)

1-40: Comprehensive Review of env.ts

  1. Function Implementation:

    • requiredString: This function correctly checks if a string value is present for a given key and throws a descriptive error if not. This is crucial for ensuring that essential environment variables are set.
    • requiredStringArray: This function extends the validation to check if the value is a JSON-stringified array of strings. The use of JSON.parse and subsequent validation of the array's contents is a thorough approach to ensure the configuration's integrity.
  2. Error Handling:

    • The error messages are specific and informative, which aids in quickly identifying missing or incorrectly formatted environment variables during the application startup.
  3. Suggestions:

    • Error Handling Enhancement: For requiredStringArray, the error thrown in the catch block could include the original error message from JSON.parse to provide more context about the parsing failure.
    • Unit Testing: Ensure that there are comprehensive unit tests covering scenarios like missing environment variables, incorrect formats, and successful validations.

The utility functions in this file are well-implemented with robust validation and clear error messaging. Minor enhancements in error handling could be made to provide more detailed debugging information.

apps/services/bff/src/app/modules/auth/auth.controller.ts (4)

1-19: Well-configured imports and validation pipe.

The import statements are correctly organized, and the custom validation pipe setup enhances security and data integrity by transforming and validating incoming data.


21-25: Properly configured controller and dependency injection.

The AuthController is appropriately versioned and utilizes dependency injection for the AuthService, aligning with NestJS best practices.


27-35: Secure and efficient login method implementation.

The login method correctly uses HTTP decorators and the custom validation pipe to securely handle login requests.


37-44: Consistent and secure callback method implementation.

The callback method effectively uses HTTP decorators and the custom validation pipe, similar to the login method, ensuring consistency and security.

apps/services/bff/esbuild.json (1)

1-51: Optimized and comprehensive esbuild configuration.

The configuration settings are well-suited for a Node.js environment, with a detailed list of external dependencies to optimize the build process and debugging.

apps/services/bff/src/app/modules/cache/cache.service.ts (4)

1-11: Properly configured cache service with dependency injection.

The import statements and class setup are correctly implemented, adhering to NestJS standards for services, particularly with the use of dependency injection.


13-21: Well-implemented method for generating session keys.

The createSessionKeyType method effectively generates distinct cache keys for different session types, enhancing cache management.


23-44: Robust cache handling methods with error management.

The save and get methods are well-implemented, providing robust cache entry management and appropriate error handling for not found scenarios.


46-48: Effective cache entry deletion method.

The delete method is straightforward and effectively handles the deletion of cache entries, adhering to best practices in cache management.

apps/services/bff/project.json (6)

9-25: Verify the maxWorkers setting for the build configuration.

The maxWorkers is set to 2, which might be low depending on the environment and could affect build performance. Consider adjusting this based on the available resources.


26-30: Serve configuration looks good.

The serve configuration correctly references the build target and uses the appropriate executor.


32-34: Lint configuration is appropriate.

The lint configuration uses the NX ESLint executor, which is standard for projects like this.


35-42: Test configuration is well-set.

The use of runInBand is appropriate for avoiding parallel execution issues in Jest, and the configuration points to the correct Jest config file.


43-49: Dev-services configuration supports effective local development.

Using Docker Compose for managing services is a robust choice for local development environments.


50-58: Dev configuration is optimized for development use.

The configuration allows for parallel execution of commands, which can enhance the development experience.

apps/services/bff/src/app/modules/auth/pkce.service.spec.ts (4)

15-28: Test suite for generateVerifier is comprehensive.

The tests check both the length and the character set of the generated verifier, ensuring robustness.


30-36: Test suite for generateCodeVerifier is correctly implemented.

The test effectively checks the default length and character set, ensuring the function behaves as expected.


38-45: Test suite for generateCodeChallenge is well-structured.

The test checks the output based on a given verifier and uses appropriate assertions to ensure the output is in the correct format.


47-54: Test suite for getRandomValues is essential and well-implemented.

The test verifies both the type and the length of the output array, ensuring the function's correctness.

apps/services/bff/infra/admin-portal.infra.ts (2)

3-42: Environment configuration is detailed and well-structured.

The inclusion of environment-specific URLs and a comprehensive list of scopes ensures that the service is well-configured for different operational environments.


49-62: Resource configuration is appropriate for the service.

The specified CPU and memory limits and requests are reasonable and should support the service's operational needs effectively.

apps/services/bff/src/app/modules/auth/pkce.service.ts (5)

12-14: Well-implemented method for generating PKCE code verifier.

The method correctly delegates the generation of a 50-character long verifier. This is a standard practice for PKCE to ensure sufficient entropy.


20-33: Secure implementation of PKCE code challenge generation.

The method uses SHA-256 hashing and Base64 URL encoding to generate a secure code challenge from the verifier. The use of Web Crypto API for asynchronous hashing is a best practice, enhancing the security of the operation.


39-43: Correct implementation for generating random values.

The method uses randomBytesAsync to generate cryptographically secure random bytes, which is essential for security-sensitive operations like PKCE.


49-62: Robust method for generating PKCE verifier.

The method generates a cryptographically strong random string using a well-chosen character set. This approach ensures that the verifier is both random and suitable for URL encoding.


71-77: Accurate implementation of Base64 URL encoding.

The method correctly converts a Buffer to a Base64 URL-safe string, making appropriate replacements to ensure the string is safe for URL usage. This is crucial for encoding values that will be transmitted over URLs.

apps/services/bff/src/app/modules/auth/auth.service.ts (5)

1-33: Initial setup and imports are correctly implemented.

The use of dependency injection for the logger and configuration services aligns with NestJS best practices.


37-56: Secure and robust URI validation.

The validateRedirectUri method effectively prevents open redirects by validating URIs against allowed patterns. The use of regex to handle wildcards enhances its robustness.


86-110: Correct implementation of fetchPAR.

The method effectively handles the fetching of Pushed Authorization Requests (PAR) using consistent HTTP request handling via the postRequest method.


112-128: Secure token fetching implemented correctly.

The fetchTokens method securely fetches tokens using the authorization code and code verifier, maintaining consistency in HTTP request handling.


130-225: Well-implemented authentication flow in login and callback methods.

These methods handle the core authentication flow, including secure session management and user redirection. The use of caching and URI validation enhances security and user experience.

Copy link

codecov bot commented Aug 30, 2024

Codecov Report

Attention: Patch coverage is 22.39748% with 246 lines in your changes missing coverage. Please review.

Project coverage is 36.64%. Comparing base (7adc95a) to head (d1f3010).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
libs/react-spa/bff/src/lib/BffProvider.tsx 2.43% 80 Missing ⚠️
libs/react-spa/shared/src/hooks/usePolling.tsx 2.38% 41 Missing ⚠️
libs/react-spa/shared/src/hooks/useBroadcaster.ts 17.64% 28 Missing ⚠️
libs/react-spa/bff/src/lib/BffPoller.tsx 4.34% 22 Missing ⚠️
libs/react-spa/bff/src/lib/bff.state.ts 15.78% 16 Missing ⚠️
libs/react-spa/bff/src/lib/bff.hooks.ts 61.76% 13 Missing ⚠️
libs/react-spa/bff/src/lib/bff.utils.ts 25.00% 12 Missing ⚠️
...tions-admin/src/components/DownloadDraftButton.tsx 0.00% 10 Missing ⚠️
libs/shared/mocking/src/msw/startMocking.ts 20.00% 8 Missing ⚠️
libs/infra-nest-server/src/lib/bootstrap.ts 60.00% 2 Missing ⚠️
... and 11 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #15835      +/-   ##
==========================================
- Coverage   36.67%   36.64%   -0.03%     
==========================================
  Files        6858     6872      +14     
  Lines      142789   143068     +279     
  Branches    40704    40770      +66     
==========================================
+ Hits        52364    52432      +68     
- Misses      90425    90636     +211     
Flag Coverage Δ
air-discount-scheme-backend 54.17% <75.00%> (+0.13%) ⬆️
air-discount-scheme-web 0.00% <ø> (ø)
api 3.37% <ø> (ø)
api-domains-air-discount-scheme 37.30% <100.00%> (+0.36%) ⬆️
api-domains-assets 26.71% <ø> (ø)
api-domains-auth-admin 48.48% <ø> (ø)
api-domains-communications 39.92% <100.00%> (+<0.01%) ⬆️
api-domains-criminal-record 47.83% <20.00%> (-0.18%) ⬇️
api-domains-driving-license 44.61% <65.21%> (+0.13%) ⬆️
api-domains-education 31.58% <100.00%> (ø)
api-domains-health-insurance 34.77% <ø> (ø)
api-domains-mortgage-certificate 34.93% <20.00%> (-0.05%) ⬇️
api-domains-payment-schedule 41.51% <100.00%> (+0.34%) ⬆️
application-api-files 56.78% <100.00%> (ø)
application-core 71.49% <ø> (ø)
application-system-api 41.33% <58.06%> (+0.01%) ⬆️
application-template-api-modules 27.83% <66.66%> (+0.05%) ⬆️
application-templates-accident-notification 29.24% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 26.30% <ø> (ø)
application-templates-driving-license 18.40% <ø> (ø)
application-templates-estate 12.19% <10.82%> (-0.07%) ⬇️
application-templates-example-payment 25.20% <ø> (ø)
application-templates-financial-aid 15.55% <100.00%> (+0.08%) ⬆️
application-templates-general-petition 23.42% <ø> (ø)
application-templates-inheritance-report 6.50% <ø> (ø)
application-templates-marriage-conditions 15.18% <ø> (ø)
application-templates-mortgage-certificate 43.58% <100.00%> (+0.02%) ⬆️
application-templates-parental-leave 30.04% <ø> (+0.09%) ⬆️
application-types 6.62% <ø> (ø)
application-ui-components 1.27% <ø> (ø)
application-ui-shell 20.87% <10.82%> (-0.36%) ⬇️
auth-nest-tools 30.20% <100.00%> (+0.18%) ⬆️
auth-react 21.94% <6.49%> (-0.32%) ⬇️
clients-charge-fjs-v2 24.11% <ø> (ø)
clients-driving-license 40.56% <20.00%> (-0.12%) ⬇️
clients-driving-license-book 43.70% <20.00%> (-0.11%) ⬇️
clients-financial-statements-inao 49.32% <ø> (ø)
clients-license-client 1.83% <ø> (ø)
clients-middlewares 73.22% <100.00%> (+0.10%) ⬆️
clients-regulations 42.66% <20.00%> (-0.14%) ⬇️
clients-rsk-company-registry 29.76% <ø> (ø)
clients-syslumenn 49.38% <20.00%> (-0.11%) ⬇️
cms 0.42% <ø> (ø)
cms-translations 39.05% <100.00%> (+<0.01%) ⬆️
content-search-index-manager 95.65% <ø> (ø)
content-search-toolkit 8.16% <ø> (ø)
contentful-apps 5.20% <ø> (ø)
download-service 44.39% <75.00%> (+0.17%) ⬆️
financial-aid-backend 51.38% <100.00%> (+0.15%) ⬆️
financial-aid-shared 17.81% <ø> (ø)
icelandic-names-registry-backend 54.34% <73.68%> (+0.37%) ⬆️
infra-nest-server 48.37% <71.42%> (+0.19%) ⬆️
island-ui-core 28.86% <100.00%> (ø)
judicial-system-api 19.52% <ø> (ø)
judicial-system-web 27.65% <100.00%> (ø)
license-api 42.73% <75.00%> (+0.27%) ⬆️
localization 10.15% <ø> (ø)
nest-audit 68.20% <ø> (ø)
nest-core 43.54% <ø> (ø)
nest-feature-flags 51.52% <ø> (ø)
nest-problem 45.82% <28.57%> (-0.03%) ⬇️
nest-swagger 51.71% <ø> (ø)
portals-admin-regulations-admin 1.85% <0.00%> (+<0.01%) ⬆️
portals-core 15.91% <14.60%> (-0.11%) ⬇️
reference-backend 49.74% <28.57%> (-0.05%) ⬇️
services-auth-delegation-api 57.57% <76.19%> (+0.11%) ⬆️
services-auth-personal-representative 45.11% <76.19%> (+0.06%) ⬆️
services-endorsements-api 53.72% <75.00%> (+0.13%) ⬆️
services-sessions 65.49% <75.00%> (+0.14%) ⬆️
services-university-gateway 49.47% <28.57%> (+0.01%) ⬆️
services-user-notification 46.99% <76.19%> (+0.05%) ⬆️
services-user-profile 61.85% <75.00%> (+0.08%) ⬆️
shared-components 26.93% <18.65%> (-0.58%) ⬇️
shared-form-fields 31.22% <100.00%> (ø)
shared-mocking 60.89% <0.00%> (-3.73%) ⬇️
shared-problem 87.50% <ø> (ø)
shared-utils 27.69% <0.00%> (ø)
skilavottord-ws 24.14% <ø> (ø)
web 1.80% <100.00%> (ø)

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

Files with missing lines Coverage Δ
apps/api/src/app/environments/environment.ts 0.00% <ø> (ø)
libs/auth/scopes/src/index.ts 100.00% <100.00%> (ø)
...auth/scopes/src/lib/clients/admin-portal-scopes.ts 100.00% <100.00%> (ø)
...th/scopes/src/lib/clients/service-portal-scopes.ts 100.00% <100.00%> (ø)
libs/portals/core/src/hooks/useNavigation.ts 91.66% <100.00%> (ø)
libs/portals/core/src/utils/modules.ts 89.28% <ø> (ø)
...portals/core/src/utils/router/prepareRouterData.ts 100.00% <ø> (ø)
libs/react-spa/bff/src/lib/BffContext.tsx 100.00% <100.00%> (ø)
libs/react/feature-flags/src/lib/context.tsx 12.90% <ø> (+0.40%) ⬆️
libs/service-portal/information/src/module.tsx 0.00% <ø> (ø)
... and 28 more

... and 1 file 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 7adc95a...d1f3010. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Aug 30, 2024

Datadog Report

All test runs 2b26e15 🔗

83 Total Test Services: 0 Failed, 80 Passed
🔻 Test Sessions change in coverage: 11 decreased, 20 increased, 165 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
air-discount-scheme-backend 0 0 0 82 0 27.72s N/A Link
air-discount-scheme-web 0 0 0 2 0 8.18s N/A Link
api 0 0 0 4 0 2.45s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 20.57s N/A Link
api-domains-assets 0 0 0 3 0 12.37s N/A Link
api-domains-auth-admin 0 0 0 18 0 13s N/A Link
api-domains-communications 0 0 0 5 0 30.71s 1 no change Link
api-domains-criminal-record 0 0 0 5 0 8.68s N/A Link
api-domains-driving-license 0 0 0 23 0 26.54s 1 increased (+0.09%) Link
api-domains-education 0 0 0 8 0 17.07s N/A Link

🔻 Code Coverage Decreases vs Default Branch (11)

This report shows up to 5 code coverage decreases.

  • react-spa-shared - jest 15.62% (-8.97%) - Details
  • shared-mocking - jest 58.86% (-4.01%) - Details
  • shared-components - jest 33.24% (-1.35%) - Details
  • portals-core - jest 23.79% (-0.75%) - Details
  • auth-react - jest 30.7% (-0.73%) - Details

Copy link
Member

@brynjarorng brynjarorng left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Member

@obmagnusson obmagnusson left a comment

Choose a reason for hiding this comment

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

Code Owned files LGTM

Copy link
Member

@thordurhhh thordurhhh left a comment

Choose a reason for hiding this comment

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

Service Portal looking good. 🙌

Copy link
Member

@Toti91 Toti91 left a comment

Choose a reason for hiding this comment

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

Code owned LGTM

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

🧹 Outside diff range and nitpick comments (4)
apps/services/bff/src/app/modules/user/dto/get-user.dto.ts (1)

3-7: Add JSDoc documentation for better code maintainability.

Consider adding class-level documentation to explain the DTO's purpose and usage.

+/**
+ * Data Transfer Object for user retrieval requests.
+ * Used when fetching user information with an optional refresh token.
+ */
 export class GetUserDto {
   @IsOptional()
   @IsString()
   refresh?: string
 }
libs/react-spa/bff/src/lib/BffProvider.tsx (1)

24-42: Consider breaking down the component for better maintainability

The BffProvider component handles multiple responsibilities (authentication, state management, UI rendering). Consider:

  1. Extracting the state management logic into a custom hook
  2. Moving the UI components into separate files
  3. Breaking down the renderContent function into smaller components

This would improve maintainability and make the code easier to test.

Also applies to: 193-236

libs/react-spa/bff/src/lib/BffPoller.tsx (2)

36-40: Use @example instead of @usage in JSDoc comment

The JSDoc tag @usage is not standard. Consider replacing it with @example to conform with JSDoc conventions and improve documentation clarity.

Apply this diff to update the JSDoc tag:

- * @usage:
+ * @example

81-81: Correct typo in comment: "notifiy" should be "notify"

There's a typographical error in the comment on line 81. "Notifiy" should be "notify".

Apply this diff to fix the typo:

-      // If session has changed (e.g. delegation switch), then notifiy tabs/windows/iframes and execute the callback.
+      // If session has changed (e.g. delegation switch), then notify tabs/windows/iframes and execute the callback.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 468bf6e and 8e23efc.

📒 Files selected for processing (5)
  • apps/services/bff/src/app/modules/user/dto/get-user.dto.ts (1 hunks)
  • apps/services/bff/src/app/modules/user/user.controller.ts (1 hunks)
  • apps/services/bff/src/app/modules/user/user.service.ts (1 hunks)
  • libs/react-spa/bff/src/lib/BffPoller.tsx (1 hunks)
  • libs/react-spa/bff/src/lib/BffProvider.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
apps/services/bff/src/app/modules/user/dto/get-user.dto.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/bff/src/app/modules/user/user.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/bff/src/app/modules/user/user.service.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/react-spa/bff/src/lib/BffPoller.tsx (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/react-spa/bff/src/lib/BffProvider.tsx (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (10)
apps/services/bff/src/app/modules/user/dto/get-user.dto.ts (2)

1-7: LGTM! The basic implementation follows NestJS best practices.

The DTO is well-structured with proper validation decorators and TypeScript types.


6-6: Verify security measures for refresh token handling.

The refresh token is sensitive data. Ensure that:

  1. The token is transmitted securely
  2. Proper rate limiting is in place
  3. Token validation is implemented in the service layer
✅ Verification successful

Refresh token security measures are properly implemented

The codebase demonstrates robust security measures for refresh token handling:

  1. Secure transmission:

    • Tokens are stored in HTTP-only, secure cookies with SameSite=lax protection
    • Tokens are encrypted before being cached using CryptoService
  2. Token lifecycle management:

    • Proper token revocation on logout and session changes
    • Automatic refresh token rotation
    • Token expiration handling with safety margins
  3. Additional security features:

    • Tokens are encrypted before caching to prevent unauthorized access
    • Refresh tokens are handled server-side only
    • Proper error handling and logging for token operations

The implementation follows security best practices for refresh token handling in the BFF (Backend-for-Frontend) pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for rate limiting implementation
rg -A 5 "RateLimit|ThrottlerModule|@Throttle" apps/services/bff/

# Check for token validation in the service
ast-grep --pattern 'class UserService {
  $$$
  validate$_($$$) {
    $$$
  }
  $$$
}'

Length of output: 155


Script:

#!/bin/bash
# Check for rate limiting and security configurations
rg -A 5 "ThrottlerModule|RateLimit|@Throttle" apps/services/bff/src/
rg -A 5 "refresh.*token" apps/services/bff/src/

# Check for token validation and security measures
ast-grep --pattern 'class $_ {
  $$$
  validateRefresh($$$) {
    $$$
  }
  $$$
}'

# Check for HTTP security headers and secure transmission
rg -A 5 "secure:|httpOnly:|sameSite:" apps/services/bff/src/

# Look for auth guards and middleware
rg -A 5 "@UseGuards|implements CanActivate" apps/services/bff/src/

Length of output: 12742

apps/services/bff/src/app/modules/user/user.controller.ts (2)

1-8: LGTM! Well-structured imports with clear separation of concerns.

The imports are properly organized, utilizing shared types and following NestJS best practices.


10-13: Clarify the versioning strategy for the API.

While supporting both VERSION_NEUTRAL and '1' provides flexibility, it's important to:

  1. Document the versioning strategy
  2. Clarify when VERSION_NEUTRAL vs v1 should be used
  3. Consider how this aligns with the overall BFF service versioning plan

Let's check if there's documentation about the API versioning strategy:

#!/bin/bash
# Search for API versioning documentation
rg -g '*.md' -i 'api version|versioning strategy' 
libs/react-spa/bff/src/lib/BffProvider.tsx (4)

1-22: LGTM! Well-structured imports and type definitions.

The imports are properly organized, and the BffProviderProps type is well-documented with JSDoc comments.


44-74: Skip comment about setTimeout in LOGOUT event handler

A previous review comment already addresses the concerns about the setTimeout usage in the LOGOUT event handler.


75-159: Skip comments about authentication function safety checks

Previous review comments already address the concerns about proper null checks in signOut and nationalId validation in switchUser.


161-175: Skip comment about URL parameter sanitization

A previous review comment already addresses the security concerns about sanitizing error messages from URL parameters.

apps/services/bff/src/app/modules/user/user.service.ts (1)

18-26: Adherence to NestJS dependency injection patterns

The UserService demonstrates proper usage of NestJS dependency injection by injecting necessary services such as CryptoService, CacheService, IdsService, and AuthService. This approach enhances modularity and maintainability.

libs/react-spa/bff/src/lib/BffPoller.tsx (1)

1-97: Code implementation follows best practices and guidelines

The BffPoller component is well-structured and adheres to the coding guidelines. It effectively uses TypeScript for defining props, promotes reusability across NextJS apps, and ensures efficient use of hooks.

coderabbitai[bot]
coderabbitai bot previously requested changes Oct 31, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
infra/src/dsl/adapters/get-ssm-params.ts (1)

Line range hint 1-47: Enhance DSL documentation and integration clarity.

As this is part of the DSL infrastructure, please add:

  1. Documentation explaining the SSM parameter naming conventions and structure
  2. Integration examples with Helm charts
  3. Usage examples for different environments

Add a documentation block at the top of the file:

/**
 * AWS SSM Parameter Store Integration
 * 
 * This module provides DSL utilities for fetching configuration from AWS SSM Parameter Store.
 * It's used to populate Helm values during infrastructure deployment.
 *
 * @example
 * // Parameter naming convention:
 * // /[environment]/[service]/[key]
 * const params = await getSsmParams([
 *   '/staging/services-bff-portals-admin/secret',
 *   '/staging/services-bff-portals-admin/config'
 * ]);
 *
 * // Integration with Helm:
 * // values.yaml:
 * // bffConfig:
 * //   secret: ${ssm:/staging/services-bff-portals-admin/secret}
 * 
 * @see ../bff.ts - BFF service configuration
 * @see ../../charts/islandis/values.*.yaml - Helm values integration
 */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8e23efc and e8907bd.

📒 Files selected for processing (2)
  • infra/src/cli/render-local-mocks.ts (1 hunks)
  • infra/src/dsl/adapters/get-ssm-params.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • infra/src/cli/render-local-mocks.ts
🧰 Additional context used
📓 Path-based instructions (1)
infra/src/dsl/adapters/get-ssm-params.ts (1)

Pattern infra/src/dsl/**/*: "Confirm that the code adheres to the following:

  • The clarity and expressiveness of the DSL syntax.
  • Integration with Helm charts and Kubernetes resources.
  • Documentation on how to use the DSL to create complex Helm values."

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.

Great job! 👏

@snaerseljan snaerseljan added deprecated:automerge (Disabled) Merge this PR as soon as all checks pass and removed deprecated:automerge (Disabled) Merge this PR as soon as all checks pass labels Oct 31, 2024
@snaerseljan snaerseljan added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Oct 31, 2024
coderabbitai[bot]
coderabbitai bot previously requested changes Oct 31, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 14

🧹 Outside diff range and nitpick comments (2)
apps/services/bff/src/app/modules/proxy/proxy.service.ts (2)

28-28: Consider renaming droppedResponseHeaders for clarity

The variable name droppedResponseHeaders might be unclear. Consider renaming it to excludedResponseHeaders for better readability.

Apply this diff to rename the variable:

-const droppedResponseHeaders = ['access-control-allow-origin']
+const excludedResponseHeaders = ['access-control-allow-origin']

Remember to update all references to this variable within the file.


168-174: Ensure method visibility aligns with NestJS best practices

The proxyGraphQLRequest method is marked as public, but it's not clear if this method is intended to be called from outside the service. Review whether this method should be public or private.

If it's only used within this service, consider changing it to private:

-      public async proxyGraphQLRequest({
+      private async proxyGraphQLRequest({

This aligns with the NestJS practice of encapsulating service logic.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e8907bd and dde3349.

📒 Files selected for processing (4)
  • apps/services/bff/src/app/modules/proxy/proxy.service.ts (1 hunks)
  • charts/islandis/values.dev.yaml (3 hunks)
  • charts/islandis/values.prod.yaml (3 hunks)
  • charts/islandis/values.staging.yaml (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/services/bff/src/app/modules/proxy/proxy.service.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 (12)
charts/islandis/values.staging.yaml (3)

421-421: LGTM: Required namespace grant for API service communication

The addition of 'services-bff-portals-admin' to api grantNamespaces is necessary to enable communication between the API service and the new BFF service.


2056-2062: 🛠️ Refactor suggestion

Optimize HPA settings for better scaling responsiveness

The current HPA configuration uses a high CPU average utilization of 90% as the scaling threshold. This could lead to delayed scaling and potential performance issues during traffic spikes.

Consider lowering the threshold for more responsive scaling:

  scaling:
    metric:
-     cpuAverageUtilization: 90
+     cpuAverageUtilization: 70
      nginxRequestsIrate: 5
    replicas:
      max: 10
      min: 2

Likely invalid or redundant comment.


2047-2054: Verify health check endpoint implementation

The health check paths need verification to ensure they match the actual implementation:

  • Liveness: /stjornbord/bff/liveness
  • Readiness: /stjornbord/bff/health/check

Let's verify the health check endpoint implementation:

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

2222-2227: Resource configuration looks well-balanced!

The resource allocation provides good headroom for traffic spikes while maintaining efficient resource utilization:

  • 4:1 CPU limit to request ratio allows for request handling bursts
  • 2:1 memory limit to request ratio provides space for garbage collection

2175-2177: Namespace configuration follows security best practices!

The namespace configuration correctly:

  • Grants access to identity-server for authentication
  • Follows the principle of least privilege by limiting access to only required namespaces
charts/islandis/values.dev.yaml (5)

421-421: LGTM: Namespace grant for BFF service

The addition of 'services-bff-portals-admin' to api.grantNamespaces is correct and aligns with the PR objectives to enable API access for the new BFF service.


1805-1807: LGTM: Identity Server namespace grant

The addition of 'identity-server' to portals-admin.grantNamespaces is appropriate for enabling authentication via Identity Server.


2309-2316: ⚠️ Potential issue

Adjust health check timing configuration

The current health check configuration could be improved:

  1. Initial delay of 3s might be too short for the service to fully initialize
  2. Readiness probe should have a longer initial delay than liveness probe
  3. Both probes having identical timing could lead to race conditions

Apply this diff to improve the probe configuration:

  healthCheck:
    liveness:
      initialDelaySeconds: 3
      path: '/stjornbord/bff/liveness'
      timeoutSeconds: 3
    readiness:
-     initialDelaySeconds: 3
+     initialDelaySeconds: 10
      path: '/stjornbord/bff/health/check'
      timeoutSeconds: 3

Likely invalid or redundant comment.


2296-2296: Verify PAR support configuration

The BFF_PAR_SUPPORT_ENABLED is set to 'false'. Please verify if this is intentional and document the reason, as Pushed Authorization Requests (PAR) can provide additional security benefits.

✅ Verification successful

PAR support is consistently disabled across all environments

The BFF_PAR_SUPPORT_ENABLED flag is set to 'false' in all environment configurations (dev, staging, and production), indicating this is an intentional system-wide setting rather than an environment-specific configuration error. While Pushed Authorization Requests (PAR) can provide additional security benefits, the consistent configuration across environments suggests this is a deliberate architectural decision.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if PAR support is enabled in other environments
# Look for BFF_PAR_SUPPORT_ENABLED in other environment files
rg "BFF_PAR_SUPPORT_ENABLED" charts/islandis/

Length of output: 13723


Script:

#!/bin/bash
# Let's check BFF_PAR_SUPPORT_ENABLED across all environment files
rg "BFF_PAR_SUPPORT_ENABLED" charts/islandis/values.*.yaml

Length of output: 341


2299-2299: Review client scopes for least privilege

The IDENTITY_SERVER_CLIENT_SCOPES includes a broad range of scopes. Please review if all these scopes are necessary for the BFF service:

  • @admin.island.is/delegations
  • @admin.island.is/ads
  • @admin.island.is/regulations
  • @admin.island.is/regulations:manage
  • And many others...

Consider applying the principle of least privilege by only including scopes that are absolutely necessary.

✅ Verification successful

Let me generate another script to understand how these scopes are used in the admin portal specifically.


Let me check the BFF-specific configurations to understand the context better.


Let me try one final search to locate the BFF service configuration.


Based on the gathered information, I can now provide a final response:

The broad scope list is justified for the admin portal BFF service

The scopes listed in IDENTITY_SERVER_CLIENT_SCOPES are appropriate for this specific BFF (Backend-For-Frontend) service because:

  1. This is the BFF service for "stjornbord" (admin portal) as indicated by BFF_NAME: 'stjornbord' and IDENTITY_SERVER_CLIENT_ID: '@admin.island.is/bff-stjornbord'
  2. As an admin portal BFF, it needs to proxy requests to various admin functionalities, which explains the comprehensive scope list
  3. The service acts as a secure middleware between the admin frontend and backend services, requiring all these permissions to properly facilitate admin operations

The principle of least privilege is maintained here as these scopes are specifically tailored for the admin portal's requirements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check scope usage in the codebase
# Search for actual usage of these scopes in the code
echo "Checking scope usage:"
for scope in delegations ads regulations "regulations:manage" "icelandic-names-registry" "application-system:admin" "application-system:institution" "document-provider" auth "auth:admin" petitions "service-desk" "ads:explicit" "signature-collection:manage" "signature-collection:process" "form-system" "form-system:admin" "delegation-system" "delegation-system:admin"; do
  echo "Checking @admin.island.is/$scope"
  rg -l "@admin\.island\.is/$scope" || echo "No direct usage found"
done

Length of output: 13723


Script:

#!/bin/bash
# Check how these scopes are used in admin portal scope definitions
echo "Checking admin portal scope usage:"
rg -A 5 -B 5 "export const adminPortalScope" libs/auth/scopes/src/lib/admin-portal.scope.ts

# Check if there are any specific BFF-related configurations
echo -e "\nChecking BFF-related configurations:"
rg -l "bff" charts/islandis/

Length of output: 391


Script:

#!/bin/bash
# Check BFF-specific configurations in the values files
echo "Checking BFF configurations in values files:"
rg -A 10 -B 10 "bff:" charts/islandis/values.dev.yaml

# Also check if these scopes are used in BFF-related code
echo -e "\nChecking scope usage in BFF-related code:"
fd -t f "bff" | xargs rg -l "admin\.island\.is"

Length of output: 299


Script:

#!/bin/bash
# Search for BFF service configuration more broadly
echo "Searching for BFF service configuration:"
rg -C 10 "IDENTITY_SERVER_CLIENT_SCOPES" charts/islandis/values.dev.yaml

# Look for any BFF-related files
echo -e "\nSearching for BFF-related files:"
fd -t f -e ts -e js -e yaml -e yml . | rg -i "bff"

Length of output: 4893

apps/services/bff/src/app/modules/proxy/proxy.service.ts (2)

160-160: 🛠️ Refactor suggestion

Provide more detailed error responses

When an error occurs during proxy request processing, consider forwarding the error response's status code and message to the client to provide more meaningful feedback.

Apply this diff to improve the error handling:

           this.logger.error('Error during proxy request processing: ', error)

-          res.status(error.status || 500).send('Failed to proxy request')
+          res.status(error.status || 500).send(error.message || 'Failed to proxy request')

Likely invalid or redundant comment.


207-207: ⚠️ Potential issue

Fix typo in exception message

There's a typo in the exception message: 'Proxing url failed!' should be 'Proxying URL failed!'.

Apply this diff to correct the typo:

           throw new BadRequestException('Proxing url failed!')
+          throw new BadRequestException('Proxying URL failed!')

Likely invalid or redundant comment.

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

🧹 Outside diff range and nitpick comments (3)
infra/src/dsl/feature-values.spec.ts (1)

15-15: Consider making the domain configurable.

The domain 'dev01.devland.is' is hardcoded in the environment configuration. Consider extracting this into a configuration variable or environment-specific constant to make it more maintainable across different environments.

infra/src/dsl/portal-env.spec.ts (2)

39-102: Well-structured DSL configuration with clear intent

The service configuration demonstrates excellent use of the DSL's fluent interface, making the configuration readable and maintainable. The chaining of configuration methods clearly expresses the service's requirements and infrastructure needs.

Consider documenting the following aspects to improve maintainability:

  1. The significance of buffer size settings in NGINX annotations
  2. The rationale behind replica count limits
  3. The purpose of different ingress paths per environment

220-238: Enhance environment defaults test coverage

While the replica count test is valuable, consider expanding this test suite to cover other important environment defaults such as:

  • Default resource limits and requests
  • Default ingress annotations
  • Default security context settings

Also, consider extracting the common test setup into a shared helper function to reduce duplication between test suites.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 64491f6 and 17c5ee1.

📒 Files selected for processing (6)
  • apps/services/bff/infra/admin-portal.infra.ts (1 hunks)
  • charts/islandis/values.dev.yaml (3 hunks)
  • charts/islandis/values.prod.yaml (3 hunks)
  • charts/islandis/values.staging.yaml (3 hunks)
  • infra/src/dsl/feature-values.spec.ts (5 hunks)
  • infra/src/dsl/portal-env.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/services/bff/infra/admin-portal.infra.ts
🧰 Additional context used
📓 Path-based instructions (2)
infra/src/dsl/feature-values.spec.ts (1)

Pattern infra/src/dsl/**/*: "Confirm that the code adheres to the following:

  • The clarity and expressiveness of the DSL syntax.
  • Integration with Helm charts and Kubernetes resources.
  • Documentation on how to use the DSL to create complex Helm values."
infra/src/dsl/portal-env.spec.ts (1)

Pattern infra/src/dsl/**/*: "Confirm that the code adheres to the following:

  • The clarity and expressiveness of the DSL syntax.
  • Integration with Helm charts and Kubernetes resources.
  • Documentation on how to use the DSL to create complex Helm values."
🔇 Additional comments (10)
infra/src/dsl/feature-values.spec.ts (3)

79-94: LGTM! Well-structured BFF service configuration.

The BFF service configuration is well-organized with:

  • Clear service identification and client configuration
  • Environment-specific external API URLs
  • Proper integration with the API service

119-142: LGTM! Comprehensive test coverage for BFF configuration.

The test cases thoroughly verify:

  • Identity server integration
  • Environment-specific URLs
  • Callback paths
  • Redis configuration
  • Feature deployment settings

Line range hint 181-194: Verify ingress configuration for all environments.

The ingress configuration test only verifies the dev environment. Let's ensure the configuration works correctly across all environments.

charts/islandis/values.staging.yaml (2)

421-421: LGTM: Appropriate namespace grant added

The addition of 'services-bff-portals-admin' to the API service's grantNamespaces is correct and necessary for proper interaction between the services.


2047-2054: Health check paths need verification

The health check paths include /stjornbord/bff prefix which needs to be verified against the actual implementation.

✅ Verification successful

Let me search for the actual implementation of these health check endpoints.


Let me search for any BFF-specific implementations or route configurations.


Let me check the BFF service implementation for these health check endpoints.


Health check paths are correctly configured

The health check paths in the values files are correct. The evidence shows:

  1. The BFF service uses @island.is/infra-nest-server with healthCheck: true and a global prefix of /stjornbord/bff
  2. The health check paths are consistently configured across all environments (dev, staging, prod)
  3. The paths are properly mapped in the ingress configurations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if these health check endpoints are implemented
ast-grep --pattern 'app.get("/stjornbord/bff/liveness"'
ast-grep --pattern 'app.get("/stjornbord/bff/health/check"'

# Search for health check endpoints with more flexible patterns
rg -i "stjornbord/bff/(liveness|health)" -A 3

Length of output: 1563


Script:

#!/bin/bash
# Search for health check route implementations in JavaScript/TypeScript files
fd -e js -e ts -e jsx -e tsx --exec rg -l "app\.(get|use)\(.*?(health|liveness)"

# Search for any route definitions with these paths
rg -i "('/stjornbord/bff/liveness'|'/stjornbord/bff/health/check')" --type ts --type js -A 2

Length of output: 225


Script:

#!/bin/bash
# Let's check the content of these files for health check implementations
cat ./libs/infra-next-server/src/lib/health.ts
cat ./libs/infra-express-server/src/lib/infra-express-server.ts

# Also search for any router definitions that might handle these paths
rg -i "router\.(get|use).*?(health|liveness)" --type ts --type js -A 2

Length of output: 5329


Script:

#!/bin/bash
# Search for BFF-related files and configurations
fd -e ts -e js -e tsx -e jsx bff --exec rg -l "router|app\..*?(get|use)"

# Search for any route prefix configurations
rg -i "stjornbord/bff" --type ts --type js --type json --type yaml -A 3

Length of output: 4941


Script:

#!/bin/bash
# Check BFF service implementation
cat apps/services/bff/src/main.ts
cat apps/services/bff/src/app.ts

# Look for any health check related files in BFF service
fd health check liveness -t f ./apps/services/bff

Length of output: 585

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

2221-2227: LGTM: Resource allocation is well configured

The resource configuration shows good practices:

  • Reasonable CPU limit to request ratio (4:1)
  • Appropriate memory limit to request ratio (2:1)
  • Well-balanced HPA settings for production workload

2235-2239: LGTM: Service account is properly configured

The service account configuration follows security best practices:

  • Creates dedicated service account
  • Properly associates IAM role using EKS annotation
charts/islandis/values.dev.yaml (3)

421-421: LGTM: API service namespace grant

The addition of 'services-bff-portals-admin' to API service's grantNamespaces is correct and aligns with the BFF service integration requirements.


1805-1807: LGTM: Portals-admin namespace grant

The addition of 'identity-server' to portals-admin's grantNamespaces is necessary for enabling authentication through the BFF service.


2293-2294: Review login attempt TTL configuration

The BFF_LOGIN_ATTEMPT_TTL_MS is set to 7 days (604800000ms). Consider if this duration aligns with your security requirements and if it should be configurable per environment.

✅ Verification successful

Let me gather more context about the login attempt configuration by searching for related code and documentation.


Let me check the actual implementation to understand how this TTL is being used.


Login attempt TTL configuration appears appropriate

The BFF_LOGIN_ATTEMPT_TTL_MS value of 7 days is used to cache login attempt data during the OAuth flow, storing necessary information like code verifier and target URLs. This duration is consistently set across all environments (dev, staging, prod) and aligns with typical OAuth state management practices. The implementation in the auth service shows this is used for maintaining login state rather than tracking failed attempts, making the 7-day duration reasonable.

Key observations:

  • Used for OAuth flow state management, not for security rate limiting
  • Consistent configuration across all environments
  • Similar to other cache TTLs in the system (e.g., user profile cache is set to ~1 hour)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any security guidelines or existing TTL configurations

echo "Checking for other TTL configurations:"
rg "TTL_MS|TTL_SECONDS" --type yaml

Length of output: 1189


Script:

#!/bin/bash
# Search for documentation about login attempts and security configurations
echo "Checking for documentation about login attempts:"
rg -i "login.?attempt|security" README.md docs/ 2>/dev/null

echo -e "\nChecking for code related to login attempts:"
ast-grep --pattern 'loginAttempt' 

echo -e "\nChecking for environment-specific configurations:"
rg "BFF_LOGIN" --type yaml

Length of output: 1155


Script:

#!/bin/bash
# Check the auth controller implementation and tests
echo "Checking auth controller implementation:"
rg -A 5 "loginAttempt" apps/services/bff/src/app/modules/auth/

echo -e "\nChecking for cache-related configurations:"
rg "BFF_CACHE" --type yaml

Length of output: 3078

coderabbitai[bot]
coderabbitai bot previously requested changes Oct 31, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (2)
infra/src/dsl/feature-values.spec.ts (1)

79-94: Document the BFF DSL configuration in the README.

The BFF service configuration introduces new DSL methods and patterns. Consider adding documentation that explains:

  • The bff() method parameters and their purpose
  • Required configurations for different environments
  • Integration with other services like Redis and API

Would you like me to help create a documentation template for the BFF DSL configuration?

infra/src/dsl/portal-env.spec.ts (1)

220-238: Enhance test coverage for environment defaults

The test suite for environment defaults only covers replica count settings. Consider adding tests for other default configurations such as:

  • Default resource limits and requests
  • Default ingress annotations
  • Default environment variables
 describe('Env definition defaults', () => {
   const sut = service('api').namespace('islandis').image(bffName)
   let result: SerializeSuccess<HelmService>
   beforeEach(async () => {
     result = (await generateOutputOne({
       outputFormat: renderers.helm,
       service: sut,
       runtime: new Kubernetes(Dev),
       env: Dev,
     })) as SerializeSuccess<HelmService>
   })
+  it('default resource limits', () => {
+    expect(result.serviceDef[0].resources).toBeDefined()
+    expect(result.serviceDef[0].resources.limits).toBeDefined()
+    expect(result.serviceDef[0].resources.requests).toBeDefined()
+  })
+
+  it('default ingress annotations', () => {
+    expect(result.serviceDef[0].ingress?.['primary-alb']?.annotations).toBeDefined()
+  })
+
+  it('default environment variables', () => {
+    expect(result.serviceDef[0].env).toBeDefined()
+    expect(result.serviceDef[0].env.LOG_LEVEL).toBe('info')
+  })
   it('replica max count', () => {
     expect(result.serviceDef[0].replicaCount).toStrictEqual({
       min: 2,
       max: 3,
       default: 2,
     })
   })
 })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 64491f6 and 17c5ee1.

📒 Files selected for processing (6)
  • apps/services/bff/infra/admin-portal.infra.ts (1 hunks)
  • charts/islandis/values.dev.yaml (3 hunks)
  • charts/islandis/values.prod.yaml (3 hunks)
  • charts/islandis/values.staging.yaml (3 hunks)
  • infra/src/dsl/feature-values.spec.ts (5 hunks)
  • infra/src/dsl/portal-env.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/services/bff/infra/admin-portal.infra.ts
🧰 Additional context used
📓 Path-based instructions (2)
infra/src/dsl/feature-values.spec.ts (1)

Pattern infra/src/dsl/**/*: "Confirm that the code adheres to the following:

  • The clarity and expressiveness of the DSL syntax.
  • Integration with Helm charts and Kubernetes resources.
  • Documentation on how to use the DSL to create complex Helm values."
infra/src/dsl/portal-env.spec.ts (1)

Pattern infra/src/dsl/**/*: "Confirm that the code adheres to the following:

  • The clarity and expressiveness of the DSL syntax.
  • Integration with Helm charts and Kubernetes resources.
  • Documentation on how to use the DSL to create complex Helm values."
🔇 Additional comments (18)
infra/src/dsl/portal-env.spec.ts (1)

19-31: Replace placeholder AWS account ID with a valid one

The AWS account ID '111111' appears to be a placeholder value. This could cause deployment issues if not replaced with a valid AWS account ID.

charts/islandis/values.staging.yaml (5)

421-421: LGTM: Grant namespace addition is appropriate

The addition of 'services-bff-portals-admin' to grantNamespaces is consistent with the introduction of the BFF service.


2088-2093: LGTM: Resource configuration is well-balanced

The resource limits and requests are appropriately configured for a BFF service:

  • Memory limits allow for adequate heap space
  • CPU allocation provides room for scaling

2056-2062: 🛠️ Refactor suggestion

Consider adjusting HPA settings for more responsive scaling

The HPA configuration uses a CPU average utilization of 90% as the scaling threshold. This high value might lead to delayed scaling, potentially impacting performance during traffic spikes.

Consider lowering the threshold for more responsive scaling:

  scaling:
    metric:
-     cpuAverageUtilization: 90
+     cpuAverageUtilization: 70
      nginxRequestsIrate: 5
    replicas:
      max: 10
      min: 2

Likely invalid or redundant comment.


2031-2031: ⚠️ Potential issue

Consider reducing login attempt TTL for improved security

The BFF_LOGIN_ATTEMPT_TTL_MS is set to 7 days (604800000ms). This extended period could pose security risks by allowing failed login attempts to persist longer than necessary.

Consider reducing this to 24 hours:

- BFF_LOGIN_ATTEMPT_TTL_MS: '604800000'
+ BFF_LOGIN_ATTEMPT_TTL_MS: '86400000'

Likely invalid or redundant comment.


2047-2054: Verify health check endpoint implementation

The health check paths include the '/stjornbord/bff' prefix. Ensure these endpoints are correctly implemented in the service:

  • Liveness: /stjornbord/bff/liveness
  • Readiness: /stjornbord/bff/health/check
charts/islandis/values.prod.yaml (5)

409-409: LGTM: Appropriate namespace access grant

The API service correctly grants access to the BFF service through the grantNamespaces configuration.


1670-1672: LGTM: Proper identity server integration

The admin portal correctly grants access to the identity-server namespace, enabling proper authentication flow through the BFF service.


2159-2160: ⚠️ Potential issue

Optimize cache and session timeouts

The current timeout values are too long for an admin portal context:

  1. BFF_CACHE_USER_PROFILE_TTL_MS (1 hour) could delay critical permission updates
  2. BFF_LOGIN_ATTEMPT_TTL_MS (7 days) is excessive for tracking login attempts

Apply these more appropriate timeouts:

-    BFF_CACHE_USER_PROFILE_TTL_MS: '3595000'
+    BFF_CACHE_USER_PROFILE_TTL_MS: '900000'  # 15 minutes
-    BFF_LOGIN_ATTEMPT_TTL_MS: '604800000'
+    BFF_LOGIN_ATTEMPT_TTL_MS: '86400000'     # 24 hours

Likely invalid or redundant comment.


2179-2186: ⚠️ Potential issue

Adjust health check probe timing configuration

The current probe configuration needs adjustment:

  1. Having identical delays for both probes could lead to race conditions
  2. Readiness probe's initialDelaySeconds (3s) is too aggressive for proper initialization

Apply these probe timing adjustments:

    liveness:
      initialDelaySeconds: 3
      path: '/stjornbord/bff/liveness'
      timeoutSeconds: 3
    readiness:
-     initialDelaySeconds: 3
+     initialDelaySeconds: 10
      path: '/stjornbord/bff/health/check'
      timeoutSeconds: 3

Likely invalid or redundant comment.


2157-2158: ⚠️ Potential issue

Security: Adjust allowed URLs configuration

The current URL configurations need adjustment:

  1. BFF_ALLOWED_EXTERNAL_API_URLS is missing the Identity Server URL which is required for authentication
  2. BFF_ALLOWED_REDIRECT_URIS is too permissive by allowing the entire domain

Apply this configuration:

-    BFF_ALLOWED_EXTERNAL_API_URLS: '["https://api.island.is"]'
-    BFF_ALLOWED_REDIRECT_URIS: 'https://island.is'
+    BFF_ALLOWED_EXTERNAL_API_URLS: '["https://api.island.is", "https://innskra.island.is"]'
+    BFF_ALLOWED_REDIRECT_URIS: 'https://island.is/stjornbord'

Likely invalid or redundant comment.

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

1805-1807: LGTM: Grant namespace addition for Identity Server

The addition of 'identity-server' to grantNamespaces is appropriate for enabling the BFF service to interact with the Identity Server.


2293-2296: Review BFF configuration parameters

The BFF configuration includes:

  • Long login attempt TTL (7 days)
  • PAR support is enabled
  • Base path is set to '/stjornbord'

These settings look appropriate for the admin portal BFF service.


2356-2358: LGTM: Appropriate secrets configuration

The secrets configuration includes all necessary secrets for the BFF service:

  • Token secret for session management
  • ConfigCat SDK key for feature flags
  • Identity Server client secret for authentication

2298-2299: Review client scopes for least privilege

The IDENTITY_SERVER_CLIENT_SCOPES includes a wide range of administrative scopes. Please review to ensure they adhere to the principle of least privilege and are all necessary for the BFF service.

✅ Verification successful

Let me analyze the results and generate a final response.

All client scopes are actively used in the BFF service

The verification shows that all scopes listed in IDENTITY_SERVER_CLIENT_SCOPES are properly defined and used across the codebase:

  • All scopes are defined in libs/auth/scopes/src/lib/admin-portal.scope.ts
  • The scopes are registered in the auth system via seeders in libs/auth-api-lib/seeders/data/
  • The client ID @admin.island.is/bff-stjornbord is consistently used in infrastructure code
  • These scopes represent distinct administrative functionalities needed for the BFF service to operate as an administrative backend
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: List all client scopes in use across the codebase

echo "Searching for client scope usage:"
rg "@admin\.island\.is/[a-zA-Z-]+(?::[a-zA-Z-]+)?" --type ts

Length of output: 6003


2349-2354: 🛠️ Refactor suggestion

Consider increasing resource requests

The current resource requests might be too low for a BFF service that handles proxying and authentication:

  • CPU request of 100m might be insufficient for handling multiple concurrent requests
  • Memory request of 256Mi might lead to frequent scaling under load

Apply this diff to increase the resource requests:

  resources:
    limits:
      cpu: '400m'
      memory: '512Mi'
    requests:
-     cpu: '100m'
-     memory: '256Mi'
+     cpu: '200m'
+     memory: '384Mi'

Likely invalid or redundant comment.


2309-2316: 🛠️ Refactor suggestion

Adjust health check timing configuration

The current health check configuration might need adjustment:

  1. Initial delay of 3s might be too short for the service to fully initialize
  2. Readiness probe should have a longer initial delay than liveness probe
  3. Both probes having identical timing could lead to race conditions

Apply this diff to improve the health check configuration:

  healthCheck:
    liveness:
      initialDelaySeconds: 3
      path: '/stjornbord/bff/liveness'
      timeoutSeconds: 3
    readiness:
-     initialDelaySeconds: 3
+     initialDelaySeconds: 10
      path: '/stjornbord/bff/health/check'
      timeoutSeconds: 3

Likely invalid or redundant comment.


2287-2288: Verify allowed external API URLs and redirect URIs

The configuration includes hardcoded URLs for development environment. Please ensure these URLs are correct and appropriate for the development environment.

✅ Verification successful

Based on the search results, I can see extensive usage of the dev01.devland.is domain across the codebase, including the specific URLs mentioned in the review:

  • https://api.dev01.devland.is is consistently used as the API endpoint in development environment
  • https://beta.dev01.devland.is is consistently used as the frontend URL in development environment

Let me verify one more thing to ensure these are the standard URLs used in the development environment configuration.


URLs are correctly configured for development environment

The configured URLs in the BFF settings are consistent with the standard development environment URLs used throughout the codebase:

  • https://api.dev01.devland.is is the standard API endpoint
  • https://beta.dev01.devland.is is the standard frontend URL

These match the established patterns used across multiple services and configurations in the development environment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the configured URLs match the development environment pattern

echo "Checking for development environment URLs:"
rg "dev01\.devland\.is" -A 1

Length of output: 70895


Script:

#!/bin/bash
# Check for any other API or frontend URL patterns in dev environment configs
rg -i "BFF_ALLOWED_EXTERNAL_API_URLS|BFF_ALLOWED_REDIRECT_URIS" charts/*/values.dev.yaml

Length of output: 376

@kodiakhq kodiakhq bot merged commit d0c9471 into main Oct 31, 2024
449 checks passed
@kodiakhq kodiakhq bot deleted the feat/bff branch October 31, 2024 16:12
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 deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants