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 upgrade api keys #601

Merged
merged 8 commits into from
Aug 3, 2024
Merged

Feat upgrade api keys #601

merged 8 commits into from
Aug 3, 2024

Conversation

rflihxyz
Copy link
Contributor

@rflihxyz rflihxyz commented Aug 1, 2024

  • API Keys follow this pattern: sk_{env}_{UUIDv4}
  • they're hashed on database side

Summary by CodeRabbit

  • New Features

    • Introduced a new endpoint for generating API keys, enhancing API clarity.
    • Added a modal dialog in the web app to display newly created API keys and their expiration times.
  • Bug Fixes

    • Improved error handling for API key management, providing clearer user feedback.
  • Chores

    • Updated API key authentication method from bearer tokens to API keys, requiring changes in client interactions.
  • Refactor

    • Removed token exposure in API key management UI for enhanced security.
    • Adjusted API key schema to reflect the removal of the token property.

Copy link

changeset-bot bot commented Aug 1, 2024

⚠️ No Changeset found

Latest commit: a77e17d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@CLAassistant
Copy link

CLAassistant commented Aug 1, 2024

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
0 out of 2 committers have signed the CLA.

❌ Rachid Flih
❌ naelob


Rachid Flih seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

Copy link
Contributor

coderabbitai bot commented Aug 1, 2024

Walkthrough

Walkthrough

The changes primarily enhance the security and usability of API key management across the authentication system. Key updates include a new endpoint for generating API keys, improved hashing methods for key validation, and enhanced error messaging. The user interface has been refined to provide immediate feedback through modal dialogs upon API key creation, while sensitive information handling has been tightened. These adjustments ensure a more standardized approach to API key handling and facilitate easier debugging.

Changes

File Path Change Summary
packages/api/src/@core/auth/auth.controller.ts Modified API endpoint for generateApiKey to api_keys, improving clarity of functionality.
packages/api/src/@core/auth/auth.service.ts, packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts Introduced hashed API key generation and validation, enhancing security and updating methods to manage hashed keys.
apps/webapp/src/app/(Dashboard)/api-keys/page.tsx Enhanced UI with modal dialog for displaying newly created API key and its expiration, improving user feedback.
apps/webapp/src/components/ApiKeys/columns.tsx Removed token column that displayed sensitive information, focusing on a more secure interaction model.
apps/webapp/src/components/ApiKeys/schema.ts Removed token property from apiKeySchema, indicating a shift in expected API key structure.
apps/webapp/src/hooks/delete/useDeleteApiKey.tsx Modified API endpoint from /auth/api-keys/ to /auth/api_keys/, aligning with new naming conventions.
packages/api/prisma/schema.prisma Reorganized Prisma schema by adding new fields and models, enhancing data integrity and relationships.
packages/api/src/main.ts Updated security configuration to use API key authentication via x-api-key header instead of bearer tokens.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@rflihxyz
Copy link
Contributor Author

rflihxyz commented Aug 1, 2024

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Aug 1, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Outside diff range comments (1)
packages/api/src/@core/auth/auth.service.ts (1)

Line range hint 327-366:
Enhance error handling and logging.

Consider adding logging for successful API key generation and more descriptive error messages.

+ this.logger.log(`Generating API key for user ${userId} in project ${projectId}`);

const foundProject = await this.prisma.projects.findUnique({
  where: { id_project: projectId },
});
if (!foundProject) {
  this.logger.error(`Project not found: ${projectId}`);
  throw new ReferenceError('Project not found');
}

const foundUser = await this.prisma.users.findUnique({
  where: { id_user: userId },
});
if (!foundUser) {
  this.logger.error(`User not found: ${userId}`);
  throw new ReferenceError('User Not Found');
}

const base_key = `sk_${process.env.ENV}_${uuidv4()}`;
const hashed_key = crypto.createHash('sha256').update(base_key).digest('hex');

