Repository navigation
Expand file tree
/
Copy pathsession-kit-release
More file actions
executable file
·2617 lines (2424 loc) · 100 KB
/
Copy pathsession-kit-release
File metadata and controls
executable file
·2617 lines (2424 loc) · 100 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
#!/usr/bin/env python3
"""Build, verify, activate, and roll back immutable session-kit releases.
This tool never invokes shpool or a service manager. Activation transactionally
switches the release pointer, integration marker, and receipt. Initial launcher
bootstrap is a separate, explicit operation.
"""
from __future__ import annotations
import argparse
import base64
import contextlib
import datetime as dt
import fcntl
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import shlex
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import uuid
SCHEMA_VERSION = 1
CURRENT_RELEASE_SCHEMA_VERSION = 5
HELPERS = (
"sp",
"shpool_login",
"shpool_login_tui",
"shpool_login_launcher",
"shpool_status",
"shpool_reaper",
"codex_resume_here",
)
LEGACY_REQUIRED_RELEASE_PAYLOAD = (
"bin/session_kit_common",
"lib/session_inventory.py",
"bashrc/shpool.bashrc",
"config/projects.example.tsv",
"config/session-inventory.example.json",
"deploy/session-kit-launcher",
)
REQUIRED_RELEASE_PAYLOAD_BY_SCHEMA = {
1: LEGACY_REQUIRED_RELEASE_PAYLOAD,
2: (
*LEGACY_REQUIRED_RELEASE_PAYLOAD,
"lib/sessionkit_inventory/__init__.py",
"lib/sessionkit_inventory/common.py",
),
3: (
*LEGACY_REQUIRED_RELEASE_PAYLOAD,
"lib/sessionkit_inventory/__init__.py",
"lib/sessionkit_inventory/common.py",
"lib/sessionkit_inventory/lifecycle.py",
"lib/sessionkit_inventory/providers.py",
"lib/sessionkit_inventory/state_io.py",
),
4: (
*LEGACY_REQUIRED_RELEASE_PAYLOAD,
"lib/sessionkit_inventory/__init__.py",
"lib/sessionkit_inventory/common.py",
"lib/sessionkit_inventory/lifecycle.py",
"lib/sessionkit_inventory/projects.py",
"lib/sessionkit_inventory/providers.py",
"lib/sessionkit_inventory/state_io.py",
),
# Schema 5 adds `colors`. The palettes moved into that module and split in
# two there, so it is now the single place the in-force colour set for each
# provider is declared; a payload without it cannot resolve any session
# colour. Themes are deliberately NOT required here: a release that ships
# no config/codex-themes directory at all is a supported configuration, and
# the installer removes the kit-owned themes it previously placed.
5: (
*LEGACY_REQUIRED_RELEASE_PAYLOAD,
"lib/sessionkit_inventory/__init__.py",
"lib/sessionkit_inventory/colors.py",
"lib/sessionkit_inventory/common.py",
"lib/sessionkit_inventory/lifecycle.py",
"lib/sessionkit_inventory/projects.py",
"lib/sessionkit_inventory/providers.py",
"lib/sessionkit_inventory/state_io.py",
),
}
REQUIRED_BACKUP_PAYLOAD = {
"bundle.sha256",
"canonical-head.bundle",
"canonical-state.txt",
"current-identities.json",
"installed-files.tar",
"shpool-list.json",
"source-files.after.sha256",
"source-files.before.sha256",
"source-files.stat",
}
INSTALLED_TARGET_SUFFIXES = {
".local/bin/shpool_login",
".local/bin/shpool_login_tui",
".local/bin/shpool_login_launcher",
".local/bin/shpool_reaper",
".local/bin/shpool_status",
".local/bin/sp",
".local/bin/codex_resume_here",
".bashrc",
".config/shpool/config.toml",
".config/systemd/user/shpool.service",
".config/systemd/user/shpool.socket",
".config/systemd/user/shpool-reaper.service",
".config/systemd/user/shpool-reaper.timer",
}
SHA_RE = re.compile(r"^[0-9a-f]{40,64}$")
SUM_RE = re.compile(r"^([0-9a-f]{64}) (.+)$")
SHPOOL_ID_RE = re.compile(
r"^(?:main(?:[1-9][0-9]*)?|s[0-9]{8}-[0-9]{6}-[1-9][0-9]*(?:-[1-9][0-9]*)?)$"
)
LAUNCH_RECORD_MAX_BYTES = 8192
COLLECTION_DOCUMENT_NAMES = (
"inventory.json",
"terminal-numbers.json",
"terminal-numbers-retired.json",
"terminal-numbers.initialized.json",
"recovery-manifest.json",
"recovery-pending.json",
)
COLLECTION_SEQUENCE_NAME = "collection-sequence.json"
COLLECTION_FLOOR_NAME = "collection-sequence-floor.json"
COLLECTION_MARKERS_NAME = "collection-markers"
LEGACY_INVENTORY_LOCK_NAME = "inventory.lock"
VERSIONED_INVENTORY_LOCK_NAME = "inventory-v2.lock"
LEGACY_INVENTORY_FENCE = b"session-kit publishing lock generation 2\n"
class ReleaseError(RuntimeError):
pass
def json_out(payload: dict) -> None:
print(json.dumps(payload, sort_keys=True, indent=2))
def run(argv: list[str], *, cwd: Path | None = None, capture: bool = True) -> str:
proc = subprocess.run(
argv,
cwd=cwd,
check=False,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE,
text=True,
)
if proc.returncode:
detail = proc.stderr.strip() or proc.stdout.strip()
raise ReleaseError(f"command failed ({proc.returncode}): {' '.join(argv)}: {detail}")
return proc.stdout.strip() if capture else ""
def resolve_commit(repo: Path, requested: str) -> str:
if not repo.is_dir():
raise ReleaseError(f"repository does not exist: {repo}")
if not SHA_RE.fullmatch(requested):
raise ReleaseError("--sha must be a full lowercase commit ID")
commit = run(["git", "rev-parse", "--verify", f"{requested}^{{commit}}"], cwd=repo)
if not SHA_RE.fullmatch(commit):
raise ReleaseError(f"git returned an invalid commit id: {commit!r}")
return commit
def safe_relative(raw: str) -> Path:
pure = PurePosixPath(raw)
if pure.is_absolute() or not pure.parts or any(p in ("", ".", "..") for p in pure.parts):
raise ReleaseError(f"unsafe manifest/archive path: {raw!r}")
return Path(*pure.parts)
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def atomic_json(path: Path, payload: dict, mode: int = 0o600) -> None:
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
tmp = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
try:
with tmp.open("x", encoding="utf-8") as handle:
json.dump(payload, handle, sort_keys=True, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, mode)
os.replace(tmp, path)
fsync_dir(path.parent)
finally:
with contextlib.suppress(FileNotFoundError):
tmp.unlink()
def create_json_once(path: Path, payload: dict, mode: int = 0o600) -> bool:
"""Durably publish JSON only if no entry already occupies its pathname."""
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
tmp = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
content = (json.dumps(payload, sort_keys=True, indent=2) + "\n").encode()
try:
with tmp.open("xb") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, mode)
try:
os.link(tmp, path, follow_symlinks=False)
except FileExistsError:
return False
fsync_dir(path.parent)
return True
finally:
with contextlib.suppress(FileNotFoundError):
tmp.unlink()
if path.exists() or path.is_symlink():
fsync_dir(path.parent)
def collection_floor_remedy(state_root: Path, remedy_tool: Path) -> str:
command = shlex.join(
[
"env",
f"SESSION_KIT_STATE_DIR={state_root}",
"python3",
os.fspath(remedy_tool),
]
)
return (
"collection allocation floor cannot be derived from existing state; "
"restart the machine and, before starting a picker, sp, shpool_status, "
"or any Session Kit user service, run exactly:\n "
f"{command}"
)
def _private_sequence(path: Path) -> int | None:
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
try:
descriptor = os.open(path, flags)
except FileNotFoundError:
return None
except OSError as exc:
raise ReleaseError(f"unsafe collection allocation counter: {path}: {exc}") from exc
try:
metadata = os.fstat(descriptor)
try:
pathname = path.lstat()
except OSError as exc:
raise ReleaseError(
f"cannot inspect collection allocation counter: {path}"
) from exc
if (
not stat.S_ISREG(metadata.st_mode)
or stat.S_IMODE(metadata.st_mode) != 0o600
or metadata.st_uid != os.geteuid()
or metadata.st_nlink != 1
or metadata.st_size > 8192
or (metadata.st_dev, metadata.st_ino)
!= (pathname.st_dev, pathname.st_ino)
):
raise ReleaseError(f"unsafe collection allocation counter: {path}")
payload = os.read(descriptor, 8193)
if len(payload) > 8192 or os.read(descriptor, 1):
return None
finally:
os.close(descriptor)
try:
value = json.loads(payload.decode("utf-8", "strict"))
except (UnicodeError, ValueError):
return None
sequence = value.get("last_collection_start") if isinstance(value, dict) else None
if isinstance(sequence, bool) or not isinstance(sequence, int) or sequence <= 0:
return None
return sequence
def _collection_estate_is_empty(state_root: Path) -> bool:
counter = state_root / COLLECTION_SEQUENCE_NAME
if os.path.lexists(counter):
return False
if any(os.path.lexists(state_root / name) for name in COLLECTION_DOCUMENT_NAMES):
return False
markers = state_root / COLLECTION_MARKERS_NAME
try:
metadata = markers.lstat()
except FileNotFoundError:
return True
except OSError:
return False
if not stat.S_ISDIR(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
return False
try:
next(markers.iterdir())
except StopIteration:
return True
except OSError:
return False
return False
def _locked_regular(path: Path, flags: int, mode: int) -> int | None:
keep_open = False
try:
descriptor = os.open(path, flags, mode)
except OSError:
return None
try:
opened = os.fstat(descriptor)
pathname = path.lstat()
if (
not stat.S_ISREG(opened.st_mode)
or stat.S_IMODE(opened.st_mode) != mode
or opened.st_uid != os.geteuid()
or opened.st_nlink != 1
or (opened.st_dev, opened.st_ino) != (pathname.st_dev, pathname.st_ino)
):
return None
fcntl.flock(descriptor, fcntl.LOCK_EX)
pathname = path.lstat()
if (opened.st_dev, opened.st_ino) != (pathname.st_dev, pathname.st_ino):
return None
keep_open = True
return descriptor
except OSError:
return None
finally:
if not keep_open:
with contextlib.suppress(OSError):
fcntl.flock(descriptor, fcntl.LOCK_UN)
os.close(descriptor)
def _exact_inventory_fence(path: Path) -> bool:
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
try:
descriptor = os.open(path, flags)
except OSError:
return False
try:
opened = os.fstat(descriptor)
pathname = path.lstat()
content = os.read(descriptor, len(LEGACY_INVENTORY_FENCE) + 1)
return (
stat.S_ISREG(opened.st_mode)
and stat.S_IMODE(opened.st_mode) == 0o400
and opened.st_uid == os.geteuid()
and opened.st_nlink == 1
and (opened.st_dev, opened.st_ino) == (pathname.st_dev, pathname.st_ino)
and content == LEGACY_INVENTORY_FENCE
)
except OSError:
return False
finally:
os.close(descriptor)
@contextlib.contextmanager
def collection_seed_lock(state_root: Path):
"""Serialize with either publisher generation without changing its fence."""
legacy = state_root / LEGACY_INVENTORY_LOCK_NAME
versioned = state_root / VERSIONED_INVENTORY_LOCK_NAME
open_flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_CLOEXEC", 0)
if hasattr(os, "O_NOFOLLOW"):
open_flags |= os.O_NOFOLLOW
while True:
if _exact_inventory_fence(legacy):
descriptor = _locked_regular(versioned, open_flags, 0o600)
if descriptor is None:
raise ReleaseError(f"unsafe collection publication lock: {versioned}")
if not _exact_inventory_fence(legacy):
os.close(descriptor)
continue
break
if os.path.lexists(legacy):
try:
info = legacy.lstat()
except OSError as exc:
raise ReleaseError(
f"cannot inspect collection publication lock: {legacy}"
) from exc
if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600:
raise ReleaseError(f"unsafe collection publication lock: {legacy}")
descriptor = _locked_regular(legacy, open_flags, 0o600)
if descriptor is not None:
break
if _exact_inventory_fence(legacy):
continue
raise ReleaseError(f"unsafe collection publication lock: {legacy}")
try:
yield
finally:
with contextlib.suppress(OSError):
fcntl.flock(descriptor, fcntl.LOCK_UN)
os.close(descriptor)
def seed_collection_floor(
state_root: Path, remedy_tool: Path, *, dry_run: bool = False
) -> dict:
"""Seed an absent allocation floor without consuming an allocation."""
floor = state_root / COLLECTION_FLOOR_NAME
if os.path.lexists(floor):
return {"status": "preserved", "path": str(floor)}
if dry_run and not state_root.exists():
return {"status": "would-seed", "path": str(floor), "value": 1}
if not dry_run:
state_root.mkdir(parents=True, mode=0o700, exist_ok=True)
try:
root_info = state_root.lstat()
except OSError as exc:
raise ReleaseError(f"cannot inspect collection state directory: {state_root}") from exc
if (
not stat.S_ISDIR(root_info.st_mode)
or stat.S_ISLNK(root_info.st_mode)
or stat.S_IMODE(root_info.st_mode) != 0o700
or root_info.st_uid != os.geteuid()
):
raise ReleaseError(
f"collection state directory must be current-owner mode-0700: {state_root}"
)
@contextlib.contextmanager
def maybe_lock():
if dry_run:
yield
else:
with collection_seed_lock(state_root):
yield
with maybe_lock():
if os.path.lexists(floor):
return {"status": "preserved", "path": str(floor)}
sequence = _private_sequence(state_root / COLLECTION_SEQUENCE_NAME)
if sequence is None:
if not _collection_estate_is_empty(state_root):
raise ReleaseError(collection_floor_remedy(state_root, remedy_tool))
sequence = 1
if dry_run:
status = "would-seed"
else:
status = (
"seeded"
if create_json_once(
floor,
{"schema_version": 1, "last_collection_start": sequence},
)
else "preserved"
)
result: dict[str, object] = {"status": status, "path": str(floor)}
if status != "preserved":
result["value"] = sequence
return result
def fsync_dir(path: Path) -> None:
flags = os.O_RDONLY
if hasattr(os, "O_DIRECTORY"):
flags |= os.O_DIRECTORY
fd = os.open(path, flags)
try:
os.fsync(fd)
finally:
os.close(fd)
def atomic_bytes(path: Path, content: bytes, mode: int = 0o600) -> None:
"""Write bytes durably before atomically publishing one regular file."""
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
tmp = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
try:
with tmp.open("xb") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, mode)
os.replace(tmp, path)
fsync_dir(path.parent)
finally:
with contextlib.suppress(FileNotFoundError):
tmp.unlink()
def capture_entry(path: Path) -> dict:
"""Capture one absent, regular, or symlink entry for exact rollback."""
if path.is_symlink():
metadata = path.lstat()
return {
"kind": "symlink",
"target": os.readlink(path),
"uid": metadata.st_uid,
"gid": metadata.st_gid,
"atime_ns": metadata.st_atime_ns,
"mtime_ns": metadata.st_mtime_ns,
}
if not path.exists():
return {"kind": "absent"}
if not path.is_file():
raise ReleaseError(f"transaction target is not a regular file or symlink: {path}")
metadata = path.stat()
return {
"kind": "file",
"content": path.read_bytes(),
"mode": stat.S_IMODE(metadata.st_mode),
"uid": metadata.st_uid,
"gid": metadata.st_gid,
"atime_ns": metadata.st_atime_ns,
"mtime_ns": metadata.st_mtime_ns,
}
def remove_entry(path: Path) -> None:
if path.is_symlink() or path.is_file():
path.unlink()
elif path.exists():
raise ReleaseError(f"refusing to replace directory during rollback: {path}")
def restore_entry(path: Path, saved: dict) -> None:
"""Atomically restore a captured entry's type, bytes/target, and metadata."""
path.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
kind = saved["kind"]
if kind == "absent":
remove_entry(path)
fsync_dir(path.parent)
return
temporary = path.parent / f".{path.name}.restore.{os.getpid()}.{uuid.uuid4().hex}"
try:
if kind == "symlink":
os.symlink(saved["target"], temporary)
with contextlib.suppress(PermissionError):
os.lchown(temporary, saved["uid"], saved["gid"])
with contextlib.suppress(NotImplementedError, PermissionError):
os.utime(
temporary,
ns=(saved["atime_ns"], saved["mtime_ns"]),
follow_symlinks=False,
)
elif kind == "file":
with temporary.open("xb") as handle:
handle.write(saved["content"])
handle.flush()
os.fsync(handle.fileno())
os.chmod(temporary, saved["mode"])
with contextlib.suppress(PermissionError):
os.chown(temporary, saved["uid"], saved["gid"])
os.utime(temporary, ns=(saved["atime_ns"], saved["mtime_ns"]))
else:
raise ReleaseError(f"unsupported rollback entry kind: {kind}")
os.replace(temporary, path)
fsync_dir(path.parent)
finally:
with contextlib.suppress(FileNotFoundError):
temporary.unlink()
def restore_entries(entries: list[tuple[Path, dict]]) -> None:
errors: list[str] = []
for path, saved in reversed(entries):
try:
restore_entry(path, saved)
except (OSError, ReleaseError) as exc:
errors.append(f"{path}: {exc}")
if errors:
raise ReleaseError("transaction rollback failed: " + "; ".join(errors))
def encode_saved_entry(saved: dict) -> dict:
encoded = dict(saved)
content = encoded.get("content")
if isinstance(content, bytes):
encoded["content_base64"] = base64.b64encode(content).decode("ascii")
del encoded["content"]
return encoded
def decode_saved_entry(encoded: object) -> dict:
if not isinstance(encoded, dict):
raise ReleaseError("bootstrap transaction has an invalid saved entry")
kind = encoded.get("kind")
expected_keys = {
"absent": {"kind"},
"file": {
"kind",
"content_base64",
"mode",
"uid",
"gid",
"atime_ns",
"mtime_ns",
},
"symlink": {
"kind",
"target",
"uid",
"gid",
"atime_ns",
"mtime_ns",
},
}
if kind not in expected_keys or set(encoded) != expected_keys[kind]:
raise ReleaseError("bootstrap transaction has an invalid saved entry")
for name in ("uid", "gid", "atime_ns", "mtime_ns"):
if kind != "absent" and (
not isinstance(encoded.get(name), int) or encoded[name] < 0
):
raise ReleaseError("bootstrap transaction has invalid saved metadata")
if kind == "file" and (
not isinstance(encoded.get("mode"), int)
or encoded["mode"] < 0
or encoded["mode"] > 0o7777
):
raise ReleaseError("bootstrap transaction has invalid saved mode")
if kind == "symlink" and not isinstance(encoded.get("target"), str):
raise ReleaseError("bootstrap transaction has invalid saved symlink")
saved = dict(encoded)
if saved["kind"] == "file":
raw = saved.pop("content_base64", None)
if not isinstance(raw, str):
raise ReleaseError("bootstrap transaction file entry has no content")
try:
saved["content"] = base64.b64decode(raw, validate=True)
except ValueError as exc:
raise ReleaseError("bootstrap transaction has invalid base64 content") from exc
return saved
def entry_matches_saved(path: Path, saved: dict) -> bool:
"""Compare rollback-relevant bytes, type, ownership, and mode."""
kind = saved["kind"]
try:
if kind == "absent":
return not path.exists() and not path.is_symlink()
if kind == "symlink":
metadata = path.lstat()
return (
path.is_symlink()
and os.readlink(path) == saved["target"]
and metadata.st_uid == saved["uid"]
and metadata.st_gid == saved["gid"]
)
if not path.is_file() or path.is_symlink():
return False
metadata = path.stat()
return (
path.read_bytes() == saved["content"]
and stat.S_IMODE(metadata.st_mode) == saved["mode"]
and metadata.st_uid == saved["uid"]
and metadata.st_gid == saved["gid"]
)
except OSError:
return False
def validate_journal_file(path: Path, expected_uid: int, kind: str) -> dict:
if not path.is_file() or path.is_symlink():
raise ReleaseError(f"unsafe {kind} transaction journal: {path}")
metadata = path.stat()
if stat.S_IMODE(metadata.st_mode) != 0o600 or metadata.st_uid != expected_uid:
raise ReleaseError(
f"unsafe {kind} transaction journal mode or owner: {path}"
)
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise ReleaseError(f"invalid {kind} transaction journal: {exc}") from exc
if not isinstance(payload, dict):
raise ReleaseError(f"invalid {kind} transaction journal schema")
return payload
def decode_journal_entries(
payload: dict, expected_paths: list[Path], kind: str
) -> list[tuple[Path, dict]]:
encoded_entries = payload.get("entries")
if not isinstance(encoded_entries, list) or len(encoded_entries) != len(
expected_paths
):
raise ReleaseError(f"invalid {kind} transaction journal entries")
entries: list[tuple[Path, dict]] = []
for encoded, expected_path in zip(encoded_entries, expected_paths, strict=True):
if (
not isinstance(encoded, dict)
or set(encoded) != {"path", "saved"}
or encoded.get("path") != str(expected_path)
):
raise ReleaseError(
f"{kind} transaction targets do not match this invocation"
)
entries.append((expected_path, decode_saved_entry(encoded["saved"])))
return entries
def bootstrap_transaction_paths(args: argparse.Namespace) -> list[Path]:
return [
args.root / "current",
args.root / "launcher",
*(args.bin_dir / helper for helper in HELPERS),
args.state_dir / "last-activation.json",
]
def bootstrap_journal_path(state_dir: Path) -> Path:
return state_dir / "bootstrap-transaction.json"
def activation_journal_path(state_dir: Path) -> Path:
return state_dir / "activation-transaction.json"
def ensure_no_pending_bootstrap(state_dir: Path) -> None:
journal = bootstrap_journal_path(state_dir)
if journal.exists() or journal.is_symlink():
raise ReleaseError(
f"pending bootstrap transaction must be recovered by bootstrap first: {journal}"
)
def ensure_no_pending_activation(state_dir: Path) -> None:
journal = activation_journal_path(state_dir)
if journal.exists() or journal.is_symlink():
raise ReleaseError(
f"pending activation transaction must be recovered by activate or rollback first: {journal}"
)
def write_bootstrap_journal(path: Path, payload: dict) -> None:
atomic_json(path, payload, mode=0o600)
def clear_bootstrap_journal(path: Path) -> None:
with contextlib.suppress(FileNotFoundError):
path.unlink()
fsync_dir(path.parent)
def write_activation_journal(path: Path, payload: dict) -> None:
atomic_json(path, payload, mode=0o600)
def clear_activation_journal(path: Path) -> None:
with contextlib.suppress(FileNotFoundError):
path.unlink()
fsync_dir(path.parent)
def bootstrap_checkpoint(label: str) -> None:
"""Failure-injection seam; production execution is intentionally a no-op."""
del label
def recover_bootstrap_transaction(args: argparse.Namespace) -> str | None:
"""Finish a committed bootstrap or restore every entry from an incomplete one."""
journal_path = bootstrap_journal_path(args.state_dir)
if not journal_path.exists() and not journal_path.is_symlink():
return None
payload = validate_journal_file(
journal_path, args.home.stat().st_uid, "bootstrap"
)
expected_steps = [
"current",
"launcher",
*(f"helper:{helper}" for helper in HELPERS),
"receipt",
]
completed_steps = payload.get("completed_steps")
postimage = payload.get("postimage")
if (
set(payload)
!= {
"schema_version",
"action",
"transaction_id",
"commit",
"phase",
"completed_steps",
"entries",
"postimage",
}
or payload.get("schema_version") != SCHEMA_VERSION
or payload.get("action") != "bootstrap"
or not re.fullmatch(r"[0-9a-f]{32}", str(payload.get("transaction_id", "")))
or not SHA_RE.fullmatch(str(payload.get("commit", "")))
or payload.get("phase") not in {"prepared", "committed"}
or not isinstance(completed_steps, list)
or completed_steps != expected_steps[: len(completed_steps)]
or (payload.get("phase") == "committed" and completed_steps != expected_steps)
or not isinstance(postimage, dict)
or set(postimage) != {
"launcher_content_base64",
"helper_target",
"receipt",
}
or not isinstance(postimage.get("launcher_content_base64"), str)
or not isinstance(postimage.get("helper_target"), str)
or not isinstance(postimage.get("receipt"), dict)
):
raise ReleaseError("invalid bootstrap transaction journal schema")
entries = decode_journal_entries(
payload, bootstrap_transaction_paths(args), "bootstrap"
)
try:
expected_launcher = base64.b64decode(
postimage["launcher_content_base64"], validate=True
)
except ValueError as exc:
raise ReleaseError("invalid bootstrap transaction launcher postimage") from exc
expected_helper_target = postimage["helper_target"]
expected_receipt = postimage["receipt"]
if (
expected_helper_target
!= os.path.relpath(args.root / "launcher", args.bin_dir)
or set(expected_receipt)
!= {
"schema_version",
"action",
"activated_commit",
"previous_commit",
"backup_bundle",
"activated_at",
}
or expected_receipt.get("schema_version") != SCHEMA_VERSION
or expected_receipt.get("action") != "bootstrap"
or expected_receipt.get("activated_commit") != payload.get("commit")
or expected_receipt.get("previous_commit") is not None
or not isinstance(expected_receipt.get("backup_bundle"), str)
or not isinstance(expected_receipt.get("activated_at"), str)
):
raise ReleaseError("invalid bootstrap transaction postimage")
if payload.get("phase") == "committed":
launcher = args.root / "launcher"
receipt_path = args.state_dir / "last-activation.json"
expected_uid = args.home.stat().st_uid
try:
active = release_commit_from_current(args.root)
validate_bootstrap(args.root, args.bin_dir)
launcher_metadata = launcher.stat()
launcher_ok = (
launcher.is_file()
and not launcher.is_symlink()
and launcher.read_bytes() == expected_launcher
and stat.S_IMODE(launcher_metadata.st_mode) == 0o555
and launcher_metadata.st_uid == expected_uid
)
helpers_ok = all(
(args.bin_dir / helper).is_symlink()
and os.readlink(args.bin_dir / helper) == expected_helper_target
and (args.bin_dir / helper).lstat().st_uid == expected_uid
for helper in HELPERS
)
receipt_metadata = receipt_path.stat()
receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
receipt_ok = (
receipt_path.is_file()
and not receipt_path.is_symlink()
and stat.S_IMODE(receipt_metadata.st_mode) == 0o600
and receipt_metadata.st_uid == expected_uid
)
except (OSError, ValueError, ReleaseError):
active = None
launcher_ok = False
helpers_ok = False
receipt = None
receipt_ok = False
if (
active == payload.get("commit")
and launcher_ok
and helpers_ok
and receipt_ok
and receipt == expected_receipt
):
clear_bootstrap_journal(journal_path)
return "finished-committed"
raise ReleaseError(
"committed bootstrap poststate is inconsistent; journal retained"
)
if not incomplete_bootstrap_state_is_expected(
args,
payload,
entries,
expected_launcher,
expected_helper_target,
expected_receipt,
):
raise ReleaseError(
"incomplete bootstrap state diverged from its journal; journal retained"
)
try:
restore_entries(entries)
except BaseException:
# Keep the fsynced journal for the next recovery attempt.
raise
clear_bootstrap_journal(journal_path)
return "restored-incomplete"
def incomplete_bootstrap_state_is_expected(
args: argparse.Namespace,
payload: dict,
entries: list[tuple[Path, dict]],
expected_launcher: bytes,
expected_helper_target: str,
expected_receipt: dict,
) -> bool:
"""Accept only the recorded prefix or one atomically completed next step."""
paths = bootstrap_transaction_paths(args)
saved = {path: entry for path, entry in entries}
expected_uid = args.home.stat().st_uid
def target_current() -> bool:
try:
return release_commit_from_current(args.root) == payload["commit"]
except ReleaseError:
return False
def target_launcher() -> bool:
launcher = args.root / "launcher"
try:
metadata = launcher.stat()
return (
launcher.is_file()
and not launcher.is_symlink()
and launcher.read_bytes() == expected_launcher
and stat.S_IMODE(metadata.st_mode) == 0o555
and metadata.st_uid == expected_uid
)
except OSError:
return False
def target_helper(helper: str) -> bool:
link = args.bin_dir / helper
try:
metadata = link.lstat()
return (
link.is_symlink()
and os.readlink(link) == expected_helper_target
and metadata.st_uid == expected_uid
)
except OSError:
return False
def target_receipt() -> bool:
receipt = args.state_dir / "last-activation.json"
try:
metadata = receipt.stat()
return (
receipt.is_file()
and not receipt.is_symlink()
and json.loads(receipt.read_text(encoding="utf-8"))
== expected_receipt
and stat.S_IMODE(metadata.st_mode) == 0o600
and metadata.st_uid == expected_uid
)
except (OSError, ValueError):
return False
target_checks = [
target_current,
target_launcher,
*(lambda helper=helper: target_helper(helper) for helper in HELPERS),
target_receipt,
]
completed = len(payload["completed_steps"])
for target_count in range(completed, min(completed + 1, len(paths)) + 1):
if all(
target_checks[index]()
if index < target_count
else entry_matches_saved(path, saved[path])
for index, path in enumerate(paths)
):
return True
return False
def release_files(root: Path, *, include_manifests: bool = False) -> list[Path]:
skip = set() if include_manifests else {"MANIFEST.sha256", "MANIFEST.modes"}
files: list[Path] = []
for path in root.rglob("*"):
rel = path.relative_to(root)
if path.is_symlink():
raise ReleaseError(f"release contains a symlink: {rel}")
if path.is_file() and rel.as_posix() not in skip:
files.append(rel)
return sorted(files, key=lambda p: p.as_posix().encode())
def normalize_release_modes(root: Path) -> None:
for path in sorted(root.rglob("*"), reverse=True):
if path.is_symlink():
raise ReleaseError(f"release contains a symlink: {path.relative_to(root)}")
if path.is_dir():