casekit 0.9.1__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.
- casekit-0.9.1/.gitignore +17 -0
- casekit-0.9.1/LICENSE +21 -0
- casekit-0.9.1/PKG-INFO +49 -0
- casekit-0.9.1/README.md +35 -0
- casekit-0.9.1/docs/CHANGELOG.md +47 -0
- casekit-0.9.1/docs/COMPATIBILITY.md +9 -0
- casekit-0.9.1/pyproject.toml +75 -0
- casekit-0.9.1/src/casekit/__init__.py +8 -0
- casekit-0.9.1/src/casekit/caps.py +60 -0
- casekit-0.9.1/src/casekit/decision_log.py +237 -0
- casekit-0.9.1/src/casekit/evidence.py +29 -0
- casekit-0.9.1/src/casekit/export.py +146 -0
- casekit-0.9.1/src/casekit/fetch.py +229 -0
- casekit-0.9.1/src/casekit/jsonschema/case-1.0.json +274 -0
- casekit-0.9.1/src/casekit/narrative.py +76 -0
- casekit-0.9.1/src/casekit/py.typed +0 -0
- casekit-0.9.1/src/casekit/schema.py +187 -0
- casekit-0.9.1/src/casekit/scoring.py +60 -0
- casekit-0.9.1/src/casekit/text.py +161 -0
- casekit-0.9.1/tests/test_caps.py +70 -0
- casekit-0.9.1/tests/test_decision_log.py +160 -0
- casekit-0.9.1/tests/test_evidence.py +35 -0
- casekit-0.9.1/tests/test_export.py +126 -0
- casekit-0.9.1/tests/test_fetch.py +292 -0
- casekit-0.9.1/tests/test_guards.py +72 -0
- casekit-0.9.1/tests/test_narrative.py +63 -0
- casekit-0.9.1/tests/test_schema.py +126 -0
- casekit-0.9.1/tests/test_scoring.py +56 -0
- casekit-0.9.1/tests/test_text.py +198 -0
casekit-0.9.1/.gitignore
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
.venv/
|
|
4
|
+
.pytest_cache/
|
|
5
|
+
.ruff_cache/
|
|
6
|
+
.coverage
|
|
7
|
+
htmlcov/
|
|
8
|
+
dist/
|
|
9
|
+
build/
|
|
10
|
+
*.egg-info/
|
|
11
|
+
|
|
12
|
+
# Local machine state written by tasks.py and hooks (never committed)
|
|
13
|
+
.buildkit/state/
|
|
14
|
+
.buildkit/approvals/
|
|
15
|
+
.claude/settings.local.json
|
|
16
|
+
.env
|
|
17
|
+
.env.*
|
casekit-0.9.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) casekit contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
casekit-0.9.1/PKG-INFO
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: casekit
|
|
3
|
+
Version: 0.9.1
|
|
4
|
+
Summary: Building blocks for evidence-backed security case tools: schema, scoring breakdowns, citation checks, untrusted-text neutralizing, capped responses, append-only decision logs, atomic exports and bounded fetching.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Requires-Dist: pydantic<3,>=2.14
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# casekit
|
|
16
|
+
|
|
17
|
+
Building blocks for evidence-backed security case tools: the parts of a "rank these findings
|
|
18
|
+
into cases, explain why, let an analyst decide" tool that don't depend on the data source.
|
|
19
|
+
|
|
20
|
+
| Module | What it gives you |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `casekit.schema` | Pydantic v2 models: `Case`, `Evidence`, `ScoreComponent`, `ScoreBreakdown`, `Claim`, `Narrative`, `Decision`. The published JSON Schema is `casekit/jsonschema/case-1.0.json`. |
|
|
23
|
+
| `casekit.evidence` | Canonical JSON, sha256 of it, stable prefixed IDs. |
|
|
24
|
+
| `casekit.scoring` | `score_with_breakdown(weights, parts)`: a transparent total that always carries its per-component breakdown. `rank()` with deterministic ties. |
|
|
25
|
+
| `casekit.narrative` | `validate_citations(narrative, evidence_ids)`: invented IDs and uncited claims, as a report. |
|
|
26
|
+
| `casekit.text` | Neutralize untrusted upstream text: invisible/bidi stripping, Markdown that can't form links or tags, CSV formula defusing, `neutralize()` for model-bound text. |
|
|
27
|
+
| `casekit.caps` | Response budgets: `fit_page()` returns the largest page under the budget, with `truncated` + `next_cursor`. |
|
|
28
|
+
| `casekit.decision_log` | Append-only JSONL behind `confirm=True`. It is size-capped, record-capped and locked for concurrent writers, and its lines are hash-chained. `verify_chain` finds edits before the last line. Store `head()` elsewhere to detect a truncated tail. It is a worklog, not tamper-proof against someone who can write the file. |
|
|
29
|
+
| `casekit.export` | Atomic multi-file exports confined to one directory, with strictly safe file names (no Windows device names, no case-insensitive collisions). JSON and CSV output is deterministic, and the CSV header and every cell are formula-defused. |
|
|
30
|
+
| `casekit.fetch` | Bounded HTTP: scheme + host allowlist, size cap, per-operation and total timeouts, environment proxies ignored. Redirects are off unless asked; when on, every hop is allowlisted, https→http is refused, and on any origin change only safe headers are sent and no body. Stdlib transport, injectable. |
|
|
31
|
+
|
|
32
|
+
Design rules (enforced by `tests/test_guards.py`):
|
|
33
|
+
- One runtime dependency, `pydantic>=2.14,<3`. **No `mcp` dependency**, ever: casekit must outlive MCP SDK majors. Tool layers return its plain dicts and strings.
|
|
34
|
+
- Only `casekit.fetch` touches the network.
|
|
35
|
+
- Python 3.11+.
|
|
36
|
+
|
|
37
|
+
## Versioning
|
|
38
|
+
- SemVer for the Python API; `SCHEMA_VERSION` (currently `1.0`) for the case JSON, separately.
|
|
39
|
+
- Consumers pin `casekit>=0.9,<1` now and `casekit>=1.N,<2` after 1.0.
|
|
40
|
+
- A breaking schema change bumps the major version and `SCHEMA_VERSION`, and ships a `casekit.migrate` function. Deprecations warn for one minor release first.
|
|
41
|
+
- The published schema is pinned by a golden test: change the models, and the test tells you to regenerate and version it.
|
|
42
|
+
|
|
43
|
+
## Development
|
|
44
|
+
```powershell
|
|
45
|
+
uv sync
|
|
46
|
+
uv run python tools/tasks.py hooks # once per clone: gitleaks + attribution git hooks
|
|
47
|
+
uv run python tools/tasks.py check # lint + format + tests with coverage + gitleaks history
|
|
48
|
+
uv run python tools/tasks.py schema # regenerate jsonschema/case-<version>.json after a model change
|
|
49
|
+
```
|
casekit-0.9.1/README.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# casekit
|
|
2
|
+
|
|
3
|
+
Building blocks for evidence-backed security case tools: the parts of a "rank these findings
|
|
4
|
+
into cases, explain why, let an analyst decide" tool that don't depend on the data source.
|
|
5
|
+
|
|
6
|
+
| Module | What it gives you |
|
|
7
|
+
|---|---|
|
|
8
|
+
| `casekit.schema` | Pydantic v2 models: `Case`, `Evidence`, `ScoreComponent`, `ScoreBreakdown`, `Claim`, `Narrative`, `Decision`. The published JSON Schema is `casekit/jsonschema/case-1.0.json`. |
|
|
9
|
+
| `casekit.evidence` | Canonical JSON, sha256 of it, stable prefixed IDs. |
|
|
10
|
+
| `casekit.scoring` | `score_with_breakdown(weights, parts)`: a transparent total that always carries its per-component breakdown. `rank()` with deterministic ties. |
|
|
11
|
+
| `casekit.narrative` | `validate_citations(narrative, evidence_ids)`: invented IDs and uncited claims, as a report. |
|
|
12
|
+
| `casekit.text` | Neutralize untrusted upstream text: invisible/bidi stripping, Markdown that can't form links or tags, CSV formula defusing, `neutralize()` for model-bound text. |
|
|
13
|
+
| `casekit.caps` | Response budgets: `fit_page()` returns the largest page under the budget, with `truncated` + `next_cursor`. |
|
|
14
|
+
| `casekit.decision_log` | Append-only JSONL behind `confirm=True`. It is size-capped, record-capped and locked for concurrent writers, and its lines are hash-chained. `verify_chain` finds edits before the last line. Store `head()` elsewhere to detect a truncated tail. It is a worklog, not tamper-proof against someone who can write the file. |
|
|
15
|
+
| `casekit.export` | Atomic multi-file exports confined to one directory, with strictly safe file names (no Windows device names, no case-insensitive collisions). JSON and CSV output is deterministic, and the CSV header and every cell are formula-defused. |
|
|
16
|
+
| `casekit.fetch` | Bounded HTTP: scheme + host allowlist, size cap, per-operation and total timeouts, environment proxies ignored. Redirects are off unless asked; when on, every hop is allowlisted, https→http is refused, and on any origin change only safe headers are sent and no body. Stdlib transport, injectable. |
|
|
17
|
+
|
|
18
|
+
Design rules (enforced by `tests/test_guards.py`):
|
|
19
|
+
- One runtime dependency, `pydantic>=2.14,<3`. **No `mcp` dependency**, ever: casekit must outlive MCP SDK majors. Tool layers return its plain dicts and strings.
|
|
20
|
+
- Only `casekit.fetch` touches the network.
|
|
21
|
+
- Python 3.11+.
|
|
22
|
+
|
|
23
|
+
## Versioning
|
|
24
|
+
- SemVer for the Python API; `SCHEMA_VERSION` (currently `1.0`) for the case JSON, separately.
|
|
25
|
+
- Consumers pin `casekit>=0.9,<1` now and `casekit>=1.N,<2` after 1.0.
|
|
26
|
+
- A breaking schema change bumps the major version and `SCHEMA_VERSION`, and ships a `casekit.migrate` function. Deprecations warn for one minor release first.
|
|
27
|
+
- The published schema is pinned by a golden test: change the models, and the test tells you to regenerate and version it.
|
|
28
|
+
|
|
29
|
+
## Development
|
|
30
|
+
```powershell
|
|
31
|
+
uv sync
|
|
32
|
+
uv run python tools/tasks.py hooks # once per clone: gitleaks + attribution git hooks
|
|
33
|
+
uv run python tools/tasks.py check # lint + format + tests with coverage + gitleaks history
|
|
34
|
+
uv run python tools/tasks.py schema # regenerate jsonschema/case-<version>.json after a model change
|
|
35
|
+
```
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.9.1 (2026-11-30)
|
|
4
|
+
- Packaging only, no code changes: the first PyPI release. `release.yml` now publishes each `v*` tag to TestPyPI, then to PyPI, and each step waits for a maintainer's approval.
|
|
5
|
+
|
|
6
|
+
## 0.9.0 (2026-11-30, TestPyPI only)
|
|
7
|
+
- First version. It was extracted from exposure-case-builder (`text_safety`, `disposition`, `export`, the generic parts of `scoring` and `fetch_tenable`) and from the ai-sec-buildkit component template (`caps`, `textsafe`).
|
|
8
|
+
- New in casekit:
|
|
9
|
+
- pydantic v2 `schema` with the published `case-1.0.json`;
|
|
10
|
+
- `evidence` (canonical hashing, stable IDs);
|
|
11
|
+
- `narrative.validate_citations`;
|
|
12
|
+
- hash-chained `decision_log`.
|
|
13
|
+
- Hardened before the first push, after an independent security review (2026-11-22):
|
|
14
|
+
- `fetch`:
|
|
15
|
+
- a total deadline and chunked reads;
|
|
16
|
+
- a string allowlist is refused, and entries must be bare hostnames;
|
|
17
|
+
- redirects compare the origin (scheme, host, port), refuse https→http, and keep only safe headers and no body across origins;
|
|
18
|
+
- environment proxies are ignored, and URLs with whitespace or control characters are refused.
|
|
19
|
+
- `decision_log`:
|
|
20
|
+
- a writer lock;
|
|
21
|
+
- caps on the record size and the file size (including the new line);
|
|
22
|
+
- reads only the tail to find the last line;
|
|
23
|
+
- `head()` anchor;
|
|
24
|
+
- exact-byte line hashes, so CRs and blank lines are flagged;
|
|
25
|
+
- no NaN.
|
|
26
|
+
- `export`:
|
|
27
|
+
- strict file names and casefold collision checks;
|
|
28
|
+
- unique temp names;
|
|
29
|
+
- `safe_stem` defaults to 16 hex characters;
|
|
30
|
+
- the CSV header and non-string cells are defused;
|
|
31
|
+
- no NaN.
|
|
32
|
+
- `neutralize`: bounded work on huge input, and invisible fillers and variation selectors are stripped.
|
|
33
|
+
- `text` (`md_text`, `md_cell`, `md_code`, `single_line`, `strip_invisible`):
|
|
34
|
+
- bare URLs are defused after `_`, `*`, `~`, `(` and mid-word too (no word boundary; still linear time);
|
|
35
|
+
- `md_text` backslash-escapes a leading heading, bullet, ordered-list, `~~~` fence, thematic break or table delimiter row, so it is safe as its own paragraph;
|
|
36
|
+
- line breaks (LF, CR, VT, FF, NEL, LS, PS) and tabs become spaces instead of being deleted, so words are no longer glued together (also in `strip_invisible`);
|
|
37
|
+
- the `md_*` helpers also drop invisible fillers and variation selectors (now including the Mongolian ones, also for `neutralize`). `strip_invisible` keeps them on purpose, so a caller that refuses changed values does not reject emoji (U+FE0F).
|
|
38
|
+
- `schema`:
|
|
39
|
+
- no control or bidi characters in text fields;
|
|
40
|
+
- bounded weights and collections.
|
|
41
|
+
- `narrative`:
|
|
42
|
+
- an empty narrative fails;
|
|
43
|
+
- an `is_backed` policy hook;
|
|
44
|
+
- `min_coverage` is validated.
|
|
45
|
+
- `rank` rejects NaN, and `fit_page` rejects `limit < 1`.
|
|
46
|
+
- `stable_id` is 24 hex characters.
|
|
47
|
+
- Packaging: the sdist ships only the package, its tests, README, LICENSE and these docs.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Compatibility
|
|
2
|
+
|
|
3
|
+
- **Python API:** SemVer. Before 1.0, a minor release may break the API; consumers pin `casekit>=0.9,<1`. From 1.0 on, consumers pin `casekit>=1.N,<2`.
|
|
4
|
+
- **Case JSON:** versioned separately by `casekit.SCHEMA_VERSION` (now `1.0`), published as `casekit/jsonschema/case-<version>.json`. Non-Python consumers validate against that file.
|
|
5
|
+
- **Breaking schema change:** bump the major version *and* `SCHEMA_VERSION`, ship the new schema file next to the old one, and ship `casekit.migrate` to convert old cases.
|
|
6
|
+
- **Deprecations:** warn (`DeprecationWarning`) for one minor release before removal.
|
|
7
|
+
- **Golden tests** pin serialized output (`tests/test_schema.py`, `tests/test_evidence.py`). If a golden changes, the release is breaking unless the change is a bug fix.
|
|
8
|
+
- **Python:** 3.11 and newer; CI runs the floor (3.11) and the house line (3.14) on Linux and Windows.
|
|
9
|
+
- **Dependencies:** `pydantic>=2.14,<3` only. Never `mcp`, never an HTTP client (`casekit.fetch` uses the stdlib, with an injectable transport).
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "casekit"
|
|
3
|
+
version = "0.9.1"
|
|
4
|
+
description = "Building blocks for evidence-backed security case tools: schema, scoring breakdowns, citation checks, untrusted-text neutralizing, capped responses, append-only decision logs, atomic exports and bounded fetching."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
# One runtime dependency, on purpose. Never add `mcp`: casekit must outlive MCP SDK majors
|
|
10
|
+
# (tests/test_guards.py enforces this).
|
|
11
|
+
dependencies = ["pydantic>=2.14,<3"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Programming Language :: Python :: 3.11",
|
|
15
|
+
"Programming Language :: Python :: 3.14",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[dependency-groups]
|
|
20
|
+
dev = [
|
|
21
|
+
"pytest==9.2.0",
|
|
22
|
+
"coverage==7.17.4",
|
|
23
|
+
"ruff==0.17.6",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["hatchling==1.33.0"]
|
|
28
|
+
build-backend = "hatchling.build"
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/casekit"]
|
|
32
|
+
|
|
33
|
+
# An allowlist: without it the sdist ships every tracked file, including CLAUDE.md, .claude/,
|
|
34
|
+
# .githooks/ and docs/plan.md. pyproject.toml and PKG-INFO are always added.
|
|
35
|
+
# tests/test_guards.py keeps this list closed.
|
|
36
|
+
[tool.hatch.build.targets.sdist]
|
|
37
|
+
only-include = [
|
|
38
|
+
"src/casekit",
|
|
39
|
+
"tests",
|
|
40
|
+
"README.md",
|
|
41
|
+
"LICENSE",
|
|
42
|
+
"docs/CHANGELOG.md",
|
|
43
|
+
"docs/COMPATIBILITY.md",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|
|
48
|
+
addopts = "-q"
|
|
49
|
+
|
|
50
|
+
[tool.coverage.run]
|
|
51
|
+
source = ["casekit"]
|
|
52
|
+
branch = true
|
|
53
|
+
|
|
54
|
+
[tool.coverage.report]
|
|
55
|
+
fail_under = 90
|
|
56
|
+
show_missing = true
|
|
57
|
+
skip_covered = true
|
|
58
|
+
|
|
59
|
+
[tool.ruff]
|
|
60
|
+
line-length = 100
|
|
61
|
+
# The library supports 3.11+ (its floor), even though development runs on house Python 3.14.
|
|
62
|
+
target-version = "py311"
|
|
63
|
+
# .githooks is byte-identical to ai-sec-buildkit's and linted there.
|
|
64
|
+
extend-exclude = [".githooks"]
|
|
65
|
+
|
|
66
|
+
[tool.ruff.lint]
|
|
67
|
+
select = ["E", "F", "W", "I", "B", "UP", "S", "BLE", "SIM", "C4", "RUF", "T20"]
|
|
68
|
+
ignore = [
|
|
69
|
+
"S603", # subprocess with list args is the intended pattern (tools/tasks.py)
|
|
70
|
+
"S607", # git/gitleaks resolved from PATH on purpose
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
[tool.ruff.lint.per-file-ignores]
|
|
74
|
+
"tests/**" = ["S101", "S105", "S106", "S108"]
|
|
75
|
+
"tools/**" = ["T20"]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""casekit: building blocks for evidence-backed security case tools.
|
|
2
|
+
|
|
3
|
+
Data-source neutral: source clients, field semantics and narrative prompts stay in each
|
|
4
|
+
component. No dependency on `mcp` (tests/test_guards.py).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.9.1"
|
|
8
|
+
SCHEMA_VERSION = "1.0"
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Response budgets: every tool response fits in a character budget, paginating beyond it.
|
|
2
|
+
|
|
3
|
+
House rule: default 20,000 characters, with `truncated: true` + `next_cursor` when a page had
|
|
4
|
+
to be cut. Plain dicts in, plain dicts out, so this works under any MCP SDK (or none).
|
|
5
|
+
Extracted from the buildkit component template (caps.py).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
|
|
13
|
+
DEFAULT_MAX_CHARS = 20_000
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def size(obj: object) -> int:
|
|
17
|
+
"""Characters of the canonical JSON form, the measure every budget uses."""
|
|
18
|
+
return len(json.dumps(obj, ensure_ascii=False, sort_keys=True))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class OverBudget(ValueError):
|
|
22
|
+
"""A single item does not fit the budget; the caller must summarize it instead."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def fit_page(
|
|
26
|
+
items: Sequence[dict],
|
|
27
|
+
start: int,
|
|
28
|
+
limit: int,
|
|
29
|
+
build: Callable[[list[dict]], dict],
|
|
30
|
+
max_chars: int = DEFAULT_MAX_CHARS,
|
|
31
|
+
) -> dict:
|
|
32
|
+
"""Largest page of items[start:start+limit] whose built response fits the budget.
|
|
33
|
+
|
|
34
|
+
Invariants: the page is non-empty when items remain (the cursor always advances), and
|
|
35
|
+
`truncated` is True exactly when `next_cursor` is set (more items exist). `build`'s
|
|
36
|
+
result is never modified; a new dict is returned.
|
|
37
|
+
"""
|
|
38
|
+
if limit < 1:
|
|
39
|
+
raise ValueError("limit must be at least 1, or the cursor can never advance")
|
|
40
|
+
page = list(items[start : start + limit])
|
|
41
|
+
while True:
|
|
42
|
+
nxt = start + len(page)
|
|
43
|
+
more = nxt < len(items)
|
|
44
|
+
response = {**build(page), "truncated": more, "next_cursor": str(nxt) if more else None}
|
|
45
|
+
used = size(response)
|
|
46
|
+
if used <= max_chars:
|
|
47
|
+
return response
|
|
48
|
+
if len(page) <= 1:
|
|
49
|
+
raise OverBudget(f"one item needs {used} characters; the budget is {max_chars}")
|
|
50
|
+
page = page[: max(1, min(len(page) - 1, len(page) * max_chars // used))]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse_cursor(cursor: str | None, total: int) -> int:
|
|
54
|
+
"""Offset for a cursor from `fit_page`; None/"" is the start. Anything else is rejected."""
|
|
55
|
+
if cursor in (None, ""):
|
|
56
|
+
return 0
|
|
57
|
+
text = str(cursor)
|
|
58
|
+
if not (text.isascii() and text.isdecimal()) or int(text) > total:
|
|
59
|
+
raise ValueError(f"invalid cursor: {cursor!r}")
|
|
60
|
+
return int(text)
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Append-only JSONL decision log behind an explicit confirm flag.
|
|
2
|
+
|
|
3
|
+
- Nothing is written unless `confirm is True` (a tool layer passes the human's confirmation
|
|
4
|
+
through; casekit cannot verify it, so treat the log as a worklog, not an audit trail).
|
|
5
|
+
- One line per record: sorted-key JSON (no NaN/Infinity), raw UTF-8, LF, at most
|
|
6
|
+
MAX_RECORD_BYTES; the file is capped at `max_bytes` including the new line. Writers take a
|
|
7
|
+
lock (a sidecar `<log>.lock`), so concurrent appends never fork the chain.
|
|
8
|
+
- By default each line carries `prev_sha256`, the sha256 of the previous line's exact bytes
|
|
9
|
+
(GENESIS for the first). `verify_chain` finds edits, insertions and deletions *before* the
|
|
10
|
+
last line. It cannot see a truncated tail or an edited last line, and anyone who can write
|
|
11
|
+
the file can rewrite the whole chain: store `head()` somewhere else and compare it.
|
|
12
|
+
`chain=False` writes the record unchanged, for logs that predate the chain.
|
|
13
|
+
|
|
14
|
+
Extracted from exposure-case-builder (disposition).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import time
|
|
23
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
24
|
+
from contextlib import contextmanager
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from .schema import Decision
|
|
29
|
+
|
|
30
|
+
CHAIN_KEY = "prev_sha256"
|
|
31
|
+
GENESIS = "0" * 64
|
|
32
|
+
DEFAULT_MAX_BYTES = 5 * 1024 * 1024 # a worklog, not a database
|
|
33
|
+
MAX_RECORD_BYTES = 64 * 1024
|
|
34
|
+
MAX_READ_BYTES = 4 * DEFAULT_MAX_BYTES
|
|
35
|
+
LOCK_TIMEOUT_S = 10.0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class DecisionLogError(ValueError):
|
|
39
|
+
"""The log could not be written or read; messages never include record contents."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Head:
|
|
44
|
+
"""Anchor for the tail: store it outside the log and compare later."""
|
|
45
|
+
|
|
46
|
+
lines: int
|
|
47
|
+
sha256: str # of the last line; GENESIS for an empty log
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def line_hash(raw_line: bytes) -> str:
|
|
51
|
+
"""sha256 of one line's exact bytes, without its terminating LF."""
|
|
52
|
+
return hashlib.sha256(raw_line).hexdigest()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@contextmanager
|
|
56
|
+
def _locked(target: Path) -> Iterator[None]:
|
|
57
|
+
lock_path = target.with_name(target.name + ".lock")
|
|
58
|
+
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
|
|
59
|
+
try:
|
|
60
|
+
if os.name == "nt":
|
|
61
|
+
import msvcrt
|
|
62
|
+
|
|
63
|
+
deadline = time.monotonic() + LOCK_TIMEOUT_S
|
|
64
|
+
while True:
|
|
65
|
+
try:
|
|
66
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
67
|
+
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
|
|
68
|
+
break
|
|
69
|
+
except OSError:
|
|
70
|
+
if time.monotonic() > deadline:
|
|
71
|
+
raise DecisionLogError("the log is locked by another writer") from None
|
|
72
|
+
time.sleep(0.01)
|
|
73
|
+
try:
|
|
74
|
+
yield
|
|
75
|
+
finally:
|
|
76
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
77
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
|
|
78
|
+
else:
|
|
79
|
+
import fcntl
|
|
80
|
+
|
|
81
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
82
|
+
try:
|
|
83
|
+
yield
|
|
84
|
+
finally:
|
|
85
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
86
|
+
finally:
|
|
87
|
+
os.close(fd)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _size(path: Path) -> int:
|
|
91
|
+
try:
|
|
92
|
+
return path.stat().st_size
|
|
93
|
+
except FileNotFoundError:
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _raw_lines(path: Path, max_bytes: int = MAX_READ_BYTES) -> list[bytes]:
|
|
98
|
+
"""Every line (LF-split, the empty piece after a final LF dropped)."""
|
|
99
|
+
if _size(path) > max_bytes:
|
|
100
|
+
raise DecisionLogError(f"the log is too large to read (limit {max_bytes} bytes)")
|
|
101
|
+
try:
|
|
102
|
+
data = path.read_bytes() if path.exists() else b""
|
|
103
|
+
except OSError as exc:
|
|
104
|
+
raise DecisionLogError(f"cannot read the log: {type(exc).__name__}") from None
|
|
105
|
+
lines = data.split(b"\n")
|
|
106
|
+
return lines[:-1] if lines and lines[-1] == b"" else lines
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _last_line(path: Path) -> bytes | None:
|
|
110
|
+
"""The last non-blank line, read from the tail only (O(record), not O(file))."""
|
|
111
|
+
size = _size(path)
|
|
112
|
+
if size == 0:
|
|
113
|
+
return None
|
|
114
|
+
window = min(size, MAX_RECORD_BYTES + 1024)
|
|
115
|
+
with path.open("rb") as fh:
|
|
116
|
+
fh.seek(size - window)
|
|
117
|
+
tail = fh.read(window)
|
|
118
|
+
lines = [ln for ln in tail.split(b"\n") if ln.strip()]
|
|
119
|
+
if not lines:
|
|
120
|
+
return None
|
|
121
|
+
if window < size and b"\n" not in tail.rstrip(b"\n"):
|
|
122
|
+
raise DecisionLogError("the last log line is longer than a record may be")
|
|
123
|
+
return lines[-1]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _encode(line: Mapping[str, object]) -> bytes:
|
|
127
|
+
try:
|
|
128
|
+
text = json.dumps(line, sort_keys=True, ensure_ascii=False, allow_nan=False)
|
|
129
|
+
return (text + "\n").encode("utf-8")
|
|
130
|
+
except (TypeError, ValueError, UnicodeError):
|
|
131
|
+
raise DecisionLogError("the record is not valid JSON-serializable data") from None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def append(
|
|
135
|
+
path: str | Path,
|
|
136
|
+
record: Mapping[str, object],
|
|
137
|
+
*,
|
|
138
|
+
confirm: bool,
|
|
139
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
140
|
+
chain: bool = True,
|
|
141
|
+
) -> dict:
|
|
142
|
+
"""Validate, then append exactly one line; returns the dict that was written."""
|
|
143
|
+
if confirm is not True:
|
|
144
|
+
raise DecisionLogError("writing to the decision log requires confirm=True")
|
|
145
|
+
if chain and CHAIN_KEY in record:
|
|
146
|
+
raise DecisionLogError(f"{CHAIN_KEY!r} is reserved for the hash chain")
|
|
147
|
+
target = Path(path)
|
|
148
|
+
_encode(record) # reject bad data before touching the disk
|
|
149
|
+
try:
|
|
150
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
with _locked(target):
|
|
152
|
+
line = dict(record)
|
|
153
|
+
if chain:
|
|
154
|
+
previous = _last_line(target)
|
|
155
|
+
line[CHAIN_KEY] = line_hash(previous) if previous is not None else GENESIS
|
|
156
|
+
data = _encode(line)
|
|
157
|
+
if len(data) > MAX_RECORD_BYTES:
|
|
158
|
+
raise DecisionLogError(f"the record is too large (limit {MAX_RECORD_BYTES} bytes)")
|
|
159
|
+
if _size(target) + len(data) > max_bytes:
|
|
160
|
+
raise DecisionLogError("the decision log is full; archive or trim it first")
|
|
161
|
+
flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0)
|
|
162
|
+
fd = os.open(target, flags, 0o600)
|
|
163
|
+
try:
|
|
164
|
+
os.write(fd, data) # one write of one complete line
|
|
165
|
+
finally:
|
|
166
|
+
os.close(fd)
|
|
167
|
+
except OSError as exc:
|
|
168
|
+
raise DecisionLogError(f"cannot write the log: {type(exc).__name__}") from None
|
|
169
|
+
return line
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def record_decision(
|
|
173
|
+
path: str | Path, decision: Decision, *, confirm: bool, max_bytes: int = DEFAULT_MAX_BYTES
|
|
174
|
+
) -> dict:
|
|
175
|
+
"""Append a schema-validated Decision (chained)."""
|
|
176
|
+
return append(path, decision.model_dump(mode="json"), confirm=confirm, max_bytes=max_bytes)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _parse(raw: bytes, number: int) -> dict:
|
|
180
|
+
try:
|
|
181
|
+
data = json.loads(raw.decode("utf-8"))
|
|
182
|
+
except (ValueError, RecursionError):
|
|
183
|
+
raise DecisionLogError(f"corrupt log entry at line {number}") from None
|
|
184
|
+
if not isinstance(data, dict):
|
|
185
|
+
raise DecisionLogError(f"corrupt log entry at line {number}")
|
|
186
|
+
return data
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _numbered(path: str | Path, max_bytes: int) -> Iterable[tuple[int, bytes]]:
|
|
190
|
+
for number, raw in enumerate(_raw_lines(Path(path), max_bytes), start=1):
|
|
191
|
+
if raw.strip():
|
|
192
|
+
yield number, raw
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def read(path: str | Path, max_bytes: int = MAX_READ_BYTES) -> tuple[dict, ...]:
|
|
196
|
+
"""All entries in file order; a missing file has none. A corrupt line raises."""
|
|
197
|
+
return tuple(_parse(raw, n) for n, raw in _numbered(path, max_bytes))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def read_lenient(
|
|
201
|
+
path: str | Path, max_bytes: int = MAX_READ_BYTES
|
|
202
|
+
) -> tuple[tuple[dict, ...], tuple[int, ...]]:
|
|
203
|
+
"""Valid entries plus the numbers of skipped lines, so one bad line can't stop a tool."""
|
|
204
|
+
entries: list[dict] = []
|
|
205
|
+
bad: list[int] = []
|
|
206
|
+
for number, raw in _numbered(path, max_bytes):
|
|
207
|
+
try:
|
|
208
|
+
entries.append(_parse(raw, number))
|
|
209
|
+
except DecisionLogError:
|
|
210
|
+
bad.append(number)
|
|
211
|
+
return tuple(entries), tuple(bad)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def verify_chain(path: str | Path, max_bytes: int = MAX_READ_BYTES) -> tuple[int, ...]:
|
|
215
|
+
"""Line numbers that break the chain: a `prev_sha256` that doesn't match the line before,
|
|
216
|
+
or a blank line (append never writes one). See the module docstring for what it can't see."""
|
|
217
|
+
broken: list[int] = []
|
|
218
|
+
expected = GENESIS
|
|
219
|
+
for number, raw in enumerate(_raw_lines(Path(path), max_bytes), start=1):
|
|
220
|
+
try:
|
|
221
|
+
data = _parse(raw, number) if raw.strip() else {}
|
|
222
|
+
except DecisionLogError:
|
|
223
|
+
data = {}
|
|
224
|
+
if data.get(CHAIN_KEY) != expected:
|
|
225
|
+
broken.append(number)
|
|
226
|
+
expected = line_hash(raw)
|
|
227
|
+
return tuple(broken)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def head(path: str | Path, max_bytes: int = MAX_READ_BYTES) -> Head:
|
|
231
|
+
lines = _raw_lines(Path(path), max_bytes)
|
|
232
|
+
return Head(len(lines), line_hash(lines[-1]) if lines else GENESIS)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def latest_by(entries: Iterable[Mapping[str, object]], key: str) -> dict[object, Mapping]:
|
|
236
|
+
"""The most recent entry per value of `key` (later lines win)."""
|
|
237
|
+
return {e[key]: e for e in entries if key in e}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Stable identifiers and content hashes for evidence.
|
|
2
|
+
|
|
3
|
+
Canonical JSON = sorted keys, no whitespace, raw UTF-8. Its definition is pinned by a golden
|
|
4
|
+
test: changing it would silently change every stored hash and ID.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
|
|
12
|
+
ID_HASH_CHARS = 24 # 96 bits: IDs may be built from attacker-influenced scanner data
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def canonical_json(obj: object) -> str:
|
|
16
|
+
"""Raises ValueError for NaN/Infinity (not JSON). Note 1 and 1.0 hash differently."""
|
|
17
|
+
return json.dumps(
|
|
18
|
+
obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sha256_of(obj: object) -> str:
|
|
23
|
+
return hashlib.sha256(canonical_json(obj).encode("utf-8")).hexdigest()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def stable_id(prefix: str, *parts: str) -> str:
|
|
27
|
+
"""`<prefix>-<24 hex>` from the parts; parts are hashed as a JSON list, so they can't
|
|
28
|
+
run together ("ab", "c" differs from "a", "bc")."""
|
|
29
|
+
return f"{prefix}-{sha256_of(list(parts))[:ID_HASH_CHARS]}"
|