SessionArmor 0.1.0__tar.gz → 1.0.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 (75) hide show
  1. sessionarmor-1.0.0/CHANGELOG.md +215 -0
  2. sessionarmor-1.0.0/CONTRIBUTING.md +23 -0
  3. {sessionarmor-0.1.0 → sessionarmor-1.0.0}/LICENSE +1 -1
  4. sessionarmor-1.0.0/MANIFEST.in +11 -0
  5. sessionarmor-1.0.0/PKG-INFO +373 -0
  6. sessionarmor-1.0.0/README.md +328 -0
  7. {sessionarmor-0.1.0 → sessionarmor-1.0.0}/SECURITY.md +5 -2
  8. sessionarmor-1.0.0/VERSIONING.md +78 -0
  9. sessionarmor-1.0.0/docs/ACCESSGATE_INTEGRATION.md +102 -0
  10. sessionarmor-1.0.0/docs/AUDIT_SCOPE.md +17 -0
  11. sessionarmor-1.0.0/docs/RELEASE.md +29 -0
  12. sessionarmor-1.0.0/docs/SECURE_DEVELOPMENT.md +17 -0
  13. sessionarmor-1.0.0/docs/SECURITY_ASSURANCE.md +12 -0
  14. sessionarmor-1.0.0/docs/THREAT_MODEL.md +45 -0
  15. sessionarmor-1.0.0/docs/security-model.md +58 -0
  16. sessionarmor-1.0.0/mcp/README.md +36 -0
  17. sessionarmor-1.0.0/mcp/agent-contract.json +129 -0
  18. sessionarmor-1.0.0/mcp/server.py +14 -0
  19. {sessionarmor-0.1.0 → sessionarmor-1.0.0}/pyproject.toml +30 -11
  20. sessionarmor-1.0.0/requirements/build.in +5 -0
  21. sessionarmor-1.0.0/requirements/build.txt +603 -0
  22. sessionarmor-1.0.0/setup.cfg +4 -0
  23. sessionarmor-1.0.0/src/SessionArmor.egg-info/PKG-INFO +373 -0
  24. sessionarmor-1.0.0/src/SessionArmor.egg-info/SOURCES.txt +56 -0
  25. sessionarmor-1.0.0/src/SessionArmor.egg-info/dependency_links.txt +1 -0
  26. sessionarmor-1.0.0/src/SessionArmor.egg-info/entry_points.txt +2 -0
  27. sessionarmor-1.0.0/src/SessionArmor.egg-info/requires.txt +15 -0
  28. sessionarmor-1.0.0/src/SessionArmor.egg-info/top_level.txt +1 -0
  29. sessionarmor-1.0.0/src/session_armor/__init__.py +24 -0
  30. sessionarmor-1.0.0/src/session_armor/adapters/__init__.py +1 -0
  31. sessionarmor-1.0.0/src/session_armor/adapters/django/__init__.py +12 -0
  32. sessionarmor-1.0.0/src/session_armor/adapters/django/audit.py +275 -0
  33. sessionarmor-1.0.0/src/session_armor/adapters/django/gate.py +349 -0
  34. sessionarmor-1.0.0/src/session_armor/adapters/django/session.py +564 -0
  35. sessionarmor-1.0.0/src/session_armor/adapters/django/utils.py +294 -0
  36. sessionarmor-1.0.0/src/session_armor/assurance.py +111 -0
  37. sessionarmor-1.0.0/src/session_armor/decisions.py +87 -0
  38. sessionarmor-1.0.0/src/session_armor/exceptions.py +13 -0
  39. sessionarmor-1.0.0/src/session_armor/mcp/__init__.py +1 -0
  40. sessionarmor-1.0.0/src/session_armor/mcp/agent-contract.json +129 -0
  41. sessionarmor-1.0.0/src/session_armor/mcp/server.py +324 -0
  42. sessionarmor-1.0.0/tests/conftest.py +2 -0
  43. sessionarmor-1.0.0/tests/settings.py +39 -0
  44. sessionarmor-1.0.0/tests/test_accessgate_bridge.py +57 -0
  45. sessionarmor-1.0.0/tests/test_assurance.py +51 -0
  46. sessionarmor-1.0.0/tests/test_audit.py +254 -0
  47. sessionarmor-1.0.0/tests/test_fail_closed_paths.py +219 -0
  48. sessionarmor-1.0.0/tests/test_gate.py +410 -0
  49. sessionarmor-1.0.0/tests/test_mcp_server.py +280 -0
  50. sessionarmor-1.0.0/tests/test_package.py +63 -0
  51. sessionarmor-1.0.0/tests/test_release_tools.py +62 -0
  52. sessionarmor-1.0.0/tests/test_session.py +633 -0
  53. sessionarmor-1.0.0/tests/test_utils.py +348 -0
  54. {sessionarmor-0.1.0 → sessionarmor-1.0.0}/tests/urls.py +2 -2
  55. sessionarmor-1.0.0/tools/__init__.py +1 -0
  56. sessionarmor-1.0.0/tools/generate_sbom.py +153 -0
  57. sessionarmor-0.1.0/.github/workflows/publish.yaml +0 -41
  58. sessionarmor-0.1.0/.github/workflows/tests.yaml +0 -49
  59. sessionarmor-0.1.0/.gitignore +0 -94
  60. sessionarmor-0.1.0/CHANGELOG.md +0 -20
  61. sessionarmor-0.1.0/PKG-INFO +0 -174
  62. sessionarmor-0.1.0/README.md +0 -138
  63. sessionarmor-0.1.0/src/session_armor/__init__.py +0 -29
  64. sessionarmor-0.1.0/src/session_armor/audit.py +0 -163
  65. sessionarmor-0.1.0/src/session_armor/gate.py +0 -213
  66. sessionarmor-0.1.0/src/session_armor/session.py +0 -263
  67. sessionarmor-0.1.0/src/session_armor/utils.py +0 -93
  68. sessionarmor-0.1.0/tests/conftest.py +0 -9
  69. sessionarmor-0.1.0/tests/settings.py +0 -36
  70. sessionarmor-0.1.0/tests/test_audit.py +0 -117
  71. sessionarmor-0.1.0/tests/test_gate.py +0 -161
  72. sessionarmor-0.1.0/tests/test_session.py +0 -154
  73. sessionarmor-0.1.0/tests/test_utils.py +0 -133
  74. {sessionarmor-0.1.0 → sessionarmor-1.0.0}/src/session_armor/py.typed +0 -0
  75. {sessionarmor-0.1.0 → sessionarmor-1.0.0}/tests/__init__.py +0 -0
