Tunet Engineering

Security-focused session middleware

SessionArmor

Session hardening.

Add session integrity controls to Django with three hookable middleware classes for continuity signals, privacy-aware audit logging and revocable access gates.

pip install "SessionArmor[django]"

Installation

Reference controls

  • NIST AC-12
  • NIST SC-23
  • NIST AU-3
  • OWASP
  • Django 4.2–5.2
  • Python 3.10+
decisions.pySessionArmor 0.5.0
from session_armor import AssuranceStatus, GateDecision, SessionAssurance

ok = GateDecision.allow("current_terms_accepted")
no = GateDecision.reject(
    "terms_acceptance_required", context={"doc_version": 3}
)
print(ok.outcome.value, ok.passed, ok.reason)
print(no.outcome.value, no.passed, no.reason, dict(no.context))

for bad in (True, "pass"):  # truthy values are not decisions
    try:
        GateDecision(bad, "ok")
    except TypeError as error:
        print(f"GateDecision({bad!r}) ->", error)

try:  # "trusted" cannot be asserted without evidence
    SessionAssurance(status=AssuranceStatus.TRUSTED, reason="validated")
except ValueError as error:
    print("trusted w/o evidence ->", error)

assurance = SessionAssurance.unverified("unauthenticated")
ctx = assurance.to_authorization_context()
print({k: ctx[k] for k in ("schema", "status", "reason")})

python decisions.py

pass True current_terms_accepted
reject False terms_acceptance_required {'doc_version': 3}
GateDecision(True) -> gate outcome must be a GateOutcome value.
GateDecision('pass') -> gate outcome must be a GateOutcome value.
trusted w/o evidence -> trusted assurance requires complete session evidence.
{'schema': 'session-armor.assurance/v1', 'status': 'unverified', 'reason': 'unauthenticated'}
Real output: SessionArmor 0.5.0 from PyPI, run with Python 3.13 and Django 5.2.
session_binding.pySessionArmor 0.5.0
import django
from django.conf import settings

settings.configure(
    SECRET_KEY="docs-only-example-secret-key",
    ROOT_URLCONF=__name__,
    LOGIN_URL="/login/",
)
django.setup()
urlpatterns = []

from types import SimpleNamespace
from django.contrib.sessions.backends.cache import SessionStore
from django.http import HttpResponse
from django.test import RequestFactory
from session_armor.adapters.django import SessionSecurityMiddleware

guard = SessionSecurityMiddleware(lambda request: HttpResponse("ok"))
user = SimpleNamespace(
    is_authenticated=True, sub="auth0|alice", email="alice@example.com"
)
session = SessionStore()


def visit(ip):
    request = RequestFactory().get(
        "/account/", REMOTE_ADDR=ip, HTTP_USER_AGENT="Firefox/131"
    )
    request.user, request.session = user, session
    response = guard(request)
    reason = request.session_assurance.reason
    print(ip, response.status_code, response.get("Location", "-"), reason)


visit("192.0.2.10")    # first request binds the session
visit("192.0.2.10")    # same network: trusted
visit("198.51.100.7")  # same cookie, different network
visit("192.0.2.10")
user.email = "mallory@example.com"
visit("192.0.2.10")    # identity claim changed mid-session

python session_binding.py

192.0.2.10 200 - validated
192.0.2.10 200 - validated
198.51.100.7 302 /login/ fingerprint_mismatch
192.0.2.10 200 - validated
192.0.2.10 302 /login/ claim_drift
Real output: SessionArmor 0.5.0 from PyPI, run with Python 3.13 and Django 5.2.
gate_audit.pySessionArmor 0.5.0
import json
import logging

import django
from django.conf import settings

settings.configure(SECRET_KEY="docs-only-example-secret-key")
django.setup()


class ShowAuditEvent(logging.Handler):
    """Print each audit event as readable JSON instead of one long line."""

    def emit(self, record):
        prefix, _, payload = record.getMessage().partition(" ")
        print(record.levelname, prefix)
        print(json.dumps(json.loads(payload), indent=2))


