8000 fix: sonar security hotspots (https, --ignore-scripts, api_key, math.random) by vijayraghav-io · Pull Request #5538 · formbricks/formbricks · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix: sonar security hotspots (https, --ignore-scripts, api_key, math.random) #5538

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 8000 ”, 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 16 commits into from
May 6, 2025

Conversation

vijayraghav-io
Copy link
Contributor
@vijayraghav-io vijayraghav-io commented Apr 28, 2025

What does this PR do?

Fixes #(issue)
Fixes following sonar security hotspots
1.
Screenshot 2025-04-29 at 2 08 09 PM

Screenshot 2025-04-29 at 7 33 35 AM
Screenshot 2025-04-29 at 7 34 46 AM
Screenshot 2025-04-29 at 12 15 16 PM
Screenshot 2025-04-29 at 2 04 23 PM

The below hotspot is addressed by adding a condition that SMTP_SECURE_ENABLED will be true if SMTP_PORT = '465'
Screenshot 2025-04-29 at 2 23 17 PM

Screenshot 2025-04-29 at 2 30 13 PM

How should this be tested?

Tests updated
Run Sonar scanner

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read How we Code at Formbricks
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand bits
  • Ran pnpm build
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues
  • First PR at Formbricks? Please sign the CLA! Without it we wont be able to merge it 🙏

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Formbricks Docs if changes were necessary

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added support for a new environment variable, TELEMETRY_API_KEY, for enhanced configuration flexibility.
  • Bug Fixes

    • Improved detection of secure SMTP mode by enabling it automatically when using port 465.
    • Updated placeholder and redirect URLs to use "https" for increased security.
  • Refactor

    • Switched random number generation in utility and shuffle functions to use cryptographically secure methods for improved reliability.
  • Chores

    • Updated Dockerfile and build configuration to support new environment variables and enhance installation security.

Copy link
vercel bot commented Apr 28, 2025

@vijayraghav-io is attempting to deploy a commit to the formbricks Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor
github-actions bot commented Apr 28, 2025

Thank you for following the naming conventions for pull request titles! 🙏

@vijayraghav-io vijayraghav-io changed the title fix: sonar hotspots fix: some sonar security hotspots (https, --ignore-scripts) Apr 29, 2025
@vijayraghav-io vijayraghav-io changed the title fix: some sonar security hotspots (https, --ignore-scripts) fix: sonar security hotspots (https, --ignore-scripts) Apr 29, 2025
@vijayraghav-io vijayraghav-io changed the title fix: sonar security hotspots (https, --ignore-scripts) fix: sonar security hotspots (https, --ignore-scripts, api_key, math.random) Apr 29, 2025
@vijayraghav-io vijayraghav-io marked this pull request as ready for review April 29, 2025 09:18
Copy link
Contributor
coderabbitai bot commented Apr 29, 2025

Warning

Rate limit exceeded

@mattinannt has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a1454c8 and dc61159.

📒 Files selected for processing (1)
  • apps/web/lib/telemetry.ts (1 hunks)

"""

Walkthrough

This set of changes introduces several updates across multiple files. In the Dockerfile for the web application, all global npm install commands and the pnpm install command now include the --ignore-scripts flag. The SMTP secure mode logic in the constants file is broadened to enable secure mode if the SMTP port is 465, in addition to the existing environment variable check. The environment variable schema is extended to include an optional TELEMETRY_API_KEY, which is also added to the build environment variables in the Turbo configuration and documented in environment variable docs and .env.example. The telemetry module now sources its API key from the environment rather than a hardcoded value. Test and utility code in the JS core and surveys packages is updated to use cryptographically secure random number generation instead of Math.random, affecting both the implementation and corresponding tests. Minor updates also include switching URLs from HTTP to HTTPS in mock data and UI placeholders.

Possibly related PRs

  • fix: email smtp auth mode #4571: Modifies SMTP configuration by introducing a new environment variable for SMTP authentication mode, related to SMTP setup changes.
  • chore: remove unused langfuse packages #5561: Removes Langfuse-related environment variables and dependencies while this PR adds a new telemetry environment variable; both modify environment variable declarations in apps/web/lib/env.ts.
  • fix: weak cryptography security hotspot #5600: Adds comments to suppress security warnings related to random number generation, while this PR replaces Math.random with cryptographically secure random generation in core utilities.

Suggested labels

❗️ .env changes

Suggested reviewers

  • mattinannt
    """
