Skip to content

Potential fix for code scanning alert no. 13: Insecure configuration of Helmet security middleware#206

Open
perinst wants to merge 1 commit intofeature/mergefrom
fix/security-autofix-13
Open

Potential fix for code scanning alert no. 13: Insecure configuration of Helmet security middleware#206
perinst wants to merge 1 commit intofeature/mergefrom
fix/security-autofix-13

Conversation

@perinst
Copy link
Collaborator

@perinst perinst commented Aug 30, 2025

Potential fix for https://github.com/perinst/dozu-api-service/security/code-scanning/13

To fix the issue, we will replace the contentSecurityPolicy configuration to ensure that CSP is not disabled entirely. Instead of setting it to false in non-production environments, we will provide a relaxed CSP configuration for development while keeping the default or a stricter CSP configuration for production. This ensures that CSP is always enabled, reducing the risk of injection attacks.

The changes will involve:

  1. Updating the contentSecurityPolicy configuration to use a relaxed policy in non-production environments.
  2. Keeping the default or stricter CSP configuration for production environments.

Suggested fixes powered by Copilot Autofix. Review carefully before merging.

Summary by CodeRabbit

  • Chores
    • Updated security headers in non-production to use an explicit Content Security Policy with defined directives: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:. Affects development and staging environments only, including local setups. Other headers (e.g., HSTS and Hide-Powered-By) remain unchanged. No impact to production users.

…of Helmet security middleware

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 30, 2025

Walkthrough

Updated Helmet middleware configuration: in non-production, contentSecurityPolicy is now an explicit directive object instead of disabled; production behavior remains unchanged. Other Helmet settings are unchanged. No exported API signatures changed.

Changes

Cohort / File(s) Summary
Security middleware config
src/config/middlewares/helmet.config.ts
Replaced non-production contentSecurityPolicy: false with a CSP directive object: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:. Production path still leaves CSP undefined. Other Helmet options unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as Application
  participant HC as helmetConfig()
  participant HM as Helmet Middleware

  App->>HC: Build Helmet options
  alt Production
    HC-->>App: options { contentSecurityPolicy: undefined, ... }
  else Non-Production
    Note over HC: Changed: explicit CSP object
    HC-->>App: options { contentSecurityPolicy: { directives... }, ... }
  end
  App->>HM: Initialize middleware with options
  App->>HM: Handle request
  HM-->>App: Set security headers (CSP varies by env)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

I twitch my ears at headers tight,
A CSP now guards the night—
In dev, a gentle whitelist hums,
In prod, the stricter silence comes.
Hop, hop, secure we go,
With Helmet snug from nose to toe. 🐇🛡️

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/security-autofix-13

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@perinst perinst marked this pull request as ready for review August 30, 2025 15:13
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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 52ac80a and b41f52c.

📒 Files selected for processing (1)
  • src/config/middlewares/helmet.config.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/config/middlewares/helmet.config.ts (1)
src/config/env.config.ts (1)
  • config (54-74)

Comment on lines +10 to +19
contentSecurityPolicy: config.isProduction
? undefined
: {
directives: {
"default-src": ["'self'"],
"script-src": ["'self'", "'unsafe-inline'"],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "data:"],
},
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Production CSP is unintentionally disabled (contentSecurityPolicy: undefined).

This sets CSP to undefined in production, which disables the CSP header. That contradicts the PR objective and keeps the app vulnerable in prod.

Apply this diff to enforce a stricter CSP in production and a relaxed CSP in non-production:

