Skip to content

Add SMP encoders service and environment-driven Django settings with security defaults#913

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

Add SMP encoders service and environment-driven Django settings with security defaults#913
Smartappli merged 1 commit into
masterfrom
audit-security-and-apply-fixes-y1eln0

Conversation

@Smartappli
Copy link
Copy Markdown
Owner

@Smartappli Smartappli commented May 11, 2026

Motivation

  • Expose segmentation-models-pytorch (SMP) encoder discovery through the API and identify TIMM-backed encoders.
  • Make Django configuration environment-driven to avoid unsafe defaults in production and provide basic security hardening.
  • Add coverage for the new encoders endpoint in the test suite.

Description

  • Added an env_bool helper and switched DEBUG to read from DJANGO_DEBUG, populated ALLOWED_HOSTS from DJANGO_ALLOWED_HOSTS, and enforced that a non-default DJANGO_SECRET_KEY is required when not debugging in FARM/settings.py.
  • Introduced several production-oriented security settings in FARM/settings.py (e.g. SECURE_BROWSER_XSS_FILTER, SECURE_CONTENT_TYPE_NOSNIFF, X_FRAME_OPTIONS, SECURE_REFERRER_POLICY, CSRF_COOKIE_SECURE, SESSION_COOKIE_SECURE, SECURE_SSL_REDIRECT) with defaults controllable via environment variables.
  • Added a new encoders microservice in MAGE/api/services/encoders.py that inspects segmentation_models_pytorch and returns encoder names and a list of TIMM-backed encoders.
  • Integrated the encoders service into the gateway in MAGE/api/main.py by mounting /services/encoders and adding a backward-compatible /encoders route.
  • Extended tests in MAGE/tests/test_main.py with a FakeSMP shim, registered it in the import fixture, and added test_encoders_list to validate the /encoders endpoint.

Testing

  • Ran the API unit tests with pytest MAGE/tests/test_main.py and the suite succeeded.
  • The new test_encoders_list passed, validating encoder discovery and detection of TIMM-backed names.

Codex Task

Summary by CodeRabbit

  • New Features

    • Added /encoders API endpoint that lists available encoders and identifies TIMM-backed variants.
  • Configuration

    • Application settings now configurable via environment variables for flexible deployment.
    • Enhanced security hardening features enabled in production mode, including protection against XSS, clickjacking, and insecure cookies.

Review Change Stack

@Smartappli Smartappli merged commit bbe76c0 into master May 11, 2026
8 of 21 checks passed
@Smartappli Smartappli deleted the audit-security-and-apply-fixes-y1eln0 branch May 11, 2026 21:00
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 11, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 92cb4c49-ac7e-46c0-b6cc-7545b24de53e

📥 Commits

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

📒 Files selected for processing (4)
  • FARM/FARM/settings.py
  • MAGE/api/main.py
  • MAGE/api/services/encoders.py
  • MAGE/tests/test_main.py

Walkthrough

This PR introduces two independent functional changes: Django settings now retrieve configuration and security properties from environment variables with production-safe defaults, and a new Encoders microservice is added to the MAGE gateway with endpoints for health checks and dynamic encoder listing.

Changes

Django Settings Hardening

Layer / File(s) Summary
Environment Configuration Helpers
FARM/FARM/settings.py
env_bool() helper parses boolean environment variables; DEBUG and ALLOWED_HOSTS now derive from DJANGO_DEBUG and DJANGO_ALLOWED_HOSTS environment variables with defaults favoring production safety.
Security Hardening Settings
FARM/FARM/settings.py
Adds XSS filter, content-type nosniff, clickjacking protection, referrer policy, and configures secure CSRF/session cookies and HTTPS redirect from environment variables (defaulting to enabled when not in debug mode).

Encoders Service and Integration

Layer / File(s) Summary
Encoders Service Implementation
MAGE/api/services/encoders.py
New FastAPI service exposes /health endpoint for status checks and /encoders endpoint that dynamically imports segmentation_models_pytorch, extracts and sorts encoder names, identifies TIMM-backed (tu-prefixed) encoders, and returns both lists with total counts. Returns HTTP 503 if import fails.
Gateway API Integration
MAGE/api/main.py
Imports encoder route handler and service app; registers GET /encoders REST endpoint tagged under encoders; mounts encoder microservice at /services/encoders alongside existing library/model/module service mounts.
Test Coverage and Mocks
MAGE/tests/test_main.py
Introduces FakeSMPEncoders and FakeSMP mock classes for deterministic testing; updates app_module fixture to inject fake into sys.modules; adds test_encoders_list to validate endpoint returns encoders and timm_backed_encoders keys with correct TIMM encoder filtering.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Smartappli/AIMER#774: Related to environment-driven Django settings; this PR extends SECRET_KEY env handling with broader env_bool parsing, DEBUG/ALLOWED_HOSTS sourcing, and security configuration.

