Repository navigation
Expand file tree
/
Copy pathblobstore.py
More file actions
2996 lines (2766 loc) · 135 KB
/
Copy pathblobstore.py
File metadata and controls
2996 lines (2766 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""SHA256-addressed blob store for rescued tool results. Global keys, per-session indexes."""
import hashlib
import json
import logging
import os
import re
import tempfile
import time
import threading
from contextlib import contextmanager
from functools import wraps
from pathlib import Path
try:
import fcntl # POSIX-only file locking for cross-process RMW safety.
_HAVE_FCNTL = True
except ImportError: # pragma: no cover - non-POSIX fallback path
fcntl = None # type: ignore[assignment]
_HAVE_FCNTL = False
if __package__:
from .excerpt import detect_type as _detect_type
from .index import build_outline as _struct_outline
from .index import render_outline as _render_outline
from .navigation import NavigationView, navigation_view as _navigation_view
from .chunking import chunk_lines as _chunk_lines
from . import semantic as _sem
from .labels import (label_for_tool, label_for_args as _label_for_args,
VALID_LABELS, _LABEL_UPGRADE_PATTERNS,
_BUILTIN_TOOL_LABELS)
from .entities import (get_registry as _entity_registry,
extract_entities as _extract_entities,
distinct_entity_kinds as _distinct_entity_kinds)
from .hermes_home import default_store_path as _default_store_path_shared
else:
from excerpt import detect_type as _detect_type # type: ignore[no-redef]
from index import build_outline as _struct_outline # type: ignore[no-redef]
from index import render_outline as _render_outline # type: ignore[no-redef]
from navigation import NavigationView, navigation_view as _navigation_view # type: ignore[no-redef]
from chunking import chunk_lines as _chunk_lines # type: ignore[no-redef]
import semantic as _sem # type: ignore[no-redef]
from labels import (label_for_tool, label_for_args as _label_for_args, # type: ignore[no-redef]
VALID_LABELS, _LABEL_UPGRADE_PATTERNS, # type: ignore[no-redef]
_BUILTIN_TOOL_LABELS) # type: ignore[no-redef]
from entities import (get_registry as _entity_registry, # type: ignore[no-redef]
extract_entities as _extract_entities, # type: ignore[no-redef]
distinct_entity_kinds as _distinct_entity_kinds) # type: ignore[no-redef]
from hermes_home import default_store_path as _default_store_path_shared # type: ignore[no-redef]
# Sensitivity ordering for content-aware label resolution (FIX-1). The
# highest index in this tuple wins when comparing two labels; this is the
# single source of truth for "credential > personal > internal > public"
# comparisons in BlobStore. passref consumes it via
# BlobStore._max_label_for_blob (fail-closed lookup), not its own copy.
_LABEL_SENSITIVITY = {"public": 0, "internal": 1, "personal": 2,
"credential": 3}
_SLICE_MASK_MARKER = "[masked:credential-shape]"
# T4.1: version-ref grammar — a blob ref is the 12-hex content id, optionally
# followed by ``@N`` for a specific version in the chain. The fetch handler
# parses this before the 12-hex validation, so older callers that pass a bare
# bid remain byte-identical.
_BLOB_REF_RE = re.compile(r"^([0-9a-f]{12})(?:@(\d+))?$")
# Refusal marker returned by fetch when @N does not exist in the chain. The
# exact shape is part of the T4.1 contract (tests pin the literal prefix).
VERSION_NOT_FOUND_MARKER_PREFIX = "[Toolaria: version "
VERSION_NOT_FOUND_MARKER_MIDDLE = " not found for blob "
VERSION_NOT_FOUND_MARKER_SUFFIX = "]"
# Over-fetch headroom for masked grep/chain: raw output is gathered at 4x
# cap so post-mask re-capping still fills the budget. (Correctness agent:
# named once — the two call sites must not drift.)
_MASK_OVERFETCH_FACTOR = 4
# Credential-shape checks use fixed, linear patterns on the whole line.
# Query regexes retain their separate per-line/time caps; limiting the
# security scan to a prefix would expose secrets later in long JSON values.
_SLICE_BUDGET_MARKER_PREFIX = (
"[Toolaria: credential slice budget exhausted for "
)
_SLICE_BUDGET_MARKER_SUFFIX = (
"; use allowlisted destinations]"
)
_CREDENTIAL_SLICE_BUDGET_DEFAULT = 2000
# ── T3.1: entity_kinds resolver ────────────────────────────────────────────
def _compute_entity_kinds(args, cfg) -> list[str]:
"""Return the sorted distinct entity kinds referenced by *args*.
Best-effort: a broken entity_registry (e.g. an uncompilable regex
that survived validation) yields an empty list with a logged
warning rather than crashing the rescue path. The
``entity_registry`` itself is validated at register time (FIX-4
posture), so under normal operation this is O(args size).
"""
if not cfg:
return []
try:
registry = _entity_registry(cfg)
except Exception as exc:
logger.warning(
"toolaria: entity_registry resolve failed: %s; "
"falling back to empty entity_kinds", exc,
)
return []
if not registry:
return []
try:
matches = _extract_entities(args, registry)
except Exception as exc:
logger.warning(
"toolaria: extract_entities failed: %s; "
"falling back to empty entity_kinds", exc,
)
return []
return _distinct_entity_kinds(matches)
# ── Phase 1 helpers (T1.3 redaction, T1.4 integrity marker) ─────────────
# Deterministic marker returned (and logged) when fetch-time integrity verify
# fails. Exact string is part of the T1.4 contract — the test matrix asserts
# the literal shape, and downstream parsers may key off the prefix.
INTEGRITY_FAIL_MARKER_PREFIX = (
"[Toolaria: integrity check failed for blob "
)
INTEGRITY_FAIL_MARKER_SUFFIX = "; content does not match index hash]"
# Secret-key name pattern (matches by key, case-insensitive): any field whose
# name looks like an API key / token / password / bearer / secret must be
# scrubbed BEFORE the args snapshot lands in the index.
# Boundaries are letter-only lookarounds, NOT \b: underscore counts as a word
# character, so \btoken\b cannot match inside access_token / refresh_token /
# client_secret — exactly the snake_case shapes real APIs use. The lookarounds
# still reject benign lookalikes (tokenizer: 'token' + 'i'; keynote: no hit).
_SECRET_KEY_RE = re.compile(
r"(?i)(?<![A-Za-z])(api[_-]?key|token|password|authorization|bearer|secret)(?![A-Za-z])"
)
# Secret-value pattern (matches the literal text, regardless of key):
# - sk-XXXXXXX (8+ alphanumerics after the prefix) — common API key shapes
# - "bearer <token>" — Authorization headers leaking into args
_SECRET_VALUE_RE = re.compile(
r"sk-[A-Za-z0-9]{8,}|bearer\s+\S+", re.IGNORECASE
)
_REDACTED = "[REDACTED]"
def _redact_args_snapshot(args, max_chars: int):
"""Produce a JSON-serializable, redaction-safe snapshot of *args*.
Recurses through dicts/lists; values whose KEY matches a secret
pattern are replaced with the REDACTED marker, and any string VALUE
that matches a secret pattern (sk-… or bearer …) is also masked
regardless of its key. The result is truncated to ``max_chars``.
None or empty args return None (null provenance). Non-JSON-native
values fall back to ``repr``; an unserializable input becomes an
empty dict so a broken tool never blocks a rescue.
"""
if args is None:
return None
try:
snap = _scrub(args)
text = json.dumps(snap, sort_keys=True, default=repr, ensure_ascii=False)
except Exception:
return {}
if len(text) > max_chars:
text = text[:max_chars] + f"\n[Toolaria: args_snapshot truncated at {max_chars} chars]"
return text
def _scrub(value):
"""Recursively redact *value* in-place-ish (returns a new container)."""
if isinstance(value, dict):
out = {}
for k, v in value.items():
key = str(k)
if _SECRET_KEY_RE.search(key):
out[key] = _REDACTED
else:
out[key] = _scrub(v)
return out
if isinstance(value, list):
return [_scrub(v) for v in value]
if isinstance(value, tuple):
return [_scrub(v) for v in value]
if isinstance(value, str):
return _SECRET_VALUE_RE.sub(_REDACTED, value)
return value
_LOCK = threading.RLock()
_STORE_LOCK_STATE = threading.local()
_STORE_LOCK_FDS: set[int] = set()
def _reset_store_locks_after_fork():
# Close inherited descriptors without LOCK_UN: unlocking a shared open
# file description in the child would also unlock the parent's operation.
global _LOCK, _STORE_LOCK_STATE, _STORE_LOCK_FDS
for fd in _STORE_LOCK_FDS:
try:
os.close(fd)
except OSError:
pass
_LOCK = threading.RLock()
_STORE_LOCK_STATE = threading.local()
_STORE_LOCK_FDS = set()
if hasattr(os, "register_at_fork"):
os.register_at_fork(after_in_child=_reset_store_locks_after_fork)
def _store_operation(method):
"""Serialise a complete publication/metadata operation with cleanup."""
@wraps(method)
def guarded(self, *args, **kwargs):
with self._store_guard():
return method(self, *args, **kwargs)
return guarded
_BLOB_ID_RE = re.compile(r"^[0-9a-f]{12}$")
class _FlockAcquire:
"""Context manager wrapping fcntl.flock(LOCK_EX) + release.
flock is a per-process, per-file-descriptor advisory lock:
re-acquiring an EX lock on the same fd is a no-op (it just
increments the per-process reference count), and closing any
fd to that file releases the lock. We open a dedicated fd per
charge so each release is independent, and we release via
LOCK_UN + close in __exit__ so a second process can acquire
immediately after this charge returns.
"""
__slots__ = ("_fd", "_path", "_locked")
def __init__(self, fd, path):
self._fd = fd
self._path = path
self._locked = False
def __enter__(self):
if fcntl is None:
return self
fcntl.flock(self._fd, fcntl.LOCK_EX)
self._locked = True
return self
def __exit__(self, exc_type, exc, tb):
if self._locked and fcntl is not None:
try:
fcntl.flock(self._fd, fcntl.LOCK_UN)
finally:
self._locked = False
return False
class _SliceBudgetExceeded(Exception):
"""Internal control-flow signal raised by
``BlobStore._charge_slice_budget`` when the per-blob
credential-slice byte budget has been exceeded. The fetch()
dispatcher catches this and returns the deterministic budget-
exhausted marker to the caller."""
def __init__(self, marker: str):
super().__init__(marker)
self.marker = marker
# Phase 0 hardening (T0.1): explicit perms on every file/dir created by the
# store. mkdir and write_bytes honour umask, so a permissive umask (or a
# pre-existing tree left by an older install) would otherwise leak blobs at
# world-readable. Setting the mode explicitly after every create makes the
# guarantee independent of umask and of installation history.
_DIR_MODE = 0o700
_FILE_MODE = 0o600
# HG-C2 (hermaguard Phase 4): Fernet token signature. Every Fernet
# token starts with version byte 0x80 (0b10000000) followed by an 8-byte
# big-endian timestamp — raw base64url decoding of the token's first
# group yields that header. Plaintext blob content (UTF-8 JSON, text,
# logs) begins with 0x80 with negligible probability.
_FERNET_MAGIC = b"\x80"
def _looks_like_fernet(data: bytes) -> bool:
"""Cheap on-disk heuristic: does *data* start like a Fernet token?
Fernet tokens are base64url of [0x80 || ts8 || ciphertext || hmac];
the decoded first byte is always 0x80. Used only to stamp the index
``enc`` marker when a blob file predates the session writing it —
the decrypt path itself never trusts this (Fernet verifies HMAC).
"""
if not data or len(data) < 60: # min Fernet b64 length >> 57 chars
return False
try:
head = data.split(b".", 1)[0]
import base64
return base64.urlsafe_b64decode(
head + b"=" * (-len(head) % 4))[:1] == _FERNET_MAGIC
except Exception:
return False
logger = logging.getLogger(__name__)
def _chmod_safe(path, mode: int) -> bool:
"""Best-effort chmod that logs and swallows permission errors.
Returns True on success, False on failure. A chmod failure (e.g. a
read-only mount, an immutable file, or an unsupported platform) must
never crash store init: the store is still usable, just without the
perm tightening. The warning makes the gap visible for the operator.
"""
try:
os.chmod(path, mode)
return True
except OSError as exc:
logger.warning("toolaria: chmod %s to 0o%o failed: %s", path, mode, exc)
return False
def _tighten_perms(root: Path, mode: int) -> None:
"""Walk *root* (a dir) and chmod every dir/file under it to *mode*.
Used for init-time migration of older permissive stores (0755 dirs,
0644 files). Failures on individual entries are swallowed (logged by
_chmod_safe); migration is best-effort.
"""
for dirpath, dirnames, filenames in os.walk(root):
_chmod_safe(Path(dirpath), _DIR_MODE)
for name in filenames:
_chmod_safe(Path(dirpath) / name, mode)
# The grep engine. Arbitrary user regex against adversarial blob content is a
# ReDoS hazard that no static denylist fully closes (e.g. a*a*a*...X or
# (a|a)*X backtrack exponentially in C, where a between-lines timeout never
# fires). The `regex` module honours a mid-search timeout, so when it is
# present every pattern is bounded. Without it we fall back to literal
# substring search only (linear, safe); metacharacter patterns are refused
# with a hint to install `regex`.
try:
import regex as _regex_engine
_HAVE_REGEX = True
except ImportError:
_regex_engine = None
_HAVE_REGEX = False
# T4.2: Fernet at-rest encryption (D8 — credential-tier only). The
# `cryptography` package is an optional extra; the canonical test runner
# installs it via ``uv run --with cryptography``. When absent the store
# stays inert for UNCONFIGURED stores (no key = plaintext exactly as
# always), but a CONFIGURED key without the library now REFUSES
# credential writes — reviewer fix 3, 2026-08-25.
try:
from cryptography.fernet import Fernet as _Fernet
_HAVE_FERNET = True
except ImportError:
_Fernet = None # type: ignore[assignment]
_HAVE_FERNET = False
# T4.2: refusal marker returned when an encrypted blob's key is missing
# or corrupt (or when Fernet refuses the ciphertext). The marker is the
# ONLY string a read path may surface for an unreadable encrypted blob —
# never partial plaintext, never a stack trace. Prefix/suffix are
# exported so T4.4 audit + downstream tests can pin the literal shape.
ENCRYPTION_FAIL_MARKER_PREFIX = "[Toolaria: encrypted blob "
ENCRYPTION_FAIL_MARKER_SUFFIX = (
" cannot be decrypted (missing/corrupt key); content withheld]"
)
class _EncryptionUnavailable(Exception):
"""Internal control-flow signal raised when an encrypted blob cannot
be decrypted (missing key file, corrupt key, or malformed
ciphertext). Read paths catch this and return
``ENCRYPTION_FAIL_MARKER_PREFIX..SUFFIX``; never partial plaintext."""
# Patterns containing any of these are "regex" rather than literal; refused on
# the fallback path.
_META_CHARS = set(r".^$*+?{}[]\|()")
# Control characters are never allowed in a pattern.
_CONTROL_RE = re.compile(r"[\x00-\x1f]")
def _default_store_path() -> Path:
"""Blob store under the Hermes home.
Resolution lives in :mod:`hermes_home` so a process without ``HERMES_HOME``
cannot create a second store beside the real one.
"""
return _default_store_path_shared()
class BlobStore:
def __init__(self, cfg: dict):
self.cfg = cfg
bp = (Path(cfg["store_path"]).expanduser() if cfg.get("store_path") else _default_store_path()).resolve()
# Create root first so the subsequent sub-dir mkdirs do not need
# parents=True (and thus skip the root chmod below).
bp.mkdir(parents=True, exist_ok=True)
_chmod_safe(bp, _DIR_MODE)
self.store_path = bp
self._store_lock_path = bp / ".store.lock"
self.blob_dir = bp / "blobs"
self.meta_dir = bp / "sessions"
self.sidecar_dir = bp / "sidecars"
self.blob_dir.mkdir(exist_ok=True)
self.meta_dir.mkdir(exist_ok=True)
self.sidecar_dir.mkdir(exist_ok=True)
for d in (self.blob_dir, self.meta_dir, self.sidecar_dir):
_chmod_safe(d, _DIR_MODE)
# Migration: tighten any older permissive tree the install may have
# left behind (0755 dirs / 0644 files). Best-effort; chmod failures
# are logged but do not stop init.
_tighten_perms(self.blob_dir, _FILE_MODE)
_tighten_perms(self.meta_dir, _FILE_MODE)
_tighten_perms(self.sidecar_dir, _FILE_MODE)
# Hot-blob tracking: in-memory fetch log keyed by (safe_sid, blob_id).
# Records fetch timestamps; recency-weighted count computed during sweep.
# Persisted to index entries during sweep; reloaded on init.
self._fetch_log: dict[tuple[str, str], list[float]] = {}
with self._store_guard():
self._load_fetch_log()
# T1.2: sequences sidecar lazily created on first write when enabled.
self._sequences_dir = bp / "sequences"
# RISKY-3 (Phase 4): dedicated lockfile for cross-process
# serialisation of credential-slice budget RMW. Eagerly
# touched at init so the lockfile exists from the moment
# the store is ready (an operator can `ls` it, and two
# concurrent processes can immediately race on it without
# the first charge paying the touch cost). The fcntl.flock
# is wrapped around the entire read-modify-write of
# credential_served_chars so two processes charging the same
# blob can't lose increments.
self._budget_lock_path = bp / ".budget.lock"
try:
self._budget_lock_path.touch(exist_ok=True)
_chmod_safe(self._budget_lock_path, _FILE_MODE)
except OSError as exc:
logger.debug(
"toolaria: could not pre-create .budget.lock at %s: %s",
self._budget_lock_path, exc,
)
# CAREFUL (a) Phase 4: in-memory fallback accumulator so the
# budget is still enforced within the process when
# _write_idx_file fails (disk full, permission denied,
# operator-broken mount). Cleared on every successful
# persist so a transient failure does not silently inflate
# the in-memory tally.
self._budget_fallback: dict[str, int] = {}
# CAREFUL (b) Phase 4: log the legacy empty-session
# fallback at most once per process so the operator sees
# the legacy dispatcher is in use without spamming every
# charge with a WARNING line.
self._empty_session_logged = False
# T4.2: cached Fernet instance, lazy-resolved from
# ``toolaria_key_file``. ``None`` ⇒ encryption is inactive
# (no key configured, library missing, or key invalid — the
# store treats any of these as inert plaintext). Rotation
# resets the cache so the new key is picked up on next
# encrypt / decrypt. A single instance per BlobStore keeps
# the hot path O(1) after the first credential put.
self._fernet = None
self._fernet_missing_logged = False
# HG-M4 (hermaguard Phase 4): O(1) encrypted-bid lookup cache.
# None = unknown (scan needed), True/False = cached verdict.
# Written through by put() when it stamps enc=True.
self._enc_cache: dict[str, bool] = {}
@contextmanager
def _store_guard(self):
"""One re-entrant lock shared by every writer and sweep of this store.
The thread lock protects the nesting registry; flock protects the
complete blob/index transaction across POSIX processes. Never unlink
the lock file: replacing its inode would split the coordination domain.
Lock acquisition failures propagate rather than publishing unguarded.
"""
with _LOCK:
if not _HAVE_FCNTL:
if not getattr(self, "_store_lock_warning", False):
logger.warning(
"toolaria: POSIX flock unavailable; use one process "
"per store_path (thread-only coordination)")
self._store_lock_warning = True
yield
return
active = getattr(_STORE_LOCK_STATE, "active", None)
if active is None:
active = _STORE_LOCK_STATE.active = {}
key = str(self.store_path)
if key in active:
yield
return
flags = os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0)
fd = os.open(self._store_lock_path, flags, _FILE_MODE)
_STORE_LOCK_FDS.add(fd)
try:
os.fchmod(fd, _FILE_MODE)
fcntl.flock(fd, fcntl.LOCK_EX)
active[key] = fd
try:
yield
finally:
del active[key]
fcntl.flock(fd, fcntl.LOCK_UN)
finally:
_STORE_LOCK_FDS.discard(fd)
os.close(fd)
# ── T4.2 encryption helpers (Fernet at-rest, credential-only) ─────
def _encryption_active(self) -> bool:
"""True iff ``toolaria_key_file`` is configured AND cryptography
is importable.
Reviewer fix 3 (2026-08-25 re-review): a CONFIGURED key with a
MISSING cryptography package is no longer treated as "inert".
That combination previously degraded to silent plaintext for
credential puts — an operator who believed encryption was on.
Now the put path consults ``_require_encryption_ready`` and
REFUSES credential writes (fail closed) when the library is
absent; this predicate stays True-only-for-real so inert-mode
checks (no key configured at all) keep their meaning.
"""
if not _HAVE_FERNET:
if not self._fernet_missing_logged:
kf = self.cfg.get("toolaria_key_file")
if kf:
logger.warning(
"toolaria: cryptography.fernet unavailable; "
"toolaria_key_file=%s configured — CREDENTIAL "
"WRITES WILL BE REFUSED (fail closed, reviewer "
"fix 3). Install cryptography to enable "
"encryption. Warning emitted once per process.",
kf,
)
self._fernet_missing_logged = True
return False
return bool(self.cfg.get("toolaria_key_file"))
def _require_encryption_ready(self) -> None:
"""Raise unless encryption can actually run.
Reviewer fix 3: called by every credential-write path. When the
operator configured a key file but the cryptography package is
missing, we refuse rather than silently store plaintext.
"""
kf = self.cfg.get("toolaria_key_file")
if kf and not _HAVE_FERNET:
raise _EncryptionUnavailable(
f"toolaria_key_file={kf} is configured but the "
f"cryptography package is unavailable; refusing to "
f"write credential content under plaintext (fail "
f"closed). Install 'cryptography' or remove the key "
f"setting.")
def _encryption_configured(self) -> bool:
"""True iff the operator configured ``toolaria_key_file``.
Used by fail-closed gates: this must be independent of whether
Fernet support actually loaded, so a configured-but-broken
environment refuses instead of degrading to plaintext.
"""
return bool(self.cfg.get("toolaria_key_file"))
def _load_or_create_fernet(self):
"""Return a cached Fernet, creating the key file at 0600 if missing.
Returns ``None`` when encryption is inactive (no key configured
OR cryptography missing). On a corrupt existing key file the
helper raises ``_EncryptionUnavailable`` so callers fail loud —
we never silently substitute a fresh key (that would orphan
every previously-encrypted blob).
"""
if not self._encryption_active():
return None
if self._fernet is not None:
return self._fernet
kf = self.cfg["toolaria_key_file"]
kpath = Path(kf).expanduser()
try:
kpath.parent.mkdir(parents=True, exist_ok=True)
# HG-M5 (hermaguard Phase 4): the key directory must not be
# world-listable; tighten to match the store's dir mode.
_chmod_safe(kpath.parent, _DIR_MODE)
except OSError as exc:
# HG-H2 (hermaguard Phase 4): fail CLOSED on write-side key
# I/O failures. Returning None here would silently fall
# back to plaintext for credential puts — exactly what the
# T4.2 contract forbids.
raise _EncryptionUnavailable(
f"key file dir unavailable: {kpath.parent}: {exc}")
key_bytes: bytes | None = None
generated = False
if kpath.exists():
try:
key_bytes = kpath.read_bytes().strip()
except OSError as exc:
# HG-H2: unreadable existing key is a fail-closed case.
raise _EncryptionUnavailable(
f"key file unreadable: {kpath}: {exc}")
try:
self._fernet = _Fernet(key_bytes)
return self._fernet
except Exception:
# Existing key file is corrupt — refuse rather than
# overwrite (overwriting would orphan every encrypted
# blob written under the previous key). Raise so the
# read path catches _EncryptionUnavailable and returns
# the deterministic marker.
logger.warning(
"toolaria: key file %s exists but is not a valid "
"Fernet key; refusing to overwrite. Reads of "
"encrypted blobs will fail safe.",
kpath,
)
raise _EncryptionUnavailable(
f"corrupt key file: {kpath}")
# Generate a fresh key.
# HG-H4 (hermaguard Phase 4): auto-bootstrap orphans every
# previously-encrypted blob under the lost key. If any live
# entry says enc=True, refuse and demand manual recovery.
if self._has_encrypted_blobs():
raise _EncryptionUnavailable(
f"key file missing but encrypted blobs exist "
f"({kpath}); refusing to auto-generate a new key — "
f"restore the original key file first")
key_bytes = _Fernet.generate_key()
generated = True
try:
# HG-M2 + HG-M5: atomic O_EXCL create at 0600 from birth —
# no umask window, last-writer-wins race closed.
fd = os.open(str(kpath),
os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
with os.fdopen(fd, "wb") as f:
f.write(key_bytes)
except FileExistsError:
# Lost a creation race with another process: use theirs.
try:
self._fernet = _Fernet(
kpath.read_bytes().strip())
return self._fernet
except Exception as exc:
raise _EncryptionUnavailable(
f"key file race lost and winner's key invalid: "
f"{kpath}: {exc}")
except OSError as exc:
# HG-H2: fail closed.
raise _EncryptionUnavailable(
f"could not persist new key file {kpath}: {exc}")
logger.warning(
"toolaria: generated new Fernet key at %s (0600). "
"This is a one-time bootstrap — subsequent runs reuse the "
"file. Backup the key file: losing it makes every encrypted "
"credential blob unreadable.",
kpath,
)
self._fernet = _Fernet(key_bytes)
return self._fernet
def _has_encrypted_blobs(self) -> bool:
"""True iff any session index holds a live entry with enc=True.
HG-H4 guard: used before auto-generating a replacement key so a
lost key file can never be silently replaced while encrypted
ciphertext still depends on the old key.
"""
for ip in sorted(self.meta_dir.glob("*.json")):
for entry in (self._read_idx_file(ip).get("blobs")
or {}).values():
if (isinstance(entry, dict)
and entry.get("enc") is True
and "swept_at" not in entry):
return True
return False
def _blob_encrypted(self, blob_id: str) -> bool:
"""True iff any session's index entry for *blob_id* carries
``enc: True``.
Index-driven (not disk-driven) so a missing/corrupt key file
cannot produce a false positive — the entry field is the
authoritative source of truth for which on-disk bytes are
ciphertext vs plaintext.
HG-M4 (hermaguard Phase 4): positive results are cached
per-process (a blob that is ciphertext stays ciphertext for its
lifetime — content-addressed, never re-encrypted in place
except by rotation, which rewrites under lock). NEGATIVE
results are NOT cached (reviewer fix 5, 2026-08-25): another
process can upgrade a plaintext blob to encrypted at any time,
so a cached False would be a stale lie that ends in an
integrity-failure read. The common case (plaintext blob read
repeatedly) still costs one scan per fetch; the scan is bounded
by session count and is unchanged pre-T4.2 behaviour.
"""
cached = self._enc_cache.get(blob_id)
if cached is not None:
return cached
for ip in sorted(self.meta_dir.glob("*.json")):
entry = self._read_idx_file(ip).get("blobs", {}).get(blob_id)
if isinstance(entry, dict) and entry.get("enc") is True:
self._enc_cache[blob_id] = True
return True
return False
def _encrypt_bytes(self, plain: bytes) -> bytes | None:
"""Fernet-encrypt *plain* using the cached key. Returns ``None``
when encryption is inactive (caller falls back to plaintext
write with a single WARNING). Raises ``_EncryptionUnavailable``
when the key is missing or corrupt — the put path catches that
and refuses the write rather than partial-encrypting.
"""
f = self._load_or_create_fernet()
if f is None:
return None
return f.encrypt(plain)
def _decrypt_bytes(self, blob_id: str, cipher: bytes) -> bytes:
"""Fernet-decrypt *cipher* for *blob_id*. Raises
``_EncryptionUnavailable`` on any failure (missing key file,
corrupt key, malformed ciphertext, library mismatch). The
caller is responsible for translating the exception into the
deterministic refusal marker — this helper never returns
partial plaintext.
"""
# Resolve the Fernet without auto-creating a key file: on a
# read path we want a missing key to fail safe, not bootstrap
# a brand-new key that would orphan every existing encrypted
# blob.
if not _HAVE_FERNET:
raise _EncryptionUnavailable("cryptography.fernet unavailable")
if self._fernet is None:
kf = self.cfg.get("toolaria_key_file")
if not kf:
raise _EncryptionUnavailable("no toolaria_key_file")
kpath = Path(kf).expanduser()
if not kpath.exists():
raise _EncryptionUnavailable(f"key file missing: {kpath}")
try:
key_bytes = kpath.read_bytes().strip()
except OSError as exc:
raise _EncryptionUnavailable(
f"key file unreadable: {exc}") from exc
try:
self._fernet = _Fernet(key_bytes)
except Exception as exc:
raise _EncryptionUnavailable(
f"key file invalid: {exc}") from exc
try:
return self._fernet.decrypt(cipher)
except Exception as exc:
# InvalidToken (wrong key / tampered ciphertext) and any
# other failure collapse into the same uniform refusal —
# no information leak distinguishing the cause.
raise _EncryptionUnavailable(
f"Fernet decrypt failed for {blob_id}: {exc}") from exc
# ── T4.3 key rotation ────────────────────────────────────────────────
@_store_operation
def rotate_key(self, new_key_path: str) -> int:
"""Re-encrypt every encrypted credential blob under a new
Fernet key in one pass. Returns the number of blobs
re-encrypted.
Algorithm (abort-safe):
1. Resolve the OLD Fernet from the CURRENT key file. If
the current key file is missing or invalid the rotation
aborts before touching any blob — the store stays on
whatever it had.
2. Load or generate the NEW key at *new_key_path* (writes
0600 if generating). The OLD key file is NOT touched.
3. Walk every on-disk blob whose entry carries ``enc: True``
and atomic-rewrite it under the new key. Per-blob
failures collect the bid; the partial state is rolled
back by re-encrypting each already-rotated blob under
the OLD key so the store keeps serving under the old
key until the operator retries.
4. On full success: update ``cfg["toolaria_key_file"]`` to
point at the new path, drop the cached Fernet so reads
pick up the new key, write ONE ``key_rotated`` ledger
row with the count.
5. On any per-blob failure during the pass: re-encrypt
every already-rotated blob back under the OLD key,
restore ``cfg["toolaria_key_file"]`` to the OLD path,
and re-raise the original exception. NO ledger row is
emitted for a failed pass.
The OLD key file (when ``new_key_path != old_path``) is
retained after a successful rotation — losing it makes the
pre-rotation ciphertexts unreadable, so the operator may
want to keep it until they confirm the new-key decrypts
everything.
"""
if not _HAVE_FERNET:
raise _EncryptionUnavailable(
"cryptography.fernet unavailable; cannot rotate key")
# 1. Resolve old key.
old_path = self.cfg.get("toolaria_key_file")
if not old_path:
raise _EncryptionUnavailable(
"no toolaria_key_file configured; nothing to rotate")
old_path_p = Path(old_path).expanduser()
try:
old_key_bytes = old_path_p.read_bytes().strip()
old_fernet = _Fernet(old_key_bytes)
except Exception as exc:
raise _EncryptionUnavailable(
f"old key file {old_path_p} unreadable or invalid: {exc}"
) from exc
# 2. Resolve new key (load if exists, generate if missing).
new_path_p = Path(new_key_path).expanduser()
try:
new_path_p.parent.mkdir(parents=True, exist_ok=True)
except OSError as exc:
raise _EncryptionUnavailable(
f"could not create new key file dir {new_path_p.parent}: "
f"{exc}") from exc
new_key_bytes: bytes
generated = False
if new_path_p.exists():
try:
new_key_bytes = new_path_p.read_bytes().strip()
_Fernet(new_key_bytes) # validate
except Exception as exc:
raise _EncryptionUnavailable(
f"new key file {new_path_p} unreadable or invalid: "
f"{exc}") from exc
else:
new_key_bytes = _Fernet.generate_key()
generated = True
new_fernet = _Fernet(new_key_bytes)
# HG-H3 (hermaguard Phase 4): an in-place "rotation" with
# identical key material is a silent no-op that still writes a
# key_rotated ledger row — the compromised key keeps working.
# Refuse it outright.
if new_key_bytes == old_key_bytes:
raise _EncryptionUnavailable(
f"rotate_key: new path {new_path_p} resolves to the SAME "
f"key as {old_path_p}; generate a genuinely new key "
f"(rotation to the same material is refused)")
# HG-C3 Window 1 (hermaguard Phase 4): persist the NEW key file
# BEFORE re-encrypting any blob. The old order encrypted every
# blob in memory first and wrote the key afterwards — a crash
# in between left all ciphertext under a key that existed
# nowhere on disk (permanent loss). Atomic tmp+replace at 0600.
try:
fd, tmp_name = tempfile.mkstemp(
dir=new_path_p.parent,
prefix=f".{new_path_p.name}.", suffix=".tmp")
with os.fdopen(fd, "wb") as f:
f.write(new_key_bytes)
os.chmod(tmp_name, _FILE_MODE)
os.replace(tmp_name, new_path_p)
except OSError as exc:
# HG-C3 Window 3: persistence failure must ABORT the whole
# rotation — no blob has been touched yet, so this is clean.
raise _EncryptionUnavailable(
f"could not persist new key file {new_path_p}: {exc}; "
f"no blobs were modified") from exc
# 3. Walk every encrypted blob and re-encrypt.
#
# HG-M3 (hermaguard Phase 4): the whole walk runs under the
# process-global _LOCK. Without it a concurrent put() encrypts
# under the OLD cached Fernet after the bid snapshot is taken;
# that blob then never enters this rotation and becomes
# orphaned when self._fernet swaps to the new key. Holding
# _LOCK means puts either land before the snapshot (old key,
# included in the walk) or after the swap (new key, correct).
# Cross-process callers are out of scope here: rotate_key is an
# operator-invoked maintenance action; multi-process rotation is
# rejected by the cfg-restart contract documented at step 5.
rotated: list[str] = []
last_exc: Exception | None = None
try:
with _LOCK:
encrypted_bids = self._collect_encrypted_bids()
for bid in encrypted_bids:
bpath = self.blob_dir / bid
try:
cipher_old = bpath.read_bytes()
plain = old_fernet.decrypt(cipher_old)
cipher_new = new_fernet.encrypt(plain)
self._atomic_write_blob(bpath, cipher_new)
rotated.append(bid)
except Exception as exc:
last_exc = exc
raise
except Exception:
# 4. Abort-safety: roll back the already-rotated blobs.
logger.warning(
"toolaria: T4.3 rotation failed mid-pass (%s); rolling "
"back %d already-rotated blob(s) under the old key",
last_exc, len(rotated),
)
for bid in rotated:
bpath = self.blob_dir / bid
try:
cipher_new = bpath.read_bytes()
plain = new_fernet.decrypt(cipher_new)
cipher_old = old_fernet.encrypt(plain)
self._atomic_write_blob(bpath, cipher_old)
except Exception as rb_exc:
# A rollback failure is logged loudly; the caller
# already gets the original exception. The store
# may now be inconsistent (some blobs under the
# new key, some under the old); the operator must
# intervene.
logger.error(
"toolaria: T4.3 rollback FAILED for %s: %s; "
"store may be in an inconsistent state — restore "
"from backup or re-run rotation",
bid, rb_exc,
)
# If we generated the new key file but the rotation failed,
# remove it so a future retry doesn't see a half-rotated
# new key (it'd be a valid key but unused).
if generated:
try:
new_path_p.unlink()
except OSError:
pass
raise
# 5. Successful pass: the new key file was persisted BEFORE the
# re-encryption walk (HG-C3 Window 1 fix), so a crash at any
# later point leaves every blob decryptable by a key that
# exists on disk. Nothing further to persist here.
#
# HG-C3 Window 2 (residual, documented): cfg mutation is
# in-memory only. On restart config.yaml still names the OLD
# key path — but since rotation now persists the new key to its
# own path BEFORE touching blobs and the old key file is
# retained, a restart falls back to the old key which still
# decrypts pre-rotation blobs; post-rotation ciphertext needs
# the operator to update toolaria_key_file in config.yaml. The
# ledger row + this docstring make that contract explicit.
# Switch cfg + cache.
self.cfg["toolaria_key_file"] = str(new_path_p)
self._fernet = new_fernet
# 6. Ledger row.
try:
if __package__:
from .ledger import log_key_rotation
else:
from ledger import log_key_rotation # type: ignore[no-redef]
log_key_rotation(
self.cfg, count=len(rotated),
old_key_file=str(old_path_p),
new_key_file=str(new_path_p),
)
except Exception as exc:
logger.warning(
"toolaria: could not write key_rotation ledger row: %s",
exc,
)
return len(rotated)
def _collect_encrypted_bids(self) -> list[str]:
"""Return a sorted list of bid strings whose index entry
carries ``enc: True``.
Walks every session index so cross-session encrypted blobs
are caught even when only one session was used during the
rotation window.
"""
bids: set[str] = set()
for ip in sorted(self.meta_dir.glob("*.json")):
idx = self._read_idx_file(ip)
for bid, entry in (idx.get("blobs") or {}).items():
if isinstance(entry, dict) and entry.get("enc") is True:
# HG-H1 (hermaguard Phase 4): tombstones preserve
# enc=True for audit, but their blob files are
# gone — including them would abort every rotation
# with FileNotFoundError once any encrypted
# credential has been swept. Live entries only.
if "swept_at" in entry:
continue
bids.add(bid)
return sorted(bids)
@staticmethod
def _atomic_write_blob(bpath, data: bytes) -> None:
"""Atomic replace of a blob file with *data* at 0600.