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

Ma/elastic role #1139

Merged
merged 2 commits into from
Dec 3, 2024
Merged

Ma/elastic role #1139

merged 2 commits into from
Dec 3, 2024

Conversation

markusahlstrand
Copy link

@markusahlstrand markusahlstrand commented Dec 3, 2024

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Removed the deletion of records from the "tickets" table, streamlining cleanup operations.
  • New Features

    • Enhanced error handling in the authentication response generation process for improved reliability.
    • Introduced a new function for sending emails via an external API, complete with error handling for failed requests.
  • Refactor

    • Simplified the context fixture by removing the tickets property, improving the clarity of the function's logic.

Copy link

coderabbitai bot commented Dec 3, 2024

Walkthrough

The pull request introduces several changes across multiple files. The cleanup function no longer deletes records from the "tickets" table, while the deletion logic for other tables remains intact. The generateTokens function's customClaims structure is modified for specific clients, and error handling in the generateAuthResponse function is enhanced. A new asynchronous send function is added to handle email sending via an external API, and the ContextFixtureParams interface is updated to remove the tickets property, streamlining the context fixture logic.

Changes

File Change Summary
src/handlers/cleanup.ts Removed deletion of records from the "tickets" table in the cleanup function; other deletion logic remains unchanged.
src/helpers/generate-auth-response.ts Modified customClaims structure in generateTokens function for specific clients; enhanced error handling in generateAuthResponse.
src/services/email/resend.ts Added new asynchronous send function for sending emails via an external API, including error handling for requests.
test/fixtures/context.ts Removed tickets property from ContextFixtureParams interface and corresponding logic in contextFixture function.

Possibly related PRs

  • Ma/ticket #1131: The changes in this PR involve replacing the retrieval of a ticket with a code in the ticketAuth function, which is related to the removal of ticket handling in the main PR's cleanup function.
  • fix: add token debug #1138: This PR modifies the generateTokens function, which is in the same file as the main PR's generateAuthResponse function. Although the changes are not directly related to the deletion of records, they both involve modifications to authentication processes.

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

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.

Copy link

@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 (1)
src/services/email/resend.ts (1)

20-26: Consider type safety improvements for the request body

The request body structure should be type-safe to match Resend's API requirements.

Add a type definition for the request body:

interface ResendEmailRequest {
  from: string;
  to: string[];
  subject: string;
  html?: string;
  text?: string;
}

Then use it in the code:

-  const body = {
+  const body: ResendEmailRequest = {
     from: `${emailOptions.from.name} <${emailOptions.from.email}>`,
     to: recipients,
     subject: emailOptions.subject,
     html: htmlContent ? htmlContent.value : undefined,
     text: textContent ? textContent.value : undefined,
   };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b96a6b5 and 527b52b.

📒 Files selected for processing (4)
  • src/handlers/cleanup.ts (0 hunks)
  • src/helpers/generate-auth-response.ts (1 hunks)
  • src/services/email/resend.ts (1 hunks)
  • test/fixtures/context.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • src/handlers/cleanup.ts
  • test/fixtures/context.ts
🔇 Additional comments (1)
src/helpers/generate-auth-response.ts (1)

139-142: ⚠️ Potential issue

Verify compatibility of role format change

Changing the role format from array to string could break existing consumers expecting an array of roles.

Let's verify the impact:

✅ Verification successful

Based on the comprehensive analysis of the codebase, I can now provide the final response:

Role format change is safe to proceed

The change from array to string format for the roles claim in the "sesamy-elastic" client's custom claims is safe because:

  1. The role is only set for internal Sesamy users (email ending with "@sesamy.com")
  2. The authentication middleware doesn't validate or use the roles claim for authorization
  3. No direct consumers of the roles claim were found in the codebase
  4. The authorization is primarily based on JWT scopes and permissions, not roles
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consumers of the roles claim in the codebase

# Search for role-related patterns
echo "Searching for role array access patterns..."
rg -A 2 'roles\[' 

echo "Searching for role type definitions..."
ast-grep --pattern 'type $_ = {
  $$$
  roles: $_[]
  $$$
}'

echo "Searching for role assignments..."
rg -A 2 'roles.*=.*\[.*\]'

Length of output: 372


Script:

#!/bin/bash
# Let's try a broader search for roles-related patterns

echo "Searching for roles type annotations..."
ast-grep --pattern 'roles: $_'