const new_api_key = await this.prisma.api_keys.create({
  data: {
    id_api_key: uuidv4(),
    api_key_hash: hashed_key,
    name: keyName,
    id_project: projectId as string,
    id_user: userId as string,
  },
});
if (!new_api_key) {
  this.logger.error('Failed to create API key in the database');
  throw new ReferenceError('API key undefined');
}

this.logger.log(`API key generated successfully for user ${userId} in project ${projectId}`);
return { api_key: base_key, ...new_api_key };
Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between fc1caac and d5c8fc2.

Files ignored due to path filters (3)
  • docker-compose.dev.yml is excluded by !**/*.yml
  • docker-compose.source.yml is excluded by !**/*.yml
  • docker-compose.yml is excluded by !**/*.yml
Files selected for processing (4)
  • packages/api/src/@core/auth/auth.controller.ts (1 hunks)
  • packages/api/src/@core/auth/auth.service.ts (4 hunks)
  • packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts (2 hunks)
  • packages/api/src/@core/connections/@utils/index.ts (1 hunks)
Additional context used
Biome
packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts

[error] 5-5: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

Additional comments not posted (3)
packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts (2)

14-14: LGTM! Configuration change for HeaderAPIKeyStrategy.

The update to use the x-api-key header without a prefix is a good change for enhancing the specificity of API key handling.


22-24: LGTM! Improved security with API key hashing.

The addition of the hashing mechanism using SHA-256 enhances security by ensuring that the API key is not exposed in its original form during processing.

packages/api/src/@core/auth/auth.controller.ts (1)

107-107: LGTM! Improved route clarity for generateApiKey.

The change to use the api_keys endpoint enhances the API's clarity by explicitly indicating that the method is responsible for generating API keys.

Comment on lines +386 to 393
async getProjectIdForApiKey(hashed_apiKey: string) {
try {
// Decode the JWT to verify if it's valid and get the payload
const decoded = this.jwtService.verify(apiKey, {
secret: process.env.JWT_SECRET,
});

//const hashed_api_key = this.hashApiKey(apiKey);
const saved_api_key = await this.prisma.api_keys.findUnique({
where: {
api_key_hash: apiKey,
api_key_hash: hashed_apiKey,
},
});

Copy link
Contributor

Choose a reason for hiding this comment

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

Add logging and improve error handling.

Consider adding logging for successful retrieval and handling cases where the API key is not found.

+ this.logger.log(`Retrieving project ID for API key`);

const saved_api_key = await this.prisma.api_keys.findUnique({
  where: {
    api_key_hash: hashed_apiKey,
  },
});

if (!saved_api_key) {
  this.logger.error(`API key not found: ${hashed_apiKey}`);
  throw new ReferenceError('API key not found');
}

this.logger.log(`Project ID retrieved successfully for API key`);
return saved_api_key.id_project;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async getProjectIdForApiKey(hashed_apiKey: string) {
try {
// Decode the JWT to verify if it's valid and get the payload
const decoded = this.jwtService.verify(apiKey, {
secret: process.env.JWT_SECRET,
});
//const hashed_api_key = this.hashApiKey(apiKey);
const saved_api_key = await this.prisma.api_keys.findUnique({
where: {
api_key_hash: apiKey,
api_key_hash: hashed_apiKey,
},
});
async getProjectIdForApiKey(hashed_apiKey: string) {
this.logger.log(`Retrieving project ID for API key`);
const saved_api_key = await this.prisma.api_keys.findUnique({
where: {
api_key_hash: hashed_apiKey,
},
});
if (!saved_api_key) {
this.logger.error(`API key not found: ${hashed_apiKey}`);
throw new ReferenceError('API key not found');
}
this.logger.log(`Project ID retrieved successfully for API key`);
return saved_api_key.id_project;

@@ -2,6 +2,7 @@ import { HeaderAPIKeyStrategy } from 'passport-headerapikey';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../auth.service';
import * as crypto from 'crypto';
Copy link
Contributor

Choose a reason for hiding this comment

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

Use the node: protocol for Node.js built-in modules.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.

- import * as crypto from 'crypto';
+ import * as crypto from 'node:crypto';
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import * as crypto from 'crypto';
import * as crypto from 'node:crypto';
Tools
Biome

[error] 5-5: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

Comment on lines 402 to 438

// TO DO : add Expiration in part 3

// Decode the JWT to verify if it's valid and get the payload
const decoded = this.jwtService.verify(apiKey, {
secret: process.env.JWT_SECRET,
});
// const decoded = this.jwtService.verify(apiKey, {
// secret: process.env.JWT_SECRET,
// });


//const hashed_api_key = this.hashApiKey(apiKey);
// pseudo-code:
// 1 - SHA256 the API key from the header
const hashed_key = crypto.createHash('sha256').update(apiKey).digest('hex');


// 2- check against DB
// if not found, return false
const saved_api_key = await this.prisma.api_keys.findUnique({
where: {
api_key_hash: apiKey,
api_key_hash: hashed_key,
},
});

if (!saved_api_key) {
throw new ReferenceError('Api Key undefined');
}
if (String(decoded.project_id) !== String(saved_api_key.id_project)) {
throw new ReferenceError(
'Failed to validate API key: projectId mismatch.',
);
}

// Validate that the JWT payload matches the provided userId and projectId
if (String(decoded.sub) !== String(saved_api_key.id_user)) {
throw new ReferenceError(
'Failed to validate API key: userId mismatch.',
);
throw new ReferenceError('API Key not found.');
}
// if (String(decoded.project_id) !== String(saved_api_key.id_project)) {
// throw new ReferenceError(
// 'Failed to validate API key: projectId mismatch.',
// );
// }

// // Validate that the JWT payload matches the provided userId and projectId
// if (String(decoded.sub) !== String(saved_api_key.id_user)) {
// throw new ReferenceError(
// 'Failed to validate API key: userId mismatch.',
// );
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve logging, error handling, and remove commented-out code.

Add logging for validation steps, improve error messages, and remove commented-out code for clarity.

+ this.logger.log(`Validating API key`);

const hashed_key = crypto.createHash('sha256').update(apiKey).digest('hex');

const saved_api_key = await this.prisma.api_keys.findUnique({
  where: {
    api_key_hash: hashed_key,
  },
});

if (!saved_api_key) {
  this.logger.error(`API key not found: ${hashed_key}`);
  throw new ReferenceError('API key not found');
}

this.logger.log(`API key validated successfully`);
return true;

Committable suggestion was skipped due to low confidence.

Comment on lines +19 to +21
console.log('**********')
console.log(token);
console.log('**********')
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid logging sensitive information.

Logging sensitive information such as tokens can pose a security risk. Consider removing or obfuscating the token in the logs.

- console.log('**********')
- console.log(token);
- console.log('**********')
+ console.log('**********')
+ console.log('Token received');
+ console.log('**********')
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log('**********')
console.log(token);
console.log('**********')
console.log('**********')
console.log('Token received');
console.log('**********')

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Outside diff range comments (1)
apps/webapp/src/components/ApiKeys/columns.tsx (1)

[!TIP]
Codebase Verification

Partial removal of token column.

The token column has been partially removed from apps/webapp/src/components/ApiKeys/columns.tsx. However, related functionality such as copying the token is still present in the code. Ensure that all references to the token are properly cleaned up to avoid potential issues.

  • apps/webapp/src/components/ApiKeys/columns.tsx: References to token in the handleCopy function and state management logic.
Analysis chain

Line range hint 1-1:
Removal of token column.

The column for displaying the token has been removed. Ensure that this change does not negatively impact the user experience and functionality.


The token column appears to still be referenced in the apps/webapp/src/components/ApiKeys/columns.tsx file. We need to verify if the token column is indeed removed and if the related functionality, such as copying the token, is impacted.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of removing the `token` column from the API keys table.

# Test: Search for the usage of the `token` column in the codebase. Expect: No occurrences of `token` in the context of the API keys table.
rg --type js --type ts 'token' -A 10 | rg 'columns'

Length of output: 7297


Script:

#!/bin/bash
# Check if the `token` column is defined in the `apps/webapp/src/components/ApiKeys/columns.tsx` file.
rg 'token' apps/webapp/src/components/ApiKeys/columns.tsx -A 10

# Check if there are any other references to the `token` column in the `apps/webapp/src/components/ApiKeys/columns.tsx` file.
rg 'token' apps/webapp/src/components/ApiKeys/columns.tsx

Length of output: 885

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between d5c8fc2 and 8d1bf6a.

Files ignored due to path filters (1)
  • packages/api/swagger/swagger-spec.yaml is excluded by !**/*.yaml