-    contentSecurityPolicy: config.isProduction
-      ? undefined
-      : {
-          directives: {
-            "default-src": ["'self'"],
-            "script-src": ["'self'", "'unsafe-inline'"],
-            "style-src": ["'self'", "'unsafe-inline'"],
-            "img-src": ["'self'", "data:"],
-          },
-        },
+    contentSecurityPolicy: config.isProduction
+      ? {
+          useDefaults: true,
+          directives: {
+            "default-src": ["'self'"],
+            "base-uri": ["'self'"],
+            "frame-ancestors": ["'none'"],
+            "object-src": ["'none'"],
+            "script-src": ["'self'"],
+            "style-src": ["'self'"],
+            "img-src": ["'self'", "data:"],
+          },
+        }
+      : {
+          useDefaults: true,
+          directives: {
+            "default-src": ["'self'"],
+            "script-src": ["'self'", "'unsafe-inline'"],
+            "style-src": ["'self'", "'unsafe-inline'"],
+            "img-src": ["'self'", "data:"],
+          },
+          // Optionally enable in dev to observe violations without blocking:
+          // reportOnly: true,
+        },
📝 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
contentSecurityPolicy: config.isProduction
? undefined
: {
directives: {
"default-src": ["'self'"],
"script-src": ["'self'", "'unsafe-inline'"],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "data:"],
},
},
contentSecurityPolicy: config.isProduction
? {
useDefaults: true,
directives: {
"default-src": ["'self'"],
"base-uri": ["'self'"],
"frame-ancestors": ["'none'"],
"object-src": ["'none'"],
"script-src": ["'self'"],
"style-src": ["'self'"],
"img-src": ["'self'", "data:"],
},
}
: {
useDefaults: true,
directives: {
"default-src": ["'self'"],
"script-src": ["'self'", "'unsafe-inline'"],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "data:"],
},
// Optionally enable in dev to observe violations without blocking:
// reportOnly: true,
},
🤖 Prompt for AI Agents
In src/config/middlewares/helmet.config.ts around lines 10 to 19, the current
code sets contentSecurityPolicy to undefined in production which disables the
CSP header; instead, configure a strict CSP when config.isProduction is true and
a relaxed CSP when false: change the ternary so that when production you provide
a restrictive directives object (e.g., default-src 'self'; script-src 'self'
with no 'unsafe-inline'; style-src 'self' possibly with nonce or removing
'unsafe-inline'; img-src 'self' data:; connect-src as needed), and when not
production keep the current relaxed directives (allowing 'unsafe-inline' for
scripts/styles). Ensure you return a valid directives object in both branches so
Helmet emits the header in production.

💡 Verification agent

🧩 Analysis chain

Quick sanity check: ensure CSP isn’t disabled elsewhere and header appears in both envs.

Run these read-only checks.


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Search for any CSP disabled configurations:"
rg -nP --glob '!**/node_modules/**' '\bcontentSecurityPolicy\s*:\s*(false|undefined)\b' || true

echo
echo "Verify helmet middleware is applied:"
rg -nP -C3 '\bhelmetConfig\s*\(' src || true

echo
echo "Manual check (after starting the app):"
echo "DEV:  curl -sSI http://localhost:3333 | rg -i '^content-security-policy'"
echo "PROD: NODE_ENV=production curl -sSI http://localhost:3333 | rg -i '^content-security-policy'"

Length of output: 807


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Searching for any helmet() calls in src files:"
rg -nP --glob '!**/node_modules/**' '\bhelmet\s*\(' src || true

echo
echo "Searching for @fastify/helmet or fastifyHelmet registrations:"
rg -nP --glob '!**/node_modules/**' '(?:@fastify/helmet|fastifyHelmet)' -n src || true

Length of output: 504


Ensure CSP middleware is properly configured and applied

  • In src/index.ts:37 replace app.use(helmet()) with app.use(helmetConfig()) so your custom CSP directives actually take effect.
  • The ternary in helmet.config.ts (contentSecurityPolicy: config.isProduction ? undefined : { … }) currently disables CSP in production—invert or adjust this condition if you intend to enable CSP in the production environment.
🤖 Prompt for AI Agents
In src/config/middlewares/helmet.config.ts around lines 10 to 19 and
src/index.ts at line 37, the CSP is currently applied only in non-production
(contentSecurityPolicy uses config.isProduction ? undefined : {...}) and the app
entry uses app.use(helmet()) so your custom helmet config never gets applied;
invert or adjust the ternary to enable the desired CSP in production (e.g., use
config.isProduction ? { directives: ... } : undefined) and update src/index.ts
to call app.use(helmetConfig()) instead of app.use(helmet()) so the custom CSP
directives are actually applied.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Dec 6, 2025

@perinst perinst requested a review from a team December 30, 2025 06:49
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