SessionArmor 0.1.0__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. sessionarmor-0.5.0/CHANGELOG.md +94 -0
  2. {sessionarmor-0.1.0 → sessionarmor-0.5.0}/LICENSE +1 -1
  3. sessionarmor-0.5.0/MANIFEST.in +9 -0
  4. sessionarmor-0.5.0/PKG-INFO +288 -0
  5. sessionarmor-0.5.0/README.md +245 -0
  6. {sessionarmor-0.1.0 → sessionarmor-0.5.0}/SECURITY.md +6 -2
  7. sessionarmor-0.5.0/docs/ACCESSGATE_INTEGRATION.md +40 -0
  8. sessionarmor-0.5.0/docs/AUDIT_SCOPE.md +17 -0
  9. sessionarmor-0.5.0/docs/RELEASE.md +18 -0
  10. sessionarmor-0.5.0/docs/SECURE_DEVELOPMENT.md +17 -0
  11. sessionarmor-0.5.0/docs/SECURITY_ASSURANCE.md +12 -0
  12. sessionarmor-0.5.0/docs/THREAT_MODEL.md +42 -0
  13. sessionarmor-0.5.0/docs/security-model.md +58 -0
  14. sessionarmor-0.5.0/mcp/README.md +35 -0
  15. sessionarmor-0.5.0/mcp/agent-contract.json +128 -0
  16. sessionarmor-0.5.0/mcp/server.py +14 -0
  17. {sessionarmor-0.1.0 → sessionarmor-0.5.0}/pyproject.toml +23 -11
  18. sessionarmor-0.5.0/requirements/build.in +5 -0
  19. sessionarmor-0.5.0/setup.cfg +4 -0
  20. sessionarmor-0.5.0/src/SessionArmor.egg-info/PKG-INFO +288 -0
  21. sessionarmor-0.5.0/src/SessionArmor.egg-info/SOURCES.txt +51 -0
  22. sessionarmor-0.5.0/src/SessionArmor.egg-info/dependency_links.txt +1 -0
  23. sessionarmor-0.5.0/src/SessionArmor.egg-info/entry_points.txt +2 -0
  24. sessionarmor-0.5.0/src/SessionArmor.egg-info/requires.txt +14 -0
  25. sessionarmor-0.5.0/src/SessionArmor.egg-info/top_level.txt +1 -0
  26. sessionarmor-0.5.0/src/session_armor/__init__.py +24 -0
  27. sessionarmor-0.5.0/src/session_armor/adapters/__init__.py +1 -0
  28. sessionarmor-0.5.0/src/session_armor/adapters/django/__init__.py +12 -0
  29. sessionarmor-0.5.0/src/session_armor/adapters/django/audit.py +204 -0
  30. sessionarmor-0.5.0/src/session_armor/adapters/django/gate.py +259 -0
  31. sessionarmor-0.5.0/src/session_armor/adapters/django/session.py +386 -0
  32. sessionarmor-0.5.0/src/session_armor/adapters/django/utils.py +225 -0
  33. sessionarmor-0.5.0/src/session_armor/assurance.py +111 -0
  34. sessionarmor-0.5.0/src/session_armor/decisions.py +81 -0
  35. sessionarmor-0.5.0/src/session_armor/exceptions.py +13 -0
  36. sessionarmor-0.5.0/src/session_armor/mcp/__init__.py +1 -0
  37. sessionarmor-0.5.0/src/session_armor/mcp/agent-contract.json +128 -0
  38. sessionarmor-0.5.0/src/session_armor/mcp/server.py +306 -0
  39. sessionarmor-0.5.0/tests/conftest.py +2 -0
  40. sessionarmor-0.5.0/tests/settings.py +39 -0
  41. sessionarmor-0.5.0/tests/test_assurance.py +51 -0
  42. sessionarmor-0.5.0/tests/test_audit.py +107 -0
  43. sessionarmor-0.5.0/tests/test_gate.py +190 -0
  44. sessionarmor-0.5.0/tests/test_mcp_server.py +150 -0
  45. sessionarmor-0.5.0/tests/test_package.py +42 -0
  46. sessionarmor-0.5.0/tests/test_release_tools.py +20 -0
  47. sessionarmor-0.5.0/tests/test_session.py +219 -0
  48. sessionarmor-0.5.0/tests/test_utils.py +224 -0
  49. {sessionarmor-0.1.0 → sessionarmor-0.5.0}/tests/urls.py +2 -2
  50. sessionarmor-0.5.0/tools/__init__.py +1 -0
  51. sessionarmor-0.5.0/tools/generate_sbom.py +153 -0
  52. sessionarmor-0.1.0/.github/workflows/publish.yaml +0 -41
  53. sessionarmor-0.1.0/.github/workflows/tests.yaml +0 -49
  54. sessionarmor-0.1.0/.gitignore +0 -94
  55. sessionarmor-0.1.0/CHANGELOG.md +0 -20
  56. sessionarmor-0.1.0/PKG-INFO +0 -174
  57. sessionarmor-0.1.0/README.md +0 -138
  58. sessionarmor-0.1.0/src/session_armor/__init__.py +0 -29
  59. sessionarmor-0.1.0/src/session_armor/audit.py +0 -163
  60. sessionarmor-0.1.0/src/session_armor/gate.py +0 -213
  61. sessionarmor-0.1.0/src/session_armor/session.py +0 -263
  62. sessionarmor-0.1.0/src/session_armor/utils.py +0 -93
  63. sessionarmor-0.1.0/tests/conftest.py +0 -9
  64. sessionarmor-0.1.0/tests/settings.py +0 -36
  65. sessionarmor-0.1.0/tests/test_audit.py +0 -117
  66. sessionarmor-0.1.0/tests/test_gate.py +0 -161
  67. sessionarmor-0.1.0/tests/test_session.py +0 -154
  68. sessionarmor-0.1.0/tests/test_utils.py +0 -133
  69. {sessionarmor-0.1.0 → sessionarmor-0.5.0}/src/session_armor/py.typed +0 -0
  70. {sessionarmor-0.1.0 → sessionarmor-0.5.0}/tests/__init__.py +0 -0