Files selected for processing (7)
  • apps/webapp/src/app/(Dashboard)/api-keys/page.tsx (3 hunks)
  • apps/webapp/src/components/ApiKeys/columns.tsx (1 hunks)
  • apps/webapp/src/components/ApiKeys/schema.ts (1 hunks)
  • apps/webapp/src/hooks/delete/useDeleteApiKey.tsx (1 hunks)
  • packages/api/prisma/schema.prisma (4 hunks)
  • packages/api/src/@core/auth/auth.service.ts (10 hunks)
  • packages/api/src/main.ts (1 hunks)
Additional context used
Biome
packages/api/src/@core/auth/auth.service.ts

[error] 450-450: The catch clause that only rethrows the original error is redundant.

These unnecessary catch clauses can be confusing. It is recommended to remove them.

(lint/complexity/noUselessCatch)

Additional comments not posted (19)
apps/webapp/src/components/ApiKeys/schema.ts (1)

4-7: Removal of token property in apiKeySchema.

The token property has been removed from the schema definition. Ensure that all parts of the codebase that relied on this property are updated accordingly.

Verification successful

No issues found with the removal of the token property from apiKeySchema.

The token property was not found in the context of apiKeySchema across the codebase. Therefore, its removal does not impact any dependent code.

  • apiKeySchema is defined in apps/webapp/src/components/ApiKeys/schema.ts and is not referenced elsewhere with the token property.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of removing the `token` property from the `apiKeySchema`.