audit_log = logging.getLogger("security.audit")
audit_log.addHandler(ShowAuditEvent())
audit_log.setLevel(logging.DEBUG)

from types import SimpleNamespace
from django.contrib.sessions.backends.cache import SessionStore
from django.http import HttpResponse
from django.test import RequestFactory
from session_armor import GateDecision
from session_armor.adapters.django import AuditMiddleware, GateMiddleware


class ComplianceGate(GateMiddleware):
    gate_id = "compliance"

    def check(self, request):
        if request.user.accepted_terms:
            return GateDecision.allow("current_terms_accepted")
        return GateDecision.reject("terms_acceptance_required")


app = AuditMiddleware(ComplianceGate(lambda request: HttpResponse("ok")))
request = RequestFactory().post(
    "/records/", REMOTE_ADDR="192.0.2.10", HTTP_USER_AGENT="Firefox/131"
)
request.user = SimpleNamespace(
    is_authenticated=True, sub="auth0|alice", accepted_terms=False
)
request.session = SessionStore()
print("response:", app(request).status_code)

python gate_audit.py

WARNING AUDIT_DENIED
{
  "duration_ms": 0,
  "event": "request.completed",
  "ip_hash": "d28e606551a74de17dc3d2177b0416b6",
  "method": "POST",
  "path": "/records/",
  "rid": "56b6d20a7436498eb6aa38d33f32fa06",
  "status": 403,
  "ua": "Firefox/131",
  "uid": "auth0|alice"
}
response: 403
Real output: SessionArmor 0.5.0 from PyPI, run with Python 3.13 and Django 5.2.

Each window shows a snippet exactly as it was run and the output it printed, using the version published on PyPI.

01Middleware

Two middleware, one gate base class

SessionSecurityMiddleware and AuditMiddleware work on their own. Subclass GateMiddleware for workflow gates. Each class solves a distinct security problem.

SessionSecurity

Applies configurable request-context continuity signals, absolute and idle timeouts, and selected claim-drift checks.

  • IP + User-Agent fingerprint binding
  • 8h absolute / 30min idle timeouts
  • Identity-claim drift detection (sub and email by default)
  • Customizable exempt paths

AuditMiddleware

Privacy-aware authenticated-request events with keyed IP pseudonyms, safe field handling, and customizable identity hooks.

  • One audit event per authenticated request
  • Customizable identity extraction
  • AU-3 / AU-12 reference structure
  • Hookable via method overrides

GateMiddleware

Base class for building cacheable conditional gates — compliance checks, onboarding flows, feature flags.

  • Cacheable gate results
  • Typed fail-closed decisions
  • Custom check + on_reject hooks
  • Composable with other middleware

02Capabilities

Security capabilities.

Defence-in-depth controls for an existing, correctly configured Django authentication and session stack.

Fingerprint binding

Configurable IP and User-Agent continuity signals can invalidate a session when its request context changes.

  • IP address binding (configurable)
  • User-Agent binding (configurable)
  • Trusted proxy depth support

Timeout enforcement

Dual timeout strategy — absolute limit prevents stale sessions, idle limit catches abandoned ones.

  • 8-hour absolute timeout (default)
  • 30-minute idle timeout (default)
  • Supports AC-12-oriented timeout policy

Claim drift detection

Detects when selected authenticated claims change mid-session and applies the configured rejection response.

  • Monitors critical claims per request
  • Customizable claim selection
  • SC-23-oriented continuity control

Audit trail

Structured authenticated-request events with keyed IP pseudonyms, field sanitization, and customizable identity hooks.

  • Structured JSON audit events
  • Exempt path filtering
  • AU-3/AU-12-oriented event structure

Also in the package

Gate lifecycle

Revocable cached decisions

Use TTL rechecks, explicit invalidation, shared state versions, or sticky_pass_max_age so long-lived sessions do not retain stale gate decisions.

SessionArmor attaches read-only session evidence (schema session-armor.assurance/v1) that an authorization layer can require before granting access.

