ragleap-security 0.1.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.
- ragleap_security-0.1.0/.gitignore +40 -0
- ragleap_security-0.1.0/CHANGELOG.md +29 -0
- ragleap_security-0.1.0/PKG-INFO +57 -0
- ragleap_security-0.1.0/README.md +33 -0
- ragleap_security-0.1.0/docs/threat-model.md +26 -0
- ragleap_security-0.1.0/pyproject.toml +39 -0
- ragleap_security-0.1.0/scripts/mutation_check.py +93 -0
- ragleap_security-0.1.0/src/ragleap_security/__init__.py +16 -0
- ragleap_security-0.1.0/src/ragleap_security/audit.py +181 -0
- ragleap_security-0.1.0/src/ragleap_security/limits.py +77 -0
- ragleap_security-0.1.0/src/ragleap_security/scope.py +85 -0
- ragleap_security-0.1.0/src/ragleap_security/secrets.py +113 -0
- ragleap_security-0.1.0/tests/test_audit.py +220 -0
- ragleap_security-0.1.0/tests/test_limits.py +90 -0
- ragleap_security-0.1.0/tests/test_scope.py +96 -0
- ragleap_security-0.1.0/tests/test_secrets.py +119 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Environment
|
|
2
|
+
.env
|
|
3
|
+
*.env.local
|
|
4
|
+
|
|
5
|
+
# Python
|
|
6
|
+
__pycache__/
|
|
7
|
+
*.py[cod]
|
|
8
|
+
*.egg-info/
|
|
9
|
+
venv/
|
|
10
|
+
.venv/
|
|
11
|
+
|
|
12
|
+
# Node
|
|
13
|
+
node_modules/
|
|
14
|
+
|
|
15
|
+
# Docker
|
|
16
|
+
docker-compose.override.yml
|
|
17
|
+
|
|
18
|
+
# IDE
|
|
19
|
+
.vscode/
|
|
20
|
+
.idea/
|
|
21
|
+
|
|
22
|
+
# OS
|
|
23
|
+
.DS_Store
|
|
24
|
+
Thumbs.db
|
|
25
|
+
|
|
26
|
+
# Logs
|
|
27
|
+
*.log
|
|
28
|
+
.env
|
|
29
|
+
|
|
30
|
+
# Package build artifacts
|
|
31
|
+
dist/
|
|
32
|
+
build/
|
|
33
|
+
|
|
34
|
+
# RagLeap command
|
|
35
|
+
.ragleap-ollama
|
|
36
|
+
backups/
|
|
37
|
+
|
|
38
|
+
# Folder grants are the owner's private choices
|
|
39
|
+
grants/*
|
|
40
|
+
!grants/README.txt
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `ragleap-security` are documented here. Format
|
|
4
|
+
loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
|
+
|
|
6
|
+
## [0.1.0] - 2026-10-23
|
|
7
|
+
|
|
8
|
+
First version (design: #899). Nothing existed before, so there are no behaviour changes.
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- `Scope`, `ScopeError`, `require_scope`: immutable tenant scopes with an unambiguous key.
|
|
13
|
+
- `AuditLog`, `verify`, `VerifyResult`, `AuditError`: a hash-chained, append-only JSONL audit log.
|
|
14
|
+
- `SecretStr`, `from_env`, `redact`, `SecretError`: secret handling and heuristic redaction.
|
|
15
|
+
- `check_size`, `check_json_shape`, `bounded_read`, `Deadline`, `LimitError`: hard input limits.
|
|
16
|
+
- `docs/threat-model.md` and `scripts/mutation_check.py` (30 mutations).
|
|
17
|
+
|
|
18
|
+
### Verified
|
|
19
|
+
|
|
20
|
+
- 101 tests pass on Python 3.10 (the VPS) and on Python 3.12 (the author's sandbox). All 30 mutations are killed on Python 3.10 and 3.12.
|
|
21
|
+
- The CI test job passes on Python 3.10, 3.11 and 3.12 (PR #907).
|
|
22
|
+
|
|
23
|
+
### Not verified
|
|
24
|
+
|
|
25
|
+
- Windows, network filesystems.
|
|
26
|
+
- Tenant isolation end to end: no store uses `Scope` yet.
|
|
27
|
+
- The cross-process and in-process locks under adversarial timing (the race tests are probabilistic).
|
|
28
|
+
- The published wheel and sdist had not been installed from PyPI when this was written (the GitHub Release records that check).
|
|
29
|
+
- No independent security review has been done.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ragleap-security
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Small, auditable security primitives for the ragleap libraries: immutable tenant scopes, a tamper-evident hash-chained audit log, secret handling and redaction, and hard input limits. Standard library only. Not independently audited.
|
|
5
|
+
Project-URL: Homepage, https://github.com/ragleap/ragleap-core
|
|
6
|
+
Project-URL: Repository, https://github.com/ragleap/ragleap-core
|
|
7
|
+
Project-URL: Issues, https://github.com/ragleap/ragleap-core/issues
|
|
8
|
+
Author: RagLeap
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
Keywords: audit-log,llm,multi-tenant,redaction,secrets,security,self-hosted
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Security
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest>=8.0.0; extra == 'test'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# ragleap-security
|
|
26
|
+
|
|
27
|
+
Small, auditable security primitives for the ragleap libraries. Standard library only. Alpha. **Not independently audited**: see `docs/threat-model.md` for exactly what is and is not defended.
|
|
28
|
+
|
|
29
|
+
## What is in 0.1.0
|
|
30
|
+
|
|
31
|
+
- `Scope`: an immutable tenant scope (tenant, subject, agent, session) with an unambiguous key, `covers`, `narrow` and `require_scope`, so stores can refuse to work without one.
|
|
32
|
+
- `AuditLog`: an append-only JSON Lines log with a SHA-256 hash chain and `verify()`. Tamper-evident, not tamper-proof (see the threat model).
|
|
33
|
+
- `SecretStr`, `from_env`, `redact`: secrets that do not print themselves, read from the environment by name, and a heuristic redactor for logs.
|
|
34
|
+
- `check_size`, `check_json_shape`, `bounded_read`, `Deadline`: hard limits for untrusted input.
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from ragleap_security import AuditLog, Scope, SecretStr, from_env, redact
|
|
38
|
+
|
|
39
|
+
scope = Scope("acme", subject="alice")
|
|
40
|
+
log = AuditLog("audit.jsonl")
|
|
41
|
+
token = from_env("MY_SERVICE_TOKEN")
|
|
42
|
+
log.append("login.ok", {"user": "alice", "token": token}, scope)
|
|
43
|
+
assert log.verify().ok
|
|
44
|
+
print(redact(f"request failed with {token.reveal()}", [token]))
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Verifying it yourself
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
pip install -e ".[test]"
|
|
51
|
+
pytest
|
|
52
|
+
python scripts/mutation_check.py # breaks one protection at a time; every mutation must be killed
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Not in 0.1.0
|
|
56
|
+
|
|
57
|
+
Encryption, an SSRF-safe HTTP helper, a policy engine, output detectors and a red-team harness are planned (issue #899) and not available yet.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# ragleap-security
|
|
2
|
+
|
|
3
|
+
Small, auditable security primitives for the ragleap libraries. Standard library only. Alpha. **Not independently audited**: see `docs/threat-model.md` for exactly what is and is not defended.
|
|
4
|
+
|
|
5
|
+
## What is in 0.1.0
|
|
6
|
+
|
|
7
|
+
- `Scope`: an immutable tenant scope (tenant, subject, agent, session) with an unambiguous key, `covers`, `narrow` and `require_scope`, so stores can refuse to work without one.
|
|
8
|
+
- `AuditLog`: an append-only JSON Lines log with a SHA-256 hash chain and `verify()`. Tamper-evident, not tamper-proof (see the threat model).
|
|
9
|
+
- `SecretStr`, `from_env`, `redact`: secrets that do not print themselves, read from the environment by name, and a heuristic redactor for logs.
|
|
10
|
+
- `check_size`, `check_json_shape`, `bounded_read`, `Deadline`: hard limits for untrusted input.
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
from ragleap_security import AuditLog, Scope, SecretStr, from_env, redact
|
|
14
|
+
|
|
15
|
+
scope = Scope("acme", subject="alice")
|
|
16
|
+
log = AuditLog("audit.jsonl")
|
|
17
|
+
token = from_env("MY_SERVICE_TOKEN")
|
|
18
|
+
log.append("login.ok", {"user": "alice", "token": token}, scope)
|
|
19
|
+
assert log.verify().ok
|
|
20
|
+
print(redact(f"request failed with {token.reveal()}", [token]))
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Verifying it yourself
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install -e ".[test]"
|
|
27
|
+
pytest
|
|
28
|
+
python scripts/mutation_check.py # breaks one protection at a time; every mutation must be killed
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Not in 0.1.0
|
|
32
|
+
|
|
33
|
+
Encryption, an SSRF-safe HTTP helper, a policy engine, output detectors and a red-team harness are planned (issue #899) and not available yet.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# ragleap-security 0.1.0: threat model
|
|
2
|
+
|
|
3
|
+
Status: first version. It covers only what 0.1.0 contains. Anything not listed as defended is not defended. This library has had no independent security review.
|
|
4
|
+
|
|
5
|
+
## Scope of 0.1.0
|
|
6
|
+
|
|
7
|
+
Four modules: `scope` (tenant scopes), `audit` (hash-chained log), `secrets` (secret wrapper and redaction), `limits` (input limits). Standard library only. No store uses these yet; ragleap-memory (#900) is the first planned consumer.
|
|
8
|
+
|
|
9
|
+
## Threats
|
|
10
|
+
|
|
11
|
+
| # | Threat | What 0.1.0 does | Backed by | Not defended |
|
|
12
|
+
|---|--------|-----------------|-----------|--------------|
|
|
13
|
+
| 1 | One tenant reads or writes another tenant's data because a scope is missing, forged or ambiguous | `Scope` is immutable and validated; `key` is unambiguous; `covers` and `require_scope` accept only an exact `Scope` (no strings, dicts or subclasses) | `tests/test_scope.py`; 7 mutations in `scripts/mutation_check.py` | A store that never calls `require_scope`, or never filters by scope, is not protected. No store exists yet, so tenant isolation as a whole is **not verified**. |
|
|
14
|
+
| 2 | A secret is printed, logged, pickled or serialized by accident | `SecretStr` masks `str`, `repr`, `format` and f-strings, refuses pickle and JSON, is unhashable, compares in constant time; `from_env` reads by variable name and its errors never contain values; `redact` removes known values and common credential formats | `tests/test_secrets.py`; 9 mutations | Code that calls `reveal()` and logs the result. A secret in a format `redact` does not know (it is a heuristic with false negatives). Secrets in process memory, swap or core dumps. Other processes of the same user reading the environment. |
|
|
15
|
+
| 3 | Someone edits, deletes, reorders or inserts a record in the audit log | `verify()` detects it through sequence numbers, chain links and SHA-256 hashes; appends fail closed on a corrupt or incomplete log; the log file is created with mode 0600 (the lock file too, which is not mutation-checked) | `tests/test_audit.py`; 6 mutations | Cutting records off the END of the log is not detected unless you keep the last hash or count outside the log and pass it as an anchor. Someone who can rewrite the whole file and recompute every hash is not detected (the tests pin both limitations). Deleting the file. A trusted writer that records false events. Timestamps are not trusted. |
|
|
16
|
+
| 4 | A forged or malformed audit record (log injection) | Event names are restricted; records are single-line canonical JSON with ASCII escaping; size is capped at 65,536 bytes; `SecretStr` values are written as `[REDACTED]` | `tests/test_audit.py`; 2 mutations | Secrets that are not wrapped in `SecretStr` are written as given. Callers must not put secrets in audit data. |
|
|
17
|
+
| 5 | Hostile input exhausts memory or CPU | `check_size`, `check_json_shape` (iterative, so no recursion crash), `bounded_read`, cooperative `Deadline`; `redact` has a length cap and was timed on four hostile inputs | `tests/test_limits.py`, `tests/test_secrets.py`; 6 mutations | Limits only apply where a caller invokes them. `Deadline` does not interrupt running code. |
|
|
18
|
+
| 6 | Concurrent writers corrupt the audit chain | An in-process lock and, on POSIX, a file lock | Thread test (8 threads, 200 records) and process test (4 processes, 80 records) | Not mutation-checked (race tests are probabilistic). Windows multi-process, network filesystems and Python versions other than those tested are **not verified**. |
|
|
19
|
+
|
|
20
|
+
## Not covered in 0.1.0
|
|
21
|
+
|
|
22
|
+
Encryption at rest, an SSRF-safe HTTP helper, a policy engine, secret and PII detection for outputs, a red-team harness, prompt-injection defences (the taint rule lives in ragleap-agents), supply-chain controls, and independent review. These are planned in #899 and are not claimed here.
|
|
23
|
+
|
|
24
|
+
## How this document is checked
|
|
25
|
+
|
|
26
|
+
`python scripts/mutation_check.py` breaks one protection at a time in a temporary copy and requires a test to fail. All 30 listed mutations were killed when this version was written. A killed mutation shows the protection is exercised by a test; it does not show the protection is sufficient.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ragleap-security"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Small, auditable security primitives for the ragleap libraries: immutable tenant scopes, a tamper-evident hash-chained audit log, secret handling and redaction, and hard input limits. Standard library only. Not independently audited."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "RagLeap" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["security", "audit-log", "multi-tenant", "secrets", "redaction", "llm", "self-hosted"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Topic :: Security",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
dependencies = []
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
test = ["pytest>=8.0.0"]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://github.com/ragleap/ragleap-core"
|
|
35
|
+
Repository = "https://github.com/ragleap/ragleap-core"
|
|
36
|
+
Issues = "https://github.com/ragleap/ragleap-core/issues"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/ragleap_security"]
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Mutation check for ragleap-security (repository only, not part of the installed package).
|
|
3
|
+
|
|
4
|
+
For each mutation below it copies the package to a temp directory, breaks one protection in the
|
|
5
|
+
copy, and runs the test suite. A mutation is KILLED if a test fails, SURVIVED if every test still
|
|
6
|
+
passes (meaning that protection is not really tested). The real source is never modified.
|
|
7
|
+
|
|
8
|
+
python scripts/mutation_check.py
|
|
9
|
+
|
|
10
|
+
Exit code 0 only if the unmodified suite passes and every mutation is killed. Run from the package
|
|
11
|
+
directory. Not covered, by design: the cross-process and in-process locks (their race tests are
|
|
12
|
+
probabilistic, so a surviving mutant there would prove nothing either way)."""
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
PKG = Path(__file__).resolve().parent.parent
|
|
20
|
+
S, A, K, L = "src/ragleap_security/scope.py", "src/ragleap_security/audit.py", "src/ragleap_security/secrets.py", "src/ragleap_security/limits.py"
|
|
21
|
+
|
|
22
|
+
# (name, [(file, old, new), ...]) ; each old string must occur exactly once in its file
|
|
23
|
+
MUTATIONS = [
|
|
24
|
+
("scope: key separator removed", [(S, 'return "/".join(f"{f}=', 'return "".join(f"{f}=')]),
|
|
25
|
+
("scope: '/' allowed in parts", [(S, "[A-Za-z0-9_.:@-]{0,127}", "[A-Za-z0-9_.:@/-]{0,127}")]),
|
|
26
|
+
("scope: covers ignores tenant", [(S, "if self.tenant != other.tenant:", "if False:")]),
|
|
27
|
+
("scope: covers accepts subclasses", [(S, "if type(other) is not Scope:", "if not isinstance(other, Scope):")]),
|
|
28
|
+
("scope: require_scope accepts subclasses", [(S, "if type(value) is not Scope:", "if not isinstance(value, Scope):")]),
|
|
29
|
+
("scope: narrow may overwrite a set part", [(S, "if values[name] is not None and values[name] != value:", "if False:")]),
|
|
30
|
+
("scope: parse accepts a key without tenant", [(S, 'if "tenant" not in values:', "if False:")]),
|
|
31
|
+
("audit: record hash not checked", [(A, 'if not isinstance(rec["hash"], str) or not hmac.compare_digest(rec["hash"], _digest(body)):', 'if not isinstance(rec["hash"], str):')]),
|
|
32
|
+
("audit: sequence and chain link not checked", [(A, 'if rec["seq"] != count + 1 or isinstance(rec["seq"], bool):', "if False:"), (A, 'if rec["prev"] != prev:', "if False:")]),
|
|
33
|
+
("audit: anchor count not checked", [(A, "if expected_count is not None and expected_count != count:", "if False:")]),
|
|
34
|
+
("audit: anchor hash not checked", [(A, "if expected_last_hash is not None and not hmac.compare_digest(expected_last_hash, prev):", "if False:")]),
|
|
35
|
+
("audit: append after an incomplete record", [(A, 'if not tail.endswith(b"\\n"):', "if False:")]),
|
|
36
|
+
("audit: record size cap removed", [(A, "if len(line) > MAX_RECORD_BYTES:", "if False:")]),
|
|
37
|
+
("audit: SecretStr written in clear", [(A, 'return "[REDACTED]"', "return o.reveal()")]),
|
|
38
|
+
("audit: log file made world-readable", [(A, "os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600", "os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644")]),
|
|
39
|
+
("secrets: str() reveals the value", [(K, 'def __str__(self) -> str:\n return "**********"', "def __str__(self) -> str:\n return self._v")]),
|
|
40
|
+
("secrets: format() reveals the value", [(K, 'def __format__(self, spec: str) -> str:\n return "**********"', "def __format__(self, spec: str) -> str:\n return self._v")]),
|
|
41
|
+
("secrets: pickling allowed", [(K, 'raise TypeError("SecretStr cannot be pickled")', "return (SecretStr, (self._v,))")]),
|
|
42
|
+
("secrets: exact-value redaction off", [(K, "if isinstance(v, str) and len(v) >= MIN_REDACT_LEN:", "if False:")]),
|
|
43
|
+
("secrets: short values redacted", [(K, "len(v) >= MIN_REDACT_LEN", "len(v) >= 1")]),
|
|
44
|
+
("secrets: sk- keys not redacted", [(K, '(re.compile(r"\\bsk-[A-Za-z0-9_-]{16,200}"), MASK),', "")]),
|
|
45
|
+
("secrets: AWS keys not redacted", [(K, '(re.compile(r"\\bAKIA[0-9A-Z]{16}\\b"), MASK),', "")]),
|
|
46
|
+
("secrets: private keys not redacted", [(K, '.{0,8000}?-----END', ".{0,0}?-----END")]),
|
|
47
|
+
("secrets: redact length cap removed", [(K, "if len(text) > max_chars:", "if False:")]),
|
|
48
|
+
("limits: size boundary off by one", [(L, "if n > max_bytes:", "if n >= max_bytes:")]),
|
|
49
|
+
("limits: size counted in characters", [(L, 'n = len(data.encode("utf-8", "surrogatepass"))', "n = len(data)")]),
|
|
50
|
+
("limits: bounded_read cannot see excess", [(L, "fp.read(max_bytes + 1)", "fp.read(max_bytes)")]),
|
|
51
|
+
("limits: depth not checked", [(L, "if depth > max_depth:", "if False:")]),
|
|
52
|
+
("limits: node count not checked", [(L, "if nodes > max_nodes:", "if False:")]),
|
|
53
|
+
("limits: deadline never expires at the boundary", [(L, "return self._clock() >= self._end", "return self._clock() > self._end")]),
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def run_tests(root: Path) -> bool:
|
|
58
|
+
env = {"PYTHONPATH": str(root / "src"), "PATH": "/usr/bin:/bin"}
|
|
59
|
+
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", str(root / "tests")],
|
|
60
|
+
cwd=root, env={**env, "PYTHONDONTWRITEBYTECODE": "1"}, capture_output=True, text=True)
|
|
61
|
+
return r.returncode == 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def main() -> int:
|
|
65
|
+
survivors = []
|
|
66
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
67
|
+
base = Path(tmp) / "base"
|
|
68
|
+
shutil.copytree(PKG, base, ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache", "scripts"))
|
|
69
|
+
if not run_tests(base):
|
|
70
|
+
print("The unmodified test suite fails; fix that first.")
|
|
71
|
+
return 2
|
|
72
|
+
print("baseline: tests pass")
|
|
73
|
+
for i, (name, edits) in enumerate(MUTATIONS):
|
|
74
|
+
work = Path(tmp) / f"m{i}"
|
|
75
|
+
shutil.copytree(base, work)
|
|
76
|
+
for rel, old, new in edits:
|
|
77
|
+
p = work / rel
|
|
78
|
+
text = p.read_text()
|
|
79
|
+
if text.count(old) != 1:
|
|
80
|
+
print(f"ERROR {name}: anchor not found exactly once in {rel}")
|
|
81
|
+
return 2
|
|
82
|
+
p.write_text(text.replace(old, new))
|
|
83
|
+
killed = not run_tests(work)
|
|
84
|
+
print(("KILLED " if killed else "SURVIVED ") + name)
|
|
85
|
+
if not killed:
|
|
86
|
+
survivors.append(name)
|
|
87
|
+
shutil.rmtree(work)
|
|
88
|
+
print(f"\n{len(MUTATIONS) - len(survivors)} of {len(MUTATIONS)} mutations killed")
|
|
89
|
+
return 1 if survivors else 0
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
if __name__ == "__main__":
|
|
93
|
+
sys.exit(main())
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""ragleap-security: small, auditable security primitives for the ragleap libraries.
|
|
2
|
+
|
|
3
|
+
Standard library only. Not independently audited. See docs/threat-model.md for what is and is not
|
|
4
|
+
defended."""
|
|
5
|
+
from ragleap_security.audit import GENESIS, AuditError, AuditLog, VerifyResult, verify
|
|
6
|
+
from ragleap_security.limits import Deadline, LimitError, bounded_read, check_json_shape, check_size
|
|
7
|
+
from ragleap_security.scope import Scope, ScopeError, require_scope
|
|
8
|
+
from ragleap_security.secrets import SecretError, SecretStr, from_env, redact
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"AuditError", "AuditLog", "Deadline", "GENESIS", "LimitError", "Scope", "ScopeError", "SecretError",
|
|
14
|
+
"SecretStr", "VerifyResult", "__version__", "bounded_read", "check_json_shape", "check_size",
|
|
15
|
+
"from_env", "redact", "require_scope", "verify",
|
|
16
|
+
]
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""A tamper-evident, append-only audit log: JSON Lines with a SHA-256 hash chain.
|
|
2
|
+
|
|
3
|
+
Tamper-EVIDENT, not tamper-proof. verify() detects an edited, reordered, inserted or removed record
|
|
4
|
+
in the middle of the log. It cannot detect that the END of the log was cut off, or that someone who
|
|
5
|
+
can rewrite the whole file recomputed every hash, unless you keep the last hash (or the record count)
|
|
6
|
+
somewhere they cannot write and pass it to verify() as an anchor."""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import hashlib
|
|
11
|
+
import hmac
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import threading
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
from typing import Any, Dict, Iterator, Optional
|
|
19
|
+
|
|
20
|
+
from .scope import Scope, require_scope
|
|
21
|
+
from .secrets import SecretStr
|
|
22
|
+
|
|
23
|
+
try: # POSIX cross-process lock; on platforms without fcntl only threads in one process are safe
|
|
24
|
+
import fcntl
|
|
25
|
+
except ImportError: # pragma: no cover
|
|
26
|
+
fcntl = None # type: ignore[assignment]
|
|
27
|
+
|
|
28
|
+
GENESIS = "0" * 64
|
|
29
|
+
MAX_RECORD_BYTES = 65_536
|
|
30
|
+
_EVENT = re.compile(r"[a-z][a-z0-9_.-]{0,63}\Z")
|
|
31
|
+
_KEYS = {"seq", "ts", "event", "scope", "data", "prev", "hash"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AuditError(Exception):
|
|
35
|
+
"""The log cannot be appended to (corrupt, too large, bad input). Appends fail closed."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _default(o: Any) -> Any:
|
|
39
|
+
if isinstance(o, SecretStr):
|
|
40
|
+
return "[REDACTED]"
|
|
41
|
+
raise TypeError(f"value of type {type(o).__name__} is not JSON serializable")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _canon(record: Dict[str, Any]) -> bytes:
|
|
45
|
+
return json.dumps(record, sort_keys=True, separators=(",", ":"), ensure_ascii=True, default=_default).encode("ascii")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _digest(record_without_hash: Dict[str, Any]) -> str:
|
|
49
|
+
return hashlib.sha256(_canon(record_without_hash)).hexdigest()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class VerifyResult:
|
|
54
|
+
ok: bool
|
|
55
|
+
records: int
|
|
56
|
+
last_hash: str
|
|
57
|
+
error: Optional[str] = None
|
|
58
|
+
line: Optional[int] = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def verify(path: str, *, expected_count: Optional[int] = None, expected_last_hash: Optional[str] = None) -> VerifyResult:
|
|
62
|
+
"""Check every record's sequence number, chain link and hash. A missing or empty file is a valid
|
|
63
|
+
empty log. Pass expected_count / expected_last_hash (kept outside the log) to detect truncation."""
|
|
64
|
+
path = os.fspath(path)
|
|
65
|
+
prev, count = GENESIS, 0
|
|
66
|
+
|
|
67
|
+
def bad(msg: str, line: int) -> VerifyResult:
|
|
68
|
+
return VerifyResult(False, count, prev, msg, line)
|
|
69
|
+
|
|
70
|
+
if os.path.exists(path):
|
|
71
|
+
with open(path, "rb") as f:
|
|
72
|
+
for n, raw in enumerate(f, start=1):
|
|
73
|
+
if len(raw) > MAX_RECORD_BYTES + 1:
|
|
74
|
+
return bad("record too large", n)
|
|
75
|
+
if not raw.endswith(b"\n"):
|
|
76
|
+
return bad("last record is incomplete", n)
|
|
77
|
+
try:
|
|
78
|
+
rec = json.loads(raw)
|
|
79
|
+
except ValueError:
|
|
80
|
+
return bad("record is not valid JSON", n)
|
|
81
|
+
if not isinstance(rec, dict) or set(rec) != _KEYS:
|
|
82
|
+
return bad("record has the wrong fields", n)
|
|
83
|
+
if rec["seq"] != count + 1 or isinstance(rec["seq"], bool):
|
|
84
|
+
return bad("sequence number is out of order", n)
|
|
85
|
+
if rec["prev"] != prev:
|
|
86
|
+
return bad("chain link does not match the previous record", n)
|
|
87
|
+
body = {k: v for k, v in rec.items() if k != "hash"}
|
|
88
|
+
if not isinstance(rec["hash"], str) or not hmac.compare_digest(rec["hash"], _digest(body)):
|
|
89
|
+
return bad("record hash does not match its content", n)
|
|
90
|
+
prev, count = rec["hash"], count + 1
|
|
91
|
+
if expected_count is not None and expected_count != count:
|
|
92
|
+
return VerifyResult(False, count, prev, "record count does not match the anchor", None)
|
|
93
|
+
if expected_last_hash is not None and not hmac.compare_digest(expected_last_hash, prev):
|
|
94
|
+
return VerifyResult(False, count, prev, "last hash does not match the anchor", None)
|
|
95
|
+
return VerifyResult(True, count, prev)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class AuditLog:
|
|
99
|
+
"""Append-only audit log at `path` (created with mode 0600). Safe for several threads, and for
|
|
100
|
+
several processes on POSIX."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, path: str):
|
|
103
|
+
self.path = os.fspath(path)
|
|
104
|
+
self._tlock = threading.Lock()
|
|
105
|
+
|
|
106
|
+
@contextlib.contextmanager
|
|
107
|
+
def _locked(self) -> Iterator[None]:
|
|
108
|
+
with self._tlock:
|
|
109
|
+
if fcntl is None: # pragma: no cover
|
|
110
|
+
yield
|
|
111
|
+
return
|
|
112
|
+
fd = os.open(self.path + ".lock", os.O_RDWR | os.O_CREAT, 0o600)
|
|
113
|
+
try:
|
|
114
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
115
|
+
yield
|
|
116
|
+
finally:
|
|
117
|
+
os.close(fd) # closing releases the flock
|
|
118
|
+
|
|
119
|
+
def _last(self) -> tuple:
|
|
120
|
+
try:
|
|
121
|
+
size = os.path.getsize(self.path)
|
|
122
|
+
except FileNotFoundError:
|
|
123
|
+
return 0, GENESIS
|
|
124
|
+
if size == 0:
|
|
125
|
+
return 0, GENESIS
|
|
126
|
+
window = 2 * MAX_RECORD_BYTES
|
|
127
|
+
with open(self.path, "rb") as f:
|
|
128
|
+
f.seek(max(0, size - window))
|
|
129
|
+
tail = f.read()
|
|
130
|
+
if not tail.endswith(b"\n"):
|
|
131
|
+
raise AuditError("the log ends with an incomplete record; refusing to append")
|
|
132
|
+
lines = tail.split(b"\n")
|
|
133
|
+
try:
|
|
134
|
+
rec = json.loads(lines[-2])
|
|
135
|
+
body = {k: v for k, v in rec.items() if k != "hash"}
|
|
136
|
+
if set(rec) != _KEYS or rec["hash"] != _digest(body):
|
|
137
|
+
raise ValueError
|
|
138
|
+
return rec["seq"], rec["hash"]
|
|
139
|
+
except (ValueError, TypeError, IndexError, AttributeError):
|
|
140
|
+
raise AuditError("the last record is not valid; refusing to append") from None
|
|
141
|
+
|
|
142
|
+
def append(self, event: str, data: Optional[Dict[str, Any]] = None, scope: Optional[Scope] = None) -> Dict[str, Any]:
|
|
143
|
+
"""Append one record and return it. `event` is lower-case words (a-z 0-9 . _ -). SecretStr
|
|
144
|
+
values in `data` are written as [REDACTED]. Raises AuditError rather than write a bad record."""
|
|
145
|
+
if not isinstance(event, str) or not _EVENT.match(event):
|
|
146
|
+
raise AuditError("invalid event name")
|
|
147
|
+
if data is None:
|
|
148
|
+
data = {}
|
|
149
|
+
if not isinstance(data, dict):
|
|
150
|
+
raise AuditError("data must be a dict")
|
|
151
|
+
scope_key = require_scope(scope).key if scope is not None else None
|
|
152
|
+
with self._locked():
|
|
153
|
+
seq, prev = self._last()
|
|
154
|
+
body = {
|
|
155
|
+
"seq": seq + 1,
|
|
156
|
+
"ts": datetime.now(timezone.utc).isoformat(timespec="microseconds"),
|
|
157
|
+
"event": event,
|
|
158
|
+
"scope": scope_key,
|
|
159
|
+
"data": data,
|
|
160
|
+
"prev": prev,
|
|
161
|
+
}
|
|
162
|
+
try:
|
|
163
|
+
record = dict(body, hash=_digest(body))
|
|
164
|
+
line = _canon(record) + b"\n"
|
|
165
|
+
except (TypeError, ValueError) as e:
|
|
166
|
+
raise AuditError(f"data cannot be serialized: {e}") from None
|
|
167
|
+
if len(line) > MAX_RECORD_BYTES:
|
|
168
|
+
raise AuditError(f"record is larger than {MAX_RECORD_BYTES} bytes")
|
|
169
|
+
fd = os.open(self.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
170
|
+
try:
|
|
171
|
+
view = memoryview(line)
|
|
172
|
+
while view:
|
|
173
|
+
view = view[os.write(fd, view):]
|
|
174
|
+
os.fsync(fd)
|
|
175
|
+
finally:
|
|
176
|
+
os.close(fd)
|
|
177
|
+
return json.loads(line)
|
|
178
|
+
|
|
179
|
+
def verify(self, *, expected_count: Optional[int] = None, expected_last_hash: Optional[str] = None) -> VerifyResult:
|
|
180
|
+
with self._locked():
|
|
181
|
+
return verify(self.path, expected_count=expected_count, expected_last_hash=expected_last_hash)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Hard limits for untrusted input: size, nesting depth, node count, and deadlines."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, BinaryIO
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LimitError(ValueError):
|
|
9
|
+
"""A configured limit was exceeded. The message never contains the input."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _nonneg_int(value: Any, name: str) -> None:
|
|
13
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
14
|
+
raise ValueError(f"{name} must be a non-negative int")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def check_size(data: Any, max_bytes: int, what: str = "input") -> None:
|
|
18
|
+
"""Raise LimitError if a str (measured as UTF-8) or bytes value is larger than max_bytes."""
|
|
19
|
+
_nonneg_int(max_bytes, "max_bytes")
|
|
20
|
+
if isinstance(data, str):
|
|
21
|
+
n = len(data.encode("utf-8", "surrogatepass"))
|
|
22
|
+
elif isinstance(data, (bytes, bytearray, memoryview)):
|
|
23
|
+
n = len(data)
|
|
24
|
+
else:
|
|
25
|
+
raise TypeError("data must be str or bytes")
|
|
26
|
+
if n > max_bytes:
|
|
27
|
+
raise LimitError(f"{what} is larger than {max_bytes} bytes")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check_json_shape(obj: Any, *, max_depth: int = 32, max_nodes: int = 100_000) -> None:
|
|
31
|
+
"""Raise LimitError if nested dict/list/tuple data is deeper than max_depth or has more than
|
|
32
|
+
max_nodes values. Iterative, so hostile nesting cannot cause a RecursionError."""
|
|
33
|
+
for name, v in (("max_depth", max_depth), ("max_nodes", max_nodes)):
|
|
34
|
+
if isinstance(v, bool) or not isinstance(v, int) or v < 1:
|
|
35
|
+
raise ValueError(f"{name} must be a positive int")
|
|
36
|
+
stack = [(obj, 1)]
|
|
37
|
+
nodes = 0
|
|
38
|
+
while stack:
|
|
39
|
+
cur, depth = stack.pop()
|
|
40
|
+
nodes += 1
|
|
41
|
+
if nodes > max_nodes:
|
|
42
|
+
raise LimitError(f"data has more than {max_nodes} values")
|
|
43
|
+
if depth > max_depth:
|
|
44
|
+
raise LimitError(f"data is nested deeper than {max_depth} levels")
|
|
45
|
+
if isinstance(cur, dict):
|
|
46
|
+
stack.extend((v, depth + 1) for v in cur.values())
|
|
47
|
+
elif isinstance(cur, (list, tuple)):
|
|
48
|
+
stack.extend((v, depth + 1) for v in cur)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def bounded_read(fp: BinaryIO, max_bytes: int, what: str = "input") -> bytes:
|
|
52
|
+
"""Read at most max_bytes from fp; raise LimitError if there is more."""
|
|
53
|
+
_nonneg_int(max_bytes, "max_bytes")
|
|
54
|
+
data = fp.read(max_bytes + 1)
|
|
55
|
+
if len(data) > max_bytes:
|
|
56
|
+
raise LimitError(f"{what} is larger than {max_bytes} bytes")
|
|
57
|
+
return data
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Deadline:
|
|
61
|
+
"""A monotonic deadline. Use check() inside loops that handle untrusted work."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, seconds: float, clock=time.monotonic):
|
|
64
|
+
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)) or seconds < 0:
|
|
65
|
+
raise ValueError("seconds must be a non-negative number")
|
|
66
|
+
self._clock = clock
|
|
67
|
+
self._end = clock() + float(seconds)
|
|
68
|
+
|
|
69
|
+
def remaining(self) -> float:
|
|
70
|
+
return max(0.0, self._end - self._clock())
|
|
71
|
+
|
|
72
|
+
def expired(self) -> bool:
|
|
73
|
+
return self._clock() >= self._end
|
|
74
|
+
|
|
75
|
+
def check(self, what: str = "operation") -> None:
|
|
76
|
+
if self.expired():
|
|
77
|
+
raise LimitError(f"{what} exceeded its deadline")
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Immutable tenant scopes. Stores must require a Scope so isolation cannot be skipped by a caller."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
|
|
8
|
+
_PART = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:@-]{0,127}\Z")
|
|
9
|
+
_FIELDS = ("tenant", "subject", "agent", "session")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ScopeError(ValueError):
|
|
13
|
+
"""An invalid scope, or something that is not a Scope was used where one is required."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Scope:
|
|
18
|
+
"""Who a piece of data belongs to: a tenant, and optionally a subject, agent and session.
|
|
19
|
+
|
|
20
|
+
Each part is 1 to 128 characters of letters, digits and _ . : @ -, starting with a letter or
|
|
21
|
+
digit. '/' and '=' are not allowed, which makes `key` unambiguous: two different scopes never
|
|
22
|
+
share a key."""
|
|
23
|
+
|
|
24
|
+
tenant: str
|
|
25
|
+
subject: Optional[str] = None
|
|
26
|
+
agent: Optional[str] = None
|
|
27
|
+
session: Optional[str] = None
|
|
28
|
+
|
|
29
|
+
def __post_init__(self) -> None:
|
|
30
|
+
for f in _FIELDS:
|
|
31
|
+
v = getattr(self, f)
|
|
32
|
+
if v is None:
|
|
33
|
+
if f == "tenant":
|
|
34
|
+
raise ScopeError("tenant is required")
|
|
35
|
+
continue
|
|
36
|
+
if not isinstance(v, str) or not _PART.match(v):
|
|
37
|
+
raise ScopeError(f"invalid {f}")
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def key(self) -> str:
|
|
41
|
+
return "/".join(f"{f}={getattr(self, f)}" for f in _FIELDS if getattr(self, f) is not None)
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def parse(cls, key: str) -> "Scope":
|
|
45
|
+
if not isinstance(key, str) or not key:
|
|
46
|
+
raise ScopeError("invalid scope key")
|
|
47
|
+
values = {}
|
|
48
|
+
last = -1
|
|
49
|
+
for part in key.split("/"):
|
|
50
|
+
name, sep, value = part.partition("=")
|
|
51
|
+
if not sep or name not in _FIELDS or _FIELDS.index(name) <= last:
|
|
52
|
+
raise ScopeError("invalid scope key")
|
|
53
|
+
last = _FIELDS.index(name)
|
|
54
|
+
values[name] = value
|
|
55
|
+
if "tenant" not in values:
|
|
56
|
+
raise ScopeError("invalid scope key")
|
|
57
|
+
return cls(**values)
|
|
58
|
+
|
|
59
|
+
def covers(self, other: Any) -> bool:
|
|
60
|
+
"""True if `other` is this scope or narrower: same tenant, and every part set here is equal
|
|
61
|
+
there. A tenant-wide scope covers its subjects; a subject scope never covers its tenant."""
|
|
62
|
+
if type(other) is not Scope:
|
|
63
|
+
return False
|
|
64
|
+
if self.tenant != other.tenant:
|
|
65
|
+
return False
|
|
66
|
+
return all(getattr(self, f) is None or getattr(self, f) == getattr(other, f) for f in _FIELDS[1:])
|
|
67
|
+
|
|
68
|
+
def narrow(self, **parts: str) -> "Scope":
|
|
69
|
+
"""Return a narrower scope. Parts already set cannot be changed."""
|
|
70
|
+
values = {f: getattr(self, f) for f in _FIELDS}
|
|
71
|
+
for name, value in parts.items():
|
|
72
|
+
if name not in _FIELDS or name == "tenant":
|
|
73
|
+
raise ScopeError("only subject, agent and session can be narrowed")
|
|
74
|
+
if values[name] is not None and values[name] != value:
|
|
75
|
+
raise ScopeError(f"{name} is already set")
|
|
76
|
+
values[name] = value
|
|
77
|
+
return Scope(**values)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def require_scope(value: Any) -> Scope:
|
|
81
|
+
"""Return value if it is exactly a Scope. Strings, dicts, None and subclasses are refused, so
|
|
82
|
+
a caller cannot pass a forged object that claims to cover more than it does."""
|
|
83
|
+
if type(value) is not Scope:
|
|
84
|
+
raise ScopeError("a Scope is required")
|
|
85
|
+
return value
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Secret handling: a wrapper that never prints its value, env lookup by name, and redaction."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hmac
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from typing import Iterable, Optional, Union
|
|
8
|
+
|
|
9
|
+
from .limits import LimitError
|
|
10
|
+
|
|
11
|
+
MASK = "[REDACTED]"
|
|
12
|
+
_ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}\Z")
|
|
13
|
+
MIN_REDACT_LEN = 6 # exact-value redaction ignores values shorter than this (it would shred text)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SecretError(Exception):
|
|
17
|
+
"""A secret is missing or misused. The message never contains a secret value."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SecretStr:
|
|
21
|
+
"""Holds a secret. str(), repr(), format() and f-strings show a mask; reveal() returns the value.
|
|
22
|
+
It cannot be pickled or used as a dict key, and equality is constant-time."""
|
|
23
|
+
|
|
24
|
+
__slots__ = ("_v",)
|
|
25
|
+
|
|
26
|
+
def __init__(self, value: str):
|
|
27
|
+
if not isinstance(value, str):
|
|
28
|
+
raise TypeError("SecretStr needs a str")
|
|
29
|
+
self._v = value
|
|
30
|
+
|
|
31
|
+
def reveal(self) -> str:
|
|
32
|
+
return self._v
|
|
33
|
+
|
|
34
|
+
def __repr__(self) -> str:
|
|
35
|
+
return "SecretStr('**********')"
|
|
36
|
+
|
|
37
|
+
def __str__(self) -> str:
|
|
38
|
+
return "**********"
|
|
39
|
+
|
|
40
|
+
def __format__(self, spec: str) -> str:
|
|
41
|
+
return "**********"
|
|
42
|
+
|
|
43
|
+
def __bool__(self) -> bool:
|
|
44
|
+
return bool(self._v)
|
|
45
|
+
|
|
46
|
+
def __eq__(self, other: object) -> bool:
|
|
47
|
+
if isinstance(other, SecretStr):
|
|
48
|
+
other_v = other._v
|
|
49
|
+
elif isinstance(other, str):
|
|
50
|
+
other_v = other
|
|
51
|
+
else:
|
|
52
|
+
return NotImplemented
|
|
53
|
+
return hmac.compare_digest(self._v.encode("utf-8", "surrogatepass"), other_v.encode("utf-8", "surrogatepass"))
|
|
54
|
+
|
|
55
|
+
__hash__ = None # type: ignore[assignment]
|
|
56
|
+
|
|
57
|
+
def __reduce__(self):
|
|
58
|
+
raise TypeError("SecretStr cannot be pickled")
|
|
59
|
+
|
|
60
|
+
def __copy__(self) -> "SecretStr":
|
|
61
|
+
return SecretStr(self._v)
|
|
62
|
+
|
|
63
|
+
def __deepcopy__(self, memo) -> "SecretStr":
|
|
64
|
+
return SecretStr(self._v)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def from_env(name: str, *, required: bool = True) -> Optional[SecretStr]:
|
|
68
|
+
"""Read a secret from the environment variable `name`. An unset or empty variable is missing.
|
|
69
|
+
The error names the variable, never a value."""
|
|
70
|
+
if not isinstance(name, str) or not _ENV_NAME.match(name):
|
|
71
|
+
raise SecretError("invalid environment variable name")
|
|
72
|
+
value = os.environ.get(name)
|
|
73
|
+
if not value:
|
|
74
|
+
if required:
|
|
75
|
+
raise SecretError(f"environment variable {name} is not set")
|
|
76
|
+
return None
|
|
77
|
+
return SecretStr(value)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_PATTERNS = [
|
|
81
|
+
(re.compile(r"-----BEGIN [A-Z ]{0,30}PRIVATE KEY-----.{0,8000}?-----END [A-Z ]{0,30}PRIVATE KEY-----", re.S), MASK),
|
|
82
|
+
(re.compile(r"(?i)(authorization\s*[:=]\s*)(?:(?:bearer|basic|token)\s+)?[A-Za-z0-9._~+/=-]{8,512}"), r"\1" + MASK),
|
|
83
|
+
(re.compile(r"\bBearer\s+[A-Za-z0-9._~+/=-]{8,512}"), "Bearer " + MASK),
|
|
84
|
+
(re.compile(r"\bsk-[A-Za-z0-9_-]{16,200}"), MASK),
|
|
85
|
+
(re.compile(r"\bgsk_[A-Za-z0-9]{16,200}"), MASK),
|
|
86
|
+
(re.compile(r"\bAIza[0-9A-Za-z_-]{30,60}"), MASK),
|
|
87
|
+
(re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,100}"), MASK),
|
|
88
|
+
(re.compile(r"\bgithub_pat_[A-Za-z0-9_]{50,120}"), MASK),
|
|
89
|
+
(re.compile(r"\bAKIA[0-9A-Z]{16}\b"), MASK),
|
|
90
|
+
(re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,100}"), MASK),
|
|
91
|
+
(re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"), MASK),
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def redact(text: str, secrets: Iterable[Union[SecretStr, str]] = (), *, max_chars: int = 1_000_000) -> str:
|
|
96
|
+
"""Replace known secret values and common credential formats in text with a mask.
|
|
97
|
+
|
|
98
|
+
This is a heuristic. It removes the exact values you pass in `secrets` (values shorter than
|
|
99
|
+
MIN_REDACT_LEN characters are ignored) and credentials that match well-known formats. It cannot
|
|
100
|
+
find a secret in a format it does not know. Treat it as a last line of defence for logs and
|
|
101
|
+
error messages, never as a reason to log secrets."""
|
|
102
|
+
if not isinstance(text, str):
|
|
103
|
+
raise TypeError("text must be a str")
|
|
104
|
+
if len(text) > max_chars:
|
|
105
|
+
raise LimitError(f"text is longer than {max_chars} characters")
|
|
106
|
+
out = text
|
|
107
|
+
for s in secrets:
|
|
108
|
+
v = s.reveal() if isinstance(s, SecretStr) else s
|
|
109
|
+
if isinstance(v, str) and len(v) >= MIN_REDACT_LEN:
|
|
110
|
+
out = out.replace(v, MASK)
|
|
111
|
+
for pattern, repl in _PATTERNS:
|
|
112
|
+
out = pattern.sub(repl, out)
|
|
113
|
+
return out
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import stat
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from ragleap_security import GENESIS, AuditError, AuditLog, Scope, SecretStr, verify
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture
|
|
15
|
+
def log(tmp_path):
|
|
16
|
+
return AuditLog(tmp_path / "audit.jsonl")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def fill(log, n=5):
|
|
20
|
+
for i in range(n):
|
|
21
|
+
log.append("step.done", {"i": i}, Scope("acme", "u1"))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def lines(log):
|
|
25
|
+
return open(log.path, "rb").read().split(b"\n")[:-1]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def write_lines(log, ls):
|
|
29
|
+
open(log.path, "wb").write(b"".join(l + b"\n" for l in ls))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def rehash(rec):
|
|
33
|
+
body = {k: v for k, v in rec.items() if k != "hash"}
|
|
34
|
+
canon = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()
|
|
35
|
+
rec["hash"] = hashlib.sha256(canon).hexdigest()
|
|
36
|
+
return rec
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_empty_and_missing_log_verify_ok(log):
|
|
40
|
+
r = log.verify()
|
|
41
|
+
assert r.ok and r.records == 0 and r.last_hash == GENESIS
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_append_chain_and_verify(log):
|
|
45
|
+
fill(log)
|
|
46
|
+
r = log.verify()
|
|
47
|
+
assert r.ok and r.records == 5
|
|
48
|
+
recs = [json.loads(l) for l in lines(log)]
|
|
49
|
+
assert [x["seq"] for x in recs] == [1, 2, 3, 4, 5]
|
|
50
|
+
assert recs[0]["prev"] == GENESIS and recs[1]["prev"] == recs[0]["hash"]
|
|
51
|
+
assert recs[0]["scope"] == "tenant=acme/subject=u1"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_append_returns_the_written_record(log):
|
|
55
|
+
rec = log.append("a.b", {"x": 1})
|
|
56
|
+
assert json.loads(lines(log)[0]) == rec and rec["scope"] is None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_file_mode_is_private(log):
|
|
60
|
+
fill(log, 1)
|
|
61
|
+
assert stat.S_IMODE(os.stat(log.path).st_mode) == 0o600
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_secretstr_is_redacted_in_the_log(log):
|
|
65
|
+
log.append("login.ok", {"password": SecretStr("hunter" + "2-hunter2"), "user": "u1"})
|
|
66
|
+
raw = open(log.path).read()
|
|
67
|
+
assert "hunter2" not in raw and "[REDACTED]" in raw and log.verify().ok
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_edited_record_is_detected(log):
|
|
71
|
+
fill(log)
|
|
72
|
+
ls = lines(log)
|
|
73
|
+
rec = json.loads(ls[2])
|
|
74
|
+
rec["data"]["i"] = 99
|
|
75
|
+
ls[2] = json.dumps(rec).encode()
|
|
76
|
+
write_lines(log, ls)
|
|
77
|
+
r = log.verify()
|
|
78
|
+
assert not r.ok and r.line == 3
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_deleted_middle_record_is_detected(log):
|
|
82
|
+
fill(log)
|
|
83
|
+
ls = lines(log)
|
|
84
|
+
del ls[2]
|
|
85
|
+
write_lines(log, ls)
|
|
86
|
+
r = log.verify()
|
|
87
|
+
assert not r.ok and r.line == 3
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_reordered_and_inserted_records_are_detected(log):
|
|
91
|
+
fill(log)
|
|
92
|
+
ls = lines(log)
|
|
93
|
+
ls[1], ls[2] = ls[2], ls[1]
|
|
94
|
+
write_lines(log, ls)
|
|
95
|
+
assert not log.verify().ok
|
|
96
|
+
fill_log = AuditLog(str(log.path) + "2")
|
|
97
|
+
fill(fill_log)
|
|
98
|
+
other = lines(fill_log)
|
|
99
|
+
ls = lines(log)
|
|
100
|
+
ls.insert(2, other[1])
|
|
101
|
+
write_lines(log, ls)
|
|
102
|
+
assert not log.verify().ok
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_wrong_fields_bad_json_and_incomplete_record_are_detected(log):
|
|
106
|
+
fill(log, 2)
|
|
107
|
+
good = lines(log)
|
|
108
|
+
write_lines(log, [good[0], b"not json"])
|
|
109
|
+
assert log.verify().error == "record is not valid JSON"
|
|
110
|
+
rec = json.loads(good[0])
|
|
111
|
+
rec["extra"] = 1
|
|
112
|
+
write_lines(log, [json.dumps(rec).encode()])
|
|
113
|
+
assert log.verify().error == "record has the wrong fields"
|
|
114
|
+
open(log.path, "wb").write(good[0] + b"\n" + good[1][:20])
|
|
115
|
+
assert log.verify().error == "last record is incomplete"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_truncated_tail_is_NOT_detected_without_an_anchor(log):
|
|
119
|
+
# Documented limitation: cutting records off the end leaves a valid shorter log.
|
|
120
|
+
fill(log)
|
|
121
|
+
ls = lines(log)
|
|
122
|
+
write_lines(log, ls[:3])
|
|
123
|
+
assert log.verify().ok
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_truncated_tail_is_detected_with_an_anchor(log):
|
|
127
|
+
fill(log)
|
|
128
|
+
anchor = log.verify()
|
|
129
|
+
write_lines(log, lines(log)[:3])
|
|
130
|
+
assert not log.verify(expected_count=anchor.records).ok
|
|
131
|
+
assert not log.verify(expected_last_hash=anchor.last_hash).ok
|
|
132
|
+
assert log.verify(expected_count=3).ok # positive control
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_full_rewrite_with_recomputed_hashes_is_NOT_detected(log):
|
|
136
|
+
# Documented limitation: tamper-evident, not tamper-proof, against someone who can rewrite the file.
|
|
137
|
+
fill(log, 3)
|
|
138
|
+
recs = [json.loads(l) for l in lines(log)]
|
|
139
|
+
recs[1]["data"]["i"] = 99
|
|
140
|
+
prev = GENESIS
|
|
141
|
+
out = []
|
|
142
|
+
for r in recs:
|
|
143
|
+
r["prev"] = prev
|
|
144
|
+
r = rehash(r)
|
|
145
|
+
prev = r["hash"]
|
|
146
|
+
out.append(json.dumps(r, sort_keys=True, separators=(",", ":")).encode())
|
|
147
|
+
write_lines(log, out)
|
|
148
|
+
assert log.verify().ok
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def test_append_refuses_to_extend_a_corrupt_log(log):
|
|
152
|
+
fill(log, 2)
|
|
153
|
+
good = lines(log)
|
|
154
|
+
write_lines(log, [good[0], b"garbage"])
|
|
155
|
+
with pytest.raises(AuditError):
|
|
156
|
+
log.append("more.events")
|
|
157
|
+
open(log.path, "wb").write(good[0] + b"\n" + good[1][:20])
|
|
158
|
+
with pytest.raises(AuditError):
|
|
159
|
+
log.append("more.events")
|
|
160
|
+
rec = json.loads(good[1])
|
|
161
|
+
rec["data"]["i"] = 7
|
|
162
|
+
write_lines(log, [good[0], json.dumps(rec).encode()])
|
|
163
|
+
with pytest.raises(AuditError):
|
|
164
|
+
log.append("more.events")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@pytest.mark.parametrize("event", ["", "Upper", "1abc", "has space", "a" * 65, None, 5, "x\n"])
|
|
168
|
+
def test_bad_event_names_refused(log, event):
|
|
169
|
+
with pytest.raises(AuditError):
|
|
170
|
+
log.append(event)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_bad_data_and_scope_refused(log):
|
|
174
|
+
with pytest.raises(AuditError):
|
|
175
|
+
log.append("a.b", ["not", "a", "dict"])
|
|
176
|
+
with pytest.raises(AuditError):
|
|
177
|
+
log.append("a.b", {"x": object()})
|
|
178
|
+
with pytest.raises(Exception):
|
|
179
|
+
log.append("a.b", {}, scope="tenant=acme") # a string is not a Scope
|
|
180
|
+
assert not os.path.exists(log.path) or log.verify().records == 0
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def test_oversized_record_refused_and_log_unchanged(log):
|
|
184
|
+
fill(log, 1)
|
|
185
|
+
before = open(log.path, "rb").read()
|
|
186
|
+
with pytest.raises(AuditError):
|
|
187
|
+
log.append("big.one", {"blob": "x" * 70_000})
|
|
188
|
+
assert open(log.path, "rb").read() == before
|
|
189
|
+
log.append("big.ok", {"blob": "x" * 60_000}) # positive control just under the limit
|
|
190
|
+
assert log.verify().ok
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def test_threads_keep_the_chain_valid(log):
|
|
194
|
+
def work():
|
|
195
|
+
for i in range(25):
|
|
196
|
+
log.append("t.work", {"i": i})
|
|
197
|
+
|
|
198
|
+
ts = [threading.Thread(target=work) for _ in range(8)]
|
|
199
|
+
[t.start() for t in ts]
|
|
200
|
+
[t.join() for t in ts]
|
|
201
|
+
r = log.verify()
|
|
202
|
+
assert r.ok and r.records == 200
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@pytest.mark.skipif(sys.platform == "win32", reason="cross-process locking is POSIX only")
|
|
206
|
+
def test_processes_keep_the_chain_valid(log):
|
|
207
|
+
code = (
|
|
208
|
+
"import sys; from ragleap_security import AuditLog; l = AuditLog(sys.argv[1])\n"
|
|
209
|
+
"[l.append('p.work', {'i': i}) for i in range(20)]"
|
|
210
|
+
)
|
|
211
|
+
env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
|
|
212
|
+
ps = [subprocess.Popen([sys.executable, "-c", code, str(log.path)], env=env) for _ in range(4)]
|
|
213
|
+
assert all(p.wait() == 0 for p in ps)
|
|
214
|
+
r = log.verify()
|
|
215
|
+
assert r.ok and r.records == 80
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def test_module_level_verify_matches_method(log):
|
|
219
|
+
fill(log, 2)
|
|
220
|
+
assert verify(log.path) == log.verify()
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import io
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from ragleap_security import Deadline, LimitError, bounded_read, check_json_shape, check_size
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_check_size_str_bytes_and_boundary():
|
|
9
|
+
check_size("abc", 3)
|
|
10
|
+
check_size(b"abc", 3)
|
|
11
|
+
with pytest.raises(LimitError):
|
|
12
|
+
check_size("abcd", 3)
|
|
13
|
+
with pytest.raises(LimitError):
|
|
14
|
+
check_size(b"abcd", 3)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_check_size_counts_utf8_bytes_not_characters():
|
|
18
|
+
with pytest.raises(LimitError):
|
|
19
|
+
check_size("ééé", 5) # 3 characters, 6 bytes
|
|
20
|
+
check_size("ééé", 6)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_check_size_message_has_no_input():
|
|
24
|
+
with pytest.raises(LimitError) as e:
|
|
25
|
+
check_size("secret-value", 3)
|
|
26
|
+
assert "secret-value" not in str(e.value)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@pytest.mark.parametrize("bad", [-1, True, 1.5, "3", None])
|
|
30
|
+
def test_check_size_rejects_bad_limits(bad):
|
|
31
|
+
with pytest.raises(ValueError):
|
|
32
|
+
check_size("a", bad)
|
|
33
|
+
with pytest.raises(TypeError):
|
|
34
|
+
check_size(5, 10)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_json_shape_depth_and_nodes():
|
|
38
|
+
deep = cur = []
|
|
39
|
+
for _ in range(40):
|
|
40
|
+
nxt = []
|
|
41
|
+
cur.append(nxt)
|
|
42
|
+
cur = nxt
|
|
43
|
+
with pytest.raises(LimitError):
|
|
44
|
+
check_json_shape(deep, max_depth=32)
|
|
45
|
+
check_json_shape(deep, max_depth=64) # positive control
|
|
46
|
+
with pytest.raises(LimitError):
|
|
47
|
+
check_json_shape(list(range(10)), max_nodes=5)
|
|
48
|
+
check_json_shape({"a": [1, 2, {"b": 3}]})
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_json_shape_survives_hostile_nesting_without_recursion_error():
|
|
52
|
+
cur = []
|
|
53
|
+
root = cur
|
|
54
|
+
for _ in range(100_000):
|
|
55
|
+
nxt = []
|
|
56
|
+
cur.append(nxt)
|
|
57
|
+
cur = nxt
|
|
58
|
+
with pytest.raises(LimitError):
|
|
59
|
+
check_json_shape(root)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_json_shape_rejects_bad_settings():
|
|
63
|
+
for kw in ({"max_depth": 0}, {"max_nodes": 0}, {"max_depth": True}):
|
|
64
|
+
with pytest.raises(ValueError):
|
|
65
|
+
check_json_shape([], **kw)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_bounded_read():
|
|
69
|
+
assert bounded_read(io.BytesIO(b"abc"), 3) == b"abc"
|
|
70
|
+
with pytest.raises(LimitError):
|
|
71
|
+
bounded_read(io.BytesIO(b"abcd"), 3)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_deadline_with_fake_clock():
|
|
75
|
+
now = [100.0]
|
|
76
|
+
d = Deadline(5, clock=lambda: now[0])
|
|
77
|
+
assert not d.expired() and d.remaining() == 5
|
|
78
|
+
d.check()
|
|
79
|
+
now[0] = 104.9
|
|
80
|
+
assert not d.expired()
|
|
81
|
+
now[0] = 105.0
|
|
82
|
+
assert d.expired() and d.remaining() == 0
|
|
83
|
+
with pytest.raises(LimitError):
|
|
84
|
+
d.check("work")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@pytest.mark.parametrize("bad", [-1, True, "5", None])
|
|
88
|
+
def test_deadline_rejects_bad_seconds(bad):
|
|
89
|
+
with pytest.raises(ValueError):
|
|
90
|
+
Deadline(bad)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from ragleap_security import Scope, ScopeError, require_scope
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_valid_scope_and_key():
|
|
7
|
+
s = Scope("acme", "alice", "bot", "s1")
|
|
8
|
+
assert s.key == "tenant=acme/subject=alice/agent=bot/session=s1"
|
|
9
|
+
assert Scope("acme").key == "tenant=acme"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@pytest.mark.parametrize("bad", ["", " ", "a/b", "a=b", "a b", "-x", "x\n", "a" * 129, "é", None, 5])
|
|
13
|
+
def test_invalid_tenant_refused(bad):
|
|
14
|
+
with pytest.raises(ScopeError):
|
|
15
|
+
Scope(bad)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@pytest.mark.parametrize("field", ["subject", "agent", "session"])
|
|
19
|
+
def test_invalid_optional_parts_refused(field):
|
|
20
|
+
with pytest.raises(ScopeError):
|
|
21
|
+
Scope("acme", **{field: "a/b"})
|
|
22
|
+
with pytest.raises(ScopeError):
|
|
23
|
+
Scope("acme", **{field: ""})
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_boundary_length_accepted():
|
|
27
|
+
assert Scope("a" * 128).tenant == "a" * 128 # positive control for the length check
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_key_is_injective_and_roundtrips():
|
|
31
|
+
scopes = [Scope("a"), Scope("a", "b"), Scope("a", agent="b"), Scope("a", session="b"),
|
|
32
|
+
Scope("a", "b", "c"), Scope("a", "b", "c", "d"), Scope("a.b", "c")]
|
|
33
|
+
keys = [s.key for s in scopes]
|
|
34
|
+
assert len(set(keys)) == len(keys)
|
|
35
|
+
for s in scopes:
|
|
36
|
+
assert Scope.parse(s.key) == s
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@pytest.mark.parametrize("bad", ["", "tenant", "subject=x", "tenant=a/subject", "tenant=a/zzz=b",
|
|
40
|
+
"tenant=a/agent=x/subject=y", "tenant=a/tenant=b", "tenant=a//subject=b"])
|
|
41
|
+
def test_parse_rejects_malformed_keys(bad):
|
|
42
|
+
with pytest.raises(ScopeError):
|
|
43
|
+
Scope.parse(bad)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_scope_is_immutable_and_hashable():
|
|
47
|
+
s = Scope("a")
|
|
48
|
+
with pytest.raises(Exception):
|
|
49
|
+
s.tenant = "b"
|
|
50
|
+
assert {s: 1}[Scope("a")] == 1
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_covers_tenant_wide_covers_narrower_not_reverse():
|
|
54
|
+
wide, narrow = Scope("a"), Scope("a", "u1", "bot")
|
|
55
|
+
assert wide.covers(narrow) and wide.covers(wide)
|
|
56
|
+
assert not narrow.covers(wide)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_covers_refuses_other_tenant_and_other_subject():
|
|
60
|
+
assert not Scope("a").covers(Scope("b"))
|
|
61
|
+
assert not Scope("a", "u1").covers(Scope("a", "u2"))
|
|
62
|
+
assert not Scope("a", "u1").covers(Scope("a"))
|
|
63
|
+
assert Scope("a", "u1").covers(Scope("a", "u1", "bot")) # positive control
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_covers_refuses_non_scope_and_subclass():
|
|
67
|
+
class Fake(Scope):
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
assert not Scope("a").covers("tenant=a")
|
|
71
|
+
assert not Scope("a").covers(Fake("a"))
|
|
72
|
+
assert not Scope("a").covers(None)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_narrow_adds_parts_and_cannot_change_set_parts():
|
|
76
|
+
s = Scope("a").narrow(subject="u1")
|
|
77
|
+
assert s == Scope("a", "u1")
|
|
78
|
+
assert s.narrow(subject="u1") == s # same value is fine
|
|
79
|
+
with pytest.raises(ScopeError):
|
|
80
|
+
s.narrow(subject="u2")
|
|
81
|
+
with pytest.raises(ScopeError):
|
|
82
|
+
s.narrow(tenant="b")
|
|
83
|
+
with pytest.raises(ScopeError):
|
|
84
|
+
s.narrow(color="red")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_require_scope_accepts_only_exact_scope():
|
|
88
|
+
s = Scope("a")
|
|
89
|
+
assert require_scope(s) is s
|
|
90
|
+
|
|
91
|
+
class Fake(Scope):
|
|
92
|
+
pass
|
|
93
|
+
|
|
94
|
+
for bad in ("tenant=a", {"tenant": "a"}, None, Fake("a"), 5):
|
|
95
|
+
with pytest.raises(ScopeError):
|
|
96
|
+
require_scope(bad)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import pickle
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from ragleap_security import LimitError, SecretError, SecretStr, from_env, redact
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _j(*parts):
|
|
11
|
+
"""Join pieces at runtime so no credential-shaped literal sits in this file (secret scanners)."""
|
|
12
|
+
return "".join(parts)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
PASSWORD = _j("hunter", "2-hunter2")
|
|
16
|
+
VALUE = _j("s3cr3t", "-value")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_secretstr_never_shows_value():
|
|
20
|
+
s = SecretStr(PASSWORD)
|
|
21
|
+
for shown in (str(s), repr(s), f"{s}", "%s" % s, "{}".format(s), format(s, ">30")):
|
|
22
|
+
assert "hunter2" not in shown
|
|
23
|
+
assert s.reveal() == PASSWORD
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_secretstr_not_json_pickle_or_hashable():
|
|
27
|
+
import json
|
|
28
|
+
|
|
29
|
+
s = SecretStr("abcdefgh")
|
|
30
|
+
with pytest.raises(TypeError):
|
|
31
|
+
json.dumps({"k": s})
|
|
32
|
+
with pytest.raises(TypeError):
|
|
33
|
+
pickle.dumps(s)
|
|
34
|
+
with pytest.raises(TypeError):
|
|
35
|
+
hash(s)
|
|
36
|
+
with pytest.raises(TypeError):
|
|
37
|
+
SecretStr(b"bytes")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_secretstr_equality_and_bool():
|
|
41
|
+
assert SecretStr("abc") == SecretStr("abc")
|
|
42
|
+
assert SecretStr("abc") == "abc"
|
|
43
|
+
assert SecretStr("abc") != SecretStr("abd")
|
|
44
|
+
assert SecretStr("abc") != 5
|
|
45
|
+
assert SecretStr("x") and not SecretStr("")
|
|
46
|
+
assert SecretStr("a\ud800") == SecretStr("a\ud800") # lone surrogate does not crash
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_secretstr_copy_keeps_masking():
|
|
50
|
+
s = copy.copy(SecretStr("abcdefgh"))
|
|
51
|
+
assert "abcdefgh" not in repr(s)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_from_env(monkeypatch):
|
|
55
|
+
monkeypatch.setenv("RS_TEST_KEY", "value-123456")
|
|
56
|
+
assert from_env("RS_TEST_KEY").reveal() == "value-123456"
|
|
57
|
+
monkeypatch.delenv("RS_TEST_KEY")
|
|
58
|
+
with pytest.raises(SecretError) as e:
|
|
59
|
+
from_env("RS_TEST_KEY")
|
|
60
|
+
assert "RS_TEST_KEY" in str(e.value)
|
|
61
|
+
assert from_env("RS_TEST_KEY", required=False) is None
|
|
62
|
+
monkeypatch.setenv("RS_TEST_KEY", "")
|
|
63
|
+
assert from_env("RS_TEST_KEY", required=False) is None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@pytest.mark.parametrize("bad", ["", "1ABC", "A-B", "A B", "A=B", None, "x" * 200])
|
|
67
|
+
def test_from_env_rejects_bad_names(bad):
|
|
68
|
+
with pytest.raises(SecretError):
|
|
69
|
+
from_env(bad)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
KNOWN = [
|
|
73
|
+
_j("sk", "-abcdefghijklmnopqrstuv1234"), _j("gsk", "_abcdefghijklmnopqrstuvwx"), _j("AI", "za") + "a" * 35,
|
|
74
|
+
_j("gh", "p_") + "a" * 36, _j("github", "_pat_") + "a" * 60, _j("AK", "IAABCDEFGHIJKLMNOP"),
|
|
75
|
+
_j("xo", "xb-1234567890-abcdefghij"), _j("ey", "Jabcdefghij.", "eyJabcdefghij.", "abcdefghijkl"),
|
|
76
|
+
_j("Bea", "rer abcdef123456"),
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@pytest.mark.parametrize("secret", KNOWN)
|
|
81
|
+
def test_redact_known_formats(secret):
|
|
82
|
+
out = redact(f"before {secret} after")
|
|
83
|
+
assert secret not in out and "[REDACTED]" in out and out.startswith("before ") and out.endswith(" after")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_redact_private_key_block():
|
|
87
|
+
block = _j("-----BEGIN RSA ", "PRIVATE KEY-----\nMIIEabc\ndef\n-----END RSA ", "PRIVATE KEY-----")
|
|
88
|
+
assert "MIIEabc" not in redact("x\n" + block + "\ny")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_redact_authorization_header_keeps_name():
|
|
92
|
+
out = redact(_j("Author", "ization: Basic dXNlcjpwYXNzd29yZA=="))
|
|
93
|
+
assert "dXNlcjpw" not in out and out.lower().startswith("authorization")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_redact_exact_values_and_short_values():
|
|
97
|
+
assert redact(f"token is {VALUE} here", [SecretStr(VALUE)]) == "token is [REDACTED] here"
|
|
98
|
+
assert redact("a short ab here", ["ab"]) == "a short ab here" # below MIN_REDACT_LEN: untouched
|
|
99
|
+
assert redact("keep it", [SecretStr("")]) == "keep it"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_redact_leaves_ordinary_text():
|
|
103
|
+
text = "The quarterly meeting is at 3pm. See sk and AKIA are just words."
|
|
104
|
+
assert redact(text) == text
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_redact_limits_and_types():
|
|
108
|
+
with pytest.raises(LimitError):
|
|
109
|
+
redact("x" * 11, max_chars=10)
|
|
110
|
+
with pytest.raises(TypeError):
|
|
111
|
+
redact(b"bytes")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_redact_is_linear_on_hostile_input():
|
|
115
|
+
for hostile in ("Bearer " + "a" * 400_000, _j("-----BEGIN ", "PRIVATE KEY-----") * 20_000,
|
|
116
|
+
"authorization:" + " " * 400_000, "sk-" * 300_000):
|
|
117
|
+
t = time.monotonic()
|
|
118
|
+
redact(hostile)
|
|
119
|
+
assert time.monotonic() - t < 5
|