# Test: Search for the usage of `apiKeySchema` and `token` in the codebase. Expect: No occurrences of `token` in the context of `apiKeySchema`.
rg --type js --type ts 'apiKeySchema' -A 10 | rg 'token'

Length of output: 54


Script:

#!/bin/bash
# Description: Verify the impact of removing the `token` property from the `apiKeySchema`.

# Search for any usage of `token` in the codebase to ensure it is not used independently.
rg --type js --type ts 'token'

# Search for any usage of `apiKeySchema` in the codebase to ensure no dependent code is affected.
rg --type js --type ts 'apiKeySchema'

Length of output: 225882

apps/webapp/src/hooks/delete/useDeleteApiKey.tsx (1)

11-11: Change in endpoint URL.

The endpoint URL has been changed from /auth/api-keys/ to /auth/api_keys/. Ensure that all parts of the codebase that interact with this endpoint are updated accordingly.

Verification successful

Change in endpoint URL verified.

The endpoint URL has been changed from /auth/api-keys/ to /auth/api_keys/ in the codebase. The change is correctly applied in apps/webapp/src/hooks/delete/useDeleteApiKey.tsx, and no other occurrences of the old or new endpoint URL were found.

  • apps/webapp/src/hooks/delete/useDeleteApiKey.tsx:
    const response = await fetch(`${config.API_URL}/auth/api_keys/${apiKeyData.id_api_key}`, {
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of changing the endpoint URL from `/auth/api-keys/` to `/auth/api_keys/`.

# Test: Search for the usage of the old endpoint URL in the codebase. Expect: No occurrences of `/auth/api-keys/`.
rg --type js --type ts '/auth/api-keys/'

Length of output: 40


Script:

#!/bin/bash
# Description: Verify the usage of the new endpoint URL `/auth/api_keys/` in the codebase.

# Test: Search for the usage of the new endpoint URL in the codebase. Expect: Occurrences of `/auth/api_keys/`.
rg --type js --type ts '/auth/api_keys/'

Length of output: 188


Script:

#!/bin/bash
# Description: Verify the consistent usage of the new endpoint URL `/auth/api_keys/` in the codebase.

# Test: Search for any other occurrences of the new endpoint URL in the codebase.
rg '/auth/api_keys/'

Length of output: 168

packages/api/src/main.ts (2)

61-61: LGTM! Swagger documentation updated correctly.

The Swagger documentation now correctly reflects the new api_key security scheme.


51-58: Verify the new API key configuration.

The new API key configuration using .addApiKey looks correct. Ensure that all clients are updated to use the new x-api-key header for authentication.

Verification successful

Verify the new API key configuration.

The new API key configuration using .addApiKey looks correct and is being used in the authentication strategy (auth-header-api-key.strategy.ts). Ensure that all clients are updated to use the new x-api-key header for authentication.

  • packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all clients are updated to use the new `x-api-key` header for authentication.

# Test: Search for the usage of the `x-api-key` header in the codebase. Expect: Occurrences of the new header.
rg --type javascript --type typescript -A 5 $'x-api-key'

Length of output: 90


Script:

#!/bin/bash
# Description: Verify that all clients are updated to use the new `x-api-key` header for authentication.

# Test: Search for the usage of the `x-api-key` header in the codebase. Expect: Occurrences of the new header.
rg --type js --type ts -A 5 'x-api-key'

Length of output: 926

apps/webapp/src/app/(Dashboard)/api-keys/page.tsx (4)

54-54: LGTM! State management for new API key added correctly.

The new state variables newApiKey and isKeyModalOpen are correctly implemented to manage the display of the newly created API key and its expiration time.

Also applies to: 58-58


65-74: LGTM! Lifecycle management for newApiKey added correctly.

The useEffect hook correctly manages the lifecycle of newApiKey, ensuring that the key is only available for a limited time.


121-127: LGTM! API key storage and modal opening added correctly.

The onSubmit function now correctly stores the API key and its expiration time in state and opens the modal upon successful creation of the API key.


246-261: LGTM! Modal dialog for displaying new API key added correctly.

The new modal dialog provides a user-friendly way to display the newly created API key and its expiration time.

packages/api/src/@core/auth/auth.service.ts (8)

Line range hint 46-60:
LGTM! Reset token verification and password update added correctly.

The resetPassword method now correctly verifies the reset token and securely updates the user's password in the database.


68-73: LGTM! Reset token verification using bcrypt added correctly.

The verifyResetToken method now correctly compares the request token with the database token using bcrypt.


Line range hint 79-103:
LGTM! Reset token generation and storage added correctly.

The requestPasswordReset method now correctly generates a reset token, hashes it using bcrypt, and updates the user's reset token in the database.


Line range hint 113-131:
LGTM! Logging for sending reset email added correctly.

The sendResetEmail method now correctly logs the sending of the reset email for better traceability.


162-170: LGTM! Exclusion of api_key_hash from returned API keys added correctly.

The getApiKeys method now correctly excludes the api_key_hash field from the returned API keys, improving security.


Line range hint 336-377:
LGTM! Secure API key generation and storage added correctly.

The generateApiKeyForUser method now correctly generates a base key using a UUID and environment variables, hashes it with SHA-256, and stores it in the database.


395-402: LGTM! Hashed API key usage added correctly.

The getProjectIdForApiKey method now correctly accepts a hashed API key instead of a plain text API key, improving security.


411-447: LGTM! Secure API key validation added correctly.

The validateApiKey method now correctly hashes the API key and checks it against the database, improving security.

Also applies to: 453-453

packages/api/prisma/schema.prisma (3)

1736-1755: LGTM!

The ecom_addresses model is correctly defined with appropriate fields and relationships.


1757-1759: LGTM! But verify the completeness of the model.

The ecom_fulfilment_orders model is minimal. Ensure that this meets the application requirements.


1761-1763: LGTM! But verify the completeness of the model.

The ecom_order_line_items model is minimal. Ensure that this meets the application requirements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Outside diff range comments (1)
packages/api/src/@core/auth/auth.service.ts (1)

Line range hint 53-72:
Remove commented-out code and redundant code duplication.

The code segment includes commented-out code and redundant code duplication. Clean up the code for better readability and maintainability.

-    // Verify the reset token
-    const isValidToken = await this.verifyResetToken(
-      checkResetRequestIsValid.reset_token,
-      reset_token,
-    );

    if (!isValidToken) {
      throw new BadRequestException('Invalid reset token');
    }

    // Hash the new password
    const hashedPassword = await bcrypt.hash(new_password, 10);

    // Update the user's password in the database
-    const updatedPassword = await this.prisma.users.update({
      where: { email },
      data: { password_hash: hashedPassword },
    });
-    console.log(updatedPassword);
    return { message: 'Password reset successfully' };
Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 8d1bf6a and 4f4d42d.

Files ignored due to path filters (4)
  • docker-compose.dev.yml is excluded by !**/*.yml
  • docker-compose.source.yml is excluded by !**/*.yml
  • docker-compose.yml is excluded by !**/*.yml
  • packages/api/swagger/swagger-spec.yaml is excluded by !**/*.yaml
Files selected for processing (3)
  • packages/api/prisma/schema.prisma (2 hunks)
  • packages/api/src/@core/auth/auth.service.ts (12 hunks)
  • packages/api/src/main.ts (1 hunks)
Additional context used
Biome
packages/api/src/@core/auth/auth.service.ts

[error] 20-20: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


[error] 142-142: Expected an expression but instead found '}'.

Expected an expression here.

(parse)


[error] 142-142: Expected a statement but instead found ')'.

Expected a statement here.

(parse)

Additional comments not posted (11)
packages/api/src/main.ts (2)

56-56: LGTM! Verify the integration of the new security schema.

The code correctly sets the security schema to use the new api_key security scheme.

Ensure that the new security schema is correctly integrated and consistent with the rest of the codebase.

Verification successful

Integration of the new security schema verified.

The api_key security scheme is defined and utilized in various parts of the codebase, indicating proper integration and usage.

  • packages/api/src/main.ts: Line 56 sets the security schema.
  • Multiple references to api_key in configuration, service, and component files.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of the new security schema.

# Test: Search for the usage of `document.security` in the codebase.
rg --type python -A 5 $'document.security'

Length of output: 72


Script:

#!/bin/bash
# Description: Verify the integration of the new security schema.

# Test: Search for the usage of `document.security` in TypeScript/JavaScript files.
rg --type js --type ts -A 5 'document.security'

Length of output: 406


Script:

#!/bin/bash
# Description: Verify the definition and usage of the `api_key` security scheme in the Swagger/OpenAPI configuration.

# Test: Search for the definition of the `api_key` security scheme in TypeScript/JavaScript files.
rg --type js --type ts -A 5 'api_key'

Length of output: 84640


46-53: LGTM! Verify the integration of API key security.

The code correctly adds API key security configuration to the Swagger documentation.

Ensure that the new API key security configuration is correctly integrated and consistent with the rest of the codebase.

packages/api/src/@core/auth/auth.service.ts (5)

81-86: LGTM!

The code correctly verifies the reset token using bcrypt.


185-190: LGTM!

The code correctly retrieves API keys for a given project.


Line range hint 362-403:
LGTM!

The code correctly generates and stores a hashed API key.


437-473: LGTM!

The code correctly validates the API key by hashing it and checking against the database.


98-98: Remove commented-out code.

The code segment includes commented-out code. Clean up the code for better readability and maintainability.

-    // Send email with resetToken (implementation depends on your email service)
-    await this.sendResetEmail(email, resetToken);
    return { message: 'Password reset link sent' };

Likely invalid or redundant comment.

packages/api/prisma/schema.prisma (4)

1649-1649: LGTM!

The code correctly adds the new remote_deleted field to the ecom_customers model.


1729-1748: LGTM!

The code correctly renames the model and adds the new id_ecom_order field to the ecom_addresses model.


1750-1752: LGTM!

The code correctly adds the new primary key field to the ecom_fulfilment_orders model.


1754-1755: LGTM!

The code correctly adds the new primary key field to the ecom_order_line_items model.

Comment on lines 132 to 141
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
//secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
},
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix syntax error and remove commented-out code.

The code segment has a syntax error and includes commented-out code. Clean up the code for better readability and maintainability.

-      host: process.env.SMTP_HOST,
-      port: Number(process.env.SMTP_PORT),
-      //secure: false,
-      auth: {
-        user: process.env.SMTP_USER,
-        pass: process.env.SMTP_PASSWORD,
-      },
+    const transporter = nodemailer.createTransport({
+      host: process.env.SMTP_HOST,
+      port: Number(process.env.SMTP_PORT),
+      secure: false,
+      auth: {
+        user: process.env.SMTP_USER,
+        pass: process.env.SMTP_PASSWORD,
+      },
    });
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
//secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
},
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
});

