Skip to content

Harden FARM Django security configuration defaults#912

Merged
Smartappli merged 1 commit into
masterfrom
audit-security-and-apply-fixes
May 11, 2026
Merged

Harden FARM Django security configuration defaults#912
Smartappli merged 1 commit into
masterfrom
audit-security-and-apply-fixes

Conversation

@Smartappli
Copy link
Copy Markdown
Owner

@Smartappli Smartappli commented May 11, 2026

Motivation

  • The Django settings contained insecure hardcoded defaults (DEBUG=True, empty ALLOWED_HOSTS, and a development fallback SECRET_KEY) and lacked baseline production security flags, risking accidental insecure deployments.

Description

  • Updated FARM/FARM/settings.py to add an env_bool() helper and read DJANGO_DEBUG and DJANGO_ALLOWED_HOSTS from the environment instead of using hardcoded values.
  • Replaced DEBUG = True with DEBUG = env_bool("DJANGO_DEBUG", default=False) and set ALLOWED_HOSTS to a safe default of localhost,127.0.0.1 when not provided.
  • Added a runtime guard that raises a RuntimeError if the default insecure secret key is still present while DEBUG is disabled.
  • Enabled baseline production hardening settings: SECURE_BROWSER_XSS_FILTER, SECURE_CONTENT_TYPE_NOSNIFF, X_FRAME_OPTIONS = "DENY", SECURE_REFERRER_POLICY, secure CSRF/session cookies, and SECURE_SSL_REDIRECT, all tunable via environment variables.

Testing

  • Ran python -m py_compile FARM/FARM/settings.py, which completed without errors.

Codex Task

Summary by CodeRabbit

Release Notes

  • Security

    • Enabled XSS filter, content-type sniffing protection, and clickjacking defense.
    • Added referrer policy and secure cookie configurations.
    • Added runtime validation to prevent deployment with insecure defaults in production.
  • Improvements

    • Configuration now driven by environment variables for flexible deployment management.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 11, 2026

Walkthrough

The PR converts Django settings from hardcoded development defaults to environment-driven configuration. It adds an env_bool() helper, sets DEBUG and ALLOWED_HOSTS from environment variables, validates that non-debug deployments use a custom SECRET_KEY, and introduces baseline security hardening settings for XSS, content-type sniffing, clickjacking, referrer policy, and secure cookies/SSL redirects.

Changes

Django Settings Environment-Driven Configuration

Layer / File(s) Summary
Environment Parsing and Basic Config
FARM/FARM/settings.py
Adds env_bool() helper for parsing environment variables. Sets DEBUG from DJANGO_DEBUG (default False), ALLOWED_HOSTS from DJANGO_ALLOWED_HOSTS (default localhost,127.0.0.1), and raises RuntimeError if non-debug environments use the default insecure SECRET_KEY.
Security Hardening Settings
FARM/FARM/settings.py
Adds Django security settings: SECURE_BROWSER_XSS_FILTER, SECURE_CONTENT_TYPE_NOSNIFF, X_FRAME_OPTIONS, SECURE_REFERRER_POLICY, and configures CSRF_COOKIE_SECURE, SESSION_COOKIE_SECURE, and SECURE_SSL_REDIRECT based on DEBUG status via environment variables.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A Django settings shift so neat,
From hardcoded defaults to env-complete,
Security checks now guard the gate,
Production-safe, never too late!
The secret stays safe, no risk of bait. 🔐

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: hardening Django security configuration defaults in the FARM settings module.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch audit-security-and-apply-fixes

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codacy-production
Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 high

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
Security 1 high

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request implements environment-driven configuration for DEBUG, ALLOWED_HOSTS, and security settings in settings.py, including a check to ensure a secret key is set in production. Review feedback points out that SECURE_SSL_REDIRECT may cause infinite loops behind proxies without SECURE_PROXY_SSL_HEADER and notes that SECURE_BROWSER_XSS_FILTER is deprecated, suggesting the use of Content Security Policy (CSP) instead.

Comment thread FARM/FARM/settings.py
SECURE_REFERRER_POLICY = "same-origin"
CSRF_COOKIE_SECURE = env_bool("DJANGO_CSRF_COOKIE_SECURE", default=not DEBUG)
SESSION_COOKIE_SECURE = env_bool("DJANGO_SESSION_COOKIE_SECURE", default=not DEBUG)
SECURE_SSL_REDIRECT = env_bool("DJANGO_SECURE_SSL_REDIRECT", default=not DEBUG)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

security-high high

Enabling SECURE_SSL_REDIRECT by default in production (DEBUG=False) is a strong security measure, but it frequently causes infinite redirect loops when the application is deployed behind a reverse proxy (like Nginx, Traefik, or a Cloud Load Balancer) that terminates SSL and forwards requests via HTTP.

To prevent this, you typically need to configure SECURE_PROXY_SSL_HEADER.

Warning: Only enable this if you are behind a trusted proxy that is configured to strip the X-Forwarded-Proto header from incoming client requests to prevent spoofing.

