Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
7495160
TD-5420: a computer with no secret service has no keychain
captcrock Nov 30, 2026
6d838b9
TD-5420: revert reading no secret service as no keychain
captcrock Nov 30, 2026
f216b50
TD-5420: no secret service, audit.key_store, and exports a key store …
captcrock Nov 30, 2026
be6aa07
TD-5420: the four audit key store rules, and the review's seven findings
captcrock Nov 30, 2026
8adcb6f
TD-5420: review round 3: a failed switch starts over, windows bound t…
captcrock Nov 30, 2026
12eff3d
TD-5420: review round 4: rule B replaced by the set-aside, robust out…
captcrock Nov 30, 2026
e999c7e
TD-5420: review round 5: audit.key never trusted beside a keychain he…
captcrock Nov 30, 2026
31f26fe
TD-5420: review round 6: a late table's genesis at the switch, non-UT…
captcrock Dec 1, 2026
6e36af2
TD-5420: review round 7: switch before reads, a folder log holds sign…
captcrock Dec 1, 2026
55cf0e6
TD-5420: review round 8: a folder-key window counts, a lock waits at …
captcrock Dec 1, 2026
34cf16b
TD-5420: the narrow fix for 0.5.14: take out audit.key_store, the swi…
captcrock Dec 1, 2026
49c10b0
TD-5420: the usage export never refuses for integrity (the manager's …
captcrock Dec 1, 2026
701e179
TD-5420: assert the audit export never refuses, it names the break
captcrock Dec 1, 2026
c8feb63
TD-5420: review round 2 of the narrowed PR: honest words, no dead ref…
captcrock Dec 1, 2026
8d35096
TD-5420: review round 3: a failed check marks every usage record
captcrock Dec 1, 2026
bd79b45
Merge remote-tracking branch 'origin/main' into td/5420-no-secret-ser…
captcrock Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
635 changes: 635 additions & 0 deletions DECISIONS.md

Large diffs are not rendered by default.

47 changes: 34 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,16 @@ directives in [`AGENTS.md`](AGENTS.md) §2 and enforced in code.
it, its own hash (over its row number and its values), and an HMAC made with an integrity key
([`audit_chain.py`](core/tstd/audit_chain.py)). Rows written before this existed are covered
by one digest per table, taken when the chain began. Doctor checks the whole chain and names
the first bad row; an export of model calls refuses whenever Doctor's audit row fails for
the rows themselves (writes that were lost, below, do not stop it), and otherwise holds the rows of `audit.db` and every kept file below, each naming its file in a
`source` column, so it adds up to the usage report.
the first bad row; an export of model calls refuses only when the chain is actually broken
(a bad link, hash or signature, a removed marker, a log set aside as changed or damaged, a
kept file it cannot read, or unsigned rows outside every recorded key store outage window;
writes that were lost, below, do not stop it). When the key store could not be used to
verify the rows (no secret service running, a locked keychain), it still works, and each
row says `integrity: not verified, key store unavailable since <time>` (or `from <time> to
<time>` for an outage that ended); otherwise `integrity: verified`. It holds the rows of
`audit.db` and every kept file below, each naming its file in a `source` column, so it adds
up to the usage report; a row from a kept file is never "verified", since no check covers
it.
Exactly what that guarantees:
- an edit, an insertion, a deletion or a renumbering of any row before the newest is
detected: the chain breaks there. Removing every chain marker is reported too ("the chain
Expand All @@ -273,9 +280,9 @@ directives in [`AGENTS.md`](AGENTS.md) §2 and enforced in code.
`audit.tampered.json` from the data folder. If the file cannot be moved, that run records
in memory. A folder written by a newer TST Desk is not checked; an `audit.db` alone
written by one is set aside as `audit.db.newer-<stamp>` (last point below);
- a missing or locked key store never stops recording: when neither the OS keychain nor
`audit.key` can be used, rows are still written, unsigned, and Doctor's audit row says so
(below). That is the promise; surviving every lock, crash or full disk is not:
- a missing or locked key store never stops recording: when the key store cannot be used,
rows are still written, unsigned, inside a recorded outage window, and Doctor's audit row
says so (below). That is the promise; surviving every lock, crash or full disk is not:
- a write (a turn with its model calls, a tool call, a session starting or reattaching) that
meets a lock or busy error anywhere is kept whole, in memory, and the kept writes are
retried, oldest first and each whole, before the next write, a spend read and Doctor's
Expand All @@ -284,7 +291,7 @@ directives in [`AGENTS.md`](AGENTS.md) §2 and enforced in code.
waiting, and the chat is told its write is kept, not that nothing is recorded. If
`audit.db` cannot even be read for Doctor's check (another program holds it locked),
the row fails saying the log could not be checked just now, with how many wait, and the
export refuses until it can be checked. At most 10,000 are kept;
usage export marks its rows not verified. At most 10,000 are kept;
- if a kept write still cannot be written when TST Desk quits, it is lost. Quitting tries
once more, waiting a fraction of a second on a lock so it stays inside the five-second
shutdown limit; what is left is counted, and only the count and the time (no row data)
Expand Down Expand Up @@ -329,11 +336,25 @@ directives in [`AGENTS.md`](AGENTS.md) §2 and enforced in code.
and is made only when the keychain says it holds none, so a failed read never replaces it.
While the keychain holds it, only rows signed with it vouch: a row signed with a key in the
data folder fails, since anyone who can write that folder could have put one there;
- when the keychain cannot be used, the key is `audit.key` in the data folder (0600), and
Doctor says "integrity key not in the OS keychain": then anyone who can read that folder
has the key, and a full backup of the data folder holds it too, so whoever has the backup
could forge the log. An `audit.key` that cannot be read is never replaced; that run
records unsigned rows;
- only on a computer with no keychain helper is the key `audit.key` in the data folder
(0600), and Doctor says "integrity key not in the OS keychain": then anyone who can read
that folder has the key, and a full backup of the data folder holds it too, so whoever has
the backup could forge the log. An `audit.key` that cannot be read is never replaced; that
run records unsigned rows. A locked keychain, or a Linux computer with no secret service
running, is an outage, not "no keychain": nothing is minted in its place, and with no
secret service Doctor says "No secret service is running. Start your keyring once and
restart TST Desk.";
- when the key store cannot be used
([`docs/configuration.md`](docs/configuration.md#the-audit-logs-integrity-key-no-setting)):
"not verified" exports cover only rows written inside a recorded outage window, and an
unsigned row outside every window is a break (the usage export still writes every row,
marked "the chain check failed", and Doctor names the cause; the audit export writes every
row and names the break in its header); a locked or timed-out
keychain never makes `audit.key`. Nor does a run that cannot find the keychain helper on
a folder that records the keychain keyed it (`audit.keychain-keyed`). With a keychain
helper installed, a row signed with `audit.key` never verifies, so a log that key signed
before a helper was installed reads as changed once the keychain is used (moving it over
is TD-5429, not in this version);
- a record that the log was chained (in the keychain, or `audit.chain-begun` in the data
folder) stops anyone from making the chain start over on edited rows. It is copied to the
keychain the first time TST Desk runs with a usable keychain. The file, like `audit.key`,
Expand All @@ -343,7 +364,7 @@ directives in [`AGENTS.md`](AGENTS.md) §2 and enforced in code.
before it counts as nothing), a log whose markers are gone is never started over: that
run begins no chain at all, not even for its empty tables (a log with no rows still
begins), Doctor's audit row fails ("unlock the OS keychain and restart TST Desk") and
export refuses. The first run that can read the keychain begins the chain over every row
both exports say the rows are not verified. The first run that can read the keychain begins the chain over every row
then present, or reports it removed if the record is there. The exception is a computer
with no keychain at all: there is nothing to read, so the `audit.chain-begun` file alone
decides, which protects only against someone who cannot write the data folder;
Expand Down
169 changes: 169 additions & 0 deletions core/tests/audit_key_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
"""A keychain whose secret service can be gone, and the logs the TD-5420 key tests start from.

``secret-tool``'s stderr is played through the real Linux lookup
(``keychain_secret_tool.lookup``) and the real classification, from a
runner that never starts a process: the real OS keychain is never touched.
"""

from __future__ import annotations

import json
import sqlite3
import time
from pathlib import Path
from typing import Any

import pytest

from tests.audit_chain_helpers import FakeKeychain
from tstd import keychain, keychain_secret_tool
from tstd.audit import MIGRATIONS, AuditStore
from tstd.audit_hash import row_hash, sign
from tstd.audit_key import IntegrityKey
from tstd.audit_queries import export_jsonl

NO_SERVICE = b"secret-tool: The name org.freedesktop.secrets was not provided by any .service files"


class Keyring(FakeKeychain):
"""A keychain whose secret service can be gone: then the CLI's own stderr decides."""

def __init__(self, monkeypatch: pytest.MonkeyPatch, stderr: bytes = NO_SERVICE) -> None:
super().__init__(monkeypatch)
self.gone = True
self.asked = 0
working_get = keychain.get_audit_secret
working_put = keychain.store_audit_secret

async def run(args: tuple[str, ...]) -> tuple[int, bytes, bytes]:
return 1, b"", stderr

async def get(account: str) -> str:
self.asked += 1
if self.gone:
service = "com.thatsimpletech.tstdesk"
return await keychain_secret_tool.lookup(service, account, run)
return await working_get(account)

async def put(account: str, value: str) -> None:
self.asked += 1
if self.gone:
raise keychain._classify_cli_failure(stderr.decode(), "Failed to store")
await working_put(account, value)

monkeypatch.setattr("tstd.keychain.get_audit_secret", get)
monkeypatch.setattr("tstd.keychain.store_audit_secret", put)


def v8_log(db: Path) -> None:
"""A 0.5.13 log (schema v8, before the chain), with a model call to export."""
db.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(db)
try:
AuditStore._migrate(conn, MIGRATIONS[:8])
conn.execute("INSERT INTO sessions VALUES ('s1', '/ws', 1000.0)")
conn.execute(
"INSERT INTO turns (session_id, turn_index, tier, tokens, cost, duration, ts)"
" VALUES ('s1', 1, 'brain', 10, 0.5, 1.0, 1001.0)"
)
conn.execute(
"INSERT INTO model_calls (session_id, turn_id, tier, model, prompt_tokens,"
" cached_prompt_tokens, completion_tokens, cost, is_classifier, ts)"
" VALUES ('s1', 1, 'brain', 'm', 5, 0, 5, 0.5, 0, 1002.0)"
)
conn.commit()
finally:
conn.close()


def jsonl(path: Path) -> list[dict[str, Any]]:
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]


def chained(db: Path, monkeypatch: pytest.MonkeyPatch) -> Keyring:
"""A log chained and signed while the keyring ran; then its service is gone."""
v8_log(db)
ring = Keyring(monkeypatch)
ring.gone = False
store = AuditStore(db)
try:
for i in range(2, 5):
store.append_turn("s1", i, "brain", 1, 0.5, 0.1, ts=1500.0 + i)
assert store.verify_chain().ok
finally:
store.close()
ring.gone = True
return ring


def forge(db: Path, store: AuditStore, table: str, from_id: int, key: IntegrityKey | None) -> None:
"""Rehash ``table`` from ``from_id`` on, linking to the row before or the genesis.

With ``key`` every row is re-signed with it; without, signatures are nulled.
"""
conn = sqlite3.connect(db)
try:
cols = store._chain.data_columns(table)
before = conn.execute(f"SELECT row_hash FROM {table} WHERE id = ?", (from_id - 1,))
prev = (before.fetchone() or (None,))[0]
if prev is None:
prev = conn.execute(
"SELECT digest FROM chain_genesis WHERE table_name = ?", (table,)
).fetchone()[0]
for rowid, *data in conn.execute(
f"SELECT id, {', '.join(cols)} FROM {table} WHERE id >= ? ORDER BY id", (from_id,)
).fetchall():
digest = row_hash(prev, rowid, dict(zip(cols, data, strict=True)))
mac, key_id = (sign(key, digest), key.key_id) if key else (None, None)
conn.execute(
f"UPDATE {table} SET prev_hash = ?, row_hash = ?, mac = ?, key_id = ? WHERE id = ?",
(prev, digest, mac, key_id, rowid),
)
prev = digest
conn.commit()
finally:
conn.close()


def turns(store: AuditStore, *indexes: int) -> None:
for i in indexes:
store.append_turn("s1", i, "brain", 1, 0.5, 0.1, ts=time.time())


def all_marked(path: object, word: str | None = None) -> bool:
"""Every record of a usage export is marked, never refused (0.5.14).

Records of the checked ``audit.db`` carry exactly ``word`` (by default
the chain check's failure word); any other file's start with it.
"""
import csv
import json

from tstd.audit_integrity import CHECK_FAILED

want = CHECK_FAILED if word is None else word
text = Path(str(path)).read_text()
try:
rows = [json.loads(x) for x in text.splitlines()]
except ValueError:
rows = list(csv.DictReader(text.splitlines()))
return bool(rows) and all(
r["integrity"] == want
if r["source"] == "audit.db"
else str(r["integrity"]).startswith(want)
for r in rows
)


def marked_not_verified(
store: AuditStore, tmp_path: Path, match: str, word: str | None = None
) -> None:
"""The usage export never refuses (0.5.14): every row is marked, Doctor names why."""
import re

from tstd.audit_doctor import audit_doctor_row

out = tmp_path / "marked.jsonl"
export_jsonl(store, out)
assert all_marked(out, word), out.read_text()
assert re.search(match, audit_doctor_row(store.verify_chain()).detail)
3 changes: 2 additions & 1 deletion core/tests/test_audit_approvals.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from tstd.audit import MIGRATIONS, AuditStore, audit_db_path
from tstd.audit_chain import LATE_TABLES, V9_TABLES
from tstd.audit_doctor import audit_doctor_row
from tstd.audit_integrity import VERIFIED
from tstd.audit_rows import read_all
from tstd.audit_structure import expected_master, read_master, structure_problem
from tstd.audit_wire import AuditFilters
Expand Down Expand Up @@ -224,7 +225,7 @@ def test_the_export_carries_the_approval_columns(tmp_path: Path, fmt: str) -> No
finally:
store.close()
path = tmp_path / f"out.{fmt}"
assert write_export("csv" if fmt == "csv" else "jsonl", chain, found.rows, path) == 1
assert write_export("csv" if fmt == "csv" else "jsonl", chain, found.rows, path, VERIFIED) == 1
if fmt == "jsonl":
(row,) = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()[1:]]
else:
Expand Down
28 changes: 18 additions & 10 deletions core/tests/test_audit_chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import sqlite3
import stat
import sys
import time
from collections.abc import Iterator
from pathlib import Path

Expand All @@ -22,10 +23,12 @@
from tests.audit_chain_helpers import count_rows as _rows
from tests.audit_chain_helpers import fill as _fill
from tests.audit_chain_helpers import raw as _raw
from tests.audit_key_helpers import all_marked
from tstd import audit_key
from tstd.audit import MIGRATIONS, AuditStore
from tstd.audit_chain import CHAIN_COLUMNS, CHAINED_TABLES, ChainBroken
from tstd.audit_chain import CHAIN_COLUMNS, CHAINED_TABLES
from tstd.audit_doctor import KEY_NOT_IN_KEYCHAIN, audit_doctor_row
from tstd.audit_key_file import parse_key
from tstd.audit_queries import export_csv, export_jsonl

posix_only = pytest.mark.skipif(sys.platform == "win32", reason="POSIX file modes")
Expand Down Expand Up @@ -197,7 +200,7 @@ def test_keychain_failure_uses_a_0600_key_file_and_doctor_warns(
) -> None:
key_file = db.parent / audit_key.KEY_FILE
assert stat.S_IMODE(os.stat(key_file).st_mode) == 0o600
key = audit_key._parse(key_file.read_text(encoding="utf-8"), "file")
key = parse_key(key_file.read_text(encoding="utf-8"), "file")
assert key is not None
ids = {r[0] for r in store._conn.execute("SELECT key_id FROM turns")}
assert ids == {key.key_id}
Expand All @@ -209,10 +212,14 @@ def test_keychain_failure_uses_a_0600_key_file_and_doctor_warns(
assert key_file.read_text(encoding="utf-8").strip() not in row.detail


def test_a_locked_keychain_is_not_asked_again_and_the_file_is_used(
def test_a_locked_keychain_is_not_asked_again_and_mints_no_file(
db: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A locked keychain waits out a 5 s timeout per call; one call is enough."""
"""A locked keychain waits out a 5 s timeout per call; one call is enough.

Rule D (TD-5420): it is an outage, so no audit.key is made and rows are
recorded unsigned inside the outage window.
"""
calls: list[str] = []

async def locked(*_args: object) -> str:
Expand All @@ -227,10 +234,12 @@ async def refuse(*_args: object) -> bool:
monkeypatch.setattr("tstd.keychain.store_audit_secret", refuse)
store = AuditStore(db)
try:
store.append_session("s1", "/ws", 1.0)
store.append_session("s1", "/ws", time.time())
assert calls == ["get"]
assert store.verify_chain().key_source == "file"
assert (db.parent / audit_key.KEY_FILE).exists()
report = store.verify_chain()
assert report.key_source == "none" and report.unavailable_since is not None
assert report.unsigned and not report.unsigned_outside
assert not (db.parent / audit_key.KEY_FILE).exists()
finally:
store.close()

Expand Down Expand Up @@ -343,6 +352,5 @@ def test_export_refuses_a_broken_chain(
) -> None:
_raw(db, "UPDATE model_calls SET cost = 0")
out = tmp_path / "out" / "usage.txt"
with pytest.raises(ChainBroken, match="model_calls row 1"):
export(store, out) # type: ignore[operator]
assert not out.exists()
export(store, out) # type: ignore[operator]
assert all_marked(out) # the usage export never refuses (0.5.14)
10 changes: 7 additions & 3 deletions core/tests/test_audit_chain_anchor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from __future__ import annotations

import json
import sqlite3
from pathlib import Path

Expand All @@ -18,7 +19,7 @@
from tests.audit_chain_helpers import FakeKeychain, fill, raw
from tstd import keychain as keychain_module
from tstd.audit import MIGRATIONS, AuditStore
from tstd.audit_chain import CHAINED_TABLES, ChainBroken
from tstd.audit_chain import CHAINED_TABLES
from tstd.audit_doctor import UNANCHORED_FIX, audit_doctor_row
from tstd.audit_hash import UNANCHORED
from tstd.audit_marker import MARKER_FILE, chain_begun_account
Expand Down Expand Up @@ -101,8 +102,11 @@ def _assert_unanchored(db: Path, tmp_path: Path) -> None:
assert row.status == "fail"
assert row.fix == UNANCHORED_FIX
assert "Unlock the OS keychain and restart TST Desk" in UNANCHORED_FIX
with pytest.raises(ChainBroken):
export_jsonl(store, tmp_path / "out.jsonl")
# Not tampering, by the manager's decision: the export works, not verified.
out = tmp_path / "out.jsonl"
assert export_jsonl(store, out) == 1
(call,) = [json.loads(line) for line in out.read_text().splitlines()]
assert call["integrity"].startswith("integrity: not verified, key store unavailable since ")
finally:
store.close()

Expand Down
Loading
Loading