Repository navigation
Expand file tree
/
Copy pathcluster_sync_command.py
More file actions
executable file
·3596 lines (3285 loc) · 153 KB
/
Copy pathcluster_sync_command.py
File metadata and controls
executable file
·3596 lines (3285 loc) · 153 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
"""Restricted command wrapper for PBGui Cluster Sync SSH keys.
The script is intended for OpenSSH forced-command use. It accepts one small
Cluster Sync command through SSH_ORIGINAL_COMMAND, validates the peer node, and
limits writes to cluster state plus explicit V7/PB8 config materialization.
"""
from __future__ import annotations
import argparse
import base64
import binascii
import hashlib
import json
import os
import re
import shlex
import shutil
import sys
import time
import uuid
from contextlib import nullcontext
from datetime import datetime
from pathlib import Path
from typing import Any
from logging_helpers import human_log as _log
SERVICE = "ClusterSync"
from cluster_credentials import (
ClusterCredentialError,
EnvelopeValidationError,
NotRecipientError,
SecretContext,
SecretDecryptionError,
deserialize_sealed_secret,
ensure_node_key_material,
load_node_encryption_private_keys,
open_sealed_secret,
verify_operation,
validate_sealed_secret,
)
from cmc_leases import (
CmcLeaseError,
ClusterMailbox,
MAX_MAILBOX_MESSAGE_BYTES,
)
from credential_store import CredentialStore
from file_lock import advisory_file_lock
from master.cluster_state import (
ClusterPaths,
ClusterStateError,
MEMBERSHIP_OPS,
PB8_OPS,
PB8_OPERATION_CAPABILITY,
SYNC_EXCLUDE_FILES,
V7_OPS,
V2_CREDENTIAL_OPS,
append_operation,
build_config_manifest,
compute_config_manifest_hash,
create_join_authorization,
default_cluster_root,
ensure_local_identity,
membership_signing_public_key,
read_materialized_state,
read_local_identity,
rebuild_materialized_state,
stage_membership_operations,
validate_operation,
write_operation,
)
from master.cluster_ssh_keys import ensure_cluster_ssh_key
from master.cluster_checkpoint import (
ClusterCheckpointError,
_deserialize_membership_trust,
activate_checkpoint,
active_checkpoint_baseline,
active_checkpoint_bundle,
build_shadow_checkpoint,
checkpoint_status,
create_checkpoint_ack,
install_rebootstrap_checkpoint,
retention_cleanup_status,
retention_preview,
read_active_checkpoint,
verify_checkpoint_commit_proof,
verify_checkpoint_proposal,
write_checkpoint_object,
)
from pb7_api_keys import (
PB7ApiKeysMergeWriter,
build_tradfi_projection,
exchange_payload,
project_active_tradfi_profiles,
)
from pbgui_purefunc import PBGDIR, pb7dir, pb8dir
from secure_files import atomic_write_private_bytes, ensure_private_directory_tree
PROTOCOL_VERSION = 2
MAX_COMMAND_BYTES = 4096
MAX_OPERATION_BYTES = 1024 * 1024
MAX_OPERATION_BATCH_BYTES = 16 * 1024 * 1024
MAX_CONFIG_BLOB_BYTES = 16 * 1024 * 1024
MAX_CONFIG_BLOB_BATCH_BYTES = 16 * 1024 * 1024
MAX_SECRET_BLOB_BYTES = 1024 * 1024
MAX_SEALED_BLOB_BYTES = 16 * 1024 * 1024
MAX_APPLY_BUNDLE_BYTES = 24 * 1024 * 1024
MAX_CHECKPOINT_BYTES = 32 * 1024 * 1024
MAX_GET_OPS = 1000
MAX_GET_BLOBS = 100
MAX_BLOB_COVERAGE_HASHES = 1000
MAX_BLOB_COVERAGE_VERIFY_BYTES = 64 * 1024 * 1024
MAILBOX_INDEX_VERBS = frozenset({"get-mailbox-index", "mailbox-list"})
MAILBOX_GET_VERBS = frozenset({"get-mailbox-message", "mailbox-get"})
MAILBOX_PUT_VERBS = frozenset({"put-mailbox-message", "mailbox-put"})
MAILBOX_ACK_VERBS = frozenset({"ack-mailbox-message", "mailbox-ack"})
READ_VERBS = frozenset({
"handshake",
"hello",
"get-state-vector",
"get-desired-state",
"get-ops",
"get-blob",
"get-blobs",
"get-secret-blob",
"get-sealed-blob",
"missing-blobs",
*MAILBOX_INDEX_VERBS,
*MAILBOX_GET_VERBS,
"materialize-v7-preview",
"materialize-v8-preview",
"materialize-api-keys-preview",
"credential-runtime-status",
"materialize-credentials-preview",
"get-checkpoint-state",
"retention-preview",
"join-checkpoint-state",
"join-get-blob",
"join-state-vector",
"join-get-ops",
})
WRITE_VERBS = frozenset({"join", "join-hello", "join-checkpoint", "join-register", "put-op", "put-ops", "repair-op-gap", "put-blob", "put-blobs", "put-secret-blob", "put-sealed-blob", "apply-bundle", "rebuild", "materialize-v7", "materialize-v8", "materialize-api-keys", "materialize-credentials", "prepare-checkpoint", "commit-checkpoint", "install-checkpoint", *MAILBOX_PUT_VERBS, *MAILBOX_ACK_VERBS})
STDIN_VERBS = frozenset({"join-checkpoint", "join-register", "put-op", "put-ops", "repair-op-gap", "put-blob", "put-blobs", "put-secret-blob", "put-sealed-blob", "apply-bundle", "prepare-checkpoint", "commit-checkpoint", "install-checkpoint", "missing-blobs", *MAILBOX_PUT_VERBS})
SUPPORTED_VERBS = READ_VERBS | WRITE_VERBS
class ClusterSyncCommandError(RuntimeError):
"""Raised when a restricted Cluster Sync command is invalid."""
def run_command(
cluster_root: Path,
remote_node: str,
command_text: str,
stdin_data: bytes = b"",
*,
allow_join: bool = False,
) -> dict[str, Any]:
"""Execute one restricted Cluster Sync command and return a JSON payload."""
root = Path(cluster_root)
_validate_node_id(remote_node, "remote_node")
tokens = _parse_command(command_text)
verb = tokens[0]
if verb == "join":
return _join_cluster(root, remote_node, tokens, allow_join=allow_join)
if verb == "join-hello":
if not allow_join:
raise ClusterSyncCommandError("join-hello requires allow_join")
_require_arity(tokens, 3)
subject = _validate_node_id(tokens[1], "node_id")
role = _validate_role(tokens[2])
if subject != remote_node:
raise ClusterSyncCommandError("join-hello node_id must match remote node")
identity = read_local_identity(root)
payload = _hello_payload(root, identity, remote_node)
payload["join_authorization"] = _safe_state_call(
lambda: create_join_authorization(root, subject, role)
)
return payload
if verb == "join-checkpoint":
if not allow_join:
raise ClusterSyncCommandError("join-checkpoint requires allow_join")
_require_arity(tokens, 1)
payload = _read_checkpoint_control_payload(stdin_data)
cluster_id = _validate_cluster_id(payload.get("cluster_id"))
node_id = _validate_node_id(payload.get("node_id"), "node_id")
role = _validate_role(payload.get("role"))
pbname = str(payload.get("pbname") or "").strip()
checkpoint = payload.get("checkpoint")
proof = payload.get("commit_proof")
authorization = payload.get("authorization")
anchor_public_key = str(payload.get("anchor_public_key") or "")
if not isinstance(checkpoint, dict) or not isinstance(proof, dict) or not isinstance(authorization, dict):
raise ClusterSyncCommandError("join-checkpoint payload is incomplete")
if str(proof.get("coordinator_id") or "") != remote_node:
raise ClusterSyncCommandError("join-checkpoint caller must be checkpoint coordinator")
identity = _safe_state_call(
lambda: ensure_local_identity(
root,
role=role,
pbname=pbname,
cluster_id=cluster_id,
node_id=node_id,
)
)
try:
installed = install_rebootstrap_checkpoint(
root,
checkpoint,
proof,
join_authorization=authorization,
join_anchor_public_key=anchor_public_key,
defer_blob_validation=True,
)
membership = append_operation(
root,
"ADD_NODE",
{
"node_id": node_id,
"role": role,
"pbname": pbname,
"membership_authorization": authorization,
},
)
rebuild_materialized_state(root)
except (ClusterCheckpointError, ClusterStateError) as exc:
raise ClusterSyncCommandError(str(exc)) from exc
return {
"ok": True,
"cluster_id": str(identity["cluster_id"]),
"node_id": str(identity["node_id"]),
"role": role,
"pbname": pbname,
"joined_by": remote_node,
"checkpoint_id": str(checkpoint["checkpoint_id"]),
"checkpoint_epoch": int(installed["epoch"]),
"membership_op_id": str(membership["op_id"]),
}
if verb == "join-checkpoint-state":
if not allow_join:
raise ClusterSyncCommandError("join-checkpoint-state requires allow_join")
_require_arity(tokens, 2)
authorization = _verified_join_authorization(root, remote_node, tokens[1])
bundle = active_checkpoint_bundle(root)
if bundle is None:
return {"ok": True, "status": "missing", "bundle": None}
if str(bundle["commit_proof"].get("coordinator_id") or "") != str(authorization.get("signer_id") or ""):
raise ClusterSyncCommandError("join must use the elected checkpoint coordinator")
return {"ok": True, "status": "current", "bundle": bundle}
if verb == "join-state-vector":
if not allow_join:
raise ClusterSyncCommandError("join-state-vector requires allow_join")
_require_arity(tokens, 2)
_verified_join_authorization(root, remote_node, tokens[1])
materialized = _safe_state_call(lambda: rebuild_materialized_state(root, write=False))
return {
"ok": True,
"cluster_id": str((materialized.get("cluster_nodes") or {}).get("cluster_id") or ""),
"node_id": str(read_local_identity(root)["node_id"]),
"state_vector": materialized.get("state_vector") or {},
**checkpoint_status(root),
}
if verb == "join-get-ops":
if not allow_join:
raise ClusterSyncCommandError("join-get-ops requires allow_join")
_require_arity(tokens, 5)
_verified_join_authorization(root, remote_node, tokens[1])
actor = _validate_node_id(tokens[2], "actor")
from_seq = _parse_positive_int(tokens[3], "from_seq")
to_seq = _parse_positive_int(tokens[4], "to_seq")
if to_seq < from_seq or to_seq - from_seq + 1 > MAX_GET_OPS:
raise ClusterSyncCommandError("invalid join operation range")
baseline = active_checkpoint_baseline(root)
if from_seq <= int(baseline.get(actor, 0)):
return {"ok": False, "status": "checkpoint_required", **checkpoint_status(root)}
identity = read_local_identity(root)
operations, missing = _read_operation_range(
root,
actor,
from_seq,
to_seq,
expected_cluster_id=str(identity["cluster_id"]),
)
return {
"ok": True,
"cluster_id": str(identity["cluster_id"]),
"node_id": str(identity["node_id"]),
"operations": operations,
"missing": missing,
}
if verb == "join-get-blob":
if not allow_join:
raise ClusterSyncCommandError("join-get-blob requires allow_join")
_require_arity(tokens, 4)
_verified_join_authorization(root, remote_node, tokens[1])
kind = str(tokens[2])
blob_hash = _validate_hash(tokens[3])
paths = ClusterPaths.from_root(root)
if not _join_blob_allowed(root, kind, blob_hash):
raise ClusterSyncCommandError("join blob is not referenced by the active checkpoint")
if kind == "config":
return _read_blob_response(paths.config_blobs, blob_hash, secret=False, cluster_root=root)
if kind == "secret":
return _read_blob_response(paths.secret_blobs, blob_hash, secret=True)
if kind == "sealed":
return _read_blob_response(paths.sealed_blobs, blob_hash, secret=True)
raise ClusterSyncCommandError("invalid join blob kind")
if verb == "join-register":
if not allow_join:
raise ClusterSyncCommandError("join-register requires allow_join")
_require_arity(tokens, 2)
authorization = _verified_join_authorization(root, remote_node, tokens[1])
operation = _read_json_payload(stdin_data, MAX_OPERATION_BYTES)
if (
str(operation.get("op") or "") != "ADD_NODE"
or str(operation.get("actor") or "") != remote_node
or str(operation.get("node_id") or "") != remote_node
or operation.get("membership_authorization") != authorization
):
raise ClusterSyncCommandError("join-register accepts only the authorized node self-add")
_safe_state_call(lambda: write_operation(root, operation, network_input=True))
_safe_state_call(lambda: rebuild_materialized_state(root))
return {"ok": True, "op_id": str(operation["op_id"]), "node_id": remote_node}
identity = read_local_identity(root)
cluster_id = str(identity["cluster_id"])
paths = ClusterPaths.from_root(root)
if verb == "repair-op-gap":
_require_arity(tokens, 1)
_verify_remote_node_for_gap_repair(root, remote_node, cluster_id)
operation = _read_json_payload(stdin_data, MAX_OPERATION_BYTES)
return _repair_operation_gap(root, paths, cluster_id, operation)
_verify_remote_node(root, remote_node, allow_join=False)
if verb == "handshake":
payload = _hello_payload(root, identity, remote_node)
materialized = _read_materialized_snapshot(root)
payload["state_vector"] = materialized.get("state_vector") or {}
# Share the authenticated read cohort instead of starting another SSH
# forced-command Python process for the idle mailbox index request.
messages = _mailbox_call(lambda: ClusterMailbox(root).index())
payload["mailbox_index"] = {"ok": True, "count": len(messages), "messages": messages}
return payload
if verb == "hello":
payload = _hello_payload(root, identity, remote_node)
payload["credential_migration_advance"] = {"status": "delegated_to_pbcluster"}
return payload
if verb == "get-state-vector":
materialized = _read_materialized_snapshot(root)
return {
"ok": True,
"cluster_id": cluster_id,
"node_id": str(identity["node_id"]),
"state_vector": materialized.get("state_vector") or {},
**checkpoint_status(root),
}
if verb == "get-desired-state":
materialized = _read_materialized_snapshot(root)
return {
"ok": True,
"cluster_id": cluster_id,
"node_id": str(identity["node_id"]),
"desired_state": materialized.get("desired_state") or {},
}
if verb == "get-ops":
_require_arity_range(tokens, 3, 4)
actor = _validate_node_id(tokens[1], "actor")
from_seq = _parse_positive_int(tokens[2], "from_seq")
to_seq = _parse_positive_int(tokens[3], "to_seq") if len(tokens) == 4 else from_seq
baseline = active_checkpoint_baseline(root)
if from_seq <= int(baseline.get(actor, 0)):
return {
"ok": False,
"status": "checkpoint_required",
"cluster_id": cluster_id,
"node_id": str(identity["node_id"]),
**checkpoint_status(root),
}
operations, missing = _read_operation_range(root, actor, from_seq, to_seq, expected_cluster_id=cluster_id)
return {
"ok": True,
"cluster_id": cluster_id,
"node_id": str(identity["node_id"]),
"actor": actor,
"from_seq": from_seq,
"to_seq": to_seq,
"operations": operations,
"missing": missing,
}
if verb == "get-blob":
_require_arity(tokens, 2)
return _read_blob_response(paths.config_blobs, tokens[1], secret=False, cluster_root=root)
if verb == "get-blobs":
_require_arity_range(tokens, 2, MAX_GET_BLOBS + 1)
blobs = [
_read_blob_response(paths.config_blobs, token, secret=False, cluster_root=root)
for token in tokens[1:]
]
return {"ok": True, "count": len(blobs), "blobs": blobs}
if verb == "get-secret-blob":
_require_arity(tokens, 2)
if tokens[1] in set((_credential_cutoff(root) or {}).get("obsolete_secret_blob_hashes") or []):
raise ClusterSyncCommandError("pre-cutoff plaintext secret blob is unavailable")
return _read_blob_response(paths.secret_blobs, tokens[1], secret=True)
if verb == "get-sealed-blob":
_require_arity(tokens, 2)
response = _read_blob_response(paths.sealed_blobs, tokens[1], secret=True)
_validate_sealed_blob_payload(root, base64.b64decode(response["content_b64"]))
return response
if verb == "missing-blobs":
_require_arity(tokens, 1)
request = _read_json_payload(stdin_data, MAX_OPERATION_BATCH_BYTES)
return _missing_blob_coverage(paths, request)
if verb in MAILBOX_INDEX_VERBS:
_require_arity(tokens, 1)
_verify_remote_node(root, remote_node, allow_join=False)
messages = _mailbox_call(lambda: ClusterMailbox(root).index())
return {"ok": True, "count": len(messages), "messages": messages}
if verb in MAILBOX_GET_VERBS:
_require_arity(tokens, 2)
_verify_remote_node(root, remote_node, allow_join=False)
message = _mailbox_call(lambda: ClusterMailbox(root).get(tokens[1]))
return {"ok": True, "message": message}
if verb == "materialize-v7-preview":
return _materialize_v7_configs(root, write=False)
if verb == "materialize-v8-preview":
return _materialize_pb8_configs(root, write=False)
if verb == "credential-runtime-status":
_require_arity(tokens, 1)
return {**_credential_runtime_status(root), "cluster_id": cluster_id, "node_id": str(identity["node_id"])}
if verb == "materialize-api-keys-preview":
return _materialize_api_keys(root, write=False)
if verb == "materialize-credentials-preview":
return _materialize_credentials(root, write=False)
if verb == "get-checkpoint-state":
_require_arity(tokens, 1)
bundle = active_checkpoint_bundle(root)
return {
"ok": True,
"status": "current" if bundle is not None else "missing",
"bundle": bundle,
}
if verb == "retention-preview":
_require_arity(tokens, 1)
checkpoint = build_shadow_checkpoint(root)
preview = retention_preview(root, checkpoint, item_limit=200)
return {
"ok": True,
**preview,
"automatic_cleanup": retention_cleanup_status(root),
}
if verb == "prepare-checkpoint":
_require_arity(tokens, 1)
payload = _read_checkpoint_control_payload(stdin_data)
checkpoint = payload.get("checkpoint")
proposal = payload.get("proposal")
if not isinstance(checkpoint, dict) or not isinstance(proposal, dict):
raise ClusterSyncCommandError("checkpoint prepare payload is incomplete")
try:
verified = verify_checkpoint_proposal(checkpoint, proposal)
with advisory_file_lock(root / ".append_sequence"):
local = build_shadow_checkpoint(
root,
created_at=int(checkpoint.get("created_at") or 0),
history_seconds=int(checkpoint.get("history_seconds") or 0),
)
if local["checkpoint_id"] != checkpoint.get("checkpoint_id"):
raise ClusterCheckpointError("local checkpoint does not match proposal")
write_checkpoint_object(root, local)
ack = create_checkpoint_ack(root, local, verified)
_cleanup_expired_prepared_checkpoints(root)
prepared_path = _prepared_checkpoint_path(root, str(verified["proposal_id"]))
atomic_write_private_bytes(
prepared_path,
(json.dumps({
"checkpoint_id": str(local["checkpoint_id"]),
"proposal_id": str(verified["proposal_id"]),
"expires_at": int(verified["expires_at"]),
}, indent=4, sort_keys=True) + "\n").encode("utf-8"),
)
except ClusterCheckpointError as exc:
raise ClusterSyncCommandError(str(exc)) from exc
return {"ok": True, "status": "prepared", "checkpoint_id": local["checkpoint_id"], "ack": ack}
if verb == "commit-checkpoint":
_require_arity(tokens, 1)
payload = _read_checkpoint_control_payload(stdin_data)
checkpoint = payload.get("checkpoint")
proof = payload.get("commit_proof")
if not isinstance(checkpoint, dict) or not isinstance(proof, dict):
raise ClusterSyncCommandError("checkpoint commit payload is incomplete")
try:
verified_proof = verify_checkpoint_commit_proof(checkpoint, proof)
prepared_path = _prepared_checkpoint_path(root, str(verified_proof["proposal_id"]))
if prepared_path.is_symlink() or not prepared_path.is_file():
raise ClusterCheckpointError("checkpoint was not prepared locally")
prepared = json.loads(prepared_path.read_text(encoding="utf-8"))
if (
not isinstance(prepared, dict)
or prepared.get("checkpoint_id") != checkpoint.get("checkpoint_id")
or int(prepared.get("expires_at") or 0) <= int(time.time())
):
raise ClusterCheckpointError("prepared checkpoint is invalid or expired")
current_vector = (rebuild_materialized_state(root, write=False).get("state_vector") or {})
if current_vector != checkpoint.get("baseline_vector"):
raise ClusterCheckpointError("cluster state changed after checkpoint preparation")
commit = activate_checkpoint(root, checkpoint, commit_proof=proof)
prepared_path.unlink(missing_ok=True)
except ClusterCheckpointError as exc:
raise ClusterSyncCommandError(str(exc)) from exc
return {
"ok": True,
"status": "committed",
"checkpoint_id": str(checkpoint["checkpoint_id"]),
"epoch": int(commit["epoch"]),
}
if verb == "install-checkpoint":
_require_arity(tokens, 1)
payload = _read_checkpoint_control_payload(stdin_data)
checkpoint = payload.get("checkpoint")
proof = payload.get("commit_proof")
if not isinstance(checkpoint, dict) or not isinstance(proof, dict):
raise ClusterSyncCommandError("checkpoint install payload is incomplete")
try:
result = install_rebootstrap_checkpoint(root, checkpoint, proof)
except ClusterCheckpointError as exc:
raise ClusterSyncCommandError(str(exc)) from exc
return {"ok": True, **result}
if verb == "rebuild":
materialized = _safe_state_call(lambda: rebuild_materialized_state(root))
return {
"ok": True,
"generation": int((materialized.get("cluster_nodes") or {}).get("generation") or 0),
"nodes": len(((materialized.get("cluster_nodes") or {}).get("nodes") or {})),
"instances": len(((materialized.get("desired_state") or {}).get("instances") or {})),
"pb8_instances": len(((materialized.get("desired_state") or {}).get("pb8_instances") or {})),
}
if verb == "materialize-v7":
return _materialize_v7_configs(root, write=True)
if verb == "materialize-v8":
return _materialize_pb8_configs(root, write=True)
if verb == "materialize-api-keys":
return _materialize_api_keys(root, write=True)
if verb == "materialize-credentials":
return _materialize_credentials(root, write=True)
if verb == "put-op":
_require_arity(tokens, 1)
operation = _read_json_payload(stdin_data, MAX_OPERATION_BYTES)
staged_nodes = _staged_membership_nodes(root, [operation], remote_node=remote_node)
_safe_state_call(
lambda: validate_operation(
operation,
expected_cluster_id=cluster_id,
cluster_root=root,
membership_trust=staged_nodes,
network_input=True,
)
)
_safe_state_call(
lambda: write_operation(
root,
operation,
network_input=True,
membership_trust=staged_nodes,
)
)
return {"ok": True, "op_id": str(operation["op_id"]), "actor": str(operation["actor"]), "seq": int(operation["seq"])}
if verb == "put-ops":
_require_arity(tokens, 1)
operations = _read_operation_batch_payload(stdin_data)
staged_nodes = _staged_membership_nodes(root, operations, remote_node=remote_node)
for operation in operations:
_safe_state_call(
lambda op=operation: validate_operation(
op,
expected_cluster_id=cluster_id,
cluster_root=root,
membership_trust=staged_nodes,
network_input=True,
)
)
written: list[dict[str, Any]] = []
publish_order = sorted(
operations,
key=lambda item: str(item.get("op") or "") in V2_CREDENTIAL_OPS,
)
for operation in publish_order:
_safe_state_call(
lambda op=operation: write_operation(
root,
op,
network_input=True,
membership_trust=staged_nodes,
)
)
for operation in operations:
written.append({"op_id": str(operation["op_id"]), "actor": str(operation["actor"]), "seq": int(operation["seq"])})
return {"ok": True, "count": len(written), "operations": written}
if verb == "put-blob":
_require_arity(tokens, 2)
blob_hash = _validate_hash(tokens[1])
with advisory_file_lock(root / ".append_sequence"):
path = _write_blob(paths.config_blobs, blob_hash, stdin_data, MAX_CONFIG_BLOB_BYTES, secret=False)
return {"ok": True, "hash": blob_hash, "path": _relative_cluster_path(paths.root, path)}
if verb == "put-blobs":
_require_arity(tokens, 1)
blobs = _read_blob_batch_payload(stdin_data)
written: list[dict[str, str]] = []
with advisory_file_lock(root / ".append_sequence"):
for blob in blobs:
path = _write_blob(paths.config_blobs, str(blob["hash"]), blob["raw"], MAX_CONFIG_BLOB_BYTES, secret=False)
written.append({"hash": str(blob["hash"]), "path": _relative_cluster_path(paths.root, path)})
return {"ok": True, "count": len(written), "blobs": written}
if verb == "put-secret-blob":
_require_arity(tokens, 2)
blob_hash = _validate_hash(tokens[1])
if blob_hash in set((_credential_cutoff(root) or {}).get("obsolete_secret_blob_hashes") or []):
raise ClusterSyncCommandError("pre-cutoff plaintext secret blob is obsolete")
with advisory_file_lock(root / ".append_sequence"):
path = _write_blob(paths.secret_blobs, blob_hash, stdin_data, MAX_SECRET_BLOB_BYTES, secret=True)
return {"ok": True, "hash": blob_hash, "path": _relative_cluster_path(paths.root, path)}
if verb == "put-sealed-blob":
_require_arity(tokens, 2)
blob_hash = _validate_hash(tokens[1])
_validate_sealed_blob_payload(root, stdin_data)
with advisory_file_lock(root / ".append_sequence"):
path = _write_blob(paths.sealed_blobs, blob_hash, stdin_data, MAX_SEALED_BLOB_BYTES, secret=True)
return {"ok": True, "hash": blob_hash, "path": _relative_cluster_path(paths.root, path)}
if verb in MAILBOX_PUT_VERBS:
_require_arity(tokens, 1)
_verify_remote_node(root, remote_node, allow_join=False)
message = _read_json_payload(stdin_data, MAX_MAILBOX_MESSAGE_BYTES)
created = _mailbox_call(lambda: ClusterMailbox(root).put(message))
return {
"ok": True,
"message_id": str(message.get("message_id") or ""),
"created": bool(created),
}
if verb in MAILBOX_ACK_VERBS:
_require_arity(tokens, 2)
_verify_remote_node(root, remote_node, allow_join=False)
created = _mailbox_call(lambda: ClusterMailbox(root).ack(tokens[1], remote_node))
return {"ok": True, "message_id": tokens[1], "created": bool(created)}
if verb == "apply-bundle":
_require_arity(tokens, 1)
with advisory_file_lock(root / ".append_sequence"):
return _apply_bundle(root, paths, cluster_id, stdin_data, remote_node=remote_node)
raise ClusterSyncCommandError(f"unsupported command: {verb}")
def main(argv: list[str] | None = None) -> int:
"""Command-line entry point for OpenSSH forced-command execution."""
parser = argparse.ArgumentParser(description="PBGui restricted Cluster Sync command wrapper")
parser.add_argument("--cluster-root", default=str(default_cluster_root(Path(PBGDIR))))
parser.add_argument("--remote-node", required=True)
parser.add_argument("--allow-join", action="store_true")
parser.add_argument("command", nargs=argparse.REMAINDER)
args = parser.parse_args(argv)
try:
command_text = os.environ.get("SSH_ORIGINAL_COMMAND") or " ".join(args.command).strip()
stdin_data = _read_stdin_for_command(command_text)
payload = run_command(
Path(args.cluster_root),
str(args.remote_node),
command_text,
stdin_data,
allow_join=bool(args.allow_join),
)
except Exception as exc:
error = {"ok": False, "error": str(exc)}
sys.stderr.write(json.dumps(error, sort_keys=True) + "\n")
return 1
sys.stdout.write(json.dumps(payload, sort_keys=True) + "\n")
return 0
def _read_stdin_for_command(command_text: str) -> bytes:
"""Read stdin only for commands that carry an upload payload."""
tokens = _parse_command(command_text)
if tokens[0] not in STDIN_VERBS:
return b""
return sys.stdin.buffer.read(max(MAX_CONFIG_BLOB_BATCH_BYTES, MAX_CONFIG_BLOB_BYTES, MAX_OPERATION_BATCH_BYTES, MAX_APPLY_BUNDLE_BYTES, MAX_CHECKPOINT_BYTES) + 1)
def _hello_payload(cluster_root: Path, identity: dict[str, Any], remote_node: str) -> dict[str, Any]:
"""Return peer metadata used by hello and handshake."""
payload = {
"ok": True,
"protocol_version": PROTOCOL_VERSION,
"cluster_id": str(identity["cluster_id"]),
"node_id": str(identity["node_id"]),
"role": str(identity.get("role") or ""),
"remote_node": remote_node,
"mailbox_capability": True,
"checkpoint_capability": True,
"blob_coverage_capability": True,
**checkpoint_status(cluster_root),
}
try:
payload["retention_cleanup"] = retention_cleanup_status(cluster_root)
except (ClusterCheckpointError, OSError, TypeError, ValueError):
payload["retention_cleanup"] = {
"oplog": {"status": "error", "blockers": ["retention_status_unavailable"]},
"blobs": {"status": "error", "blockers": ["retention_status_unavailable"]},
}
try:
crypto = ensure_node_key_material(cluster_root)
public_bundle = crypto.public_bundle(
str(identity.get("node_id") or ""),
str(identity.get("role") or "master"),
)
payload.update({
"crypto_public_bundle": public_bundle,
"credential_capability": {
"version": 2,
"sealed_credentials": True,
"operation_signing": "Ed25519",
"secret_encryption": "HPKE-X25519-HKDF-SHA256-AES128GCM",
"audiences": ["cluster", "masters"],
},
"capabilities": ["sealed_credentials_v2", PB8_OPERATION_CAPABILITY],
})
except Exception as exc:
payload["credential_capability"] = {
"version": 2,
"sealed_credentials": False,
"error": str(exc),
}
try:
key = ensure_cluster_ssh_key(cluster_root, node_id=str(identity.get("node_id") or ""))
payload.update({
"cluster_ssh_public_key": str(key.get("public_key") or ""),
"cluster_ssh_fingerprint": str(key.get("fingerprint") or ""),
"cluster_ssh_mode": "forced",
})
except Exception as exc:
payload["cluster_ssh_error"] = str(exc)
return payload
def _join_cluster(cluster_root: Path, remote_node: str, tokens: list[str], *, allow_join: bool) -> dict[str, Any]:
"""Initialize local identity for an explicitly approved remote join."""
if not allow_join:
raise ClusterSyncCommandError("join requires allow_join")
_require_arity_range(tokens, 5, 6)
cluster_id = _validate_cluster_id(tokens[1])
node_id = _validate_node_id(tokens[2], "node_id")
role = _validate_role(tokens[3])
pbname = str(tokens[4] or "").strip()
identity = _safe_state_call(
lambda: ensure_local_identity(
cluster_root,
role=role,
pbname=pbname,
cluster_id=cluster_id,
node_id=node_id,
)
)
membership = None
if len(tokens) == 6:
try:
decoded = base64.b64decode(tokens[5].encode("ascii"), altchars=b"-_", validate=True)
bootstrap = json.loads(decoded.decode("utf-8"))
except (UnicodeEncodeError, UnicodeDecodeError, binascii.Error, json.JSONDecodeError) as exc:
raise ClusterSyncCommandError("join bootstrap metadata is invalid") from exc
if not isinstance(bootstrap, dict):
raise ClusterSyncCommandError("join bootstrap metadata must be an object")
authorization = bootstrap.get("authorization")
authorizer_operation = bootstrap.get("authorizer_operation")
if not isinstance(authorization, dict) or not isinstance(authorizer_operation, dict):
raise ClusterSyncCommandError("join bootstrap metadata is incomplete")
if str(authorization.get("signer_id") or "") != remote_node:
raise ClusterSyncCommandError("join authorization signer must match remote node")
_safe_state_call(
lambda: write_operation(
cluster_root,
authorizer_operation,
network_input=True,
)
)
membership = _safe_state_call(
lambda: append_operation(
cluster_root,
"ADD_NODE",
{
"node_id": node_id,
"role": role,
"pbname": pbname,
"membership_authorization": authorization,
},
)
)
_safe_state_call(lambda: rebuild_materialized_state(cluster_root))
return {
"ok": True,
"cluster_id": str(identity["cluster_id"]),
"node_id": str(identity["node_id"]),
"role": str(identity.get("role") or role),
"pbname": str(identity.get("created_from_pbname") or pbname),
"joined_by": remote_node,
"membership_op_id": str((membership or {}).get("op_id") or ""),
}
def _verified_join_authorization(
cluster_root: Path,
remote_node: str,
encoded: str,
) -> dict[str, Any]:
"""Verify one node-specific join grant from the elected active master."""
try:
raw = base64.urlsafe_b64decode(str(encoded).encode("ascii") + b"=" * (-len(str(encoded)) % 4))
authorization = json.loads(raw.decode("utf-8"))
except (UnicodeEncodeError, UnicodeDecodeError, binascii.Error, json.JSONDecodeError) as exc:
raise ClusterSyncCommandError("join authorization token is invalid") from exc
if (
not isinstance(authorization, dict)
or str(authorization.get("kind") or "") != "join"
or str(authorization.get("node_id") or "") != remote_node
):
raise ClusterSyncCommandError("join authorization does not match remote node")
created_at = int(authorization.get("created_at") or 0)
now = int(time.time())
if created_at < now - 900 or created_at > now + 300:
raise ClusterSyncCommandError("join authorization has expired")
materialized = _safe_state_call(lambda: rebuild_materialized_state(cluster_root, write=False))
if str(authorization.get("cluster_id") or "") != str((materialized.get("cluster_nodes") or {}).get("cluster_id") or ""):
raise ClusterSyncCommandError("join authorization belongs to another cluster")
nodes = ((materialized.get("cluster_nodes") or {}).get("nodes") or {})
masters = sorted(
str(node_id)
for node_id, node in nodes.items()
if isinstance(node, dict)
and str(node.get("role") or "") == "master"
and node.get("enabled", True) is not False
and node.get("state_replica", True) is not False
)
signer_id = str(authorization.get("signer_id") or "")
if not masters or signer_id != masters[0]:
raise ClusterSyncCommandError("join authorization signer is not checkpoint coordinator")
public_key = str((nodes.get(signer_id) or {}).get("signing_public_key") or "")
if not public_key:
raise ClusterSyncCommandError("join authorization signer has no trusted key")
try:
verify_operation(authorization, public_key)
except ClusterCredentialError as exc:
raise ClusterSyncCommandError(str(exc)) from exc
return authorization
def _join_blob_allowed(cluster_root: Path, kind: str, blob_hash: str) -> bool:
"""Allow join-time reads only for blobs reachable from the active checkpoint."""
bundle = active_checkpoint_bundle(cluster_root)
if not isinstance(bundle, dict):
return False
checkpoint = bundle.get("checkpoint") if isinstance(bundle.get("checkpoint"), dict) else {}
refs = checkpoint.get("blob_refs") if isinstance(checkpoint.get("blob_refs"), dict) else {}
direct = {str(item) for item in refs.get(kind) or []}
if blob_hash in direct:
return True
if kind != "config":
return False
paths = ClusterPaths.from_root(cluster_root)
for manifest_hash in refs.get("config") or []:
try:
raw = _read_verified_blob(paths.config_blobs, str(manifest_hash), "config blob")
manifest = json.loads(raw.decode("utf-8"))
except (ClusterSyncCommandError, UnicodeDecodeError, json.JSONDecodeError):
continue
files = manifest.get("files") if isinstance(manifest, dict) else None
if not isinstance(files, dict):
continue
for record in files.values():
digest = str((record or {}).get("sha256") or "") if isinstance(record, dict) else ""
if digest and blob_hash == f"sha256:{digest}":
return True
return False
def _parse_command(command_text: str) -> list[str]:
"""Parse and validate SSH_ORIGINAL_COMMAND."""
raw = str(command_text or "").strip()
if not raw:
raise ClusterSyncCommandError("missing command")
if len(raw.encode("utf-8")) > MAX_COMMAND_BYTES:
raise ClusterSyncCommandError("command too large")
try:
tokens = shlex.split(raw)
except ValueError as exc:
raise ClusterSyncCommandError("invalid command syntax") from exc
if not tokens:
raise ClusterSyncCommandError("missing command")
verb = tokens[0]
if verb not in SUPPORTED_VERBS:
raise ClusterSyncCommandError(f"unsupported command: {verb}")
return tokens
def _safe_state_call(callback):
"""Convert cluster-state validation errors into wrapper errors."""
try:
return callback()
except ClusterStateError as exc:
raise ClusterSyncCommandError(str(exc)) from exc
def _read_materialized_snapshot(cluster_root: Path) -> dict[str, Any]:
"""Read the last atomically persisted state without replaying the oplog."""
return _safe_state_call(lambda: read_materialized_state(cluster_root))
def _mailbox_call(callback):
"""Convert mailbox validation errors into restricted-command errors."""
try:
return callback()
except CmcLeaseError as exc:
raise ClusterSyncCommandError(str(exc)) from exc
def _staged_membership_nodes(
cluster_root: Path,
operations: list[dict[str, Any]],
*,
remote_node: str | None = None,
):
"""Stage only membership changes authenticated against prior trust."""
identity = _safe_state_call(lambda: read_local_identity(cluster_root))
return _safe_state_call(
lambda: stage_membership_operations(
cluster_root,
operations,
expected_cluster_id=str(identity["cluster_id"]),
authenticated_remote_node=remote_node,
)
)
def _gap_repair_membership_trust(cluster_root: Path, cluster_id: str):
"""Replay authenticated membership only through each actor's contiguous tail prefix."""
checkpoint = read_active_checkpoint(cluster_root)
if not isinstance(checkpoint, dict) or str(checkpoint.get("cluster_id") or "") != cluster_id:
raise ClusterSyncCommandError("operation gap repair requires the active cluster checkpoint")
trust = _deserialize_membership_trust(checkpoint["membership_trust"])
baseline = checkpoint.get("baseline_vector") if isinstance(checkpoint.get("baseline_vector"), dict) else {}
membership_operations: list[dict[str, Any]] = []
paths = ClusterPaths.from_root(cluster_root)
if paths.oplog.exists():
for actor_dir in sorted(path for path in paths.oplog.iterdir() if path.is_dir()):
actor = str(actor_dir.name)
expected = int(baseline.get(actor, 0)) + 1
for path in sorted(actor_dir.glob("*.json")):
try:
seq = int(path.stem)
except ValueError as exc:
raise ClusterSyncCommandError("operation gap repair found an invalid filename") from exc
if seq <= int(baseline.get(actor, 0)):
continue
if seq != expected:
break
try:
operation = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise ClusterSyncCommandError("operation gap repair found an unreadable operation") from exc
if (
not isinstance(operation, dict)
or str(operation.get("actor") or "") != actor
or int(operation.get("seq") or 0) != seq
):
raise ClusterSyncCommandError("operation gap repair found a path mismatch")
if str(operation.get("op") or "") in MEMBERSHIP_OPS:
membership_operations.append(operation)
expected += 1
membership_operations.sort(
key=lambda item: (
int(item.get("created_at") or 0),
str(item.get("actor") or ""),
int(item.get("seq") or 0),
str(item.get("op_id") or ""),
)
)