-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathruntime-state-mutation-control.py
More file actions
executable file
·4024 lines (3653 loc) · 136 KB
/
Copy pathruntime-state-mutation-control.py
File metadata and controls
executable file
·4024 lines (3653 loc) · 136 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
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Root-only hold for one exact runtime state mutation.
The host may invoke only the fixed actions exposed by :func:`main`. Acquire
consumes the full bounded runtime and plan binding. Later actions consume one
exact observation plus the provider handle. The durable marker records the
exact OpenShell PID 1, its direct ``nemoclaw-start`` child, and each held
activation process. A controller restart can therefore re-establish or finish
only the original process fence.
PID 1 remains stopped until release completes. This blocks OpenShell SSH and
exec admission while a root provider exec can continue the transaction. The
helper also stops ``nemoclaw-start`` and terminates every other process that
uses the ``sandbox`` or ``gateway`` account. Activation resumes only the exact
entrypoint, proves a fresh Hermes gateway, and freezes the resulting process
tree before it returns evidence to the host.
Posture transitions use the fixed, root-owned Hermes publisher module and
accept only its exact nonce-bound receipt. The host ledger remains
authoritative for publication completion.
"""
from __future__ import annotations
import argparse
import fcntl
import hashlib
import http.client
import importlib.util
import json
import os
import pwd
import re
import secrets
import select
import signal
import stat
import sys
import time
from dataclasses import dataclass
from typing import Literal
Action = Literal[
"acquire", "assert", "publish", "rollback", "activate", "release", "recover"
]
Phase = Literal["fenced", "published", "rolled-back", "activation-proven"]
SCHEMA_VERSION = 1
PLAN_SCHEMA_VERSION = 2
SUPPORTED_STATE_ROOT = "/sandbox/.hermes"
SUPPORTED_WRITER_ACCOUNTS = ("gateway", "sandbox")
MAX_ENVELOPE_BYTES = 128 * 1024
MAX_PLAN_BYTES = 64 * 1024
MAX_MARKER_BYTES = 160 * 1024
MAX_PROC_ENTRIES = 32_768
MAX_PROC_FILE_BYTES = 1024 * 1024
MAX_CONFIG_GENERATION_BYTES = 64 * 1024
MAX_ACTIVATION_PROCESSES = 256
MAX_SELECTORS = 256
MAX_STRING_BYTES = 4096
TERM_SECONDS = 3.0
KILL_SECONDS = 5.0
PROCESS_STATE_SECONDS = 5.0
ACTIVATION_SECONDS = 150.0
HEALTH_SECONDS = 3.0
STABLE_SCANS = 3
POLL_SECONDS = 0.05
ROOT_UID = 0
ROOT_GID = 0
PROC_ROOT = "/proc"
MOUNT_NAMESPACE_PATH = "/proc/1/ns/mnt"
DURABLE_DIRECTORY = "/var/lib/nemoclaw/runtime-state-mutation"
RUNTIME_DIRECTORY = "/run/nemoclaw/runtime-state-mutation"
STARTUP_HANDOFF_DIRECTORY = "/run/nemoclaw/runtime-state-mutation-startup"
DURABLE_PARENT_MODE = 0o755
DURABLE_DIRECTORY_MODE = 0o711
RUNTIME_DIRECTORY_MODE = 0o700
STARTUP_HANDOFF_PARENT_MODE = 0o711
MARKER_NAME = "active.json"
LOCK_NAME = "control.lock"
SENTINEL_NAME = "hold.json"
ACTIVATION_RECEIPT_NAME = "activation.json"
ACTIVATION_PERMIT_NAME = "activation-permit.json"
ACTIVATION_RELEASE_NAME = "activation-release.json"
ACTIVATION_RETRY_NAME = "activation-retry.json"
ACTIVATION_CLEANUP_NAME = "activation-cleanup.json"
STARTUP_CANDIDATE_NAME = "startup-complete.json"
STARTUP_RETRY_ACK_NAME = "retry-ack.json"
RELEASED_RECEIPT_NAME = "released.json"
PUBLISHER_MODULE_PATH = (
"/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py"
)
PUBLISHER_PROTOCOL = "nemoclaw-runtime-state-mutation-publisher-v1"
ACTIVATION_PERMIT_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-permit-v1"
ACTIVATION_RELEASE_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-release-v1"
ACTIVATION_RETRY_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-retry-v1"
ACTIVATION_CLEANUP_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-cleanup-v1"
STARTUP_CANDIDATE_PROTOCOL = "nemoclaw-runtime-state-mutation-startup-complete-v1"
STARTUP_RETRY_ACK_PROTOCOL = "nemoclaw-runtime-state-mutation-retry-ack-v1"
OPENSHELL_ARGV0 = b"/opt/openshell/bin/openshell-sandbox"
NEMOCLAW_START_PATH = b"/usr/local/bin/nemoclaw-start"
HERMES_GATEWAY_PATHS = (b"/usr/local/bin/hermes", b"/usr/local/bin/hermes.real")
HERMES_INTERNAL_PORT = 18642
HERMES_HEALTH_PATH = "/health"
HERMES_CONFIG_GENERATION_PATH = "/sandbox/.hermes/.config-hash"
HEX_64 = re.compile(r"[0-9a-f]{64}\Z")
SAFE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z")
PROVIDER_ID = re.compile(r"[a-z][a-z0-9-]{0,62}\Z")
RUNTIME_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/=+\-]{0,511}\Z")
MOUNT_NAMESPACE = re.compile(r"mnt:\[[1-9][0-9]*\]\Z")
PID_NAMESPACE = re.compile(r"pid:\[[1-9][0-9]*\]\Z")
DECIMAL = re.compile(r"(?:0|[1-9][0-9]*)\Z")
TOP_LEVEL = re.compile(r"[A-Za-z0-9._-]+\Z")
CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f-\x9f]")
PUBLISHER_ERROR_CODE = re.compile(r"[a-z][a-z0-9-]{0,127}\Z")
PHASES = frozenset(("fenced", "published", "rolled-back", "activation-proven"))
ACTIONS = frozenset(
("acquire", "assert", "publish", "rollback", "activate", "release", "recover")
)
class ControlError(RuntimeError):
"""A fixed-code, non-sensitive control failure."""
def __init__(self, code: str):
super().__init__(code)
self.code = code
@dataclass(frozen=True)
class AcquireRequest:
transaction_id: str
provider_id: str
sandbox_name: str
lifecycle_generation: str
engine_binding_sha256: str
runtime_id: str
runtime_pid: int
sandbox_identity_sha256: str
container_mounts_sha256: str
state_root: str
state_root_mounts_sha256: str
plan_sha256: str
projection_sha256: str
nonce: str
plan: dict[str, object]
canonical_plan: str
target: str
rollback: str
@dataclass(frozen=True)
class StatusRequest:
action: Action
transaction_id: str
provider_id: str
sandbox_name: str
lifecycle_generation: str
engine_binding_sha256: str
runtime_id: str
runtime_pid: int
sandbox_identity_sha256: str
container_mounts_sha256: str
provider_handle: str | None
activation_provider_handle: str | None
completed_ledger_sha256: str | None
Request = AcquireRequest | StatusRequest
@dataclass(frozen=True)
class ProcessIdentity:
pid: int
state: str
parent_pid: int
start_identity: str
uids: tuple[int, int, int, int]
command: tuple[bytes, ...]
proc_device: int
proc_inode: int
def identity_key(self) -> tuple[object, ...]:
return (
self.pid,
self.parent_pid,
self.start_identity,
self.uids,
self.command,
self.proc_device,
self.proc_inode,
)
@dataclass(frozen=True)
class ProcessReference:
pid: int
start_identity: str
parent_pid: int
uids: tuple[int, int, int, int]
command_sha256: str
proc_device: int
proc_inode: int
@dataclass(frozen=True)
class FenceProof:
supervisor: ProcessReference
start: ProcessReference
writer_uids: tuple[int, ...]
@dataclass(frozen=True)
class ActivationProof:
service_pid: int
service_start_identity: str
service_uid: int
configuration_generation: str
listener_identity: str
health_sha256: str
startup_checkpoint_sha256: str
persistent_pids: tuple[int, ...]
processes: tuple[ProcessReference, ...]
def _fail(code: str) -> None:
raise ControlError(code)
def _json_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]:
result: dict[str, object] = {}
for key, value in pairs:
if key in result:
_fail("duplicate-json-field")
result[key] = value
return result
def _bounded_json_integer(value: str) -> int:
if len(value) > 10:
_fail("json-integer-out-of-range")
parsed = int(value, 10)
if parsed < 0 or parsed > 0x7FFFFFFF:
_fail("json-integer-out-of-range")
return parsed
def _reject_json_constant(_value: str) -> None:
_fail("non-finite-json-number")
def _reject_json_float(_value: str) -> None:
_fail("json-number-not-integer")
def _parse_json(raw: bytes, maximum: int, invalid_code: str) -> object:
if not raw or len(raw) > maximum or b"\x00" in raw:
_fail(invalid_code)
try:
text = raw.decode("utf-8", "strict")
value = json.loads(
text,
object_pairs_hook=_json_pairs,
parse_int=_bounded_json_integer,
parse_float=_reject_json_float,
parse_constant=_reject_json_constant,
)
except ControlError:
raise
except (UnicodeDecodeError, json.JSONDecodeError, ValueError, RecursionError):
_fail(invalid_code)
return value
def _read_stdin() -> bytes:
raw = sys.stdin.buffer.read(MAX_ENVELOPE_BYTES + 1)
if len(raw) > MAX_ENVELOPE_BYTES:
_fail("envelope-too-large")
return raw
def _exact_keys(
value: object, expected: tuple[str, ...], code: str
) -> dict[str, object]:
if not isinstance(value, dict) or tuple(value.keys()) != expected:
_fail(code)
return value
def _bounded_string(value: object, pattern: re.Pattern[str], code: str) -> str:
if (
not isinstance(value, str)
or not value
or value != value.strip()
or CONTROL_CHARACTERS.search(value)
or len(value.encode("utf-8", "strict")) > MAX_STRING_BYTES
or pattern.fullmatch(value) is None
):
_fail(code)
return value
def _hex_digest(value: object, code: str) -> str:
return _bounded_string(value, HEX_64, code)
def _decimal_identity(value: object, code: str) -> str:
return _bounded_string(value, DECIMAL, code)
def _canonical_relative_path(value: object, code: str) -> str:
if not isinstance(value, str):
_fail(code)
try:
encoded = value.encode("utf-8", "strict")
except UnicodeEncodeError:
_fail(code)
if (
not value
or len(encoded) > 512
or value.startswith("/")
or "\\" in value
or CONTROL_CHARACTERS.search(value)
or os.path.normpath(value) != value
or any(part in ("", ".", "..") for part in value.split("/"))
):
_fail(code)
return value
def _string_array(value: object, code: str, normalize) -> list[str]:
if not isinstance(value, list) or len(value) > MAX_SELECTORS:
_fail(code)
result = [normalize(item, code) for item in value]
if result != sorted(result, key=lambda item: item.encode("utf-8")) or len(
set(result)
) != len(result):
_fail(code)
return result
def _top_level(value: object, code: str) -> str:
return _bounded_string(value, TOP_LEVEL, code)
def _writable_subpath(value: object, code: str) -> str:
path = _canonical_relative_path(value, code)
parts = path.split("/")
if (
len(parts) < 2
or any("*" in part and part != "*" for part in parts)
or parts[-1] == "*"
):
_fail(code)
return path
def _writable_patterns_overlap(first: str, second: str) -> bool:
left = first.split("/")
right = second.split("/")
return all(
a == "*" or b == "*" or a == b for a, b in zip(left, right, strict=False)
)
def _normalize_state_lock_plan(value: object) -> dict[str, object]:
plan = _exact_keys(
value,
(
"version",
"readOnlyRoots",
"confidentialRoots",
"readOnlyPrefixes",
"confidentialPrefixes",
"writableSubpaths",
),
"state-lock-plan-schema",
)
if type(plan["version"]) is not int or plan["version"] != 1:
_fail("state-lock-plan-version")
read_only_roots = _string_array(
plan["readOnlyRoots"], "state-lock-plan-roots", _top_level
)
confidential_roots = _string_array(
plan["confidentialRoots"], "state-lock-plan-roots", _top_level
)
read_only_prefixes = _string_array(
plan["readOnlyPrefixes"], "state-lock-plan-prefixes", _top_level
)
confidential_prefixes = _string_array(
plan["confidentialPrefixes"], "state-lock-plan-prefixes", _top_level
)
writable_subpaths = _string_array(
plan["writableSubpaths"], "state-lock-plan-writable", _writable_subpath
)
roots = read_only_roots + confidential_roots
prefixes = read_only_prefixes + confidential_prefixes
if len(set(roots)) != len(roots) or len(set(prefixes)) != len(prefixes):
_fail("state-lock-plan-policy-overlap")
if any(root.startswith(prefix) for root in roots for prefix in prefixes):
_fail("state-lock-plan-policy-overlap")
for index, prefix in enumerate(prefixes):
if any(
prefix.startswith(other) or other.startswith(prefix)
for other in prefixes[index + 1 :]
):
_fail("state-lock-plan-policy-overlap")
if any(path.split("/", 1)[0] not in read_only_roots for path in writable_subpaths):
_fail("state-lock-plan-writable")
for index, pattern in enumerate(writable_subpaths):
if any(
_writable_patterns_overlap(pattern, other)
for other in writable_subpaths[index + 1 :]
):
_fail("state-lock-plan-writable-overlap")
return {
"version": 1,
"readOnlyRoots": read_only_roots,
"confidentialRoots": confidential_roots,
"readOnlyPrefixes": read_only_prefixes,
"confidentialPrefixes": confidential_prefixes,
"writableSubpaths": writable_subpaths,
}
def _normalize_plan(
value: object, state_root: str, projection: str
) -> dict[str, object]:
plan = _exact_keys(
value,
(
"schemaVersion",
"intent",
"target",
"rollback",
"stateLockPlan",
"stateRoot",
"selectors",
"projectionSha256",
),
"plan-schema",
)
if (
type(plan["schemaVersion"]) is not int
or plan["schemaVersion"] != PLAN_SCHEMA_VERSION
):
_fail("plan-version")
if plan["intent"] != "protection-transition":
_fail("plan-intent")
target = plan["target"]
rollback = plan["rollback"]
if target not in ("locked", "mutable") or rollback not in ("locked", "mutable"):
_fail("plan-posture")
if target == rollback:
_fail("plan-posture")
if plan["stateRoot"] != state_root or plan["projectionSha256"] != projection:
_fail("plan-binding")
state_lock_plan = _normalize_state_lock_plan(plan["stateLockPlan"])
selectors_value = plan["selectors"]
if (
not isinstance(selectors_value, list)
or not selectors_value
or len(selectors_value) > MAX_SELECTORS
):
_fail("plan-selectors")
selectors: list[dict[str, str]] = []
identities: list[str] = []
for selector_value in selectors_value:
if not isinstance(selector_value, dict) or selector_value.get("kind") not in (
"path",
"prefix",
):
_fail("plan-selector-schema")
if selector_value["kind"] == "path":
selector = _exact_keys(
selector_value, ("kind", "path"), "plan-selector-schema"
)
path = _canonical_relative_path(selector["path"], "plan-selector-path")
selectors.append({"kind": "path", "path": path})
identities.append(f"path:{path}")
else:
selector = _exact_keys(
selector_value, ("kind", "prefix"), "plan-selector-schema"
)
prefix = _top_level(selector["prefix"], "plan-selector-prefix")
selectors.append({"kind": "prefix", "prefix": prefix})
identities.append(f"prefix:{prefix}")
if identities != sorted(identities, key=lambda item: item.encode("utf-8")) or len(
set(identities)
) != len(identities):
_fail("plan-selector-order")
required = [
*(f"path:{item}" for item in state_lock_plan["readOnlyRoots"]),
*(f"path:{item}" for item in state_lock_plan["confidentialRoots"]),
*(f"prefix:{item}" for item in state_lock_plan["readOnlyPrefixes"]),
*(f"prefix:{item}" for item in state_lock_plan["confidentialPrefixes"]),
]
if any(identity not in identities for identity in required):
_fail("plan-selector-scope")
return {
"schemaVersion": PLAN_SCHEMA_VERSION,
"intent": "protection-transition",
"target": target,
"rollback": rollback,
"stateLockPlan": state_lock_plan,
"stateRoot": state_root,
"selectors": selectors,
"projectionSha256": projection,
}
def _json_bytes(value: object) -> bytes:
try:
return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode(
"utf-8", "strict"
)
except (TypeError, ValueError, UnicodeEncodeError):
_fail("json-serialization")
def _sha256(payload: bytes) -> str:
return hashlib.sha256(payload).hexdigest()
ACQUIRE_KEYS = (
"schemaVersion",
"action",
"transactionId",
"providerId",
"sandboxName",
"lifecycleGeneration",
"engineBindingSha256",
"runtimeId",
"runtimePid",
"sandboxIdentitySha256",
"containerMountsSha256",
"stateRoot",
"stateRootMountsSha256",
"plan",
"planSha256",
"projectionSha256",
"nonce",
"target",
"rollback",
)
STATUS_KEYS = (
"schemaVersion",
"action",
"transactionId",
"providerId",
"sandboxName",
"lifecycleGeneration",
"engineBindingSha256",
"runtimeId",
"runtimePid",
"sandboxIdentitySha256",
"containerMountsSha256",
)
MARKER_KEYS = (
"schemaVersion",
"phase",
"transactionId",
"providerId",
"sandboxName",
"lifecycleGeneration",
"engineBindingSha256",
"runtimeId",
"runtimePid",
"sandboxIdentitySha256",
"containerMountsSha256",
"stateRoot",
"stateRootMountsSha256",
"mountNamespace",
"stateRootDevice",
"stateRootInode",
"plan",
"planSha256",
"projectionSha256",
"nonce",
"target",
"rollback",
"fence",
"activation",
)
RELEASED_RECEIPT_KEYS = (
"schemaVersion",
"releaseState",
"transactionId",
"providerHandle",
"activationProviderHandle",
"completedLedgerSha256",
"marker",
)
PROVIDER_HANDLE = re.compile(
r"([a-z][a-z0-9-]{0,62})-state-mutation-v1:([0-9a-f]{64}):([0-9a-f]{64})\Z"
)
ACTIVATION_PROVIDER_HANDLE = re.compile(
r"([a-z][a-z0-9-]{0,62})-state-mutation-activation-v1:([0-9a-f]{64}):([0-9a-f]{64})\Z"
)
def _canonical_state_root(value: object) -> str:
if not isinstance(value, str):
_fail("state-root")
try:
encoded = value.encode("utf-8", "strict")
except UnicodeEncodeError:
_fail("state-root")
if (
not value.startswith("/sandbox/")
or value.endswith("/")
or "\\" in value
or CONTROL_CHARACTERS.search(value)
or len(encoded) > MAX_STRING_BYTES
or os.path.normpath(value) != value
):
_fail("state-root")
if value != SUPPORTED_STATE_ROOT:
_fail("state-root-unsupported")
return value
def _positive_integer(value: object, code: str) -> int:
if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
_fail(code)
return value
def _runtime_state_sha256(request: AcquireRequest) -> str:
return _sha256(
_json_bytes(
{
"schemaVersion": SCHEMA_VERSION,
"providerId": request.provider_id,
"sandboxName": request.sandbox_name,
"lifecycleGeneration": request.lifecycle_generation,
"engineBindingSha256": request.engine_binding_sha256,
"runtimeId": request.runtime_id,
"runtimePid": request.runtime_pid,
"sandboxIdentitySha256": request.sandbox_identity_sha256,
"containerMountsSha256": request.container_mounts_sha256,
"stateRoot": request.state_root,
"stateRootMountsSha256": request.state_root_mounts_sha256,
}
)
)
def _expected_transaction_id(request: AcquireRequest) -> str:
return _sha256(
_json_bytes(
{
"schemaVersion": SCHEMA_VERSION,
"action": "state-mutation",
"runtimeStateSha256": _runtime_state_sha256(request),
"planSha256": request.plan_sha256,
"projectionSha256": request.projection_sha256,
"nonce": request.nonce,
"target": request.target,
"rollback": request.rollback,
}
)
)
def _parse_request(action: Action, raw: bytes) -> Request:
value = _parse_json(raw, MAX_ENVELOPE_BYTES, "invalid-envelope-json")
expected = ACQUIRE_KEYS if action == "acquire" else STATUS_KEYS
if action not in ("acquire", "recover"):
expected += ("providerHandle",)
if action == "release":
expected += ("activationProviderHandle", "completedLedgerSha256")
envelope = _exact_keys(value, expected, "envelope-schema")
if (
type(envelope["schemaVersion"]) is not int
or envelope["schemaVersion"] != SCHEMA_VERSION
or envelope["action"] != action
):
_fail("envelope-version")
transaction_id = _hex_digest(envelope["transactionId"], "transaction-id")
provider_id = _bounded_string(envelope["providerId"], PROVIDER_ID, "provider-id")
sandbox_name = _bounded_string(envelope["sandboxName"], SAFE_NAME, "sandbox-name")
lifecycle_generation = _bounded_string(
envelope["lifecycleGeneration"], RUNTIME_ID, "lifecycle-generation"
)
engine_binding_sha256 = _hex_digest(
envelope["engineBindingSha256"], "engine-binding-digest"
)
runtime_id = _hex_digest(envelope["runtimeId"], "runtime-id")
runtime_pid = _positive_integer(envelope["runtimePid"], "runtime-pid")
sandbox_identity_sha256 = _hex_digest(
envelope["sandboxIdentitySha256"], "sandbox-identity-digest"
)
container_mounts_sha256 = _hex_digest(
envelope["containerMountsSha256"], "container-mounts-digest"
)
common: dict[str, object] = {
"schemaVersion": SCHEMA_VERSION,
"action": action,
"transactionId": transaction_id,
"providerId": provider_id,
"sandboxName": sandbox_name,
"lifecycleGeneration": lifecycle_generation,
"engineBindingSha256": engine_binding_sha256,
"runtimeId": runtime_id,
"runtimePid": runtime_pid,
"sandboxIdentitySha256": sandbox_identity_sha256,
"containerMountsSha256": container_mounts_sha256,
}
if action != "acquire":
provider_handle = (
_bounded_string(
envelope["providerHandle"], PROVIDER_HANDLE, "provider-handle"
)
if action != "recover"
else None
)
if provider_handle is not None:
provider_match = PROVIDER_HANDLE.fullmatch(provider_handle)
if provider_match is None or not secrets.compare_digest(
provider_match.group(1), provider_id
):
_fail("provider-handle")
activation_provider_handle = (
_bounded_string(
envelope["activationProviderHandle"],
ACTIVATION_PROVIDER_HANDLE,
"activation-provider-handle",
)
if action == "release"
else None
)
if activation_provider_handle is not None:
activation_match = ACTIVATION_PROVIDER_HANDLE.fullmatch(
activation_provider_handle
)
if activation_match is None or not secrets.compare_digest(
activation_match.group(1), provider_id
):
_fail("activation-provider-handle")
completed = (
_hex_digest(envelope["completedLedgerSha256"], "completed-ledger-digest")
if action == "release"
else None
)
normalized = {
**common,
**(
{"providerHandle": provider_handle}
if provider_handle is not None
else {}
),
**(
{
"activationProviderHandle": activation_provider_handle,
"completedLedgerSha256": completed,
}
if action == "release"
else {}
),
}
if raw != _json_bytes(normalized) + b"\n":
_fail("envelope-not-canonical")
return StatusRequest(
action,
transaction_id,
provider_id,
sandbox_name,
lifecycle_generation,
engine_binding_sha256,
runtime_id,
runtime_pid,
sandbox_identity_sha256,
container_mounts_sha256,
provider_handle,
activation_provider_handle,
completed,
)
state_root = _canonical_state_root(envelope["stateRoot"])
state_root_mounts_sha256 = _hex_digest(
envelope["stateRootMountsSha256"], "state-root-mounts-digest"
)
plan_sha256 = _hex_digest(envelope["planSha256"], "plan-digest")
projection_sha256 = _hex_digest(envelope["projectionSha256"], "projection-digest")
nonce = _hex_digest(envelope["nonce"], "nonce")
if not isinstance(envelope["plan"], str):
_fail("plan-transport")
plan_transport = envelope["plan"].encode("utf-8", "strict")
if not plan_transport or len(plan_transport) > MAX_PLAN_BYTES:
_fail("plan-transport")
plan_value = _parse_json(plan_transport, MAX_PLAN_BYTES, "invalid-plan-json")
plan = _normalize_plan(plan_value, state_root, projection_sha256)
canonical_plan = _json_bytes(plan).decode("utf-8", "strict")
if envelope["plan"] != canonical_plan or _sha256(plan_transport) != plan_sha256:
_fail("plan-digest-mismatch")
target = envelope["target"]
rollback = envelope["rollback"]
if (
target not in ("locked", "mutable")
or rollback not in ("locked", "mutable")
or target == rollback
or plan["target"] != target
or plan["rollback"] != rollback
):
_fail("plan-posture")
normalized = {
**common,
"stateRoot": state_root,
"stateRootMountsSha256": state_root_mounts_sha256,
"plan": canonical_plan,
"planSha256": plan_sha256,
"projectionSha256": projection_sha256,
"nonce": nonce,
"target": target,
"rollback": rollback,
}
if raw != _json_bytes(normalized) + b"\n":
_fail("envelope-not-canonical")
request = AcquireRequest(
transaction_id,
provider_id,
sandbox_name,
lifecycle_generation,
engine_binding_sha256,
runtime_id,
runtime_pid,
sandbox_identity_sha256,
container_mounts_sha256,
state_root,
state_root_mounts_sha256,
plan_sha256,
projection_sha256,
nonce,
plan,
canonical_plan,
str(target),
str(rollback),
)
if not secrets.compare_digest(
request.transaction_id, _expected_transaction_id(request)
):
_fail("transaction-binding-mismatch")
return request
PROCESS_REFERENCE_KEYS = (
"pid",
"startIdentity",
"parentPid",
"uids",
"commandSha256",
"procDevice",
"procInode",
)
FENCE_KEYS = ("supervisor", "start", "writerUids")
ACTIVATION_PERMIT_KEYS = (
"schemaVersion",
"protocol",
"transactionId",
"nonce",
"markerSha256",
"start",
"candidateDirectory",
)
ACTIVATION_RELEASE_KEYS = (
"schemaVersion",
"protocol",
"transactionId",
"nonce",
"checkpointSha256",
"start",
"candidateDirectory",
)
ACTIVATION_RETRY_KEYS = (
"schemaVersion",
"protocol",
"transactionId",
"nonce",
"permitSha256",
"checkpointSha256",
"start",
"candidateDirectory",
)
ACTIVATION_CLEANUP_KEYS = (
"schemaVersion",
"protocol",
"transactionId",
"nonce",
"start",
"candidateDirectory",
)
STARTUP_CANDIDATE_KEYS = (
"schemaVersion",
"protocol",
"transactionId",
"nonce",
"markerSha256",
"start",
)
STARTUP_RETRY_ACK_KEYS = (
"schemaVersion",
"protocol",
"transactionId",
"nonce",
"retrySha256",
"start",
)
def _process_command_sha256(command: tuple[bytes, ...]) -> str:
framed = b"".join(len(part).to_bytes(4, "big") + part for part in command)
return _sha256(framed)
def _process_reference(process: ProcessIdentity) -> ProcessReference:
return ProcessReference(
process.pid,
process.start_identity,
process.parent_pid,
process.uids,
_process_command_sha256(process.command),
process.proc_device,
process.proc_inode,
)
def _process_reference_payload(reference: ProcessReference) -> dict[str, object]:
return {
"pid": reference.pid,
"startIdentity": reference.start_identity,
"parentPid": reference.parent_pid,
"uids": list(reference.uids),
"commandSha256": reference.command_sha256,
"procDevice": str(reference.proc_device),
"procInode": str(reference.proc_inode),
}
def _process_reference_from_value(value: object, code: str) -> ProcessReference:
reference = _exact_keys(value, PROCESS_REFERENCE_KEYS, code)
pid = _positive_integer(reference["pid"], code)
parent_pid = reference["parentPid"]
uids = reference["uids"]
if (
type(parent_pid) is not int
or parent_pid < 0
or not isinstance(uids, list)
or len(uids) != 4
or any(type(uid) is not int or uid < 0 for uid in uids)
):
_fail(code)
start_identity = _decimal_identity(reference["startIdentity"], code)
command_sha256 = _hex_digest(reference["commandSha256"], code)
proc_device = _decimal_identity(reference["procDevice"], code)
proc_inode = _decimal_identity(reference["procInode"], code)
if proc_device == "0" or proc_inode == "0":
_fail(code)
return ProcessReference(
pid,
start_identity,
parent_pid,
tuple(uids), # type: ignore[arg-type]
command_sha256,
int(proc_device, 10),
int(proc_inode, 10),
)
def _fence_payload(fence: FenceProof) -> dict[str, object]:
return {
"supervisor": _process_reference_payload(fence.supervisor),
"start": _process_reference_payload(fence.start),
"writerUids": list(fence.writer_uids),
}
def _fence_from_value(value: object, code: str = "fence-marker-invalid") -> FenceProof:
fence = _exact_keys(value, FENCE_KEYS, code)
supervisor = _process_reference_from_value(fence["supervisor"], code)
start = _process_reference_from_value(fence["start"], code)
writer_uids = fence["writerUids"]
if (
supervisor.pid != 1
or supervisor.parent_pid != 0
or supervisor.uids != (ROOT_UID,) * 4
or start.pid <= 1
or start.parent_pid != 1