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

Fix duplicate security headers #8726

Merged
merged 1 commit into from
Nov 20, 2024

Conversation

SpecLad
Copy link
Contributor

@SpecLad SpecLad commented Nov 20, 2024

Motivation and context

Our NGINX configuration adds some headers to all responses, but Django already outputs these headers via SecurityMiddleware and XFrameOptionsMiddleware. So we end up with duplicate headers in the response, which has undefined semantics (and is just plain confusing).

I don't want to remove these headers from the Django configuration (because I want them to still be output when run via the development server) or from the NGINX configuration (because they should still be added when serving static files). So instead, keep them in both places, but let NGINX add each header only if the upstream server has not already added one.

Also, update the referrer policy in Django to match the one we're using elsewhere.

How has this been tested?

Manual testing.

Checklist

  • I submit my changes into the develop branch
  • I have created a changelog fragment
  • [ ] I have updated the documentation accordingly
  • [ ] I have added tests to cover my changes
  • [ ] I have linked related issues (see GitHub docs)
  • [ ] I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • New Features

    • Enhanced security header management for improved web communication safety.
    • Introduced a new setting for secure referrer policy.
    • Added configuration for ClickHouse database connection.
  • Bug Fixes

    • Resolved duplication of security headers in HTTP responses.
  • Chores

    • Updated settings related to file uploads and asset management.

Copy link
Contributor

coderabbitai bot commented Nov 20, 2024

Walkthrough

This update addresses security concerns by refining the management of security headers in HTTP responses from the backend. The Nginx configuration has been modified to dynamically assign security headers based on upstream headers, preventing redundancy. Additionally, new settings in the application configuration enhance security and file upload handling, including the introduction of a SECURE_REFERRER_POLICY and adjustments to database connection settings.

Changes

File Change Summary
changelog.d/20241120_172837_roman.md Documented the update addressing the duplication of security headers in HTTP responses.
cvat/nginx.conf Modified to include dynamic mappings for security headers based on upstream headers, replacing static definitions.
cvat/settings/base.py Introduced SECURE_REFERRER_POLICY, updated CORS_ALLOW_HEADERS, set USE_X_FORWARDED_HOST, and configured CLICKHOUSE and DATABASES.

Poem

In the land of code where rabbits play,
Security's strengthened in a clever way.
Headers now dance, no more in a line,
With mappings and settings, all is just fine.
Hooray for the changes, let’s hop with delight,
For a safer web world, our future is bright! 🐇✨


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

Our NGINX configuration adds some headers to all responses, but Django
already outputs these headers via `SecurityMiddleware` and
`XFrameOptionsMiddleware`. So we end up with duplicate headers in the
response, which has undefined semantics (and is just plain confusing).

I don't want to remove these headers from the Django configuration (because
I want them to still be output when run via the development server) _or_
from the NGINX configuration (because they should still be added when
serving static files). So instead, keep them in both places, but let NGINX
add each header only if the upstream server has not already added one.

Also, update the referrer policy in Django to match the one we're using
elsewhere.
@SpecLad SpecLad force-pushed the duplicate-security-headers branch from fa19949 to 5770c91 Compare November 20, 2024 15:33
@SpecLad SpecLad marked this pull request as ready for review November 20, 2024 15:34
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 and nitpick comments (1)
cvat/nginx.conf (1)

44-56: LGTM! The map blocks correctly implement conditional security headers.

The implementation effectively solves the duplicate headers issue while maintaining security by:

  1. Only adding headers when not provided by Django
  2. Using secure default values that align with best practices

Consider aligning the empty string conditions for consistency:

  map $upstream_http_referrer_policy $hdr_referrer_policy {
-     '' "strict-origin-when-cross-origin";
+     ""  "strict-origin-when-cross-origin";
  }

  map $upstream_http_x_content_type_options $hdr_x_content_type_options {
-     '' "nosniff";
+     ""  "nosniff";
  }

  map $upstream_http_x_frame_options $hdr_x_frame_options {
-     '' "deny";
+     ""  "deny";
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3eec9fe and 5770c91.

📒 Files selected for processing (3)
  • changelog.d/20241120_172837_roman.md (1 hunks)
  • cvat/nginx.conf (1 hunks)
  • cvat/settings/base.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • changelog.d/20241120_172837_roman.md
🔇 Additional comments (4)
cvat/nginx.conf (2)

62-64: Verify security header consistency across location blocks.

The server-level security headers look good, but we should verify that no location blocks override these headers, which could lead to inconsistent security policies.


44-64: Document the interaction with Django middleware.

Since these changes affect Django's SecurityMiddleware and XFrameOptionsMiddleware, please ensure the documentation is updated to:

  1. Explain which Django middleware classes can be disabled
  2. Document the header handling split between Nginx and Django
cvat/settings/base.py (2)

577-578: LGTM! Good security practice for referrer policy.

The 'strict-origin-when-cross-origin' setting is a secure choice that provides a good balance between functionality and security by:

  • Sending full referrer information to same-origin requests
  • Only sending the origin for cross-origin requests
  • Preventing referrer leakage when downgrading from HTTPS to HTTP

577-578: Verify complete security header configuration

Since this PR addresses duplicate security headers between NGINX and Django, we should verify that all security headers are properly configured across both NGINX and Django settings.

✅ Verification successful

Security headers are properly configured across NGINX and Django

The verification shows a well-configured security setup:

  • Django has the essential SecurityMiddleware and secure headers:

    • SECURE_PROXY_SSL_HEADER for SSL/TLS
    • SECURE_REFERRER_POLICY matching NGINX's configuration
  • NGINX implements comprehensive security headers:

    • Referrer-Policy (matching Django's strict-origin-when-cross-origin)
    • X-Content-Type-Options (nosniff)
    • X-Frame-Options (deny)
    • Cross-Origin-Opener-Policy (same-origin)
    • Cross-Origin-Embedder-Policy (credentialless/require-corp)
    • Cache control headers

The security headers are properly distributed between Django and NGINX without problematic duplications.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for security header configurations in both Django and NGINX

# Check Django security middleware and settings
echo "Checking Django security settings..."
rg -A 5 "SecurityMiddleware" 
rg "SECURE_" 

# Check NGINX security header configuration
echo "Checking NGINX security header configuration..."
fd -e conf -e "*.conf.template" | xargs rg "add_header"

Length of output: 1942

@codecov-commenter
Copy link

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 74.18%. Comparing base (3eec9fe) to head (5770c91).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #8726   +/-   ##
========================================
  Coverage    74.18%   74.18%           
========================================
  Files          401      401           
  Lines        43510    43510           
  Branches      3950     3950           
========================================
+ Hits         32278    32279    +1     
+ Misses       11232    11231    -1     
Components Coverage Δ
cvat-ui 78.50% <ø> (+<0.01%) ⬆️
cvat-server 70.49% <ø> (ø)
---- 🚨 Try these New Features:

@SpecLad SpecLad merged commit 67f511b into cvat-ai:develop Nov 20, 2024
42 of 43 checks passed
@SpecLad SpecLad deleted the duplicate-security-headers branch November 20, 2024 18:05
@cvat-bot cvat-bot bot mentioned this pull request Nov 29, 2024
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.

2 participants