✨ 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.
    • 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.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a9eedd3 and 3d06ba3.

📒 Files selected for processing (10)
  • apps/web/Dockerfile (4 hunks)
  • apps/web/lib/constants.ts (1 hunks)
  • apps/web/lib/env.ts (2 hunks)
  • apps/web/lib/survey/tests/__mock__/survey.mock.ts (1 hunks)
  • apps/web/lib/telemetry.ts (1 hunks)
  • apps/web/modules/survey/editor/components/open-question-form.tsx (1 hunks)
  • packages/js-core/src/lib/common/tests/utils.test.ts (1 hunks)
  • packages/js-co 8000 re/src/lib/common/utils.ts (1 hunks)
  • packages/surveys/src/lib/utils.ts (1 hunks)
  • turbo.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/js-core/src/lib/common/tests/utils.test.ts (1)
packages/js-core/src/lib/common/utils.ts (1)
  • shouldDisplayBasedOnPercentage (186-192)
apps/web/lib/constants.ts (1)
apps/web/lib/env.ts (1)
  • env (4-230)
🔇 Additional comments (10)
turbo.json (1)

197-197: Secure handling of telemetry API key

Adding the TELEMETRY_API_KEY to the environment variables list in the build task is a good security practice as it avoids hardcoding sensitive credentials.

apps/web/lib/env.ts (2)

104-104: Good security practice for API key handling

Adding the telemetry API key to the server environment schema as an optional string type is appropriate and consistent with how other API keys are handled in this file.


217-217: Consistent implementation of environment variable

The runtime environment mapping is correctly implemented to match the schema definition, ensuring the API key is properly loaded from process.env.

packages/js-core/src/lib/common/utils.ts (1)

187-190: Security enhancement: Replace Math.random with cryptographically secure random

Great security improvement! Replacing Math.random() with crypto.getRandomValues() addresses a security hotspot by using a cryptographically secure random number generator, which is significantly more secure for any feature that depends on unpredictability.

You've implemented this correctly by:

  1. Creating a Uint32Array
  2. Using crypto.getRandomValues to fill it
  3. Normalizing to a [0,1) range
  4. Properly scaling to match the previous behavior
packages/surveys/src/lib/utils.ts (1)

19-27: Security enhancement: Improve shuffle with cryptographically secure randomness

Excellent update to the shuffle function! This change addresses two important aspects:

  1. Security: Replacing Math.random() with crypto.getRandomValues() for cryptographically secure randomness
  2. Algorithm quality: Implementing the Fisher-Yates shuffle algorithm correctly by iterating backward

This makes the shuffle both more secure and more efficient.

packages/js-core/src/lib/common/tests/utils.test.ts (1)

402-419: Great security improvement by using cryptographically secure random number generation.

You've correctly updated the test to mock crypto.getRandomValues instead of Math.random, which aligns with the corresponding implementation change in the utility function. Using cryptographically secure random number generation is a security best practice, especially for any code that might influence decision-making or sampling.

apps/web/modules/survey/editor/components/open-question-form.tsx (1)

235-235: Good security update by using HTTPS in the URL placeholder.

Switching from HTTP to HTTPS in the placeholder example promotes secure practices. This change aligns with modern web security standards where HTTPS should be preferred over HTTP.

apps/web/lib/survey/tests/__mock__/survey.mock.ts (1)

