Dependency Pruning Improves Django Project Security and Maintainability

In progress Django AppSec

Pruning unnecessary Python dependencies in Django projects improves security and maintainability by reducing the attack surface and minimizing potential vulnerabilities.

Introduction

Dependency pruning involves removing unused or redundant Python packages from a Django project. This process helps in maintaining a lean and secure environment by eliminating potential vulnerabilities and simplifying the project's architecture.

Dependency Pruning Overview

Dependency pruning can be performed manually or through automated tools. In the case of the CreoleCorner project, the pruning was done manually by reviewing and removing unused dependencies listed in django-app/pyproject.toml and django-app/core/settings.py.

Example Changes

  • Removed djangorestframework, since no external REST API is needed. Kept django-oauth-toolkit: the token page still uses it.
  • Replaced separate psycopg and psycopg-binary entries with psycopg[binary]>=3.2.3.
  • Removed legacy pytz dependency.

Benefits of Pruning

  1. Security: Reduces the attack surface by removing unused packages that could introduce vulnerabilities.
  2. Maintainability: Simplifies the project's dependency structure, making it easier to manage and update.
  3. Smaller installs: Fewer packages to download and install, which keeps environments and container images lighter.

Example Code

# Before
dependencies = [
    "django>=5.1.3",
    "psycopg-binary>=3.2.3",
    "psycopg>=3.2.3",
    "werkzeug>=3.1.3",
    "django-extensions>=3.2.3",
    "django-htmx>=1.21.0",
    "django-oauth-toolkit>=3.0.1",
    "djangorestframework>=3.15.2",
    "gunicorn>=23.0.0",
    "whitenoise>=6.8.2",
    "pytz>=2024.2",
    "markdown>=3.7",
    "pygments>=2.18.0",
    "django-environ>=0.11.2",
]

# After
dependencies = [
    "django>=5.1.3",
    "psycopg[binary]>=3.2.3",
    "werkzeug>=3.1.3",
    "django-extensions>=3.2.3",
    "django-htmx>=1.21.0",
    "django-oauth-toolkit>=3.0.1",
    "gunicorn>=23.0.0",
    "whitenoise>=6.8.2",
    "markdown>=3.7",
    "pygments>=2.18.0",
    "django-environ>=0.11.2",
]

References

Review cards

Flashcard Why is removing an unused package a security improvement?

Every installed package is code you must track and patch for vulnerabilities. An unused one adds that work and attack surface with no benefit.

Flashcard In CreoleCorner's dependency pruning, which auth package was kept, and why?

django-oauth-toolkit: the token page still uses it. Only djangorestframework was removed.

Quiz What replaced the separate `psycopg` and `psycopg-binary` entries?
  • psycopg2-binary
  • psycopg[binary]
  • psycopg alone
  • psycopg-binary alone

The [binary] extra installs psycopg 3 together with its prebuilt binary package, in a single entry.