echo "Searching for roles usage..."
rg -A 3 'roles[^a-zA-Z]'

echo "Searching for role-based checks..."
rg -A 3 'hasRole|checkRole|userRole|isRole'

echo "Checking the auth response generator history..."
rg -A 5 'roles' src/helpers/generate-auth-response.ts

Length of output: 13331


Script:

#!/bin/bash
# Let's check for JWT token validation and usage patterns

echo "Searching for JWT token validation..."
rg -A 5 'verify.*token|validateToken|decodeToken|parseToken'

echo "Checking JWT related files..."
fd -e ts -e js jwt

echo "Searching for custom claims usage..."
rg -A 3 'customClaims|claims\.roles|token\.roles'

echo "Checking auth middleware..."
fd -e ts -e js middleware
rg -A 5 'middleware.*auth|auth.*middleware'

Length of output: 1865


Script:

#!/bin/bash
# Let's examine the JWT validation and middleware implementation

echo "Checking JWT validation implementation..."
cat src/utils/jwt.ts

echo "Checking authentication middleware..."
cat src/middlewares/authentication.ts

echo "Searching for token role validation..."
rg -A 5 'validateRole|checkScope|verifyScope|validateScope'

Length of output: 5288

Comment on lines +34 to +36
if (!response.ok) {
throw new Error(`Failed with status: ${response.status}`);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling with detailed error messages

The current error handling doesn't provide enough context about what went wrong.

Improve error handling by including the response body:

   if (!response.ok) {
-    throw new Error(`Failed with status: ${response.status}`);
+    const errorBody = await response.text();
+    throw new Error(
+      `Email sending failed with status ${response.status}: ${errorBody}`
+    );
   }
📝 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
if (!response.ok) {
throw new Error(`Failed with status: ${response.status}`);
}
if (!response.ok) {
const errorBody = await response.text();
throw new Error(
`Email sending failed with status ${response.status}: ${errorBody}`
);
}

Comment on lines +3 to +9
export default async function send(emailOptions: EmailOptions, apiKey: string) {
const apiUrl = `https://api.resend.com/emails`;

const headers = new Headers();
headers.set("Authorization", `Bearer ${apiKey}`);
headers.set("Content-Type", "application/json");

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add input validation for required parameters

The function should validate the required parameters before making the API call.

Add validation at the start of the function:

 export default async function send(emailOptions: EmailOptions, apiKey: string) {
+  if (!apiKey?.trim()) {
+    throw new Error('API key is required');
+  }
+
+  if (!emailOptions?.to?.length) {
+    throw new Error('At least one recipient is required');
+  }
+
+  if (!emailOptions.from?.email) {
+    throw new Error('Sender email is required');
+  }
+
   const apiUrl = `https://api.resend.com/emails`;
📝 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
export default async function send(emailOptions: EmailOptions, apiKey: string) {
const apiUrl = `https://api.resend.com/emails`;
const headers = new Headers();
headers.set("Authorization", `Bearer ${apiKey}`);
headers.set("Content-Type", "application/json");
export default async function send(emailOptions: EmailOptions, apiKey: string) {
if (!apiKey?.trim()) {
throw new Error('API key is required');
}
if (!emailOptions?.to?.length) {
throw new Error('At least one recipient is required');
}
if (!emailOptions.from?.email) {
throw new Error('Sender email is required');
}
const apiUrl = `https://api.resend.com/emails`;
const headers = new Headers();
headers.set("Authorization", `Bearer ${apiKey}`);
headers.set("Content-Type", "application/json");

Comment on lines +139 to 142
roles: "sesamy_admin",
subject_key: user.name || user.email,
}
: {};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Strengthen role assignment security

The current implementation assigns admin roles based solely on email domain, which could be vulnerable if email verification is not enforced.

Consider these security improvements:

  1. Verify email ownership:
   const customClaims =
-    client.id === "sesamy-elastic" && user?.email.endsWith("sesamy.com")
+    client.id === "sesamy-elastic" && 
+    user?.email.endsWith("sesamy.com") && 
+    user.email_verified === true
  1. Consider maintaining an explicit allowlist of admin users instead of relying on email domain.

Committable suggestion skipped: line range outside the PR's diff.

@markusahlstrand markusahlstrand merged commit 281db52 into main Dec 3, 2024
2 checks passed
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.

1 participant