@@ -0,0 +1,94 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.5.0] - 2026-08-16
11
+
12
+ ### Changed
13
+
14
+ - Split the dependency-free assurance and gate-decision contracts from the
15
+ optional Django middleware adapter.
16
+ - Moved Django middleware imports to `session_armor.adapters.django` and made
17
+ Django installable through the `SessionArmor[django]` extra.
18
+ - Removed the old root and module-level middleware imports so framework
19
+ boundaries remain explicit.
20
+
21
+ ### Fixed
22
+
23
+ - Use Django session mapping views when inspecting session keys, avoiding
24
+ `KeyError: 0` during real `SessionStore` initialization and validation.
25
+
26
+ ## [0.4.0] - 2026-08-15
27
+
28
+ ### Security
29
+
30
+ - Replaced ambiguous unkeyed fingerprint and claim digests with keyed,
31
+ domain-separated HMAC-SHA256 over a length-framed representation and
32
+ constant-time comparison.
33
+ - Added strict validation for session state version, completeness, timestamps,
34
+ future clock values, security settings, proxy chains, factor inputs, and
35
+ extension-hook outputs. Invalid state is flushed and fails closed.
36
+ - Forwarded headers are now ignored by default. Enabling them requires exact
37
+ trusted proxy CIDRs and a bounded hop count; catch-all CIDRs are rejected.
38
+ - Gate results are typed `GateDecision` values, cache entries are bound to the
39
+ subject/session scope, malformed cache values are ignored, and unbounded
40
+ sticky approvals are never reused.
41
+ - Audit records use full 128-bit request IDs, structured JSON, recursive value
42
+ validation, reserved-field protection, explicit suppression policy, and
43
+ exception-path events.
44
+
45
+ ### Added
46
+
47
+ - Immutable `SessionAssurance` evidence on every request and a stable,
48
+ primitive-only authorization context contract for AccessGate.
49
+ - Public `rebaseline_claims()` API for reviewed server-side identity changes.
50
+ - AccessGate integration, threat model, secure-development, audit-scope, and
51
+ release documentation.
52
+
53
+ ### Changed
54
+
55
+ - The runtime dependency is bounded to the tested Django 4.2 and 5.2 release
56
+ lines; unsupported future major versions cannot be selected silently.
57
+ - Security settings are consistently namespaced under `SESSION_ARMOR_*`.
58
+ - Gate hooks now consume and return `GateDecision`; error paths cannot opt into
59
+ pass-through.
60
+ - Private `_ss_*` state is migrated to versioned `_sa_*` state on the next
61
+ authenticated request, rotating the Django session key.
62
+
63
+ ## [0.3.0] - 2026-07-15
64
+
65
+ ### Security
66
+ - **Audit IP pseudonymization is now non-reversible.** `AuditMiddleware` previously logged the client IP as an unsalted, truncated SHA-256, which is trivially reversible for the small IPv4 space — defeating the "privacy-preserving" guarantee. IPs are now hashed with a keyed HMAC-SHA256 (`hash_ip()`), peppered by the new `SESSION_ARMOR_AUDIT_PEPPER` setting (falls back to `SECRET_KEY`). Hash tokens stay deterministic for correlation but change value; back-compat with previously logged tokens is intentionally broken.
67
+ - **`SESSION_ARMOR_TRUSTED_PROXY_DEPTH` now defaults to `1` instead of `0`.** The previous default trusted the leftmost, fully client-controlled `X-Forwarded-For` entry, allowing source-IP spoofing of fingerprint binding and audit logs when the setting was left unset (contradicting the documented default). Deployments with no reverse proxy that relied on the old leftmost behavior must set the value to `0` explicitly.
68
+ - **Audit log injection hardening.** All string fields in an audit entry — including custom `get_user_identity()` / `get_extra_fields()` values such as a JWT `sub` claim — are now run through `sanitize_for_log()`, not just `path` and `ua`. This prevents embedded newlines/control characters in attacker-influenced fields from forging log lines.
69
+ - **Exempt-path matching respects segment boundaries.** `exempt_paths` now matches on path segments (via the shared `path_is_exempt()` helper), so an exemption like `/health` no longer accidentally also exempts sibling paths such as `/health-internal`. Prefixes that already end in `/` are unaffected.
70
+
71
+ ### Added
72
+ - **`GateMiddleware.sticky_pass_max_age`** — optional absolute lifetime cap (seconds) for sticky passes (`recheck_after_pass=False`). Set it on authorization/entitlement gates so a revoked user can't retain access indefinitely; `None` (default) keeps the previous unbounded behavior.
73
+ - **`SessionSecurityMiddleware.last_active_resolution`** — minimum seconds between `_ss_last_active` writes (default `0` = every request, unchanged). Raise it to reduce session-store write amplification on busy sessions.
74
+ - **Security CI workflow** — `bandit` static analysis (blocking) and `pip-audit` dependency scanning (non-blocking, plus a weekly schedule) added under `.github/workflows/security.yaml`; both tools added to the `dev` extra.
75
+ - **Packaged MCP contract** — added the `sessionarmor-mcp` stdio command and public agent contract for review-first middleware, audit, gate, and rollout guidance.
76
+
77
+ ## [0.2.0] - 2026-06-12
78
+
79
+ ### Added
80
+ - **GateMiddleware `recheck_after_pass`** — set to `False` for "check once" gates (onboarding, compliance): a passing result stays cached for the whole session instead of being re-checked on a TTL. Failures still re-check on the TTL, and `invalidate()` still forces an immediate re-check.
81
+ - **GateMiddleware `get_state_version(request)` hook** — return a cheap version stamp (e.g. a Django cache key bumped when an admin publishes a new document version or adds an onboarding step) and the cached gate result is invalidated for every active session the moment the stamp changes, without per-request database hits.
82
+ - `invalidate()` now also clears the stored version stamp.
83
+
84
+ ## [0.1.0] - 2026-05-22
85
+
86
+ ### Added
87
+ - **SessionSecurityMiddleware** — Client fingerprint binding (IP + User-Agent hash), absolute/idle session timeouts, JWT claim drift detection, session fixation prevention via `cycle_key()`.
88
+ - **AuditMiddleware** — Privacy-preserving audit trail for authenticated requests with request ID correlation, hashed IPs, sanitized log entries.
89
+ - **GateMiddleware** — Base class for building cacheable, hookable conditional gates (compliance, onboarding, feature flags, maintenance).
90
+ - **Utilities** — `get_client_ip()` with proxy-depth awareness, `hash_value()`, `sanitize_for_log()` with control character stripping, `is_authenticated()`.
91
+ - Full hook system on all three middleware classes for zero-subclass-needed customization.
92
+ - `SESSION_ARMOR_TRUSTED_PROXY_DEPTH` setting to prevent X-Forwarded-For spoofing.
93
+ - `fail_open=False` as defense-grade default on GateMiddleware.
94
+ - CI/CD with GitHub Actions (tests on Python 3.10–3.13, PyPI publishing via trusted publishing).
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024-2026 Alex C
3
+ Copyright (c) 2024-2026 Tunet Ltd
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,9 @@
1
+ include CHANGELOG.md
2
+ include LICENSE
3
+ include README.md
4
+ include SECURITY.md
5
+ recursive-include docs *.md
6
+ recursive-include mcp *.json *.md *.py
7
+ recursive-include requirements *.in
8
+ recursive-include tests *.py
9
+ recursive-include tools *.py
@@ -0,0 +1,288 @@
1
+ Metadata-Version: 2.4
2
+ Name: SessionArmor
3
+ Version: 0.5.0
4
+ Summary: Framework-neutral session-assurance contracts with optional security adapters.
5
+ Author-email: Tunet Ltd <alex@tunet.xyz>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Tunet-xyz/session_armor
8
+ Project-URL: Product, https://tunet.xyz/engineering/session-armor/
9
+ Project-URL: Documentation, https://github.com/Tunet-xyz/session_armor#readme
10
+ Project-URL: Repository, https://github.com/Tunet-xyz/session_armor
11
+ Project-URL: Issues, https://github.com/Tunet-xyz/session_armor/issues
12
+ Project-URL: Changelog, https://github.com/Tunet-xyz/session_armor/blob/main/CHANGELOG.md
13
+ Keywords: django,middleware,security,session,audit,gates,nist,owasp
14
+ Classifier: Framework :: Django
15
+ Classifier: Framework :: Django :: 4.2
16
+ Classifier: Framework :: Django :: 5.0
17
+ Classifier: Framework :: Django :: 5.1
18
+ Classifier: Framework :: Django :: 5.2
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Security
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Intended Audience :: Developers
27
+ Requires-Python: >=3.10
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Provides-Extra: django
31
+ Requires-Dist: Django<6,>=4.2; extra == "django"
32
+ Provides-Extra: dev
33
+ Requires-Dist: Django<6,>=4.2; extra == "dev"
34
+ Requires-Dist: pytest>=8.0; extra == "dev"
35
+ Requires-Dist: pytest-django>=4.5; extra == "dev"
36
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
37
+ Requires-Dist: ruff>=0.4; extra == "dev"
38
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
39
+ Requires-Dist: django-stubs>=4.2.0; extra == "dev"
40
+ Requires-Dist: bandit>=1.7; extra == "dev"
41
+ Requires-Dist: pip-audit>=2.7; extra == "dev"
42
+ Dynamic: license-file
43
+
44
+ # SessionArmor
45
+
46
+ [![Tests](https://github.com/Tunet-xyz/session_armor/actions/workflows/tests.yaml/badge.svg)](https://github.com/Tunet-xyz/session_armor/actions/workflows/tests.yaml)
47
+ [![PyPI version](https://badge.fury.io/py/SessionArmor.svg)](https://pypi.org/project/SessionArmor/)
48
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
49
+ [![Django 4.2-5.2](https://img.shields.io/badge/django-4.2--5.2-green.svg)](https://www.djangoproject.com/)
50
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
51
+
52
+ **Framework-neutral session-assurance contracts with an optional Django adapter for session integrity, privacy-aware audit logging, and configurable request gates.**
53
+
54
+ Part of the [Tunet](https://tunet.xyz/engineering/) ecosystem — alongside [SwapLayer](https://github.com/Tunet-xyz/swap_layer) and [InfraGlyph](https://github.com/Tunet-xyz/infra_glyph). See the [SessionArmor product page](https://tunet.xyz/engineering/session-armor/) for the public capability overview.
55
+
56
+ ---
57
+
58
+ ## What It Does
59
+
60
+ The dependency-free core provides immutable assurance evidence and typed gate
61
+ decisions. The optional Django adapter provides three drop-in middleware classes
62
+ that harden an application's session layer:
63
+
64
+ | Middleware | Purpose |
65
+ |-----------|---------|
66
+ | `SessionSecurityMiddleware` | Keyed continuity binding, validated absolute/idle timeouts, claim drift detection, and typed assurance evidence |
67
+ | `AuditMiddleware` | Structured, privacy-aware security audit events for authenticated request outcomes |
68
+ | `GateMiddleware` | Typed, identity-bound workflow gates with bounded, revocation-aware caching |
69
+
70
+ All three are **hookable** — override methods to customize behavior without touching internals.
71
+
72
+ ## References
73
+
74
+ - [NIST SP 800-53 AC-12](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Session Termination)
75
+ - [NIST SP 800-53 SC-23](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Session Authenticity)
76
+ - [NIST SP 800-53 AU-3/AU-12](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Audit Content/Generation)
77
+ - [OWASP Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
78
+
79
+ SessionArmor adds controls around an existing Django authentication and session setup; it does not replace HTTPS, secure cookie settings, CSRF protection, authorization, MFA, or incident response. Fingerprint binding is a replay signal rather than proof of device identity and can require tuning for mobile or privacy-network traffic. See the [security model](docs/security-model.md) for deployment assumptions, limitations, and a release checklist.
80
+
81
+ ---
82
+
83
+ ## Installation
84
+
85
+ ```bash
86
+ pip install SessionArmor
87
+ ```
88
+
89
+ The core install has no framework dependency. Install the Django adapter when
90
+ middleware integration is required:
91
+
92
+ ```bash
93
+ pip install "SessionArmor[django]"
94
+ ```
95
+
96
+ ## Quick Start
97
+
98
+ ```python
99
+ # settings.py
100
+ MIDDLEWARE = [
101
+ 'django.middleware.security.SecurityMiddleware',
102
+ 'django.contrib.sessions.middleware.SessionMiddleware',
103
+ # ... your auth middleware ...
104
+ 'session_armor.adapters.django.SessionSecurityMiddleware',
105
+ 'session_armor.adapters.django.AuditMiddleware',
106
+ # ... rest of your middleware ...
107
+ ]
108
+
109
+ # Optional settings (shown with defaults)
110
+ SESSION_ARMOR_ABSOLUTE_TIMEOUT = 28800
111
+ SESSION_ARMOR_IDLE_TIMEOUT = 1800
112
+ SESSION_ARMOR_BIND_IP = True
113
+ SESSION_ARMOR_BIND_USER_AGENT = True
114
+ SESSION_ARMOR_DETECT_CLAIM_DRIFT = True
115
+ SESSION_ARMOR_REQUIRE_BINDING = True
116
+ SESSION_ARMOR_CLOCK_SKEW = 60
117
+ SESSION_ARMOR_LAST_ACTIVE_RESOLUTION = 0
118
+ SESSION_ARMOR_NO_STORE = True
119
+ SESSION_ARMOR_STATE_KEY = SECRET_KEY
120
+ SESSION_ARMOR_AUDIT_PEPPER = SECRET_KEY
121
+
122
+ # Forwarded headers are ignored unless both values are configured.
123
+ SESSION_ARMOR_TRUSTED_PROXY_DEPTH = 0
124
+ SESSION_ARMOR_TRUSTED_PROXY_CIDRS = ()
125
+ ```
126
+
127
+ > **Note on audit IP hashing.** Audit logs pseudonymize the client IP with a
128
+ > keyed HMAC-SHA256 so the value can't be reversed from the (low-entropy) IPv4
129
+ > space. Set a dedicated `SESSION_ARMOR_AUDIT_PEPPER` to rotate it independently
130
+ > of `SECRET_KEY`, or to share it across services for cross-log correlation.
131
+ > If unset, it falls back to `SECRET_KEY`.
132
+
133
+ > **Note on proxy trust.** The secure default (`DEPTH = 0`) ignores
134
+ > `X-Forwarded-For`. To use it, configure both the exact number of proxy hops
135
+ > and their CIDR ranges. Each trusted hop is checked from the socket peer back
136
+ > toward the client; malformed chains and catch-all trusted networks are rejected.
137
+
138
+ ## Building a Gate
139
+
140
+ ```python
141
+ from session_armor import GateDecision
142
+ from session_armor.adapters.django import GateMiddleware
143
+ from django.shortcuts import redirect
144
+
145
+ class ComplianceGate(GateMiddleware):
146
+ gate_id = 'compliance'
147
+ cache_ttl_setting = 'COMPLIANCE_CACHE_TTL'
148
+ default_cache_ttl = 3600
149
+ requires_trusted_session = True
150
+
151
+ def check(self, request) -> GateDecision:
152
+ if user_accepted_current_terms(request):
153
+ return GateDecision.allow('current_terms_accepted')
154
+ return GateDecision.reject('terms_acceptance_required')
155
+
156
+ def on_reject(self, request, decision):
157
+ return redirect('/accept-terms/')
158
+ ```
159
+
160
+ ### "Check once" gates
161
+
162
+ For gates that should only kick in once (onboarding, compliance), set
163
+ `recheck_after_pass = False`: a passing result stays cached in the session
164
+ with no TTL re-checks. To push new requirements to already-passed sessions
165
+ (a new document version, a new onboarding step), implement
166
+ `get_state_version()` against a shared cache key and bump that key on
167
+ publish — every active session re-checks exactly once, with no per-request
168
+ database hits:
169
+
170
+ ```python
171
+ from django.core.cache import cache
172
+
173
+ class ComplianceGate(GateMiddleware):
174
+ gate_id = 'compliance'
175
+ recheck_after_pass = False # Pass once, stay passed
176
+
177
+ def get_state_version(self, request) -> str | None:
178
+ # Bumped by admin tooling when a new document version is published
179
+ return cache.get(f'compliance_version:{request.user.platform}', '')
180
+
181
+ def check(self, request) -> GateDecision:
182
+ return (
183
+ GateDecision.allow('current_terms_accepted')
184
+ if user_accepted_current_terms(request)
185
+ else GateDecision.reject('terms_acceptance_required')
186
+ )
187
+ ```
188
+
189
+ > **Sticky passes and revocation.** With `recheck_after_pass = False`, a pass
190
+ > is cached until the session ends, `invalidate()` is called, or the state
191
+ > version changes — so it is **not** appropriate for authorization/entitlement
192
+ > gates where access may be revoked. For those, use a normal TTL gate, drive
193
+ > `get_state_version()`, or set `sticky_pass_max_age` (seconds) to cap how long
194
+ > a sticky pass may be reused before a forced re-check.
195
+
196
+ ## Customizing Session Security
197
+
198
+ ```python
199
+ from session_armor.adapters.django import SessionSecurityMiddleware
200
+
201
+ class MySessionSecurity(SessionSecurityMiddleware):
202
+ exempt_paths = ('/health/', '/static/')
203
+ last_active_resolution = 60 # only rewrite last-active timestamp every 60s
204
+
205
+ def get_critical_claims(self, user):
206
+ # Auth0 / OIDC claims that must not change mid-session
207
+ return [user.sub, user.organization_uuid, user.platform]
208
+
209
+ def get_login_url(self, request):
210
+ platform = getattr(request.user, 'platform', '')
211
+ return f'/{platform}/login/' if platform else '/login/'
212
+
213
+ # After a reviewed server-side claim update, use the public API rather than
214
+ # writing SessionArmor's private session keys.
215
+ MySessionSecurity(lambda request: request).rebaseline_claims(request)
216
+ ```
217
+
218
+ ## AccessGate integration
219
+
220
+ SessionArmor and AccessGate are complementary boundaries. SessionArmor decides
221
+ whether the authenticated session is still trustworthy and attaches an immutable
222
+ `request.session_assurance` record. AccessGate's Django adapter carries that
223
+ record into authorization context, where `SessionAssurancePolicy` denies stale,
224
+ missing, malformed, or subject-mismatched evidence before business policies may
225
+ grant an action:
226
+
227
+ ```python
228
+ from access_gate import AuthorizationEngine, RolePolicy, SessionAssurancePolicy
229
+
230
+ engine = AuthorizationEngine([
231
+ SessionAssurancePolicy(actions={'records.read'}),
232
+ RolePolicy({'records_reader'}, actions={'records.read'}),
233
+ ])
234
+ ```
235
+
236
+ The assurance policy is deny-only: a trusted session never grants a permission
237
+ by itself. See [`docs/ACCESSGATE_INTEGRATION.md`](docs/ACCESSGATE_INTEGRATION.md).
238
+
239
+ ## Customizing Audit Logging
240
+
241
+ ```python
242
+ from session_armor.adapters.django import AuditMiddleware
243
+
244
+ class MyAudit(AuditMiddleware):
245
+ exempt_paths = ('/health/', '/static/', '/favicon.ico')
246
+
247
+ def get_user_identity(self, request):
248
+ return {
249
+ 'uid': request.user.sub,
250
+ 'platform': request.user.platform,
251
+ 'org': request.user.organization_uuid,
252
+ }
253
+ ```
254
+
255
+ ---
256
+
257
+ ## Development
258
+
259
+ ```bash
260
+ # Clone and install
261
+ git clone https://github.com/Tunet-xyz/session_armor.git
262
+ cd session_armor
263
+ pip install -e ".[dev]"
264
+
265
+ # Run tests
266
+ pytest
267
+
268
+ # Lint
269
+ ruff check src/session_armor tests
270
+
271
+ # Type check
272
+ mypy src/session_armor
273
+ ```
274
+
275
+
276
+ ## Public Agent MCP Contract
277
+
278
+ SessionArmor includes a public agent-operability contract in [`mcp/`](mcp/). It describes how external agents can safely help with middleware ordering, security settings, audit customization, gate design, browser-visible docs, and rollout planning without requiring source-code access or production session data.
279
+
280
+ From a checkout, run the dependency-free contract server with `python mcp/server.py`. After installation, agents can use the packaged stdio command:
281
+
282
+ ```bash
283
+ sessionarmor-mcp
284
+ ```
285
+
286
+ ## License
287
+
288
+ MIT — Copyright (c) 2024-2026 Tunet Ltd. See [LICENSE](LICENSE).
@@ -0,0 +1,245 @@
1
+ # SessionArmor
2
+
3
+ [![Tests](https://github.com/Tunet-xyz/session_armor/actions/workflows/tests.yaml/badge.svg)](https://github.com/Tunet-xyz/session_armor/actions/workflows/tests.yaml)
4
+ [![PyPI version](https://badge.fury.io/py/SessionArmor.svg)](https://pypi.org/project/SessionArmor/)
5
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
6
+ [![Django 4.2-5.2](https://img.shields.io/badge/django-4.2--5.2-green.svg)](https://www.djangoproject.com/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ **Framework-neutral session-assurance contracts with an optional Django adapter for session integrity, privacy-aware audit logging, and configurable request gates.**
10
+
11
+ Part of the [Tunet](https://tunet.xyz/engineering/) ecosystem — alongside [SwapLayer](https://github.com/Tunet-xyz/swap_layer) and [InfraGlyph](https://github.com/Tunet-xyz/infra_glyph). See the [SessionArmor product page](https://tunet.xyz/engineering/session-armor/) for the public capability overview.
12
+
13
+ ---
14
+
15
+ ## What It Does
16
+
17
+ The dependency-free core provides immutable assurance evidence and typed gate
18
+ decisions. The optional Django adapter provides three drop-in middleware classes
19
+ that harden an application's session layer:
20
+
21
+ | Middleware | Purpose |
22
+ |-----------|---------|
23
+ | `SessionSecurityMiddleware` | Keyed continuity binding, validated absolute/idle timeouts, claim drift detection, and typed assurance evidence |
24
+ | `AuditMiddleware` | Structured, privacy-aware security audit events for authenticated request outcomes |
25
+ | `GateMiddleware` | Typed, identity-bound workflow gates with bounded, revocation-aware caching |
26
+
27
+ All three are **hookable** — override methods to customize behavior without touching internals.
28
+
29
+ ## References
30
+
31
+ - [NIST SP 800-53 AC-12](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Session Termination)
32
+ - [NIST SP 800-53 SC-23](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Session Authenticity)
33
+ - [NIST SP 800-53 AU-3/AU-12](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Audit Content/Generation)
34
+ - [OWASP Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
35
+
36
+ SessionArmor adds controls around an existing Django authentication and session setup; it does not replace HTTPS, secure cookie settings, CSRF protection, authorization, MFA, or incident response. Fingerprint binding is a replay signal rather than proof of device identity and can require tuning for mobile or privacy-network traffic. See the [security model](docs/security-model.md) for deployment assumptions, limitations, and a release checklist.
37
+
38
+ ---
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install SessionArmor
44
+ ```
45
+
46
+ The core install has no framework dependency. Install the Django adapter when
47
+ middleware integration is required:
48
+
49
+ ```bash
50
+ pip install "SessionArmor[django]"
51
+ ```
52
+
53
+ ## Quick Start
54
+
55
+ ```python
56
+ # settings.py
57
+ MIDDLEWARE = [
58
+ 'django.middleware.security.SecurityMiddleware',
59
+ 'django.contrib.sessions.middleware.SessionMiddleware',
60
+ # ... your auth middleware ...
61
+ 'session_armor.adapters.django.SessionSecurityMiddleware',
62
+ 'session_armor.adapters.django.AuditMiddleware',
63
+ # ... rest of your middleware ...
64
+ ]
65
+
66
+ # Optional settings (shown with defaults)
67
+ SESSION_ARMOR_ABSOLUTE_TIMEOUT = 28800
68
+ SESSION_ARMOR_IDLE_TIMEOUT = 1800
69
+ SESSION_ARMOR_BIND_IP = True
70
+ SESSION_ARMOR_BIND_USER_AGENT = True
71
+ SESSION_ARMOR_DETECT_CLAIM_DRIFT = True
72
+ SESSION_ARMOR_REQUIRE_BINDING = True
73
+ SESSION_ARMOR_CLOCK_SKEW = 60
74
+ SESSION_ARMOR_LAST_ACTIVE_RESOLUTION = 0
75
+ SESSION_ARMOR_NO_STORE = True
76
+ SESSION_ARMOR_STATE_KEY = SECRET_KEY
77
+ SESSION_ARMOR_AUDIT_PEPPER = SECRET_KEY
78
+
79
+ # Forwarded headers are ignored unless both values are configured.
80
+ SESSION_ARMOR_TRUSTED_PROXY_DEPTH = 0
81
+ SESSION_ARMOR_TRUSTED_PROXY_CIDRS = ()
82
+ ```
83
+
84
+ > **Note on audit IP hashing.** Audit logs pseudonymize the client IP with a
85
+ > keyed HMAC-SHA256 so the value can't be reversed from the (low-entropy) IPv4
86
+ > space. Set a dedicated `SESSION_ARMOR_AUDIT_PEPPER` to rotate it independently
87
+ > of `SECRET_KEY`, or to share it across services for cross-log correlation.
88
+ > If unset, it falls back to `SECRET_KEY`.
89
+
90
+ > **Note on proxy trust.** The secure default (`DEPTH = 0`) ignores
91
+ > `X-Forwarded-For`. To use it, configure both the exact number of proxy hops
92
+ > and their CIDR ranges. Each trusted hop is checked from the socket peer back
93
+ > toward the client; malformed chains and catch-all trusted networks are rejected.
94
+
95
+ ## Building a Gate
96
+
97
+ ```python
98
+ from session_armor import GateDecision
99
+ from session_armor.adapters.django import GateMiddleware
100
+ from django.shortcuts import redirect
101
+
102
+ class ComplianceGate(GateMiddleware):
103
+ gate_id = 'compliance'
104
+ cache_ttl_setting = 'COMPLIANCE_CACHE_TTL'
105
+ default_cache_ttl = 3600
106
+ requires_trusted_session = True
107
+
108
+ def check(self, request) -> GateDecision:
109
+ if user_accepted_current_terms(request):
110
+ return GateDecision.allow('current_terms_accepted')
111
+ return GateDecision.reject('terms_acceptance_required')
112
+
113
+ def on_reject(self, request, decision):
114
+ return redirect('/accept-terms/')
115
+ ```
116
+
117
+ ### "Check once" gates
118
+
119
+ For gates that should only kick in once (onboarding, compliance), set
120
+ `recheck_after_pass = False`: a passing result stays cached in the session
121
+ with no TTL re-checks. To push new requirements to already-passed sessions
122
+ (a new document version, a new onboarding step), implement
123
+ `get_state_version()` against a shared cache key and bump that key on
124
+ publish — every active session re-checks exactly once, with no per-request
125
+ database hits:
126
+
127
+ ```python
128
+ from django.core.cache import cache
129
+
130
+ class ComplianceGate(GateMiddleware):
131
+ gate_id = 'compliance'
132
+ recheck_after_pass = False # Pass once, stay passed
133
+
134
+ def get_state_version(self, request) -> str | None:
135
+ # Bumped by admin tooling when a new document version is published
136
+ return cache.get(f'compliance_version:{request.user.platform}', '')
137
+
138
+ def check(self, request) -> GateDecision:
139
+ return (
140
+ GateDecision.allow('current_terms_accepted')
141
+ if user_accepted_current_terms(request)
142
+ else GateDecision.reject('terms_acceptance_required')
143
+ )
144
+ ```
145
+
146
+ > **Sticky passes and revocation.** With `recheck_after_pass = False`, a pass
147
+ > is cached until the session ends, `invalidate()` is called, or the state
148
+ > version changes — so it is **not** appropriate for authorization/entitlement
149
+ > gates where access may be revoked. For those, use a normal TTL gate, drive
150
+ > `get_state_version()`, or set `sticky_pass_max_age` (seconds) to cap how long
151
+ > a sticky pass may be reused before a forced re-check.
152
+
153
+ ## Customizing Session Security
154
+
155
+ ```python
156
+ from session_armor.adapters.django import SessionSecurityMiddleware
157
+
158
+ class MySessionSecurity(SessionSecurityMiddleware):
159
+ exempt_paths = ('/health/', '/static/')
160
+ last_active_resolution = 60 # only rewrite last-active timestamp every 60s
161
+
162
+ def get_critical_claims(self, user):
163
+ # Auth0 / OIDC claims that must not change mid-session
164
+ return [user.sub, user.organization_uuid, user.platform]
165
+
166
+ def get_login_url(self, request):
167
+ platform = getattr(request.user, 'platform', '')
168
+ return f'/{platform}/login/' if platform else '/login/'
169
+
170
+ # After a reviewed server-side claim update, use the public API rather than
171
+ # writing SessionArmor's private session keys.
172
+ MySessionSecurity(lambda request: request).rebaseline_claims(request)
173
+ ```
174
+
175
+ ## AccessGate integration
176
+
177
+ SessionArmor and AccessGate are complementary boundaries. SessionArmor decides
178
+ whether the authenticated session is still trustworthy and attaches an immutable
179
+ `request.session_assurance` record. AccessGate's Django adapter carries that
180
+ record into authorization context, where `SessionAssurancePolicy` denies stale,
181
+ missing, malformed, or subject-mismatched evidence before business policies may
182
+ grant an action:
183
+
184
+ ```python
185
+ from access_gate import AuthorizationEngine, RolePolicy, SessionAssurancePolicy
186
+
187
+ engine = AuthorizationEngine([
188
+ SessionAssurancePolicy(actions={'records.read'}),
189
+ RolePolicy({'records_reader'}, actions={'records.read'}),
190
+ ])
191
+ ```
192
+
193
+ The assurance policy is deny-only: a trusted session never grants a permission
194
+ by itself. See [`docs/ACCESSGATE_INTEGRATION.md`](docs/ACCESSGATE_INTEGRATION.md).
195
+
196
+ ## Customizing Audit Logging
197
+
198
+ ```python
199
+ from session_armor.adapters.django import AuditMiddleware
200
+
201
+ class MyAudit(AuditMiddleware):
202
+ exempt_paths = ('/health/', '/static/', '/favicon.ico')
203
+
204
+ def get_user_identity(self, request):
205
+ return {
206
+ 'uid': request.user.sub,
207
+ 'platform': request.user.platform,
208
+ 'org': request.user.organization_uuid,
209
+ }
210
+ ```
211
+
212
+ ---
213
+
214
+ ## Development
215
+
216
+ ```bash
217
+ # Clone and install
218
+ git clone https://github.com/Tunet-xyz/session_armor.git
219
+ cd session_armor
220
+ pip install -e ".[dev]"
221
+
222
+ # Run tests
223
+ pytest
224
+
225
+ # Lint
226
+ ruff check src/session_armor tests
227
+
228
+ # Type check
229
+ mypy src/session_armor
230
+ ```
231
+
232
+
233
+ ## Public Agent MCP Contract
234
+
235
+ SessionArmor includes a public agent-operability contract in [`mcp/`](mcp/). It describes how external agents can safely help with middleware ordering, security settings, audit customization, gate design, browser-visible docs, and rollout planning without requiring source-code access or production session data.
236
+
237
+ From a checkout, run the dependency-free contract server with `python mcp/server.py`. After installation, agents can use the packaged stdio command:
238
+
239
+ ```bash
240
+ sessionarmor-mcp
241
+ ```
242
+
243
+ ## License
244
+
245
+ MIT — Copyright (c) 2024-2026 Tunet Ltd. See [LICENSE](LICENSE).
@@ -4,7 +4,9 @@
4
4
 
5
5
  | Version | Supported |
6
6
  | ------- | ------------------ |
7
- | 0.1.x | :white_check_mark: |
7
+ | 0.4.x | :white_check_mark: |
8
+ | 0.3.x | Security fixes only during migration |
9
+ | < 0.3 | :x: |
8
10
 
9
11
  ## Reporting a Vulnerability
10
12
 
@@ -14,7 +16,7 @@ We take security seriously. If you discover a security vulnerability in SessionA
14
16
 
15
17
  **Please DO NOT open a public GitHub issue for security vulnerabilities.**
16
18
 
17
- Instead, please email security concerns to: **alex@coded.uk**
19
+ Instead, please email security concerns to: **alex@tunet.xyz**
18
20
 
19
21
  Include the following in your report:
20
22
  - Description of the vulnerability
@@ -36,6 +38,8 @@ The following are in scope:
36
38
  - Log injection via sanitization bypass
37
39
  - X-Forwarded-For spoofing past proxy depth controls
38
40
  - Any bypass of gate middleware security checks
41
+ - Session-assurance confusion, subject mismatch, or stale-evidence acceptance
42
+ - Malformed cached/session state that produces an authenticated pass-through
39
43
 
40
44
  ### Out of Scope
41
45