Poem

🐰 A rabbit's leap through settings and encoders bright,
From hardcoded dreams to environment's light,
With TIMM-backed friends now listed with glee,
The gateway hops forward, a service so free!

✨ 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-y1eln0

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 · 1 minor

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

Results:
2 new issues

Category Results
Documentation 1 minor
Security 1 high

View in Codacy

🟢 Metrics 5 complexity

Metric Results
Complexity 5

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.

Comment thread FARM/FARM/settings.py
]

ALLOWED_HOSTS = []
if not DEBUG and SECRET_KEY == "dev-insecure-key-change-me":
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: 678f259ced

ℹ️ 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
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.

P1 Badge Configure proxy SSL header before forcing HTTPS redirects

Turning SECURE_SSL_REDIRECT on by default in non-debug mode can break deployments behind a TLS-terminating reverse proxy, because Django will see backend traffic as HTTP unless SECURE_PROXY_SSL_HEADER is configured. In that setup, every request is treated as insecure and redirected again, causing redirect loops and an effectively unavailable app; this change introduces that risk for any non-debug environment that doesn’t explicitly override the new default.

Useful? React with 👍 / 👎.

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 introduces a new 'encoders' service to list SMP encoders and their TIMM-backed variants, including the necessary API routes and tests. Additionally, it updates 'settings.py' to include a helper for boolean environment variables, improved configuration for 'DEBUG' and 'ALLOWED_HOSTS', and new security hardening settings. The review feedback highlights that the 'encoders' service should pre-calculate metadata to avoid blocking imports in the request path and notes that the 'SECURE_BROWSER_XSS_FILTER' setting is obsolete in modern Django versions and should be removed.

Comment on lines +7 to +36
from importlib import import_module

from fastapi import APIRouter, FastAPI, HTTPException

router = APIRouter(tags=["encoders"])


@router.get("/health")
async def healthcheck() -> dict[str, str]:
"""Service-local health-check endpoint."""
return {"encoders_service": "UP"}


@router.get("/encoders")
async def list_encoders() -> dict[str, list[str] | int]:
"""List SMP encoders and a subset that are TIMM-backed."""
try:
smp = import_module("segmentation_models_pytorch")
smp_encoders = smp.encoders
except Exception as exc:
raise HTTPException(status_code=503, detail="segmentation_models_pytorch is unavailable") from exc

names = sorted(smp_encoders.get_encoder_names())
timm_backed = [name for name in names if name.startswith("tu-")]
return {
"encoders": names,
"timm_backed_encoders": timm_backed,
"total": len(names),
"timm_backed_total": len(timm_backed),
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

Importing a heavy library like segmentation_models_pytorch inside an async request handler is inefficient and can block the FastAPI event loop, especially during the first call when the module is actually loaded. Since the list of encoders is static for a given installation, it should be imported and computed once at the module level or cached. Additionally, catching a generic Exception is too broad; it's better to specifically catch ImportError or AttributeError to handle missing optional dependencies.

from fastapi import APIRouter, FastAPI, HTTPException

# Pre-calculate encoder metadata to avoid expensive/blocking imports in the request path.
try:
    import segmentation_models_pytorch as smp
    _NAMES = sorted(smp.encoders.get_encoder_names())
    _TIMM_BACKED = [n for n in _NAMES if n.startswith("tu-")]
    _ENCODER_DATA = {
        "encoders": _NAMES,
        "timm_backed_encoders": _TIMM_BACKED,
        "total": len(_NAMES),
        "timm_backed_total": len(_TIMM_BACKED),
    }
except (ImportError, AttributeError):
    _ENCODER_DATA = None

router = APIRouter(tags=["encoders"])


@router.get("/health")
async def healthcheck() -> dict[str, str]:
    """Service-local health-check endpoint."""
    return {"encoders_service": "UP"}


@router.get("/encoders")
async def list_encoders() -> dict[str, list[str] | int]:
    """List SMP encoders and a subset that are TIMM-backed."""
    if _ENCODER_DATA is None:
        raise HTTPException(status_code=503, detail="segmentation_models_pytorch is unavailable")
    return _ENCODER_DATA

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.

medium

The SECURE_BROWSER_XSS_FILTER setting was deprecated in Django 3.0 and removed in Django 4.0. Since this project is using Django 6.0.1 (as indicated in the file header), this setting is obsolete and has no effect. It should be removed to avoid configuration clutter.

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