205-205: Security improvement - updated to HTTPS URL.

Good job updating the mock URL to use HTTPS instead of HTTP. This change is consistent with security best practices and the other changes in this PR addressing Sonar security hotspots.

apps/web/lib/constants.ts (1)

84-84: Secure handling for SMTP port 465

This change improves security by automatically enabling secure mode when SMTP port 465 is used, which is the standard port for SMTP over SSL. Previously, secure mode would only be enabled with an explicit environment variable setting, potentially allowing insecure communication on a port that should always be secured.

This fix directly addresses the SonarQube security hotspot mentioned in the PR objectives.

apps/web/Dockerfile (1)

21-21: Addition of --ignore-scripts flag improves security

Adding the --ignore-scripts flag to all npm and pnpm install commands is an excellent security improvement. This prevents potentially malicious code in pre/post-install scripts from executing during package installation, reducing the attack surface of the application during build time.

This systematically addresses the SonarQube security hotspot related to npm script execution mentioned in the PR objectives.

Also applies to: 62-62, 78-78, 144-144

@jobenjada jobenjada requested review from mattinannt and Copilot April 30, 2025 02:09
Copy link
Contributor
@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR addresses several sonar security hotspots by replacing insecure methods and hardcoded values with secure counterparts. Key changes include:

  • Refactoring random number generation in utility functions to use cryptographically secure methods.
  • Updating URLs from "http" to "https" and removing hardcoded telemetry API keys.
  • Adjusting SMTP secure enabling logic based on the SMTP port value.

Reviewed Changes

Copilot reviewed 8 out of 12 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
packages/surveys/src/lib/utils.ts Updated the shuffle algorithm to use crypto-based secure randomness with a Fisher-Yates approach.
packages/js-core/src/lib/common/utils.ts Replaced Math.random with crypto-secure random generation in percentage-based display logic.
packages/js-core/src/lib/common/tests/utils.test.ts Modified tests to mock crypto.getRandomValues, aligning them with the updated randomness approach.
apps/web/modules/survey/editor/components/open-question-form.tsx Changed placeholder URL to use "https".
apps/web/lib/telemetry.ts Replaced hardcoded telemetry API key with an environment variable.
apps/web/lib/survey/tests/mock/survey.mock.ts Updated redirect URL to use "https".
apps/web/lib/env.ts Added TELEMETRY_API_KEY configuration in the environment schema.
apps/web/lib/constants.ts Enhanced SMTP secure flag logic to enable secure mode when SMTP_PORT is "465".
Files not reviewed (4)
  • .env.example: Language not supported
  • apps/web/Dockerfile: Language not supported
  • docs/self-hosting/configuration/environment-variables.mdx: Language not supported
  • turbo.json: Language not supported

@mattinannt
Copy link
Member

@vijayraghav-io thanks a lot for the PR 😊💪
We only need to fox the telemetry api key and then we are good to go here 😊

Copy link
Contributor
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 334f58c and b0b8c1e.

📒 Files selected for processing (1)
  • .env.example (1 hunks)
🧰 Additional context used
🪛 Gitleaks (8.21.2)
.env.example

193-193: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Run Linters / Linters
  • GitHub Check: Run E2E Tests / Run E2E Tests
  • GitHub Check: Run Unit Tests / Unit Tests
  • GitHub Check: SonarQube
  • GitHub Check: Validate Docker Build

8000
@vijayraghav-io
Copy link
Contributor Author

@vijayraghav-io thanks a lot for the PR 😊💪 We only need to fox the telemetry api key and then we are good to go here 😊

Sure, Thank you 🙏 , updated telemetry api key (sonar is not flagging for .env files)

Copy link
Member
@mattinannt mattinannt left a comment

Choose a reason for hiding this comment

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

Ready to be merged 🚀

@mattinannt mattinannt merged commit 53850c9 into formbricks:main May 6, 2025
10 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0