@@ -0,0 +1,215 @@
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
+ ## [1.0.0] - 2026-11-05
11
+
12
+ ### Changed
13
+
14
+ - Stabilized the documented framework-neutral assurance and gate-decision APIs,
15
+ Django middleware adapters, extension hooks, and local MCP entry point.
16
+ - Adopted the shared SemVer, owner-review, manual-workflow, and immutable-release
17
+ policy in `VERSIONING.md`, with matching Claude and Codex instructions.
18
+ - Aligned package, runtime, and public MCP versions; preserved the assurance v1
19
+ schema and the 0.6 middleware behavior.
20
+ - Declared packaged MIT license files and a PEP 639-capable build backend.
21
+ - Made the hash-locked release toolchain cover Windows, Linux, and Python 3.10+
22
+ instead of relying on a Linux/Python 3.13-only dependency resolution.
23
+ - Allowed the AccessGate 1.x release in the development integration dependency.
24
+
25
+ ### Documentation
26
+
27
+ - Documented the stable API, pre-0.5 migration boundaries, supported integration
28
+ ranges, and the local-only scope of the public agent contract.
29
+
30
+ ### Security
31
+
32
+ - Updated the locked setuptools build tool to 84.2.1, addressing
33
+ GHSA-xmj3-9gf7-h52w in the previous Windows build toolchain.
34
+
35
+ ## [0.6.0] - 2026-10-29
36
+
37
+ ### Security
38
+
39
+ - `SessionSecurityMiddleware`, `GateMiddleware` and `AuditMiddleware` match
40
+ `exempt_paths` against `request.path_info` (the path Django routes on) instead
41
+ of `request.path`, so a `SCRIPT_NAME` taken from a forwarded request header
42
+ can no longer exempt a protected view. Remove any mount prefix written into
43
+ `exempt_paths`.
44
+ - An exempt path of `/` exempts only the root URL; as a prefix it used to exempt
45
+ every path from session checks, gates and audit.
46
+ - `SESSION_ARMOR_STATE_KEY`, `SESSION_ARMOR_AUDIT_PEPPER` and fallback keys must
47
+ be `str` or `bytes`; other types, such as an integer that `bytes()` turned into
48
+ a public all-zero key, raise `SessionConfigurationError`.
49
+ - `hash_ip()` hashes values in the reserved `session-armor:` namespace under a
50
+ separate derived key, so no digest can equal a state-MAC subkey when the audit
51
+ pepper and the state key share `SECRET_KEY`. Other digests are unchanged.
52
+ - Gate cache entries record the gate class that wrote them; a gate never reuses a
53
+ result cached by a different class with the same `gate_id`.
54
+ - Audit: `error_type` is reserved evidence that hooks can neither supply nor
55
+ change, `get_extra_fields()` keys that repeat identity keys raise
56
+ `AuditEmissionError`, and `before_log()` edits made in place on reserved fields
57
+ are rejected like edits on a copy.
58
+ - Audit: a client IP that cannot be validated is recorded as `ip_hash: null`
59
+ instead of losing the event, and a request whose view logs the user out is
60
+ recorded and attributed to the user it arrived with.
61
+
62
+ ### Added
63
+
64
+ - `SESSION_ARMOR_STATE_KEY_FALLBACKS` for graceful key rotation: retired keys only
65
+ verify existing state, which is then re-signed with the current key. When it is
66
+ unset, a state key that follows `SECRET_KEY` honours `SECRET_KEY_FALLBACKS`.
67
+ - `SessionSecurityMiddleware.establish(request, user=None)` binds a session during
68
+ the login request.
69
+ - `SessionSecurityMiddleware.refresh_assurance(request, user=None)` re-verifies
70
+ the session and re-issues trusted evidence right before a late authorization
71
+ decision, and `rebaseline_claims(..., refresh_assurance=True)` does the same
72
+ after a claim rebaseline, so integrations never build `SessionAssurance`.
73
+ - `SessionSecurityMiddleware.has_state()`, `discard_state()` and
74
+ `binding_digests()` replace reading the private `_sa_*`/`_ss_*` keys and
75
+ re-deriving per-factor diagnostics.
76
+ - `GateMiddleware.error_cache_ttl` caps how long a rejection from `on_error()` is
77
+ reused, `follow_session_exemptions` lets a gate follow SessionArmor's own
78
+ exemptions, and `get_cached_decision()` returns the last stored gate result.
79
+ - `AuditMiddleware.get_audit_path()` keeps secrets carried in URL paths out of
80
+ audit records; the returned path stays reserved evidence.
81
+
82
+ ### Changed
83
+
84
+ - A request without a User-Agent is bound to an explicit "absent" marker instead
85
+ of failing evaluation; a session started with a User-Agent still ends with
86
+ `fingerprint_mismatch` if the header disappears.
87
+ - IPv4-mapped IPv6 peers (`::ffff:a.b.c.d`) are returned and matched in IPv4
88
+ form. Dual-stack deployments see one `fingerprint_mismatch` per live session and
89
+ new audit `ip_hash` values for those clients after upgrading;
90
+ `::ffff:0:0/96` is rejected as a catch-all CIDR.
91
+ - With a non-zero `SESSION_ARMOR_TRUSTED_PROXY_DEPTH`, `get_client_ip` reads only
92
+ the client entry and the trusted hops, and forwarded entries may carry a port.
93
+ - `GateMiddleware` no longer converts exceptions from the view or inner
94
+ middleware into `gate_evaluation_error` rejections; only gate evaluation fails
95
+ closed.
96
+ - Evidence never reports `established_at`/`last_activity_at` later than its
97
+ `verified_at` when another instance's clock ran ahead, so AccessGate no longer
98
+ denies those sessions with `invalid_session_timeline`.
99
+ - HMAC subkeys are cached per key and purpose, and audit events the logger would
100
+ drop are validated but not rendered; stored MACs and emitted lines are
101
+ unchanged.
102
+ - Django hooks declare `HttpResponseBase` return types; the branch-coverage gate
103
+ is 83% with new fail-closed regression tests, and a bridge test runs real
104
+ evidence through AccessGate (the `dev` extra installs AccessGate).
105
+ - Release workflows stay manually dispatched but refuse refs other than `main`
106
+ or `v<version>`, run lint, type checks and tests first, and build with the
107
+ hash-locked tools in `requirements/build.txt`.
108
+
109
+ ### Fixed
110
+
111
+ - Contained session-evaluation and re-verification errors are logged at WARNING
112
+ with a traceback on `session_armor.session`; an exception from `on_timeout()` is
113
+ logged and no longer replaces the timeout reason; a malformed
114
+ `SESSION_ARMOR_STATE_KEY_FALLBACKS` is reported on the first request.
115
+ - `on_violation()` runs once even when terminating the session fails.
116
+ - The default `get_login_url()` honours a lazy `LOGIN_URL` such as
117
+ `reverse_lazy(...)`.
118
+ - Gates with `requires_auth = False` no longer reject every anonymous request.
119
+ - `GateDecision` applies the string-length and finite-number checks to list items
120
+ in `context`.
121
+ - Audit entries over 16,384 characters are re-rendered with only the reserved and
122
+ identity fields and `truncated: true` instead of being cut into invalid JSON.
123
+ - The MCP server writes ASCII-only JSON, reads stdin as UTF-8 under any locale,
124
+ answers unserializable responses with -32603 and invalid UTF-8 with -32700
125
+ instead of exiting, omits `outputSchema` when a tool defines none, answers
126
+ `ping`, and rejects a `null` request id; its contract lists every setting the
127
+ package reads.
128
+ - The `get_client_ip` docstring, the README "check once" gate example and the
129
+ SECURITY.md support table match the code and the 0.5.x line.
130
+
131
+ ## [0.5.0] - 2026-08-16
132
+
133
+ ### Changed
134
+
135
+ - Split the dependency-free assurance and gate-decision contracts from the
136
+ optional Django middleware adapter.
137
+ - Moved Django middleware imports to `session_armor.adapters.django` and made
138
+ Django installable through the `SessionArmor[django]` extra.
139
+ - Removed the old root and module-level middleware imports so framework
140
+ boundaries remain explicit.
141
+
142
+ ### Fixed
143
+
144
+ - Use Django session mapping views when inspecting session keys, avoiding
145
+ `KeyError: 0` during real `SessionStore` initialization and validation.
146
+
147
+ ## [0.4.0] - 2026-08-15
148
+
149
+ ### Security
150
+
151
+ - Replaced ambiguous unkeyed fingerprint and claim digests with keyed,
152
+ domain-separated HMAC-SHA256 over a length-framed representation and
153
+ constant-time comparison.
154
+ - Added strict validation for session state version, completeness, timestamps,
155
+ future clock values, security settings, proxy chains, factor inputs, and
156
+ extension-hook outputs. Invalid state is flushed and fails closed.
157
+ - Forwarded headers are now ignored by default. Enabling them requires exact
158
+ trusted proxy CIDRs and a bounded hop count; catch-all CIDRs are rejected.
159
+ - Gate results are typed `GateDecision` values, cache entries are bound to the
160
+ subject/session scope, malformed cache values are ignored, and unbounded
161
+ sticky approvals are never reused.
162
+ - Audit records use full 128-bit request IDs, structured JSON, recursive value
163
+ validation, reserved-field protection, explicit suppression policy, and
164
+ exception-path events.
165
+
166
+ ### Added
167
+
168
+ - Immutable `SessionAssurance` evidence on every request and a stable,
169
+ primitive-only authorization context contract for AccessGate.
170
+ - Public `rebaseline_claims()` API for reviewed server-side identity changes.
171
+ - AccessGate integration, threat model, secure-development, audit-scope, and
172
+ release documentation.
173
+
174
+ ### Changed
175
+
176
+ - The runtime dependency is bounded to the tested Django 4.2 and 5.2 release
177
+ lines; unsupported future major versions cannot be selected silently.
178
+ - Security settings are consistently namespaced under `SESSION_ARMOR_*`.
179
+ - Gate hooks now consume and return `GateDecision`; error paths cannot opt into
180
+ pass-through.
181
+ - Private `_ss_*` state is migrated to versioned `_sa_*` state on the next
182
+ authenticated request, rotating the Django session key.
183
+
184
+ ## [0.3.0] - 2026-07-15
185
+
186
+ ### Security
187
+ - **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.
188
+ - **`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.
189
+ - **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.
190
+ - **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.
191
+
192
+ ### Added
193
+ - **`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.
194
+ - **`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.
195
+ - **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.
196
+ - **Packaged MCP contract** — added the `sessionarmor-mcp` stdio command and public agent contract for review-first middleware, audit, gate, and rollout guidance.
197
+
198
+ ## [0.2.0] - 2026-06-12
199
+
200
+ ### Added
201
+ - **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.
202
+ - **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.
203
+ - `invalidate()` now also clears the stored version stamp.
204
+
205
+ ## [0.1.0] - 2026-05-22
206
+
207
+ ### Added
208
+ - **SessionSecurityMiddleware** — Client fingerprint binding (IP + User-Agent hash), absolute/idle session timeouts, JWT claim drift detection, session fixation prevention via `cycle_key()`.
209
+ - **AuditMiddleware** — Privacy-preserving audit trail for authenticated requests with request ID correlation, hashed IPs, sanitized log entries.
210
+ - **GateMiddleware** — Base class for building cacheable, hookable conditional gates (compliance, onboarding, feature flags, maintenance).
211
+ - **Utilities** — `get_client_ip()` with proxy-depth awareness, `hash_value()`, `sanitize_for_log()` with control character stripping, `is_authenticated()`.
212
+ - Full hook system on all three middleware classes for zero-subclass-needed customization.
213
+ - `SESSION_ARMOR_TRUSTED_PROXY_DEPTH` setting to prevent X-Forwarded-For spoofing.
214
+ - `fail_open=False` as defense-grade default on GateMiddleware.
215
+ - CI/CD with GitHub Actions (tests on Python 3.10–3.13, PyPI publishing via trusted publishing).
@@ -0,0 +1,23 @@
1
+ # Contributing to SessionArmor
2
+
3
+ Issues and pull requests are welcome. For a vulnerability, use the private
4
+ reporting route in [SECURITY.md](SECURITY.md) instead of a public issue.
5
+
6
+ Fork the repository, keep your change focused, explain its behavior and
7
+ compatibility impact, update the relevant docs, and include appropriate test
8
+ evidence. Never submit credentials, customer data, or production examples.
9
+ Contributions are provided under the repository's [MIT license](LICENSE);
10
+ preserve copyright and third-party license notices.
11
+
12
+ The owner (`@bezu-1`) reviews and approves external changes before merge.
13
+ New commits invalidate previous approval. Workflow and release configuration
14
+ receive the same owner review as application code.
15
+
16
+ PRs, issues, comments, and agent mentions cannot authorize coding agents, GitHub
17
+ Actions, paid agent-token use, or publishing credentials. Vendor-hosted GitHub
18
+ app access must also be restricted separately in the owner's account settings.
19
+ Only the owner starts manual workflows; contributors should include their local
20
+ test results. Do not request that an agent approve or merge its own work.
21
+
22
+ See [VERSIONING.md](VERSIONING.md) for the common versioning and release policy
23
+ and the README's development instructions for this package's local checks.
@@ -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,11 @@
1
+ include CHANGELOG.md
2
+ include LICENSE
3
+ include README.md
4
+ include SECURITY.md
5
+ include CONTRIBUTING.md
6
+ include VERSIONING.md
7
+ recursive-include docs *.md
8
+ recursive-include mcp *.json *.md *.py
9
+ recursive-include requirements *.in *.txt
10
+ recursive-include tests *.py
11
+ recursive-include tools *.py
@@ -0,0 +1,373 @@
1
+ Metadata-Version: 2.4
2
+ Name: SessionArmor
3
+ Version: 1.0.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: Development Status :: 5 - Production/Stable
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: Django :: 4.2
17
+ Classifier: Framework :: Django :: 5.0
18
+ Classifier: Framework :: Django :: 5.1
19
+ Classifier: Framework :: Django :: 5.2
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Security
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Classifier: Intended Audience :: Developers
28
+ Requires-Python: >=3.10
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Provides-Extra: django
32
+ Requires-Dist: Django<6,>=4.2; extra == "django"
33
+ Provides-Extra: dev
34
+ Requires-Dist: Django<6,>=4.2; extra == "dev"
35
+ Requires-Dist: pytest>=8.0; extra == "dev"
36
+ Requires-Dist: pytest-django>=4.5; extra == "dev"
37
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
38
+ Requires-Dist: ruff>=0.4; extra == "dev"
39
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
40
+ Requires-Dist: django-stubs>=4.2.0; extra == "dev"
41
+ Requires-Dist: bandit>=1.7; extra == "dev"
42
+ Requires-Dist: pip-audit>=2.7; extra == "dev"
43
+ Requires-Dist: AccessGate<2,>=0.3.0a1; extra == "dev"
44
+ Dynamic: license-file
45
+
46
+ # SessionArmor
47
+
48
+ [![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)
49
+ [![PyPI version](https://badge.fury.io/py/SessionArmor.svg)](https://pypi.org/project/SessionArmor/)
50
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
51
+ [![Django 4.2-5.2](https://img.shields.io/badge/django-4.2--5.2-green.svg)](https://www.djangoproject.com/)
52
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
53
+
54
+ **Framework-neutral session-assurance contracts with an optional Django adapter for session integrity, privacy-aware audit logging, and configurable request gates.**
55
+
56
+ Part of the [Tunet](https://tunet.xyz/engineering/) open-source libraries, alongside [AccessGate](https://github.com/Tunet-xyz/access_gate), [GeoCanon](https://github.com/Tunet-xyz/GeoCanon), and [SwapLayer](https://github.com/Tunet-xyz/swap_layer). See the [SessionArmor product page](https://tunet.xyz/engineering/session-armor/) for the public capability overview.
57
+
58
+ ## Version 1.0
59
+
60
+ The documented assurance contracts, typed gate decisions, explicit Django adapter,
61
+ extension hooks, and `sessionarmor-mcp` entry point form the stable 1.x API.
62
+ The dependency-free core supports Python 3.10–3.13; the Django extra supports
63
+ Django 4.2–5.2 (`<6`). Use a Django version still receiving upstream security
64
+ updates. The `session-armor.assurance/v1` schema remains unchanged.
65
+
66
+ Upgrading from 0.5 or 0.6 keeps the explicit imports below. Older integrations
67
+ must move middleware imports to `session_armor.adapters.django`, return
68
+ `GateDecision` from gate hooks, and use the `SESSION_ARMOR_*` settings documented
69
+ here. See the [changelog](https://github.com/Tunet-xyz/session_armor/blob/main/CHANGELOG.md) and [release procedure](https://github.com/Tunet-xyz/session_armor/blob/main/docs/RELEASE.md).
70
+
71
+ ---
72
+
73
+ ## What It Does
74
+
75
+ The dependency-free core provides immutable assurance evidence and typed gate
76
+ decisions. The optional Django adapter provides three drop-in middleware classes
77
+ that harden an application's session layer:
78
+
79
+ | Middleware | Purpose |
80
+ |-----------|---------|
81
+ | `SessionSecurityMiddleware` | Keyed continuity binding, validated absolute/idle timeouts, claim drift detection, and typed assurance evidence |
82
+ | `AuditMiddleware` | Structured, privacy-aware security audit events for authenticated request outcomes |
83
+ | `GateMiddleware` | Typed, identity-bound workflow gates with bounded, revocation-aware caching |
84
+
85
+ All three are **hookable** — override methods to customize behavior without touching internals.
86
+
87
+ ## References
88
+
89
+ - [NIST SP 800-53 AC-12](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Session Termination)
90
+ - [NIST SP 800-53 SC-23](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Session Authenticity)
91
+ - [NIST SP 800-53 AU-3/AU-12](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) (Audit Content/Generation)
92
+ - [OWASP Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
93
+
94
+ 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](https://github.com/Tunet-xyz/session_armor/blob/main/docs/security-model.md) for deployment assumptions, limitations, and a release checklist.
95
+
96
+ ---
97
+
98
+ ## Installation
99
+
100
+ ```bash
101
+ pip install SessionArmor
102
+ ```
103
+
104
+ The core install has no framework dependency. Install the Django adapter when
105
+ middleware integration is required:
106
+
107
+ ```bash
108
+ pip install "SessionArmor[django]"
109
+ ```
110
+
111
+ ## Quick Start
112
+
113
+ ```python
114
+ # settings.py
115
+ MIDDLEWARE = [
116
+ 'django.middleware.security.SecurityMiddleware',
117
+ 'django.contrib.sessions.middleware.SessionMiddleware',
118
+ # ... your auth middleware ...
119
+ 'session_armor.adapters.django.SessionSecurityMiddleware',
120
+ 'session_armor.adapters.django.AuditMiddleware',
121
+ # ... rest of your middleware ...
122
+ ]
123
+
124
+ # Optional settings (shown with defaults)
125
+ SESSION_ARMOR_ABSOLUTE_TIMEOUT = 28800
126
+ SESSION_ARMOR_IDLE_TIMEOUT = 1800
127
+ SESSION_ARMOR_BIND_IP = True
128
+ SESSION_ARMOR_BIND_USER_AGENT = True
129
+ SESSION_ARMOR_DETECT_CLAIM_DRIFT = True
130
+ SESSION_ARMOR_REQUIRE_BINDING = True
131
+ SESSION_ARMOR_CLOCK_SKEW = 60
132
+ SESSION_ARMOR_LAST_ACTIVE_RESOLUTION = 0
133
+ SESSION_ARMOR_NO_STORE = True
134
+ SESSION_ARMOR_STATE_KEY = SECRET_KEY
135
+ SESSION_ARMOR_STATE_KEY_FALLBACKS = None # None: follow SECRET_KEY_FALLBACKS
136
+ SESSION_ARMOR_AUDIT_PEPPER = SECRET_KEY
137
+
138
+ # Forwarded headers are ignored unless both values are configured.
139
+ SESSION_ARMOR_TRUSTED_PROXY_DEPTH = 0
140
+ SESSION_ARMOR_TRUSTED_PROXY_CIDRS = ()
141
+ ```
142
+
143
+ > **Note on audit IP hashing.** Audit logs pseudonymize the client IP with a
144
+ > keyed HMAC-SHA256 so the value can't be reversed from the (low-entropy) IPv4
145
+ > space. Set a dedicated `SESSION_ARMOR_AUDIT_PEPPER` to rotate it independently
146
+ > of `SECRET_KEY`, or to share it across services for cross-log correlation.
147
+ > If unset, it falls back to `SECRET_KEY`.
148
+
149
+ > **Note on key rotation.** `SESSION_ARMOR_STATE_KEY_FALLBACKS` lists retired
150
+ > state keys. They only verify existing session state, which is then re-signed
151
+ > with the current key; they never sign. Left at `None`, a state key that
152
+ > follows `SECRET_KEY` uses Django's `SECRET_KEY_FALLBACKS`, so Django's
153
+ > documented rotation keeps sessions alive. Do not keep a key that may have
154
+ > leaked. Session identifiers (the gate cache scope) change once, so gates
155
+ > re-check once.
156
+
157
+ > **Note on proxy trust.** The secure default (`DEPTH = 0`) ignores
158
+ > `X-Forwarded-For`. To use it, configure both the exact number of proxy hops
159
+ > and their CIDR ranges. Each trusted hop is checked from the socket peer back
160
+ > toward the client; a malformed client entry or hop and catch-all trusted
161
+ > networks are rejected. Entries left of the client are never read, and
162
+ > forwarded entries may carry a port.
163
+
164
+ ## Building a Gate
165
+
166
+ ```python
167
+ from session_armor import GateDecision
168
+ from session_armor.adapters.django import GateMiddleware
169
+ from django.shortcuts import redirect
170
+
171
+ class ComplianceGate(GateMiddleware):
172
+ gate_id = 'compliance'
173
+ cache_ttl_setting = 'COMPLIANCE_CACHE_TTL'
174
+ default_cache_ttl = 3600
175
+ requires_trusted_session = True
176
+
177
+ def check(self, request) -> GateDecision:
178
+ if user_accepted_current_terms(request):
179
+ return GateDecision.allow('current_terms_accepted')
180
+ return GateDecision.reject('terms_acceptance_required')
181
+
182
+ def on_reject(self, request, decision):
183
+ return redirect('/accept-terms/')
184
+ ```
185
+
186
+ A gate with `requires_trusted_session = True` rejects every path that
187
+ `SessionSecurityMiddleware` exempts, unless its own `exempt_paths` repeat them.
188
+ Set `follow_session_exemptions = True` to let those requests through instead.
189
+
190
+ If `check()` raises, `on_error()` turns the failure into a rejection, and that
191
+ rejection is cached for the full TTL like any other result. Set
192
+ `error_cache_ttl` (seconds) to re-check sooner once a dependency recovers.
193
+
194
+ The page a rejection leads to can read the last result with
195
+ `ComplianceGate.get_cached_decision(request)` or `get_context(request)`; the
196
+ `_gate_*` session keys behind them are private.
197
+
198
+ ### "Check once" gates
199
+
200
+ For gates that should only kick in once (onboarding, compliance), set
201
+ `recheck_after_pass = False`: a passing result is then reused with no TTL
202
+ re-checks, for up to `sticky_pass_max_age` seconds and while
203
+ `get_state_version()` returns the version it was cached under. A sticky pass
204
+ needs at least one of the two: with no `sticky_pass_max_age` and a `None`
205
+ version, a pass is never reused and `check()` runs on every request.
206
+ Rejections still re-check on the TTL. To push new requirements to
207
+ already-passed sessions (a new document version, a new onboarding step),
208
+ implement `get_state_version()` against a shared cache key and bump that key
209
+ on publish — every active session re-checks exactly once, with no per-request
210
+ database hits. It must return a non-empty string of at most 256 characters or
211
+ `None`; anything else, an empty string included, fails closed:
212
+
213
+ ```python
214
+ from django.core.cache import cache
215
+
216
+ class ComplianceGate(GateMiddleware):
217
+ gate_id = 'compliance'
218
+ recheck_after_pass = False # Pass once, stay passed
219
+ sticky_pass_max_age = 3600 # Re-check a pass at least hourly, version or not
220
+
221
+ def get_state_version(self, request) -> str | None:
222
+ # Bumped by admin tooling when a new document version is published;
223
+ # None until the key is first set.
224
+ return cache.get(f'compliance_version:{request.user.platform}')
225
+
226
+ def check(self, request) -> GateDecision:
227
+ return (
228
+ GateDecision.allow('current_terms_accepted')
229
+ if user_accepted_current_terms(request)
230
+ else GateDecision.reject('terms_acceptance_required')
231
+ )
232
+ ```
233
+
234
+ > **Sticky passes and revocation.** With `recheck_after_pass = False` and a
235
+ > state version but no `sticky_pass_max_age`, a pass is cached until the
236
+ > session ends, `invalidate()` is called, or the state version changes — so it
237
+ > is **not** appropriate for authorization/entitlement gates where access may
238
+ > be revoked. For those, use a normal TTL gate, drive
239
+ > `get_state_version()`, or set `sticky_pass_max_age` (seconds) to cap how long
240
+ > a sticky pass may be reused before a forced re-check.
241
+
242
+ ## Customizing Session Security
243
+
244
+ ```python
245
+ from session_armor.adapters.django import SessionSecurityMiddleware
246
+
247
+ class MySessionSecurity(SessionSecurityMiddleware):
248
+ exempt_paths = ('/health/', '/static/')
249
+ last_active_resolution = 60 # only rewrite last-active timestamp every 60s
250
+
251
+ def get_critical_claims(self, user):
252
+ # Auth0 / OIDC claims that must not change mid-session
253
+ return [user.sub, user.organization_uuid, user.platform]
254
+
255
+ def get_login_url(self, request):
256
+ platform = getattr(request.user, 'platform', '')
257
+ return f'/{platform}/login/' if platform else '/login/'
258
+
259
+ # After a reviewed server-side claim update, use the public API rather than
260
+ # writing SessionArmor's private session keys. Pass the updated user when
261
+ # request.user still holds the old claims; refresh_assurance=True also
262
+ # re-verifies and re-issues this request's evidence, so code never builds
263
+ # SessionAssurance itself.
264
+ MySessionSecurity(lambda request: request).rebaseline_claims(
265
+ request, updated_user, refresh_assurance=True
266
+ )
267
+
268
+ # At an authentication boundary (a new sign-in on an existing session), forget
269
+ # the previous state; has_state(session) says whether rebaseline_claims() can run.
270
+ MySessionSecurity.discard_state(request.session)
271
+
272
+ # In the login view, once the session holds the new identity, bind it to the
273
+ # client that logged in. Otherwise the first later request presenting the new
274
+ # cookie sets the binding (with signed cookies, at any time until it expires).
275
+ MySessionSecurity(lambda request: request).establish(request, user)
276
+ ```
277
+
278
+ `exempt_paths` are matched against `request.path_info`, the path Django routes
279
+ on, so leave any deployment mount prefix out of them. Matching respects path
280
+ segments: `/health` exempts `/health` and `/health/live` but not
281
+ `/health-internal`, and `/` exempts only the root URL.
282
+
283
+ To diagnose a `fingerprint_mismatch`, `binding_digests(request)` returns keyed
284
+ digests of each binding factor (`hash_ip(value, length=12)` with the audit
285
+ pepper), so logs can show which factor changed without holding a raw IP or
286
+ User-Agent.
287
+
288
+ ## AccessGate integration
289
+
290
+ SessionArmor and AccessGate are complementary boundaries. SessionArmor decides
291
+ whether the authenticated session is still trustworthy and attaches an immutable
292
+ `request.session_assurance` record. AccessGate's Django adapter carries that
293
+ record into authorization context, where `SessionAssurancePolicy` denies stale,
294
+ missing, malformed, or subject-mismatched evidence before business policies may
295
+ grant an action:
296
+
297
+ ```python
298
+ from access_gate import AuthorizationEngine, RolePolicy, SessionAssurancePolicy
299
+
300
+ engine = AuthorizationEngine([
301
+ SessionAssurancePolicy(actions={'records.read'}),
302
+ RolePolicy({'records_reader'}, actions={'records.read'}),
303
+ ])
304
+ ```
305
+
306
+ The assurance policy is deny-only: a trusted session never grants a permission
307
+ by itself. When slow work sits between SessionArmor and the authorization
308
+ decision, call `refresh_assurance(request)` just before deciding: it
309
+ re-verifies the session and re-issues the evidence, and can withdraw trust but
310
+ never grant it. See [`docs/ACCESSGATE_INTEGRATION.md`](https://github.com/Tunet-xyz/session_armor/blob/main/docs/ACCESSGATE_INTEGRATION.md).
311
+
312
+ ## Customizing Audit Logging
313
+
314
+ ```python
315
+ from session_armor.adapters.django import AuditMiddleware
316
+
317
+ class MyAudit(AuditMiddleware):
318
+ exempt_paths = ('/health/', '/static/', '/favicon.ico')
319
+
320
+ def get_user_identity(self, request):
321
+ return {
322
+ 'uid': request.user.sub,
323
+ 'platform': request.user.platform,
324
+ 'org': request.user.organization_uuid,
325
+ }
326
+ ```
327
+
328
+ `path` is reserved evidence that `before_log()` cannot change. When URL paths
329
+ carry secrets (invitation tokens, one-time codes), override
330
+ `get_audit_path(request)` to return a redacted path instead.
331
+
332
+ ---
333
+
334
+ ## Development
335
+
336
+ ```bash
337
+ # Clone and install
338
+ git clone https://github.com/Tunet-xyz/session_armor.git
339
+ cd session_armor
340
+ pip install -e ".[dev]"
341
+
342
+ # Run tests
343
+ pytest
344
+
345
+ # Lint
346
+ ruff check src/session_armor tests
347
+
348
+ # Type check
349
+ mypy src/session_armor
350
+ ```
351
+
352
+
353
+ ## Public Agent MCP Contract
354
+
355
+ SessionArmor includes a public agent-operability contract in [`mcp/`](https://github.com/Tunet-xyz/session_armor/tree/main/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.
356
+
357
+ From a checkout, run the dependency-free contract server with `python mcp/server.py`. After installation, agents can use the packaged stdio command:
358
+
359
+ ```bash
360
+ sessionarmor-mcp
361
+ ```
362
+
363
+ This starts a local documentation and draft-generation server using the caller's
364
+ own environment. It does not connect to Tunet's agents, paid accounts, release
365
+ credentials, or production systems, and no hosted maintainer agent is included.
366
+
367
+ ## Contributing and releases
368
+
369
+ See [CONTRIBUTING.md](https://github.com/Tunet-xyz/session_armor/blob/main/CONTRIBUTING.md) for the owner-reviewed contribution process and [VERSIONING.md](https://github.com/Tunet-xyz/session_armor/blob/main/VERSIONING.md) for the shared SemVer and release policy. Public PRs and agent mentions cannot authorize maintainer work; repository jobs require owner dispatch. Vendor-hosted GitHub app access is controlled separately in the owner's account settings.
370
+
371
+ ## License
372
+
373
+ MIT — Copyright (c) 2024-2026 Tunet Ltd. See [LICENSE](https://github.com/Tunet-xyz/session_armor/blob/main/LICENSE).