Suggested change
SECURE_SSL_REDIRECT = env_bool("DJANGO_SECURE_SSL_REDIRECT", default=not DEBUG)
SECURE_SSL_REDIRECT = env_bool("DJANGO_SECURE_SSL_REDIRECT", default=not DEBUG)
# If the app is behind a trusted proxy that terminates SSL, you likely need the following:
# SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

Comment thread FARM/FARM/settings.py


# Basic production security hardening. These can be tuned via environment.
SECURE_BROWSER_XSS_FILTER = True
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

security-medium medium

The SECURE_BROWSER_XSS_FILTER setting is deprecated in Django as modern browsers no longer support the X-XSS-Protection header. While it remains harmless, it provides minimal security benefit today. For modern protection against XSS, it is recommended to implement a Content-Security-Policy (CSP) header instead.

Copy link
Copy Markdown
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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@FARM/FARM/settings.py`:
- Line 28: Run ruff format to auto-fix the blank-line formatting errors in the
FARM settings module: invoke ruff format on the settings module (or run ruff
format across the repo), verify the module-level blank lines and import/section
spacing in the settings module are corrected to satisfy ruff, and commit the
updated file so the CI ruff format --check passes.
- Line 138: Remove the deprecated setting SECURE_BROWSER_XSS_FILTER from
settings.py: locate the line setting SECURE_BROWSER_XSS_FILTER = True and delete
it (no replacement is needed because Django 4.0+ ignores this setting).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 284b0067-0337-4c2c-a272-c2cb6db356a0

📥 Commits

Reviewing files that changed from the base of the PR and between a23b7e6 and 2489263.

📒 Files selected for processing (1)
  • FARM/FARM/settings.py

Comment thread FARM/FARM/settings.py
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "dev-insecure-key-change-me")


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix Ruff formatting issues.

The pipeline indicates ruff format --check failed due to blank line formatting. Run ruff format FARM/FARM/settings.py to auto-fix.

🔧 How to fix
ruff format FARM/FARM/settings.py
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@FARM/FARM/settings.py` at line 28, Run ruff format to auto-fix the blank-line
formatting errors in the FARM settings module: invoke ruff format on the
settings module (or run ruff format across the repo), verify the module-level
blank lines and import/section spacing in the settings module are corrected to
satisfy ruff, and commit the updated file so the CI ruff format --check passes.

Comment thread FARM/FARM/settings.py


# Basic production security hardening. These can be tuned via environment.
SECURE_BROWSER_XSS_FILTER = True
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify Django version and check for SECURE_BROWSER_XSS_FILTER references
rg -n "django.*version|Django.*version" --type=py -g 'requirements*.txt' -g 'setup.py' -g 'pyproject.toml'

Repository: Smartappli/AIMER

Length of output: 42


🌐 Web query:

Is SECURE_BROWSER_XSS_FILTER deprecated in Django 6.0?

💡 Result:

No. SECURE_BROWSER_XSS_FILTER is not deprecated in Django 6.0 because it was already removed from Django (so it is not available to deprecate there). [1][2] Evidence: Django core includes a change titled “Fixed #32678 — Removed SECURE_BROWSER_XSS_FILTER setting.” [1] The associated ticket records the setting as removed (“Resolution: fixed”). [2]

Citations:


🏁 Script executed:

head -20 FARM/FARM/settings.py

Repository: Smartappli/AIMER

Length of output: 564


Remove deprecated SECURE_BROWSER_XSS_FILTER.

SECURE_BROWSER_XSS_FILTER was removed from Django in version 4.0 and has no effect in Django 6.0.1. This setting should be removed.

Proposed fix
-SECURE_BROWSER_XSS_FILTER = True
 SECURE_CONTENT_TYPE_NOSNIFF = True
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@FARM/FARM/settings.py` at line 138, Remove the deprecated setting
SECURE_BROWSER_XSS_FILTER from settings.py: locate the line setting
SECURE_BROWSER_XSS_FILTER = True and delete it (no replacement is needed because
Django 4.0+ ignores this setting).

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 24892638c0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread FARM/FARM/settings.py
Comment on lines +45 to +47
if not DEBUG and SECRET_KEY == "dev-insecure-key-change-me":
msg = "DJANGO_SECRET_KEY must be set in non-debug environments."
raise RuntimeError(msg)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Prevent default configuration from raising at startup

With no environment variables set, this new guard now raises RuntimeError during settings import because DEBUG defaults to False while SECRET_KEY still defaults to the insecure placeholder. That means a fresh checkout cannot start ASGI or run any Django management command unless callers preconfigure DJANGO_DEBUG or DJANGO_SECRET_KEY, which is a regression from the previous out-of-the-box behavior and will break local/dev automation that relies on defaults.

Useful? React with 👍 / 👎.

Comment thread FARM/FARM/settings.py
]

ALLOWED_HOSTS = []
if not DEBUG and SECRET_KEY == "dev-insecure-key-change-me":
@Smartappli Smartappli merged commit cfa03e2 into master May 11, 2026
17 of 26 checks passed
@Smartappli Smartappli deleted the audit-security-and-apply-fixes branch May 11, 2026 21:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants