forked from hyphanet/fred
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcross_version_runtime.py
More file actions
2654 lines (2481 loc) · 150 KB
/
Copy pathcross_version_runtime.py
File metadata and controls
2654 lines (2481 loc) · 150 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
"""Owned disposable packaged-node experiments; never a protected evidence authority.
All process output, FCP transcripts, references and comparisons stay in the private root.
The adapter deliberately reports unimplemented mandatory scenarios as not-observed.
"""
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
import hashlib
import base64
import fcntl
import datetime as dt
from html.parser import HTMLParser
import importlib.util
import json
import os
import re
from pathlib import Path, PurePosixPath
import signal
import socket
import stat
import subprocess
import sys
import tarfile
import time
import tempfile
import uuid
import urllib.error
import urllib.parse
import urllib.request
import zipfile
import interop_smoke as interop
ROLES = ("candidate-sender", "candidate-recipient", "previous", "relay-no-apps")
MAX_ARCHIVE = 4 * 1024**3
MAX_FILES = 30000
MAX_EXPANDED = 8 * 1024**3
MAX_LOG_BYTES = 64 * 1024**2
MEASUREMENT_CLEANUP_HEADROOM_SECONDS = 240
RUNTIME_LAYOUT_VERSION = 2
_mail_spec = importlib.util.spec_from_file_location("cryptad_mail_demo", Path(__file__).resolve().parents[1] / "mail-prototype/two_node_demo.py")
mail_demo = importlib.util.module_from_spec(_mail_spec)
_mail_spec.loader.exec_module(mail_demo)
class RuntimeFailure(Exception):
"""A fixed public error code; never include private exception text."""
@contextmanager
def _identity_directory(path, *, private_from=None, create=False):
"""Pin every directory component and reject replaced or symlinked ancestors."""
path = Path(path).absolute()
if ".." in path.parts:
raise RuntimeFailure("private-process-identity-path-invalid")
descriptors = []
links = []
try:
descriptor = os.open(path.anchor, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
descriptors.append(descriptor)
current = Path(path.anchor)
for name in path.parts[1:]:
current /= name
private = private_from is not None and current.is_relative_to(private_from)
if private and create:
try:
os.mkdir(name, mode=0o700, dir_fd=descriptor)
except FileExistsError:
pass
child = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor)
descriptors.append(child)
info = os.fstat(child)
if private and (info.st_uid != os.geteuid() or info.st_mode & 0o077):
raise RuntimeFailure("private-process-identity-directory-invalid")
links.append((descriptor, name, info.st_dev, info.st_ino,
(info.st_uid, info.st_gid, info.st_mode) if private else None))
descriptor = child
yield descriptor
for parent, name, device, inode, private_metadata in links:
info = os.stat(name, dir_fd=parent, follow_symlinks=False)
if not stat.S_ISDIR(info.st_mode) or (info.st_dev, info.st_ino) != (device, inode):
raise RuntimeFailure("private-process-identity-ancestor-replaced")
if private_metadata is not None and (info.st_uid, info.st_gid, info.st_mode) != private_metadata:
raise RuntimeFailure("private-process-identity-directory-changed")
except OSError:
raise RuntimeFailure("private-process-identity-unavailable") from None
finally:
for descriptor in reversed(descriptors):
os.close(descriptor)
def _read_identity_at(directory, name):
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("duplicate-identity-key")
result[key] = value
return result
def reject_number(value):
raise ValueError("noninteger-identity-number")
if not hasattr(os, "O_PATH"):
raise RuntimeFailure("private-process-identity-linux-required")
# Pin without invoking a device's open method. Only a validated regular leaf may be
# reopened through our own descriptor on the reference profile's genuine procfs.
pinned = os.open(name, os.O_PATH | os.O_NOFOLLOW, dir_fd=directory)
descriptor = None
try:
before = os.fstat(pinned)
if (not stat.S_ISREG(before.st_mode) or before.st_nlink != 1
or before.st_uid != os.geteuid() or before.st_mode & 0o077
or not 1 <= before.st_size <= 4096):
raise RuntimeFailure("private-process-identity-file-invalid")
fields = lambda info: (info.st_dev, info.st_ino, info.st_mode, info.st_uid, info.st_gid,
info.st_nlink, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
descriptor = os.open("/proc/self/fd/" + str(pinned), os.O_RDONLY | os.O_NONBLOCK)
if fields(before) != fields(os.fstat(descriptor)):
raise RuntimeFailure("private-process-identity-file-replaced")
payload = os.read(descriptor, 4097)
after = os.fstat(descriptor)
retained = os.stat(name, dir_fd=directory, follow_symlinks=False)
if fields(before) != fields(after) or fields(after) != fields(retained) or len(payload) != before.st_size:
raise RuntimeFailure("private-process-identity-file-replaced")
try:
value = json.loads(payload, object_pairs_hook=unique_object,
parse_constant=reject_number, parse_float=reject_number)
except (ValueError, UnicodeError, RecursionError):
raise RuntimeFailure("private-process-identity-json-invalid") from None
if (not isinstance(value, dict) or set(value) != {"supervisor", "jvm", "configDigest"}
or not isinstance(value["supervisor"], dict) or not isinstance(value["jvm"], dict)
or not isinstance(value["configDigest"], str)):
raise RuntimeFailure("private-process-identity-shape-invalid")
return value
finally:
if descriptor is not None:
os.close(descriptor)
os.close(pinned)
def read_process_identity(root, role):
"""Read expected identity exclusively from the prospective observer control layout."""
if role not in ROLES:
raise RuntimeFailure("private-process-identity-role-invalid")
runtime_root = Path(root).absolute() / "runtime"
with _identity_directory(runtime_root / "control/processes", private_from=runtime_root) as directory:
return _read_identity_at(directory, role + ".json")
def write_process_identity(root, role, identity):
"""Atomically retain an observer-created expectation outside node-owned storage.
This layout alone makes no claim of UID or network isolation.
"""
if role not in ROLES:
raise RuntimeFailure("private-process-identity-role-invalid")
payload = json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()
if len(payload) > 4096:
raise RuntimeFailure("private-process-identity-size-invalid")
runtime_root = Path(root).absolute() / "runtime"
with _identity_directory(runtime_root / "control/processes", private_from=runtime_root, create=True) as directory:
temporary = role + "-" + uuid.uuid4().hex + ".new"
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
0o600, dir_fd=directory)
try:
with os.fdopen(descriptor, "wb") as output:
output.write(payload)
output.flush()
os.fsync(output.fileno())
os.replace(temporary, role + ".json", src_dir_fd=directory, dst_dir_fd=directory)
os.fsync(directory)
finally:
try:
os.unlink(temporary, dir_fd=directory)
except FileNotFoundError:
pass
def read_historical_process_identity(node_root):
"""Read legacy bytes for source comparison only; never use this for live continuation."""
with _identity_directory(Path(node_root) / "run") as directory:
identity = _read_identity_at(directory, "process-identity.json")
return {"runtimeLayoutVersion": 1, "isolation": "not-established", "identity": identity}
def digest_file(path):
digest = hashlib.sha256()
with Path(path).open("rb") as source:
while chunk := source.read(1024 * 1024):
digest.update(chunk)
return "sha256:" + digest.hexdigest()
def canonical_digest(value):
return "sha256:" + hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"),
allow_nan=False).encode()).hexdigest()
def tree_digest(root, require_java=True):
"""Bind the complete executable runtime, refusing links outside the selected runtime."""
root = Path(root).resolve(strict=True)
records = []
total_bytes = 0
for path in sorted(root.rglob("*")):
relative = path.relative_to(root).as_posix()
if path.is_file():
total_bytes += path.stat().st_size
if total_bytes > MAX_EXPANDED:
raise RuntimeFailure("runtime-byte-budget-exceeded")
if path.is_symlink():
target = path.resolve(strict=True)
if not target.is_relative_to(root) or not target.is_file():
raise RuntimeFailure("runtime-link-outside-selected-tree")
records.append([relative, "link", os.readlink(path), digest_file(target)])
elif path.is_file():
records.append([relative, "file", path.stat().st_mode & 0o777, digest_file(path)])
elif not path.is_dir():
raise RuntimeFailure("runtime-special-file-rejected")
if len(records) > MAX_FILES:
raise RuntimeFailure("runtime-file-budget-exceeded")
if not records or (require_java and not (root / "bin/java").is_file()):
raise RuntimeFailure("runtime-java-missing")
return canonical_digest(records)
def packaged_daemon_identity(distribution, source_commit, build_version=None):
"""Check embedded build marker and actual daemon bytes, without claiming release authority."""
jar = Path(distribution) / "lib/cryptad.jar"
try:
with zipfile.ZipFile(jar) as archive:
entries = [entry for entry in archive.infolist() if entry.filename == "META-INF/MANIFEST.MF"]
if len(entries) != 1 or entries[0].file_size > 65536:
raise RuntimeFailure("daemon-manifest-invalid")
raw = archive.read(entries[0]).decode("utf-8")
logical = []
for line in raw.replace("\r\n", "\n").splitlines():
if line.startswith(" ") and logical:
logical[-1] += line[1:]
elif not line:
break
else:
logical.append(line)
attributes = {}
for line in logical:
key, separator, value = line.partition(": ")
if not separator or key in attributes:
raise RuntimeFailure("daemon-manifest-invalid")
attributes[key] = value
revision = attributes.get("Implementation-Version", "").split()
if len(revision) != 2 or not re.fullmatch("[0-9a-f]{7,40}", revision[1]) or not source_commit.startswith(revision[1]):
raise RuntimeFailure("daemon-embedded-source-mismatch")
if build_version is not None and revision[0] != str(build_version):
raise RuntimeFailure("daemon-embedded-build-mismatch")
return digest_file(jar)
except (OSError, UnicodeError, zipfile.BadZipFile) as error:
raise RuntimeFailure("daemon-package-identity-unavailable") from error
def require_native_target(distribution, selected_target, java_home):
targets = {"linux-x64": ("x86_64", "wrapper-linux-x86-64", 62),
"linux-arm64": ("aarch64", "wrapper-linux-arm-64", 183)}
if selected_target not in targets:
raise RuntimeFailure("package-target-unsupported")
machine, binary, elf_machine = targets[selected_target]
if os.uname().machine != machine:
raise RuntimeFailure("package-target-host-mismatch")
wrapper = Path(distribution) / "bin/wrapper"
if not wrapper.exists():
wrapper = Path(distribution) / "bin" / binary
for path in (wrapper, Path(java_home) / "bin/java"):
with path.open("rb") as stream:
header = stream.read(20)
if (len(header) != 20 or header[:6] != b"\x7fELF\x02\x01"
or int.from_bytes(header[18:20], "little") != elf_machine):
raise RuntimeFailure("package-native-architecture-mismatch")
def extract_package(archive, destination, expected_digest, expected_size):
"""Extract only a pinned portable tar distribution into a new owned directory."""
archive, destination = Path(archive), Path(destination)
if archive.is_symlink() or not archive.is_file():
raise RuntimeFailure("artifact-file-invalid")
if not 0 < expected_size <= MAX_ARCHIVE or archive.stat().st_size != expected_size:
raise RuntimeFailure("artifact-size-mismatch")
if digest_file(archive) != expected_digest:
raise RuntimeFailure("artifact-digest-mismatch")
if destination.exists() or destination.is_symlink():
raise RuntimeFailure("extraction-target-exists")
try:
with tarfile.open(archive, "r:*") as source:
members = []
for member in source:
members.append(member)
if len(members) > MAX_FILES:
raise RuntimeFailure("artifact-member-budget-exceeded")
if not members:
raise RuntimeFailure("artifact-member-budget-exceeded")
names, portable = set(), set()
total = 0
for member in members:
name = PurePosixPath(member.name)
if (name.is_absolute() or not name.parts or any(p in (".", "..", "") for p in name.parts)
or "\\" in member.name or ":" in member.name or "\x00" in member.name
or member.name.startswith("./") or any(ord(c) < 32 for c in member.name)
or not (member.isfile() or member.isdir()) or member.mode & 0o7000):
raise RuntimeFailure("artifact-member-unsafe")
normalized = name.as_posix()
if normalized in names or normalized.casefold() in portable:
raise RuntimeFailure("artifact-member-collision")
names.add(normalized)
portable.add(normalized.casefold())
total += member.size
if member.size < 0 or total > MAX_EXPANDED:
raise RuntimeFailure("artifact-expanded-budget-exceeded")
member_types = {PurePosixPath(member.name).as_posix(): member.isdir() for member in members}
for name in names:
if any(str(parent) in names and not member_types[str(parent)]
for parent in PurePosixPath(name).parents if str(parent) != "."):
raise RuntimeFailure("artifact-parent-collision")
destination.mkdir(mode=0o700)
for member in members:
path = destination.joinpath(*PurePosixPath(member.name).parts)
if member.isdir():
path.mkdir(parents=True, exist_ok=True, mode=0o700)
continue
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
with source.extractfile(member) as stream, path.open("xb") as output:
remaining = member.size
while remaining:
chunk = stream.read(min(1024 * 1024, remaining))
if not chunk:
raise RuntimeFailure("artifact-member-truncated")
output.write(chunk)
remaining -= len(chunk)
path.chmod(0o700 if member.mode & 0o111 else 0o600)
roots = [destination] if (destination / "bin/cryptad").is_file() else [destination / "cryptad-dist"]
root = roots[0]
if not (root / "bin/cryptad").is_file() or not os.access(root / "bin/cryptad", os.X_OK):
raise RuntimeFailure("artifact-package-layout-unsupported")
if digest_file(archive) != expected_digest:
raise RuntimeFailure("artifact-changed-during-extraction")
return root
except (OSError, tarfile.TarError) as error:
raise RuntimeFailure("artifact-extraction-failed") from error
@contextmanager
def absolute_deadline(seconds):
"""Bound whole operations including trickled FCP frames and response consumption."""
if seconds <= 0:
raise RuntimeFailure("experiment-deadline-exceeded")
def timeout(_signal, _frame):
raise RuntimeFailure("operation-deadline-exceeded")
previous = signal.getsignal(signal.SIGALRM)
old_timer = signal.getitimer(signal.ITIMER_REAL)
if old_timer[0]:
raise RuntimeFailure("nested-process-timer-rejected")
signal.signal(signal.SIGALRM, timeout)
signal.setitimer(signal.ITIMER_REAL, seconds)
try:
yield
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, previous)
def config_identity(config, root, fnp_port, fcp_port, http_port=None, trust_digest=None):
"""Digest generated configuration with opaque substitutions for private locations/ports."""
text = Path(config).read_text(encoding="utf-8")
text = text.replace(str(root), "<owned-node-root>")
text = text.replace(f"node.listenPort={fnp_port}\n", "node.listenPort=<assigned-fnp>\n")
text = text.replace(f"fcp.port={fcp_port}\n", "fcp.port=<assigned-fcp>\n")
if http_port is not None:
text = text.replace(f"fproxy.port={http_port}\n", "fproxy.port=<assigned-http>\n")
return canonical_digest({"role": Path(root).parent.name, "configuration": text, "appTrustDigest": trust_digest})
def make_runtime_config(node_root, ports, http_port):
config = interop.make_cryptad_config(node_root, ports)
text = config.read_text(encoding="utf-8").replace("fproxy.enabled=false\n", "fproxy.enabled=true\n")
text = text.replace("End\n", f"fproxy.port={http_port}\nfproxy.bindTo=127.0.0.1\nfproxy.allowedHosts=127.0.0.1\nfproxy.allowedHostsFullAccess=127.0.0.1\nEnd\n")
config.write_text(text, encoding="utf-8")
return config
def planned_config_identity(role, fnp_port, fcp_port, http_port, trust_digest=None):
"""Derive the fixed config pin without touching a selected node or private run root."""
with tempfile.TemporaryDirectory(prefix="cryptad-config-inspection-") as temporary:
root = Path(temporary) / role / "node"
config = make_runtime_config(root, interop.Ports(fnp_port, fcp_port, 0, 0), http_port)
return config_identity(config, root, fnp_port, fcp_port, http_port, trust_digest)
def node_epoch(identity):
return canonical_digest({key: identity[key] for key in ("bootId", "pid", "startTicks")})[7:39]
def process_identity(pid):
"""Linux supervisor identity, including process-start epoch to detect PID reuse."""
root = Path("/proc") / str(pid)
fields = (root / "stat").read_text().rsplit(")", 1)[1].split()
return {"pid": pid, "startTicks": int(fields[19]),
"bootId": Path("/proc/sys/kernel/random/boot_id").read_text().strip(),
"executableDigest": digest_file(root / "exe")}
def extract_app_bundle(archive, destination, expected_digest):
"""Confine a selected signed app ZIP; Java AppHost remains signature/manifest authority."""
archive, destination = Path(archive), Path(destination)
if archive.is_symlink() or not archive.is_file() or archive.stat().st_size > 64 * 1024**2:
raise RuntimeFailure("app-bundle-file-invalid")
if digest_file(archive) != expected_digest or destination.exists():
raise RuntimeFailure("app-bundle-binding-invalid")
try:
with zipfile.ZipFile(archive) as source:
members = source.infolist()
if not members or len(members) > 4096:
raise RuntimeFailure("app-bundle-member-budget-exceeded")
names, total = set(), 0
for member in members:
name = PurePosixPath(member.filename)
mode = member.external_attr >> 16
if (not name.parts or name.is_absolute() or ".." in name.parts or "\\" in member.filename
or ":" in member.filename or member.filename.startswith("./")
or member.filename.casefold() in names or member.flag_bits & 1
or stat.S_ISLNK(mode) or stat.S_IFMT(mode) not in {0, stat.S_IFREG, stat.S_IFDIR}
or any(ord(c) < 32 for c in member.filename)):
raise RuntimeFailure("app-bundle-member-unsafe")
names.add(member.filename.casefold())
total += member.file_size
if total > 128 * 1024**2:
raise RuntimeFailure("app-bundle-expanded-budget-exceeded")
destination.mkdir(mode=0o700)
for member in members:
target = destination.joinpath(*PurePosixPath(member.filename).parts)
if member.is_dir():
target.mkdir(parents=True, exist_ok=True, mode=0o700)
continue
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
with source.open(member) as stream, target.open("xb") as output:
remaining = member.file_size
while remaining:
chunk = stream.read(min(65536, remaining))
if not chunk:
raise RuntimeFailure("app-bundle-truncated")
output.write(chunk)
remaining -= len(chunk)
target.chmod(0o700 if member.external_attr >> 16 & 0o111 else 0o600)
if not (destination / "cryptad-app.properties").is_file():
raise RuntimeFailure("app-bundle-manifest-missing")
if digest_file(archive) != expected_digest:
raise RuntimeFailure("app-bundle-changed-during-extraction")
except (OSError, zipfile.BadZipFile) as error:
raise RuntimeFailure("app-bundle-extraction-failed") from error
@contextmanager
def fixed_helper_imports():
"""Make only the pinned repository helper directories available to fixed adapters."""
root = Path(__file__).resolve().parents[2]
added = [str(root / "tools/release-certification/protected"), str(root / "tools/release-certification"), str(root / "tools/interop")]
original = list(sys.path)
sys.path[:0] = added
try:
yield
finally:
sys.path[:] = original
def fixed_helper(name):
allowed = {"sharesite_observation": "tools/release-certification/protected/sharesite_observation.py",
"app_subject_projection": "tools/release-certification/protected/app_subject_projection.py",
"cross_version_app_scenarios": "tools/interop/cross_version_app_scenarios.py",
"cross_version_recovery": "tools/interop/cross_version_recovery.py",
"cross_version_product_admission": "tools/release-certification/protected/cross_version_product_admission.py",
"cross_version_supervisor_authority": "tools/release-certification/protected/cross_version_supervisor_authority.py",
"cross_version_budget": "tools/interop/cross_version_budget.py",
"scheduler_pressure_runtime": "tools/interop/scheduler_pressure_runtime.py",
"cross_version_catalog": "tools/interop/cross_version_catalog.py"}
if name not in allowed:
raise RuntimeFailure("unselected-helper-rejected")
expected = Path(__file__).resolve().parents[2] / allowed[name]
module = __import__(name)
if Path(module.__file__).resolve() != expected:
raise RuntimeFailure("unselected-helper-rejected")
return module
def authenticate_runner_selection(plan, private_config, authorization):
try:
with fixed_helper_imports():
module = fixed_helper("cross_version_supervisor_authority")
admission = module.authenticate_runner(plan, private_config, authorization)
if not isinstance(admission, module.AuthenticatedRunner):
raise RuntimeFailure("protected-runner-authority-not-produced")
return admission
except (ValueError, OSError) as error:
raise RuntimeFailure("protected-runner-authority-unavailable") from error
def authenticate_product_selection(plan, private_config):
"""Re-authenticate original producers; byte-identical predownloaded packages may be selected."""
selection = private_config.get("productAdmission")
if selection is None:
raise RuntimeFailure("original-product-selection-required")
try:
temporary = tempfile.TemporaryDirectory(prefix="cryptad-product-admission-")
with fixed_helper_imports():
module = fixed_helper("cross_version_product_admission")
admission = module.authenticate_products(plan, selection, Path(temporary.name) / "original")
if not isinstance(admission, module.AuthenticatedProducts):
raise RuntimeFailure("original-product-authority-not-produced")
admission.bind(plan, private_config)
original_close = admission.close
def close():
try:
original_close()
finally:
temporary.cleanup()
admission.close = close
return admission
except BaseException as error:
if 'admission' in locals():
admission.close()
if 'temporary' in locals():
temporary.cleanup()
if isinstance(error, (ValueError, OSError)):
raise RuntimeFailure("original-product-authentication-failed") from error
raise
def validate_migration_selection(selection):
expected = {"role", "recoveryRole", "toolRoot", "toolTreeDigest", "javaHome", "javaTreeDigest", "nodeExecutable", "nodeDigest"}
if (not isinstance(selection, dict) or set(selection) - {"dataClass"} != expected
or selection["role"] != "candidate-sender"
or selection["recoveryRole"] not in {None, "candidate-recipient"}
or selection.get("dataClass", "upstream-writer-synthetic") not in {"upstream-writer-synthetic", "operator-owned-private-observation"}):
raise RuntimeFailure("migration-selection-invalid")
for field in ("toolRoot", "javaHome", "nodeExecutable"):
path = Path(selection[field])
if not path.is_absolute() or path.is_symlink() or not path.exists():
raise RuntimeFailure("migration-tool-path-invalid")
with fixed_helper_imports():
projection = fixed_helper("app_subject_projection")
if (projection.tree_digest(Path(selection["toolRoot"])) != selection["toolTreeDigest"]
or projection.tree_digest(Path(selection["javaHome"])) != selection["javaTreeDigest"]
or digest_file(selection["nodeExecutable"]) != selection["nodeDigest"]):
raise RuntimeFailure("migration-tool-identity-mismatch")
converter = Path(selection["toolRoot"]) / "bin/crypta-app"
if converter.is_symlink() or not converter.is_file() or not os.access(converter, os.X_OK):
raise RuntimeFailure("migration-fixed-converter-unavailable")
def validate_recovery_selection(plan, private_config, authorization):
selection = private_config.get("recovery")
declared = plan.get("cohorts", [])
if selection is None:
if declared:
raise RuntimeFailure("recovery-declared-without-private-selection")
return
if (not isinstance(selection, dict) or set(selection) != {"cohortId", "fnpPort", "fcpPort", "httpPort"}
or selection["cohortId"] != "previous-to-candidate"):
raise RuntimeFailure("recovery-selection-invalid")
expected = [{"id": "previous-to-candidate", "sourceRole": "previous", "targetRole": "candidate-sender",
"configDigest": canonical_digest(selection)}]
if declared != expected or authorization is None or authorization.get("recoveryInputsDigest") != canonical_digest(selection):
raise RuntimeFailure("recovery-selection-not-authorized")
ports = [selection[field] for field in ("fnpPort", "fcpPort", "httpPort")]
main_ports = {row[field] for row in private_config["nodes"].values() for field in ("fnpPort", "fcpPort", "httpPort")}
if (any(type(port) is not int or not 1024 <= port <= 65535 for port in ports)
or len(set(ports)) != 3 or main_ports.intersection(ports)):
raise RuntimeFailure("recovery-port-alias-rejected")
if not any(app["appId"] == "site-publisher" for app in private_config["nodes"]["previous"]["apps"]):
raise RuntimeFailure("recovery-previous-signed-app-missing")
def validate_measurement_authorization(plan, authorization):
"""Reject bounds that cannot contain the requested observations even with zero setup."""
required = plan["requestedSeconds"] + plan["policy"]["maxGapSeconds"] + MEASUREMENT_CLEANUP_HEADROOM_SECONDS
if (plan["probeIntervalSeconds"] >= plan["policy"]["maxGapSeconds"]
or authorization is not None and (type(authorization.get("maxSeconds")) is not int
or authorization["maxSeconds"] < required)):
raise RuntimeFailure("measurement-authorization-headroom-insufficient")
def validate_budget_selection(plan, private_config, authorization):
selection = private_config.get("budget")
declared = plan.get("workloadInputs", {}).get("budget")
if selection is None:
if declared is not None or (authorization or {}).get("budgetInputsDigest") is not None:
raise RuntimeFailure("budget-declared-without-private-selection")
return
if (not isinstance(selection, dict) or set(selection) != {"role", "nodeExecutable", "nodeDigest"}
or selection["role"] != "candidate-sender"):
raise RuntimeFailure("budget-selection-invalid")
binding = canonical_digest(selection)
if declared != binding or authorization is None or authorization.get("budgetInputsDigest") != binding:
raise RuntimeFailure("budget-selection-not-authorized")
if not any(app["appId"] == "feed-reader" for app in private_config["nodes"][selection["role"]]["apps"]):
raise RuntimeFailure("budget-signed-feed-reader-not-selected")
executable = Path(selection["nodeExecutable"])
if (not executable.is_absolute() or executable.is_symlink() or not executable.is_file()
or any(parent.is_symlink() for parent in executable.parents)
or not re.fullmatch(r"sha256:[0-9a-f]{64}", str(selection["nodeDigest"]))
or digest_file(executable) != selection["nodeDigest"]):
raise RuntimeFailure("budget-node-executable-not-selected")
def validate_scheduler_selection(plan, private_config, authorization):
"""Bind a finite opt-in workload before any selected daemon receives its configuration."""
selection = private_config.get("scheduler")
declared = plan.get("workloadInputs", {}).get("scheduler")
if selection is None:
if declared is not None or (authorization or {}).get("schedulerInputsDigest") is not None:
raise RuntimeFailure("scheduler-declared-without-private-selection")
return None
fields = {"role", "profile", "nodeExecutable", "nodeDigest", "configurationDigest"}
if (not isinstance(selection, dict) or set(selection) != fields
or selection["role"] != "candidate-sender" or selection["profile"] != "bounded-contention-v1"
or not all(re.fullmatch(r"sha256:[a-f0-9]{64}", str(selection[key])) for key in ("nodeDigest", "configurationDigest"))):
raise RuntimeFailure("scheduler-selection-invalid")
binding = canonical_digest({"schemaVersion": 1, **{key: selection[key] for key in
("role", "profile", "nodeDigest", "configurationDigest")}})
if (declared != binding or authorization is None or authorization.get("schedulerInputsDigest") != binding
or authorization.get("syntheticContent") is not True):
raise RuntimeFailure("scheduler-selection-not-authorized")
if not any(app.get("appId") == "feed-reader" for app in private_config["nodes"][selection["role"]]["apps"]):
raise RuntimeFailure("scheduler-signed-feed-reader-not-selected")
executable = Path(selection["nodeExecutable"])
if (not executable.is_absolute() or executable.is_symlink() or not executable.is_file()
or any(parent.is_symlink() for parent in executable.parents)
or digest_file(executable) != selection["nodeDigest"]):
raise RuntimeFailure("scheduler-node-executable-not-selected")
with fixed_helper_imports():
helper = fixed_helper("scheduler_pressure_runtime")
if canonical_digest(helper.ENVIRONMENT) != selection["configurationDigest"]:
raise RuntimeFailure("scheduler-effective-profile-not-selected")
return binding
class _BootstrapParser(HTMLParser):
def __init__(self):
super().__init__()
self.active = False
self.parts = []
self.count = 0
def handle_starttag(self, tag, attrs):
if tag == "script" and dict(attrs).get("id") == "web-shell-bootstrap":
self.active = True
self.count += 1
def handle_endtag(self, tag):
if tag == "script":
self.active = False
def handle_data(self, data):
if self.active:
self.parts.append(data)
class ObservedMailClient(mail_demo.Client):
"""Reuse Mail protocol while charging every actual command/result/control request."""
def __init__(self, supervisor, *args):
self.supervisor = supervisor
super().__init__(*args)
def post(self, path, parameters, host=False):
self.supervisor.next_operation()
self.supervisor.remaining(1)
return super().post(path, parameters, host)
class _UnfollowedRedirect(urllib.request.HTTPRedirectHandler):
"""Expose redirect metadata for the fixed app launch proof without following it."""
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
class AppHandle:
"""Private own-app session and bounded HTTP access bound to an owned node process."""
def __init__(self, supervisor, role, app_id):
self.supervisor, self.role, self.app_id = supervisor, role, app_id
self.base = "http://127.0.0.1:" + str(supervisor.private["nodes"][role]["httpPort"])
self.api = self.base + "/api/v1"
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _UnfollowedRedirect())
self.origin = self.session = self.password = None
self.session_expires_at = None
self.worker_identity = None
def request(self, method, path, parameters=None, *, principal="host", raw=False, headers_override=None):
"""Only fixed selected app, Mail, app-data and observation routes; no generic proxy."""
exact = {"/app/node/", "/api/v1/apps", "/api/v1/apps/install", "/api/v1/diagnostics",
"/api/v1/mail/command", "/api/v1/mail/result", "/api/v1/audit", "/api/v1/queue", "/api/v1/platform/contract", "/api/v1/operator/support-bundle",
"/api/v1/operator/app-data/backups", "/api/v1/operator/app-data/restore/plan", "/api/v1/operator/app-data/restore"}
if self.app_id == "feed-reader" and principal == "app":
if (method == "GET" and path == "/api/v1/content/subscriptions") or (method == "POST" and path == "/api/v1/content/fetch"):
exact.add(path)
if getattr(self.supervisor, "scheduler_lane", False) and (
(method == "POST" and (path == "/api/v1/content/subscriptions"
or re.fullmatch(r"/api/v1/content/subscriptions/[A-Za-z0-9-]{1,128}/(?:pause|resume)", path)))
or (method == "DELETE" and re.fullmatch(r"/api/v1/content/subscriptions/[A-Za-z0-9-]{1,128}", path))):
exact.add(path)
if getattr(self.supervisor, "app_budget_lane", False) and self.app_id in {
"feed-reader", "budget-importer", "budget-no-trust", "budget-no-fetch"}:
if principal == "app" and ((method == "POST" and path in {
"/api/v1/trust-graph/import", "/api/v1/trust-graph/import-uri",
"/api/v1/trust-graph/import-preview", "/api/v1/trust-graph/import-preview-uri",
"/api/v1/content/fetch", "/api/v1/content/subscriptions"})
or (method == "GET" and path in {"/api/v1/trust-graph/statements",
"/api/v1/trust-graph/anchors", "/api/v1/trust-graph/audit", "/api/v1/content/subscriptions"})
or (method == "POST" and re.fullmatch(
r"/api/v1/content/subscriptions/[A-Za-z0-9-]{1,128}/(?:pause|resume|refresh)", path))):
exact.add(path)
if principal == "host" and method == "GET" and path == "/api/v1/operator/runtime-observation":
exact.add(path)
if principal == "host" and getattr(self.supervisor, "catalog_prepared", None) is not None:
if self.supervisor.catalog_route_allowed(self.role, self.app_id, method, path) is True:
exact.add(path)
if principal == "app" and getattr(self.supervisor, "catalog_principal_probe_allowed", None) is not None:
if self.supervisor.catalog_principal_probe_allowed(self.role, self.app_id, method, path) is True:
exact.add(path)
prefixes = ("/api/v1/app-data/",)
allowed_app = {"/api/v1/apps/" + self.app_id + suffix for suffix in ("", "/start", "/stop", "/runtime", "/logs", "/audit")}
bootstrap = "/apps/" + self.app_id + "/.well-known/cryptad-bootstrap.json"
if (path not in exact | allowed_app | {bootstrap} and not path.startswith(prefixes)) or "?" in path or ".." in path:
raise RuntimeFailure("app-route-not-approved")
self.supervisor.next_operation()
headers = {"Accept": "application/json"}
values = dict(parameters or {})
if principal == "app":
if not self.session or not self.origin:
raise RuntimeFailure("own-app-session-unavailable")
headers.update({"Origin": self.origin, "X-Crypta-App-Session": self.session})
elif principal == "host":
if method != "GET":
if not self.password:
raise RuntimeFailure("owned-host-session-unavailable")
values["formPassword"] = self.password
else:
raise RuntimeFailure("app-principal-invalid")
if headers_override:
if set(headers_override) - {"Origin", "X-Crypta-App-Session"}:
raise RuntimeFailure("app-header-override-invalid")
headers.update(headers_override)
data = urllib.parse.urlencode(values).encode() if method != "GET" else None
if data and len(data) > 1024**2:
raise RuntimeFailure("app-request-budget-exceeded")
if data:
headers["Content-Type"] = "application/x-www-form-urlencoded"
query = ""
if method == "GET" and values:
consent_query = (path in {"/api/v1/consent/install-preview",
"/api/v1/consent/catalog-update-preview"}
and set(values) == {"appId", "catalogId"}
and values["appId"] == self.app_id)
budget_queue_query = (getattr(self.supervisor, "app_budget_lane", False)
and path == "/api/v1/queue" and set(values) == {"page"}
and values["page"] in {"downloads", "uploads"})
if principal != "host" or not (consent_query or budget_queue_query):
raise RuntimeFailure("app-query-not-approved")
query = "?" + urllib.parse.urlencode(values)
request = urllib.request.Request(self.base + path + query, data=data, headers=headers, method=method)
# URI Trust Graph routes retain the native 30-second fetch bound. This fixed lane waits
# long enough to observe its response instead of treating a shorter HTTP wait as cessation.
composed_uri = (getattr(self.supervisor, "app_budget_lane", False)
and principal == "app" and method == "POST"
and path in {"/api/v1/trust-graph/import-uri",
"/api/v1/trust-graph/import-preview-uri"})
response_timeout = 45 if composed_uri else 25
try:
with absolute_deadline(self.supervisor.remaining(50 if composed_uri else 30)):
try:
response = self.opener.open(request, timeout=response_timeout)
except urllib.error.HTTPError as error:
response = error
with response:
body = response.read(2 * 1024**2 + 1)
if len(body) > 2 * 1024**2:
raise RuntimeFailure("app-response-budget-exceeded")
if raw:
return response.status, body
value = {} if response.status == 204 and not body else json.loads(body)
if not isinstance(value, dict):
raise RuntimeFailure("app-response-shape-invalid")
return response.status, value
except (OSError, ValueError, mail_demo.DemoFailure) as error:
raise RuntimeFailure("private-app-http-failed") from error
def host_bootstrap(self):
status, raw = self.request("GET", "/app/node/", raw=True)
parser = _BootstrapParser()
parser.feed(raw.decode("utf-8"))
if status != 200 or parser.count != 1:
raise RuntimeFailure("owned-host-bootstrap-unavailable")
value = json.loads("".join(parser.parts))
password = value.get("formPassword")
if not isinstance(password, str) or not password or len(password) > 4096:
raise RuntimeFailure("owned-host-bootstrap-invalid")
self.password = password
def refresh_session(self):
"""Acquire a fresh ordinary bootstrap; no extended expiry or process credentials."""
status, value = self.request("GET", "/apps/" + self.app_id + "/.well-known/cryptad-bootstrap.json")
if status != 200:
raise RuntimeFailure("own-app-bootstrap-failed")
if value.get("uiOrigin") is None:
value = self.isolated_bootstrap()
self.origin = mail_demo.target(value.get("uiOrigin"))
self.session = value.get("browserSessionToken")
self.session_expires_at = value.get("browserSessionExpiresAt")
if not isinstance(self.session, str) or not self.session or len(self.session) > 4096:
raise RuntimeFailure("own-app-bootstrap-invalid")
if self.origin == self.base:
raise RuntimeFailure("isolated-own-app-origin-required")
return self
def isolated_bootstrap(self):
"""Use the existing Web Shell launch-proof handoff; follow no unvalidated redirect.
The ordinary admin bootstrap intentionally issues a same-origin fallback principal. An
isolated browser principal requires its own loopback listener and app-scoped launch nonce.
"""
launch = self.base + '/apps/' + self.app_id + '/?cryptadIsolatedLaunch'
self.supervisor.next_operation()
try:
with absolute_deadline(self.supervisor.remaining(30)):
try:
response = self.opener.open(urllib.request.Request(launch, headers={'Accept': 'text/html'}), timeout=25)
except urllib.error.HTTPError as error:
response = error
with response:
if response.status not in (301, 302, 303, 307, 308):
raise RuntimeFailure('own-app-isolated-launch-unavailable')
selected = urllib.parse.urlsplit(response.headers.get('Location', ''))
if selected.path not in ('/', '/static/') or selected.query:
raise RuntimeFailure('own-app-isolated-launch-invalid')
origin = mail_demo.target(urllib.parse.urlunsplit((selected.scheme, selected.netloc, '', '', '')))
if origin == self.base:
raise RuntimeFailure('own-app-isolated-launch-invalid')
fragment = urllib.parse.parse_qs(selected.fragment, strict_parsing=True)
if set(fragment) != {'cryptadBootstrapNonce'} or len(fragment['cryptadBootstrapNonce']) != 1:
raise RuntimeFailure('own-app-isolated-launch-invalid')
nonce = fragment['cryptadBootstrapNonce'][0]
if not re.fullmatch(r'[A-Za-z0-9_-]{16,512}', nonce):
raise RuntimeFailure('own-app-isolated-launch-invalid')
self.supervisor.next_operation()
request = urllib.request.Request(origin + '/.well-known/cryptad-bootstrap.json', headers={
'Accept': 'application/json', 'Origin': origin, 'X-Crypta-App-Bootstrap-Nonce': nonce})
with self.opener.open(request, timeout=25) as response:
raw = response.read(65537)
if response.status != 200 or len(raw) > 65536:
raise RuntimeFailure('own-app-isolated-bootstrap-invalid')
value = json.loads(raw)
if not isinstance(value, dict) or value.get('uiOrigin') != origin:
raise RuntimeFailure('own-app-isolated-bootstrap-invalid')
return value
except urllib.error.HTTPError as error:
code = error.code if error.code in (400, 401, 403, 404, 429, 500, 503) else 0
raise RuntimeFailure('own-app-isolated-bootstrap-http-' + str(code)) from None
except (OSError, ValueError, mail_demo.DemoFailure):
raise RuntimeFailure('own-app-isolated-bootstrap-failed') from None
def observe_worker(self):
status, value = self.request("GET", "/api/v1/apps/" + self.app_id + "/runtime")
runtime = value.get("runtime", {})
if status != 200 or runtime.get("running") is not True:
raise RuntimeFailure("app-child-not-running")
sandbox = runtime.get("sandbox", {})
if sandbox.get("provider") != "bubblewrap" or sandbox.get("active") is not True:
raise RuntimeFailure("real-app-sandbox-not-observed")
pid = runtime.get("pid")
if type(pid) is not int:
raise RuntimeFailure("app-child-pid-missing")
expected = self.supervisor.nodes[self.role].runtime.process.pid
cursor = pid
for _ in range(64):
if cursor == expected:
self.worker_identity = process_identity(pid)
if self.app_id == "mail-prototype":
expected_java = digest_file(self.supervisor.nodes[self.role].java_home / "bin/java")
found = False
for proc in Path("/proc").iterdir():
if not proc.name.isdigit():
continue
try:
child = int(proc.name)
if process_identity(child)["executableDigest"] != expected_java:
continue
cursor_child = child
for _ in range(64):
if cursor_child == pid:
found = True
break
fields_child = (Path("/proc") / str(cursor_child) / "stat").read_text().rsplit(")", 1)[1].split()
cursor_child = int(fields_child[1])
if cursor_child <= 1:
break
if found:
break
except (OSError, ValueError):
continue
if not found:
raise RuntimeFailure("mail-java-child-not-observed")
return
fields = (Path("/proc") / str(cursor) / "stat").read_text().rsplit(")", 1)[1].split()
cursor = int(fields[1])
if cursor <= 1:
break
raise RuntimeFailure("app-child-not-owned")
def mail_client(self):
self.refresh_session()
return ObservedMailClient(self.supervisor, self.api, self.origin, self.session, self.password)
def owned_jvm_descendants(supervisor_pid, executable_digest, proc_root=Path('/proc')):
"""Find exact JVM descendants even when the packaged wrapper creates child process groups.
Each accepted candidate's epoch is checked again after its bounded ancestry walk. The selected
supervisor epoch brackets the entire scan; unrelated matching JVM executables never qualify.
"""
before = process_identity(supervisor_pid)
descendants = []
for entry in proc_root.iterdir():
if not entry.name.isdigit():
continue
try:
candidate = int(entry.name)
identity = process_identity(candidate)
if identity['executableDigest'] != executable_digest:
continue
cursor = candidate
seen = set()
for _ in range(64):
if cursor == supervisor_pid:
if process_identity(candidate) == identity:
descendants.append(identity)
break
if cursor <= 1 or cursor in seen:
break
seen.add(cursor)
fields = (proc_root / str(cursor) / 'stat').read_text().rsplit(')', 1)[1].split()
cursor = int(fields[1])
except (OSError, ValueError, IndexError):
continue
if process_identity(supervisor_pid) != before:
raise RuntimeFailure('owned-supervisor-epoch-changed-during-scan')
return descendants
def require_persistent_identity(requests, operation, uri):
selected = [entry for entry in requests if entry.get("fields", {}).get("Identifier") == operation]
if len(selected) != 1 or selected[0].get("name") != "PersistentGet":
raise RuntimeFailure("persistent-original-request-missing-or-duplicate")
fields = selected[0]["fields"]
if fields.get("URI") != uri or fields.get("Persistence") != "forever" or fields.get("Global") != "false":
raise RuntimeFailure("persistent-original-request-substituted")
return selected[0]
def observe_partition_denial(receiver, operation, reference):
"""Require an actual bounded retrieval failure, never reinterpret protocol errors."""
receiver.send("ClientGet", interop.build_client_get_fields(operation, reference, ignore_ds=True))
frame = receiver.read_until(30, {"GetFailed", "AllData"})
if frame.fields.get("Identifier") != operation:
raise RuntimeFailure("partition-operation-binding-mismatch")
return frame.name == "GetFailed" and frame.fields.get("Code") in {"13", "14", "28", "30"}
class _BoundedWireFile:
"""Apply strict frame budgets while retaining the existing interop FCP parser."""
def __init__(self, stream):
self.stream = stream
self.header_bytes = 0
self.fields = set()
def readline(self):
line = self.stream.readline(8193)
self.header_bytes += len(line)
if len(line) > 8192 or self.header_bytes > 65536:
raise RuntimeFailure("fcp-header-budget-exceeded")
if b"=" in line:
key, value = line.rstrip(b"\n").split(b"=", 1)
if key in self.fields:
raise RuntimeFailure("fcp-duplicate-field")
self.fields.add(key)
if key == b"DataLength" and (not value.isdigit() or not 0 <= int(value) <= 1024**2):
raise RuntimeFailure("fcp-payload-budget-exceeded")
return line
def read(self, length):
if not 0 <= length <= 1024**2:
raise RuntimeFailure("fcp-payload-budget-exceeded")
return self.stream.read(length)