Audit privacy

Keyed pseudonyms and safe fields

Client IPs use keyed HMAC-SHA256 pseudonyms, attacker-influenced strings are sanitized, and exempt paths respect segment boundaries.

Custom fields and deterministic tokens can still be personal data and require retention/access controls.

Agent interface

Review-first MCP guidance

The packaged sessionarmor-mcp command helps agents reason about middleware ordering, settings, audit hooks, gate design, and rollout plans.

The public contract assumes no source, secret, or production-session access.

03Developer experience

Designed for hookability

Every middleware class is designed to be subclassed. Override the methods you need, keep the defaults for everything else.

  • Custom claim selection

    Override get_critical_claims() to define which Auth0/OIDC claims trigger drift detection.

  • Custom login URLs

    Override get_login_url() to send each tenant or platform to its own login flow.

  • Gate pattern

    Build compliance and onboarding gates with explicit GateDecision outcomes and identity-bound caches.

middleware/compliance.pyExample
from session_armor import GateDecision
from session_armor.adapters.django import GateMiddleware
from django.shortcuts import redirect

class ComplianceGate(GateMiddleware):
    gate_id = 'compliance'
    cache_ttl_setting = 'COMPLIANCE_CACHE_TTL'
    default_cache_ttl = 3600
    requires_trusted_session = True

    def check(self, request) -> GateDecision:
        if user_accepted_terms(request):
            return GateDecision.allow('terms_accepted')
        return GateDecision.reject('acceptance_required')

    def on_reject(self, request, decision):
        return redirect('/accept-terms/')

04Installation

Integration

Install from PyPI with the Django extra, then add the middleware to settings.py.

  1. 01Install the package

    pip install "SessionArmor[django]"

  2. 02Add middleware to settings.py

    settings.pyExample
    # settings.py
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        # ... your auth middleware ...
        'session_armor.adapters.django.SessionSecurityMiddleware',
        'session_armor.adapters.django.AuditMiddleware',
        # ... rest of your middleware ...
    ]
    
    # Optional settings (shown with defaults)
    SESSION_ARMOR_ABSOLUTE_TIMEOUT = 28800      # 8 hours
    SESSION_ARMOR_IDLE_TIMEOUT = 1800           # 30 minutes
    SESSION_ARMOR_BIND_IP = True
    SESSION_ARMOR_BIND_USER_AGENT = True
    SESSION_ARMOR_DETECT_CLAIM_DRIFT = True
    SESSION_ARMOR_TRUSTED_PROXY_DEPTH = 0       # default: X-Forwarded-For ignored
    SESSION_ARMOR_TRUSTED_PROXY_CIDRS = ()      # set both depth and CIDRs behind a proxy
    SESSION_ARMOR_AUDIT_PEPPER = SECRET_KEY  # Prefer a dedicated secret

05Security blueprint

A staged path to harden Django sessions

SessionArmor is designed for staged adoption. Start with session security, add audit logging, then build custom gates. Session and audit middleware work independently; trusted-session gates need SessionSecurityMiddleware.

Phase 1 — harden

Add SessionSecurityMiddleware. Bind sessions to fingerprints, enforce timeouts, and enable claim drift detection.

Phase 2 — observe

Add AuditMiddleware. It emits a structured JSON event for every authenticated, non-exempt request through the 'security.audit' logger, ready for your log pipeline.

Phase 3 — gate

Build custom GateMiddleware subclasses for compliance checks, onboarding flows, and feature flags.

Controls to verify before shipping

  • Fingerprints are continuity signals, not proof of device identity.
  • Absolute and idle timeout behavior is tested against the application policy.
  • Proxy depth matches the real ingress path so client-supplied forwarding data is not trusted accidentally.
  • Audit fields, retention, access controls, and gate revocation behavior are reviewed before rollout.

SessionArmor

Read the architecture paper

The paper sets out the threat and control model, the middleware boundary, audit event design, and what SessionArmor does not protect against.