@naelob naelob merged commit 5fe0657 into main Aug 3, 2024
8 of 15 checks passed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 4f4d42d and a77e17d.

Files selected for processing (2)
  • packages/api/prisma/schema.prisma (3 hunks)
  • packages/api/src/@core/auth/auth.service.ts (11 hunks)
Additional context used
Biome
packages/api/src/@core/auth/auth.service.ts

[error] 7-7: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

GitHub Check: Build and Test (18.x)
packages/api/src/@core/auth/auth.service.ts

[warning] 3-3:
'AuthError' is defined but never used

Additional comments not posted (6)
packages/api/src/@core/auth/auth.service.ts (2)

391-398: Add logging and improve error handling.

Consider adding logging for successful retrieval and handling cases where the API key is not found.

+ this.logger.log(`Retrieving project ID for API key`);

const saved_api_key = await this.prisma.api_keys.findUnique({
  where: {
    api_key_hash: hashed_apiKey,
  },
});

if (!saved_api_key) {
  this.logger.error(`API key not found: ${hashed_apiKey}`);
  throw new ReferenceError('API key not found');
}

this.logger.log(`Project ID retrieved successfully for API key`);
return saved_api_key.id_project;

407-443: Improve logging, error handling, and remove commented-out code.

Add logging for validation steps, improve error messages, and remove commented-out code for clarity.

+ this.logger.log(`Validating API key`);

const hashed_key = crypto.createHash('sha256').update(apiKey).digest('hex');

const saved_api_key = await this.prisma.api_keys.findUnique({
  where: {
    api_key_hash: hashed_key,
  },
});

if (!saved_api_key) {
  this.logger.error(`API key not found: ${hashed_key}`);
  throw new ReferenceError('API key not found');
}

this.logger.log(`API key validated successfully`);
return true;
packages/api/prisma/schema.prisma (4)

1649-1649: LGTM!

The addition of the remote_deleted field for soft deletion is a good practice for maintaining data integrity.


1731-1750: LGTM!

The renaming to ecom_addresses and the addition of the id_ecom_order field improve the schema's relational capabilities and naming conventions.


1752-1754: LGTM!

The addition of the ecom_fulfilment_orders model with a primary key aligns with business requirements for order processing functionalities.


1756-1758: LGTM!

The addition of the ecom_order_line_items model with a primary key aligns with business requirements for order processing functionalities.

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

Successfully merging this pull request may close these issues.

3 participants