Skip to content

Improve email whitelisting and extend to GitHub auth #2090

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

Merged
merged 6 commits into from
May 22, 2025

Conversation

nicktrn
Copy link
Collaborator

@nicktrn nicktrn commented May 21, 2025

No magic link emails will be sent out to non-whitelisted emails. GitHub auth is now also covered and errors will be displayed.

Also includes a fix for boolean env vars. The following env vars always evaluated to true if any value was set:

  • MARQS_DISABLE_REBALANCING
  • RUN_ENGINE_DEBUG_WORKER_NOTIFICATIONS
  • SMTP_SECURE
  • ALERT_SMTP_SECURE

Thanks @Kritik-J for the prior work on this! And sorry it took us so long to get this in 🫣

Fixes #833

Copy link

changeset-bot bot commented May 21, 2025

⚠️ No Changeset found

Latest commit: 07a799e

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.

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

Copy link
Contributor

coderabbitai bot commented May 21, 2025

Walkthrough

The changes introduce a new utility, BoolEnv, for consistent boolean coercion of environment variable strings, replacing previous uses of z.coerce.boolean(). A centralized email whitelist validation function, assertEmailAllowed, is added and integrated into user creation and email sending logic to enforce email authorization based on environment configuration. The login route's loader and UI are updated to display authentication errors to users. Minor adjustments to function signatures are made for parameter destructuring and consistency. No changes are made to the exports of existing entities except for the addition of the new utility functions.

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
apps/webapp/app/utils/boolEnv.ts (1)

1-9: The BoolEnv utility looks well-designed

This utility provides a consistent way to handle boolean environment variables, ensuring only "true" and "1" strings (case-insensitive) are interpreted as boolean true values. This addresses the issue mentioned in the PR description where any non-empty string would coerce to true.

I'd suggest adding a JSDoc comment to document the expected behavior for future developers.

 import { z } from "zod";

+/**
+ * Zod schema that converts string values to booleans in a consistent way:
+ * - Strings "true" and "1" (case-insensitive) are converted to boolean `true`
+ * - All other strings are converted to boolean `false`
+ * - Non-string values are passed through unchanged
+ */
 export const BoolEnv = z.preprocess((val) => {
   if (typeof val !== "string") {
     return val;
   }

   return ["true", "1"].includes(val.toLowerCase().trim());
 }, z.boolean());
apps/webapp/app/utils/email.ts (1)

3-13: Good centralization of email validation logic

The assertEmailAllowed function effectively centralizes the email whitelist validation, making it reusable across the application. This promotes consistency in how email restrictions are enforced.

I have two suggestions for improvement:

  1. Consider adding error handling for invalid regex patterns in the environment variable
  2. Make the error message more user-friendly with guidance
export function assertEmailAllowed(email: string) {
  if (!env.WHITELISTED_EMAILS) {
    return;
  }

- const regexp = new RegExp(env.WHITELISTED_EMAILS);
+ // Safely create regex with error handling
+ let regexp;
+ try {
+   regexp = new RegExp(env.WHITELISTED_EMAILS);
+ } catch (error) {
+   console.error("Invalid WHITELISTED_EMAILS regex pattern:", error);
+   throw new Error("Email validation configuration error");
+ }

  if (!regexp.test(email)) {
-   throw new Error("This email is unauthorized");
+   throw new Error("This email is not authorized. Please contact your administrator if you need access.");
  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between c8d252e and 07a799e.

📒 Files selected for processing (6)
  • apps/webapp/app/env.server.ts (5 hunks)
  • apps/webapp/app/models/user.server.ts (3 hunks)
  • apps/webapp/app/routes/login._index/route.tsx (4 hunks)
  • apps/webapp/app/services/email.server.ts (2 hunks)
  • apps/webapp/app/utils/boolEnv.ts (1 hunks)
  • apps/webapp/app/utils/email.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/webapp/app/services/email.server.ts (1)
apps/webapp/app/utils/email.ts (1)
  • assertEmailAllowed (3-13)
apps/webapp/app/env.server.ts (1)
apps/webapp/app/utils/boolEnv.ts (1)
  • BoolEnv (3-9)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (16)
apps/webapp/app/env.server.ts (5)

5-5: Good addition of BoolEnv import

Correctly imports the new BoolEnv utility from the local path.


54-54: Fixed SMTP_SECURE boolean coercion

Replaces z.coerce.boolean() with the new BoolEnv schema to ensure proper boolean coercion that only treats "true" and "1" as true values, addressing the issue mentioned in the PR.


342-342: Fixed ALERT_SMTP_SECURE boolean coercion

Replaces z.coerce.boolean() with the new BoolEnv schema for proper boolean coercion.


382-382: Fixed MARQS_DISABLE_REBALANCING boolean coercion with default value

Replaces z.coerce.boolean() with the new BoolEnv schema and sets a default value of false, ensuring consistent behavior.


460-460: Fixed RUN_ENGINE_DEBUG_WORKER_NOTIFICATIONS boolean coercion with default value

Replaces z.coerce.boolean() with the new BoolEnv schema and sets a default value of false, ensuring consistent behavior.

apps/webapp/app/services/email.server.ts (2)

10-10: LGTM: Import statement added correctly

The import of assertEmailAllowed from the utility file is correctly implemented.


68-70: Properly validates email before sending magic link

Good implementation of email validation before proceeding with sending the magic link email. This ensures that no unauthorized emails receive login links, improving security.

apps/webapp/app/models/user.server.ts (3)

10-10: LGTM: Import statement added correctly

The import of assertEmailAllowed from the utility file is correctly implemented.


41-44: Improved function signature and validation

The function signature has been updated to use destructuring, which makes the code cleaner and more consistent. The addition of the email validation ensures that users cannot be created with unauthorized email addresses.


80-81: Extended email validation to GitHub auth

Excellent addition of email validation for GitHub authentication, ensuring consistent enforcement of the whitelist across all authentication methods.

apps/webapp/app/routes/login._index/route.tsx (6)

9-9: LGTM: Import statements added correctly

The imports for FormError and getUserSession are correctly implemented.

Also applies to: 16-16


53-57: Properly handles null auth error with redirectTo

Good implementation of explicitly setting authError to null when there's a redirect. This ensures consistent data structure in the response.


65-75: Good error handling implementation

The implementation properly extracts error messages from session data, handling both error objects with message properties and other types of errors. This ensures all errors can be properly displayed to the user.


80-80: LGTM: Adding authError to the response

Correctly includes the processed auth error in the TypedJSON response.


103-103: Good UI enhancement for horizontal centering

Adding the items-center class to center the content horizontally is a good UI improvement for better alignment of the login elements.


125-125: Improves user experience with error feedback

Great addition of error display in the UI. This provides important feedback to users when authentication fails, particularly when their email is not in the whitelist.

@nicktrn nicktrn merged commit 8112c12 into main May 22, 2025
12 checks passed
@nicktrn nicktrn deleted the fix/email-whitelisting branch May 22, 2025 09:30
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.

[TRI-1857] Improve email whitelisting for self-hosters
2 participants