dacar 1.2.0__tar.gz → 1.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {dacar-1.2.0 → dacar-1.2.2}/PKG-INFO +1 -1
- {dacar-1.2.0 → dacar-1.2.2}/dacar/cli/__init__.py +12 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/cli/commands.py +169 -1
- {dacar-1.2.0 → dacar-1.2.2}/dacar/delta.py +33 -2
- {dacar-1.2.0 → dacar-1.2.2}/dacar/operation.py +43 -12
- {dacar-1.2.0 → dacar-1.2.2}/dacar/transport/rfed_sync.py +37 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar.egg-info/PKG-INFO +1 -1
- {dacar-1.2.0 → dacar-1.2.2}/dacar.egg-info/SOURCES.txt +2 -0
- {dacar-1.2.0 → dacar-1.2.2}/pyproject.toml +1 -1
- dacar-1.2.2/tests/test_cross_node_sync.py +269 -0
- dacar-1.2.2/tests/test_e2e_rfed_sync.py +217 -0
- {dacar-1.2.0 → dacar-1.2.2}/README.md +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/__init__.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/challenge.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/cli/__main__.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/cli/rns.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/cli/store.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/config.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/crdt.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/engine.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/hlc.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/namespace.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/naming.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/rfed/__init__.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/rfed/_lxmf.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/rfed/blob.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/rfed/channel.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/rfed/client.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/rfed/constants.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/rfed/stamp.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/serialization.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/threshold.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/transport/__init__.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/transport/lxmf_sync.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/transport/rns_challenge.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/transport/rns_identity.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/tuple.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar/verifier.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar.egg-info/dependency_links.txt +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar.egg-info/entry_points.txt +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar.egg-info/requires.txt +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/dacar.egg-info/top_level.txt +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/setup.cfg +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_challenge.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_cli.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_cli_discover_rfed_node.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_cli_ensure_node_identity.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_cli_online.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_cli_publish.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_config.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_crdt.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_delta.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_engine.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_hlc.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_namespace.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_operation.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_rfed_blob_dacar.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_rfed_client_response.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_rfed_publish_link.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_threshold.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_transport_lxmf.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_transport_resolver.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_transport_rfed.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_transport_rns.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_tuple.py +0 -0
- {dacar-1.2.0 → dacar-1.2.2}/tests/test_verifier.py +0 -0
|
@@ -225,6 +225,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
225
225
|
_add_global_flags(p)
|
|
226
226
|
p.set_defaults(func=_cmd_show)
|
|
227
227
|
|
|
228
|
+
# -- validate -----------------------------------------------------------
|
|
229
|
+
p = sub.add_parser("validate", help="validate state integrity and detect corruption")
|
|
230
|
+
p.add_argument("--fix", action="store_true", help="remove corrupted tuples (WARNING: cannot be undone)")
|
|
231
|
+
_add_global_flags(p)
|
|
232
|
+
p.set_defaults(func=_cmd_validate)
|
|
233
|
+
|
|
228
234
|
# -- prune --------------------------------------------------------------
|
|
229
235
|
p = sub.add_parser("prune", help="run §9 Time-Horizon Tombstone Pruning")
|
|
230
236
|
_add_global_flags(p)
|
|
@@ -375,6 +381,12 @@ def _cmd_prune(args):
|
|
|
375
381
|
return cmd_prune(args)
|
|
376
382
|
|
|
377
383
|
|
|
384
|
+
def _cmd_validate(args):
|
|
385
|
+
from dacar.cli.commands import cmd_validate
|
|
386
|
+
args.store = _store_path(args)
|
|
387
|
+
return cmd_validate(args)
|
|
388
|
+
|
|
389
|
+
|
|
378
390
|
def _cmd_alias_add(args):
|
|
379
391
|
from dacar.cli.commands import cmd_alias_add
|
|
380
392
|
args.store = _store_path(args)
|
|
@@ -844,6 +844,160 @@ def cmd_prune(args) -> int:
|
|
|
844
844
|
return EXIT_OK
|
|
845
845
|
|
|
846
846
|
|
|
847
|
+
def cmd_validate(args) -> int:
|
|
848
|
+
"""Validate state integrity and detect corrupted tuples.
|
|
849
|
+
|
|
850
|
+
Corruption can happen if:
|
|
851
|
+
- Old-style batched deltas were accepted before validation was strict
|
|
852
|
+
- State file was manually modified
|
|
853
|
+
- Bug in an earlier version of the code
|
|
854
|
+
|
|
855
|
+
This command checks for:
|
|
856
|
+
- Tuples with suspicious patterns (e.g., many object segments suggesting concatenation)
|
|
857
|
+
- Ledger entries with invalid object strings (comma-separated = ALWAYS invalid)
|
|
858
|
+
- Re-parses state to ensure it can round-trip safely
|
|
859
|
+
"""
|
|
860
|
+
store = Store(args.store, identity_override=args.identity)
|
|
861
|
+
store.ensure()
|
|
862
|
+
config = store.load_config()
|
|
863
|
+
state = store.load_state(config)
|
|
864
|
+
aliases = store.load_aliases()
|
|
865
|
+
ledger = store.load_ledger()
|
|
866
|
+
|
|
867
|
+
suspicious = []
|
|
868
|
+
checked_tuples = 0
|
|
869
|
+
|
|
870
|
+
# First check all ledger entries (corruption is often here)
|
|
871
|
+
for tuple_hash_hex, row in ledger.rows.items():
|
|
872
|
+
object_str = row.get("object")
|
|
873
|
+
if object_str:
|
|
874
|
+
# Check if object string contains commas (ALWAYS invalid - objects use : separator)
|
|
875
|
+
if "," in object_str:
|
|
876
|
+
suspicious.append({
|
|
877
|
+
"source": "ledger",
|
|
878
|
+
"reason": f"INVALID: object contains comma (objects use ':' separator): '{object_str}'",
|
|
879
|
+
"tuple_hash": tuple_hash_hex,
|
|
880
|
+
"has_state_tuple": tuple_hash_hex in state._entries,
|
|
881
|
+
})
|
|
882
|
+
# Check if object string is unusually long (more than 100 chars)
|
|
883
|
+
elif len(object_str) > 100:
|
|
884
|
+
suspicious.append({
|
|
885
|
+
"source": "ledger",
|
|
886
|
+
"reason": f"object unusually long: {len(object_str)} chars",
|
|
887
|
+
"tuple_hash": tuple_hash_hex,
|
|
888
|
+
"object_preview": object_str[:80] + "...",
|
|
889
|
+
"has_state_tuple": tuple_hash_hex in state._entries,
|
|
890
|
+
})
|
|
891
|
+
|
|
892
|
+
# Then check state tuples
|
|
893
|
+
for tup, add_ts, remove_ts in state.iter_entries():
|
|
894
|
+
checked_tuples += 1
|
|
895
|
+
|
|
896
|
+
# Skip if we already flagged this tuple from ledger
|
|
897
|
+
if any(s["tuple_hash"] == tup.hash().hex() for s in suspicious):
|
|
898
|
+
continue
|
|
899
|
+
|
|
900
|
+
# Check ledger for suspicious patterns
|
|
901
|
+
row = ledger.lookup(tup.hash())
|
|
902
|
+
if row:
|
|
903
|
+
# Check if object string contains commas (suggests concatenation)
|
|
904
|
+
if row.get("object") and "," in row["object"]:
|
|
905
|
+
suspicious.append({
|
|
906
|
+
"source": "ledger",
|
|
907
|
+
"reason": f"object contains commas: '{row['object']}'",
|
|
908
|
+
"tuple_hash": tup.hash().hex(),
|
|
909
|
+
"grantee": render_identity(tup.grantee, aliases, full=False),
|
|
910
|
+
"issuer": render_identity(tup.issuer, aliases, full=False),
|
|
911
|
+
"ledger_object": row["object"],
|
|
912
|
+
"segment_count": len(tup.object_hashes),
|
|
913
|
+
})
|
|
914
|
+
continue # Skip further checks for this tuple
|
|
915
|
+
|
|
916
|
+
# Check if object string is unusually long (more than 100 chars)
|
|
917
|
+
if row.get("object") and len(row["object"]) > 100:
|
|
918
|
+
suspicious.append({
|
|
919
|
+
"source": "ledger",
|
|
920
|
+
"reason": f"object unusually long: {len(row['object'])} chars",
|
|
921
|
+
"tuple_hash": tup.hash().hex(),
|
|
922
|
+
"grantee": render_identity(tup.grantee, aliases, full=False),
|
|
923
|
+
"issuer": render_identity(tup.issuer, aliases, full=False),
|
|
924
|
+
"ledger_object": row["object"][:80] + "...",
|
|
925
|
+
})
|
|
926
|
+
|
|
927
|
+
# Check for suspicious patterns in the tuple itself:
|
|
928
|
+
# - Very long object_hashes (many segments) might indicate concatenation
|
|
929
|
+
# - Check if any segment looks like it contains text (ASCII letters)
|
|
930
|
+
|
|
931
|
+
if len(tup.object_hashes) > 10: # More than 10 segments is unusual
|
|
932
|
+
suspicious.append({
|
|
933
|
+
"source": "state",
|
|
934
|
+
"reason": f"unusual number of object segments: {len(tup.object_hashes)}",
|
|
935
|
+
"tuple_hash": tup.hash().hex(),
|
|
936
|
+
"grantee": render_identity(tup.grantee, aliases, full=False),
|
|
937
|
+
"issuer": render_identity(tup.issuer, aliases, full=False),
|
|
938
|
+
"segment_hashes": [h.hex()[:16] for h in tup.object_hashes[:5]], # Show first 5
|
|
939
|
+
})
|
|
940
|
+
|
|
941
|
+
# Check if any segment hash looks like it might contain ASCII text
|
|
942
|
+
# (real hashes should be random-looking)
|
|
943
|
+
for h in tup.object_hashes:
|
|
944
|
+
# Count ASCII printable characters in the hash
|
|
945
|
+
printable = sum(1 for b in h if 32 <= b < 127)
|
|
946
|
+
if printable > 8: # More than half printable is suspicious
|
|
947
|
+
suspicious.append({
|
|
948
|
+
"source": "state",
|
|
949
|
+
"reason": f"suspicious object segment hash (contains {printable}/16 printable ASCII chars)",
|
|
950
|
+
"tuple_hash": tup.hash().hex(),
|
|
951
|
+
"grantee": render_identity(tup.grantee, aliases, full=False),
|
|
952
|
+
"issuer": render_identity(tup.issuer, aliases, full=False),
|
|
953
|
+
"suspicious_hash": h.hex(),
|
|
954
|
+
})
|
|
955
|
+
break
|
|
956
|
+
|
|
957
|
+
_err(f"Checked {checked_tuples} tuple(s) and {len(ledger.rows)} ledger entries")
|
|
958
|
+
|
|
959
|
+
if suspicious:
|
|
960
|
+
_err(f"Found {len(suspicious)} suspicious entry/entries:")
|
|
961
|
+
for i, item in enumerate(suspicious, 1):
|
|
962
|
+
_err(f"\n[{i}] [{item.get('source', 'unknown').upper()}] {item['reason']}")
|
|
963
|
+
_err(f" Tuple hash: {item['tuple_hash']}")
|
|
964
|
+
if 'grantee' in item:
|
|
965
|
+
_err(f" Grantee: {item['grantee']}")
|
|
966
|
+
if 'issuer' in item:
|
|
967
|
+
_err(f" Issuer: {item['issuer']}")
|
|
968
|
+
if 'ledger_object' in item:
|
|
969
|
+
_err(f" Ledger object: {item['ledger_object']}")
|
|
970
|
+
if 'object_preview' in item:
|
|
971
|
+
_err(f" Object preview: {item['object_preview']}")
|
|
972
|
+
if 'segment_count' in item:
|
|
973
|
+
_err(f" Segment count: {item['segment_count']}")
|
|
974
|
+
if 'has_state_tuple' in item:
|
|
975
|
+
_err(f" Has matching state tuple: {item['has_state_tuple']}")
|
|
976
|
+
if 'segment_hashes' in item:
|
|
977
|
+
_err(f" First 5 segment hashes: {item['segment_hashes']}")
|
|
978
|
+
if 'suspicious_hash' in item:
|
|
979
|
+
_err(f" Suspicious hash: {item['suspicious_hash']}")
|
|
980
|
+
|
|
981
|
+
if args.fix:
|
|
982
|
+
_err(f"\n⚠ --fix is not yet implemented")
|
|
983
|
+
_err(f" To manually clean up corrupted state:")
|
|
984
|
+
_err(f" 1. Back up your store directory: cp -r {store.path} {store.path}.backup")
|
|
985
|
+
_err(f" 2. Delete the corrupted files:")
|
|
986
|
+
_err(f" rm {store.state_path}")
|
|
987
|
+
_err(f" rm {store.ledger_path}")
|
|
988
|
+
_err(f" 3. Re-sync from scratch: dacar sync")
|
|
989
|
+
_err(f"\n WARNING: This will remove all locally-issued grants that")
|
|
990
|
+
_err(f" haven't been published to RFed or backed up.")
|
|
991
|
+
return EXIT_FAIL
|
|
992
|
+
else:
|
|
993
|
+
_err(f"\nTo remove corrupted entries, run: dacar validate --fix")
|
|
994
|
+
_err(f"(This will require re-syncing from RFed to restore valid grants)")
|
|
995
|
+
return EXIT_FAIL
|
|
996
|
+
else:
|
|
997
|
+
_err(f"✔ No corruption detected")
|
|
998
|
+
return EXIT_OK
|
|
999
|
+
|
|
1000
|
+
|
|
847
1001
|
# ---------------------------------------------------------------------------
|
|
848
1002
|
# Aliases / ledger
|
|
849
1003
|
# ---------------------------------------------------------------------------
|
|
@@ -1024,6 +1178,7 @@ def run_sync(
|
|
|
1024
1178
|
topic: str,
|
|
1025
1179
|
client: object,
|
|
1026
1180
|
receiver: DeltaReceiver,
|
|
1181
|
+
verbose: bool = False,
|
|
1027
1182
|
) -> int:
|
|
1028
1183
|
"""Pull pending Deltas from the rfed channel and apply via verify-on-ingest.
|
|
1029
1184
|
|
|
@@ -1033,6 +1188,19 @@ def run_sync(
|
|
|
1033
1188
|
Persists the CRDT if any Delta was applied. Returns the count applied.
|
|
1034
1189
|
"""
|
|
1035
1190
|
from dacar.transport.rfed_sync import RfedDeltaSync
|
|
1191
|
+
from dacar.delta import DeltaReceiver as DR
|
|
1192
|
+
|
|
1193
|
+
# If verbose, wrap the receiver to log rejections
|
|
1194
|
+
if verbose:
|
|
1195
|
+
class LoggingReceiver(DR):
|
|
1196
|
+
def __init__(self, state, resolver):
|
|
1197
|
+
super().__init__(state, resolver)
|
|
1198
|
+
|
|
1199
|
+
def apply_payload(self, payload, **kwargs):
|
|
1200
|
+
return super().apply_payload(payload, log_rejections=True, **kwargs)
|
|
1201
|
+
|
|
1202
|
+
receiver = LoggingReceiver(receiver._state, receiver._resolver)
|
|
1203
|
+
|
|
1036
1204
|
sync = RfedDeltaSync(receiver=receiver, client=client, topic=topic)
|
|
1037
1205
|
result = sync.subscribe(node_hash)
|
|
1038
1206
|
if getattr(result, "ok", True) is False:
|
|
@@ -1204,7 +1372,7 @@ def cmd_sync(args) -> int:
|
|
|
1204
1372
|
rx = DeltaReceiver(state, resolver)
|
|
1205
1373
|
|
|
1206
1374
|
client = RFedClient(identity=identity, rns=rns)
|
|
1207
|
-
applied = run_sync(store, state, node_hash, topic, client, rx)
|
|
1375
|
+
applied = run_sync(store, state, node_hash, topic, client, rx, verbose=True)
|
|
1208
1376
|
|
|
1209
1377
|
# Persist the keyring if any announces were observed during the window.
|
|
1210
1378
|
store.save_keyring(keyring)
|
|
@@ -40,6 +40,7 @@ class DeltaReceiver:
|
|
|
40
40
|
*,
|
|
41
41
|
now_ms: Optional[int] = None,
|
|
42
42
|
max_future_ms: Optional[int] = DEFAULT_MAX_FUTURE_MS,
|
|
43
|
+
log_rejections: bool = False,
|
|
43
44
|
) -> bool:
|
|
44
45
|
"""Apply one wire-format Delta.
|
|
45
46
|
|
|
@@ -48,14 +49,44 @@ class DeltaReceiver:
|
|
|
48
49
|
transport callback must never crash on arbitrary bytes. Signature and
|
|
49
50
|
CRDT-level rejection (unknown Issuer, bad sig, stale/future) is
|
|
50
51
|
delegated to :meth:`StateVector.ingest`.
|
|
52
|
+
|
|
53
|
+
If ``log_rejections`` is True, rejections are printed to stderr for
|
|
54
|
+
debugging (useful during sync to identify invalid deltas).
|
|
51
55
|
"""
|
|
52
56
|
try:
|
|
53
57
|
operation = Operation.from_payload(payload)
|
|
54
|
-
except (ValueError, TypeError):
|
|
58
|
+
except (ValueError, TypeError) as e:
|
|
59
|
+
if log_rejections:
|
|
60
|
+
import sys
|
|
61
|
+
print(f"dacar: rejected malformed delta: {e}", file=sys.stderr)
|
|
55
62
|
return False # malformed -> drop silently
|
|
56
|
-
|
|
63
|
+
|
|
64
|
+
# Check if issuer is known before attempting state ingest
|
|
65
|
+
issuer_hash = operation.issuer
|
|
66
|
+
keyset = self._resolver(issuer_hash)
|
|
67
|
+
if keyset is None:
|
|
68
|
+
if log_rejections:
|
|
69
|
+
import sys
|
|
70
|
+
print(f"dacar: rejected delta: unknown issuer {issuer_hash.hex()[:16]}... (not in keyring or RNS)", file=sys.stderr)
|
|
71
|
+
return False
|
|
72
|
+
|
|
73
|
+
result = self._state.ingest(
|
|
57
74
|
operation, self._resolver, now_ms=now_ms, max_future_ms=max_future_ms
|
|
58
75
|
)
|
|
76
|
+
if log_rejections and not result:
|
|
77
|
+
import sys
|
|
78
|
+
# Check if it was a timestamp issue
|
|
79
|
+
from dacar.hlc import unpack
|
|
80
|
+
physical, _ = unpack(operation.hlc)
|
|
81
|
+
now = now_ms if now_ms is not None else physical_now_ms()
|
|
82
|
+
horizon = self._state.deletion_horizon_ms
|
|
83
|
+
|
|
84
|
+
if physical < now - horizon:
|
|
85
|
+
print(f"dacar: rejected delta: timestamp is stale (too old by {(now - physical) / 1000:.0f}s, horizon {horizon / 1000:.0f}s)", file=sys.stderr)
|
|
86
|
+
else:
|
|
87
|
+
# Signature verification failed
|
|
88
|
+
print(f"dacar: rejected delta: signature verification failed for issuer {issuer_hash.hex()[:16]}...", file=sys.stderr)
|
|
89
|
+
return result
|
|
59
90
|
|
|
60
91
|
def apply_payloads(
|
|
61
92
|
self,
|
|
@@ -24,6 +24,28 @@ from dacar import serialization
|
|
|
24
24
|
from dacar.hlc import MAX_HLC
|
|
25
25
|
from dacar.tuple import Tuple
|
|
26
26
|
|
|
27
|
+
|
|
28
|
+
def _expect_bytes(value: Any, length: int, name: str) -> bytes:
|
|
29
|
+
"""Validate that value is exactly `length` bytes and return it.
|
|
30
|
+
|
|
31
|
+
Mirrors JavaScript's expectBytes() helper. Raises ValueError if invalid.
|
|
32
|
+
"""
|
|
33
|
+
if not isinstance(value, (bytes, bytearray)):
|
|
34
|
+
raise ValueError(f"{name} must be a {length}-byte binary blob, got {type(value).__name__}")
|
|
35
|
+
if len(value) != length:
|
|
36
|
+
raise ValueError(f"{name} must be {length} bytes, got {len(value)} bytes")
|
|
37
|
+
return bytes(value)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _expect_bool(value: Any, name: str) -> bool:
|
|
41
|
+
"""Validate that value is a bool and return it.
|
|
42
|
+
|
|
43
|
+
Mirrors JavaScript's expectBool() helper. Raises ValueError if invalid.
|
|
44
|
+
"""
|
|
45
|
+
if not isinstance(value, bool):
|
|
46
|
+
raise ValueError(f"{name} must be a boolean, got {type(value).__name__}")
|
|
47
|
+
return value
|
|
48
|
+
|
|
27
49
|
#: Ed25519 signatures are always 64 bytes.
|
|
28
50
|
SIGNATURE_SIZE = 64
|
|
29
51
|
#: HLC timestamps travel as 64-bit big-endian unsigned integers.
|
|
@@ -204,32 +226,41 @@ class Operation:
|
|
|
204
226
|
if not isinstance(fields, (list, tuple)) or len(fields) != 8:
|
|
205
227
|
raise ValueError("payload must be an 8-element MessagePack array")
|
|
206
228
|
issuer, grantee, action, hlc, relation_hash, object_hashes, wildcard, signatures = fields
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
229
|
+
|
|
230
|
+
# Strict type validation using helpers (mirrors JavaScript implementation)
|
|
231
|
+
issuer = _expect_bytes(issuer, 16, "issuer")
|
|
232
|
+
grantee = _expect_bytes(grantee, 16, "grantee")
|
|
233
|
+
relation_hash = _expect_bytes(relation_hash, 16, "relation_hash")
|
|
234
|
+
wildcard = _expect_bool(wildcard, "wildcard")
|
|
235
|
+
|
|
210
236
|
if action not in (int(Action.GRANT), int(Action.REVOKE)):
|
|
211
237
|
raise ValueError(f"unknown action byte {action!r}")
|
|
212
238
|
if not isinstance(hlc, int) or not 0 <= hlc <= MAX_HLC:
|
|
213
239
|
raise ValueError("hlc must be a uint64 integer")
|
|
214
240
|
if not isinstance(object_hashes, (list, tuple)):
|
|
215
241
|
raise ValueError("object_hashes must be an array of 16-byte blobs")
|
|
216
|
-
for h in object_hashes:
|
|
242
|
+
for i, h in enumerate(object_hashes):
|
|
217
243
|
if not isinstance(h, (bytes, bytearray)) or len(h) != 16:
|
|
218
|
-
raise ValueError(
|
|
219
|
-
|
|
220
|
-
|
|
244
|
+
raise ValueError(
|
|
245
|
+
f"object_hashes[{i}] must be 16 bytes, "
|
|
246
|
+
f"got {type(h).__name__} with length {len(h) if hasattr(h, '__len__') else 'N/A'}"
|
|
247
|
+
)
|
|
221
248
|
if not isinstance(signatures, (list, tuple)) or not signatures:
|
|
222
249
|
raise ValueError("signatures must be a non-empty array of 64-byte blobs")
|
|
223
|
-
for sig in signatures:
|
|
250
|
+
for i, sig in enumerate(signatures):
|
|
224
251
|
if not isinstance(sig, (bytes, bytearray)) or len(sig) != SIGNATURE_SIZE:
|
|
225
|
-
raise ValueError(
|
|
252
|
+
raise ValueError(
|
|
253
|
+
f"signatures[{i}] must be 64 bytes, "
|
|
254
|
+
f"got {type(sig).__name__} with length {len(sig) if hasattr(sig, '__len__') else 'N/A'}"
|
|
255
|
+
)
|
|
256
|
+
|
|
226
257
|
return cls(
|
|
227
258
|
tuple=Tuple(
|
|
228
|
-
relation_hash=
|
|
259
|
+
relation_hash=relation_hash,
|
|
229
260
|
object_hashes=tuple(bytes(h) for h in object_hashes),
|
|
230
261
|
wildcard=wildcard,
|
|
231
|
-
grantee=
|
|
232
|
-
issuer=
|
|
262
|
+
grantee=grantee,
|
|
263
|
+
issuer=issuer,
|
|
233
264
|
),
|
|
234
265
|
action=Action(action),
|
|
235
266
|
hlc=hlc,
|
|
@@ -42,6 +42,9 @@ from __future__ import annotations
|
|
|
42
42
|
|
|
43
43
|
from typing import Any, Optional
|
|
44
44
|
|
|
45
|
+
import RNS
|
|
46
|
+
|
|
47
|
+
import dacar.serialization
|
|
45
48
|
from dacar.delta import DeltaReceiver
|
|
46
49
|
from dacar.naming import RFED_TOPIC
|
|
47
50
|
from dacar.rfed.blob import unwrap_dacar_delta, wrap_dacar_delta
|
|
@@ -159,6 +162,23 @@ class RfedDeltaSync:
|
|
|
159
162
|
decoded = unwrap_dacar_delta(
|
|
160
163
|
inner_blob=inner_blob, channel_identity=channel_identity
|
|
161
164
|
)
|
|
165
|
+
# Remember the sender identity so future RNS recalls succeed without
|
|
166
|
+
# needing an announce. Best-effort: decode must still succeed without it.
|
|
167
|
+
try:
|
|
168
|
+
# Extract issuer_hash (field [0]) from the delta to map identity.
|
|
169
|
+
decoded_delta = dacar.serialization.unpackb(decoded.delta)
|
|
170
|
+
if isinstance(decoded_delta, list) and len(decoded_delta) > 0:
|
|
171
|
+
issuer_hash = decoded_delta[0]
|
|
172
|
+
if isinstance(issuer_hash, (bytes, bytearray)) and len(issuer_hash) == 16:
|
|
173
|
+
RNS.Identity.remember(
|
|
174
|
+
bytes(issuer_hash),
|
|
175
|
+
bytes(issuer_hash),
|
|
176
|
+
decoded.sender_pub,
|
|
177
|
+
None,
|
|
178
|
+
)
|
|
179
|
+
except Exception:
|
|
180
|
+
# Remembering is best-effort; failure doesn't affect correctness.
|
|
181
|
+
pass
|
|
162
182
|
receiver.apply_payload(decoded.delta)
|
|
163
183
|
except Exception:
|
|
164
184
|
# A malformed/forged fanout payload is dropped, not fatal —
|
|
@@ -196,6 +216,23 @@ class RfedDeltaSync:
|
|
|
196
216
|
decoded = unwrap_dacar_delta(
|
|
197
217
|
inner_blob=blob, channel_identity=channel_identity
|
|
198
218
|
)
|
|
219
|
+
# Remember the sender identity so future RNS recalls succeed without
|
|
220
|
+
# needing an announce. Best-effort: decode must still succeed without it.
|
|
221
|
+
try:
|
|
222
|
+
# Extract issuer_hash (field [0]) from the delta to map identity.
|
|
223
|
+
decoded_delta = dacar.serialization.unpackb(decoded.delta)
|
|
224
|
+
if isinstance(decoded_delta, list) and len(decoded_delta) > 0:
|
|
225
|
+
issuer_hash = decoded_delta[0]
|
|
226
|
+
if isinstance(issuer_hash, (bytes, bytearray)) and len(issuer_hash) == 16:
|
|
227
|
+
RNS.Identity.remember(
|
|
228
|
+
bytes(issuer_hash),
|
|
229
|
+
bytes(issuer_hash),
|
|
230
|
+
decoded.sender_pub,
|
|
231
|
+
None,
|
|
232
|
+
)
|
|
233
|
+
except Exception:
|
|
234
|
+
# Remembering is best-effort; failure doesn't affect correctness.
|
|
235
|
+
pass
|
|
199
236
|
if receiver.apply_payload(decoded.delta):
|
|
200
237
|
applied += 1
|
|
201
238
|
except Exception:
|
|
@@ -45,7 +45,9 @@ tests/test_cli_online.py
|
|
|
45
45
|
tests/test_cli_publish.py
|
|
46
46
|
tests/test_config.py
|
|
47
47
|
tests/test_crdt.py
|
|
48
|
+
tests/test_cross_node_sync.py
|
|
48
49
|
tests/test_delta.py
|
|
50
|
+
tests/test_e2e_rfed_sync.py
|
|
49
51
|
tests/test_engine.py
|
|
50
52
|
tests/test_hlc.py
|
|
51
53
|
tests/test_namespace.py
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "dacar"
|
|
7
|
-
version = "1.2.
|
|
7
|
+
version = "1.2.2"
|
|
8
8
|
description = "Python implementation of Dacar, a Decentralized Access Control system for Reticulum"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = { text = "EUPL-1.2" }
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Test cross-version sync: verify deltas from one node work on another
|
|
3
|
+
|
|
4
|
+
Simulates the scenario where:
|
|
5
|
+
1. Node A publishes grants (current version)
|
|
6
|
+
2. Node B syncs (current version)
|
|
7
|
+
3. Deltas should be accepted
|
|
8
|
+
|
|
9
|
+
Tests:
|
|
10
|
+
- Signature verification across nodes
|
|
11
|
+
- Keyring integration with RNS-style resolution
|
|
12
|
+
- Timestamp compatibility
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import unittest
|
|
18
|
+
|
|
19
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
20
|
+
import hashlib
|
|
21
|
+
|
|
22
|
+
from dacar import Action, Keyring, Operation, StateVector, Tuple, DeltaReceiver
|
|
23
|
+
from dacar.hlc import pack, physical_now_ms
|
|
24
|
+
from dacar.namespace import HASH_SIZE, NamespaceHasher, SALT_SIZE
|
|
25
|
+
|
|
26
|
+
HASHER = NamespaceHasher(bytes(range(SALT_SIZE)))
|
|
27
|
+
GRANTEE = bytes([2] * 16)
|
|
28
|
+
HLC = pack(physical_now_ms(), 0)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CrossNodeSyncTest(unittest.TestCase):
|
|
32
|
+
"""Test that deltas from one node can be synced to another."""
|
|
33
|
+
|
|
34
|
+
def test_delta_from_node_a_accepted_by_node_b(self):
|
|
35
|
+
"""Simulate: Node A publishes, Node B syncs.
|
|
36
|
+
|
|
37
|
+
This tests the exact scenario where both nodes use the current code.
|
|
38
|
+
"""
|
|
39
|
+
# Node A's setup
|
|
40
|
+
node_a_priv = Ed25519PrivateKey.generate()
|
|
41
|
+
node_a_hash = hashlib.sha256(node_a_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
42
|
+
|
|
43
|
+
# Node B's setup
|
|
44
|
+
node_b_priv = Ed25519PrivateKey.generate()
|
|
45
|
+
node_b_hash = hashlib.sha256(node_b_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
46
|
+
|
|
47
|
+
# Node A creates and signs a grant
|
|
48
|
+
tup = Tuple.from_plaintext(
|
|
49
|
+
object_id="blog:publish", relation="execute",
|
|
50
|
+
grantee=GRANTEE, issuer=node_a_hash, hasher=HASHER
|
|
51
|
+
)
|
|
52
|
+
op = Operation(tuple=tup, action=Action.GRANT, hlc=HLC).sign(node_a_priv)
|
|
53
|
+
delta = op.to_payload()
|
|
54
|
+
|
|
55
|
+
# Node B's state and keyring
|
|
56
|
+
state_b = StateVector()
|
|
57
|
+
keyring_b = Keyring()
|
|
58
|
+
|
|
59
|
+
# CRITICAL: Node B needs Node A's public key in the keyring
|
|
60
|
+
# This is what RNS identity resolution provides
|
|
61
|
+
keyring_b.register_single(node_a_hash, node_a_priv.public_key().public_bytes_raw())
|
|
62
|
+
|
|
63
|
+
# Node B creates a resolver (simulating RnsIdentityResolver fallback)
|
|
64
|
+
def resolver(issuer_hash: bytes):
|
|
65
|
+
return keyring_b.resolve(issuer_hash)
|
|
66
|
+
|
|
67
|
+
receiver_b = DeltaReceiver(state_b, resolver)
|
|
68
|
+
|
|
69
|
+
# Node B receives and applies the delta
|
|
70
|
+
result = receiver_b.apply_payload(delta, now_ms=HLC >> 16)
|
|
71
|
+
|
|
72
|
+
# Verify it was accepted
|
|
73
|
+
self.assertTrue(result, "Delta from Node A should be accepted by Node B")
|
|
74
|
+
|
|
75
|
+
# Verify state has the grant
|
|
76
|
+
active = list(state_b.active_tuples())
|
|
77
|
+
self.assertEqual(len(active), 1, "Node B should have 1 active grant")
|
|
78
|
+
|
|
79
|
+
# Verify the grant properties
|
|
80
|
+
tup_b = active[0]
|
|
81
|
+
self.assertEqual(tup_b.grantee, GRANTEE, "Grantee should match")
|
|
82
|
+
self.assertEqual(tup_b.issuer, node_a_hash, "Issuer should be Node A")
|
|
83
|
+
|
|
84
|
+
def test_delta_rejected_when_issuer_not_in_keyring(self):
|
|
85
|
+
"""Delta should be rejected when issuer unknown.
|
|
86
|
+
|
|
87
|
+
This simulates the sync failure when Node B doesn't have Node A's key.
|
|
88
|
+
"""
|
|
89
|
+
# Node A's setup
|
|
90
|
+
node_a_priv = Ed25519PrivateKey.generate()
|
|
91
|
+
node_a_hash = hashlib.sha256(node_a_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
92
|
+
|
|
93
|
+
# Node A creates a grant
|
|
94
|
+
tup = Tuple.from_plaintext(
|
|
95
|
+
object_id="blog:publish", relation="execute",
|
|
96
|
+
grantee=GRANTEE, issuer=node_a_hash, hasher=HASHER
|
|
97
|
+
)
|
|
98
|
+
op = Operation(tuple=tup, action=Action.GRANT, hlc=HLC).sign(node_a_priv)
|
|
99
|
+
delta = op.to_payload()
|
|
100
|
+
|
|
101
|
+
# Node B's state with EMPTY keyring (no issuer keys)
|
|
102
|
+
state_b = StateVector()
|
|
103
|
+
keyring_b = Keyring() # Empty!
|
|
104
|
+
receiver_b = DeltaReceiver(state_b, keyring_b)
|
|
105
|
+
|
|
106
|
+
# Node B tries to apply the delta
|
|
107
|
+
import sys
|
|
108
|
+
from io import StringIO
|
|
109
|
+
old_stderr = sys.stderr
|
|
110
|
+
sys.stderr = StringIO()
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
result = receiver_b.apply_payload(delta, log_rejections=True, now_ms=HLC >> 16)
|
|
114
|
+
stderr_output = sys.stderr.getvalue()
|
|
115
|
+
finally:
|
|
116
|
+
sys.stderr = old_stderr
|
|
117
|
+
|
|
118
|
+
# Verify it was rejected
|
|
119
|
+
self.assertFalse(result, "Delta should be rejected (unknown issuer)")
|
|
120
|
+
|
|
121
|
+
# Verify the rejection was logged
|
|
122
|
+
self.assertIn("rejected delta: unknown issuer", stderr_output,
|
|
123
|
+
"Should log 'unknown issuer'")
|
|
124
|
+
self.assertIn(node_a_hash.hex()[:16], stderr_output,
|
|
125
|
+
"Should include the issuer hash")
|
|
126
|
+
|
|
127
|
+
# Verify state is empty
|
|
128
|
+
self.assertEqual(len(list(state_b.active_tuples())), 0, "State should be empty")
|
|
129
|
+
|
|
130
|
+
def test_multiple_deltas_from_same_issuer_all_accepted(self):
|
|
131
|
+
"""Multiple deltas from the same issuer should all be accepted.
|
|
132
|
+
|
|
133
|
+
Simulates Node A publishing 3 grants, Node B syncing all at once.
|
|
134
|
+
"""
|
|
135
|
+
# Node A's setup
|
|
136
|
+
node_a_priv = Ed25519PrivateKey.generate()
|
|
137
|
+
node_a_hash = hashlib.sha256(node_a_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
138
|
+
|
|
139
|
+
# Node A creates 3 grants
|
|
140
|
+
objects = ["blog:publish", "grib:request", "sys:command"]
|
|
141
|
+
deltas = []
|
|
142
|
+
for i, obj_id in enumerate(objects):
|
|
143
|
+
tup = Tuple.from_plaintext(
|
|
144
|
+
object_id=obj_id, relation="execute",
|
|
145
|
+
grantee=GRANTEE, issuer=node_a_hash, hasher=HASHER
|
|
146
|
+
)
|
|
147
|
+
op = Operation(tuple=tup, action=Action.GRANT, hlc=pack(HLC >> 16, i)).sign(node_a_priv)
|
|
148
|
+
deltas.append(op.to_payload())
|
|
149
|
+
|
|
150
|
+
# Node B's setup with Node A's key in keyring
|
|
151
|
+
state_b = StateVector()
|
|
152
|
+
keyring_b = Keyring().register_single(node_a_hash, node_a_priv.public_key().public_bytes_raw())
|
|
153
|
+
receiver_b = DeltaReceiver(state_b, keyring_b)
|
|
154
|
+
|
|
155
|
+
# Node B receives all deltas
|
|
156
|
+
applied = 0
|
|
157
|
+
for delta in deltas:
|
|
158
|
+
if receiver_b.apply_payload(delta, now_ms=HLC >> 16):
|
|
159
|
+
applied += 1
|
|
160
|
+
|
|
161
|
+
# Verify all 3 were accepted
|
|
162
|
+
self.assertEqual(applied, 3, "All 3 deltas should be accepted")
|
|
163
|
+
|
|
164
|
+
# Verify state has 3 grants
|
|
165
|
+
active = list(state_b.active_tuples())
|
|
166
|
+
self.assertEqual(len(active), 3, "Node B should have 3 active grants")
|
|
167
|
+
|
|
168
|
+
# Verify each grant has a different object
|
|
169
|
+
object_hashes_seen = set()
|
|
170
|
+
for tup in active:
|
|
171
|
+
object_hashes_seen.add(tup.object_hashes)
|
|
172
|
+
self.assertEqual(len(object_hashes_seen), 3, "Each grant should have different object hashes")
|
|
173
|
+
|
|
174
|
+
def test_wrong_signature_rejected(self):
|
|
175
|
+
"""Delta with wrong signature should be rejected.
|
|
176
|
+
|
|
177
|
+
Simulates a malicious or corrupted delta claiming to be from Node A
|
|
178
|
+
but signed by someone else.
|
|
179
|
+
"""
|
|
180
|
+
# Node A's identity (claimed issuer)
|
|
181
|
+
node_a_priv = Ed25519PrivateKey.generate()
|
|
182
|
+
node_a_hash = hashlib.sha256(node_a_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
183
|
+
|
|
184
|
+
# Attacker's key (actually signs)
|
|
185
|
+
attacker_priv = Ed25519PrivateKey.generate()
|
|
186
|
+
|
|
187
|
+
# Create a grant claiming to be from Node A but signed by attacker
|
|
188
|
+
tup = Tuple.from_plaintext(
|
|
189
|
+
object_id="blog:publish", relation="execute",
|
|
190
|
+
grantee=GRANTEE, issuer=node_a_hash, hasher=HASHER
|
|
191
|
+
)
|
|
192
|
+
op = Operation(tuple=tup, action=Action.GRANT, hlc=HLC).sign(attacker_priv)
|
|
193
|
+
delta = op.to_payload()
|
|
194
|
+
|
|
195
|
+
# Node B's setup with Node A's real key
|
|
196
|
+
state_b = StateVector()
|
|
197
|
+
keyring_b = Keyring().register_single(node_a_hash, node_a_priv.public_key().public_bytes_raw())
|
|
198
|
+
receiver_b = DeltaReceiver(state_b, keyring_b)
|
|
199
|
+
|
|
200
|
+
# Node B tries to apply the delta
|
|
201
|
+
import sys
|
|
202
|
+
from io import StringIO
|
|
203
|
+
old_stderr = sys.stderr
|
|
204
|
+
sys.stderr = StringIO()
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
result = receiver_b.apply_payload(delta, log_rejections=True, now_ms=HLC >> 16)
|
|
208
|
+
stderr_output = sys.stderr.getvalue()
|
|
209
|
+
finally:
|
|
210
|
+
sys.stderr = old_stderr
|
|
211
|
+
|
|
212
|
+
# Verify it was rejected
|
|
213
|
+
self.assertFalse(result, "Delta with wrong signature should be rejected")
|
|
214
|
+
|
|
215
|
+
# Verify the rejection was logged
|
|
216
|
+
self.assertIn("rejected delta: signature verification failed", stderr_output,
|
|
217
|
+
"Should log signature verification failure")
|
|
218
|
+
|
|
219
|
+
# Verify state is empty
|
|
220
|
+
self.assertEqual(len(list(state_b.active_tuples())), 0, "State should be empty")
|
|
221
|
+
|
|
222
|
+
def test_stale_timestamp_rejected(self):
|
|
223
|
+
"""Delta with timestamp older than deletion horizon is rejected.
|
|
224
|
+
|
|
225
|
+
This is the §9 intake rejection mechanism.
|
|
226
|
+
"""
|
|
227
|
+
node_a_priv = Ed25519PrivateKey.generate()
|
|
228
|
+
node_a_hash = hashlib.sha256(node_a_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
229
|
+
|
|
230
|
+
# Create a grant with a timestamp 200 days in the past
|
|
231
|
+
old_hlc = pack(physical_now_ms() - (200 * 24 * 3600 * 1000), 0)
|
|
232
|
+
|
|
233
|
+
tup = Tuple.from_plaintext(
|
|
234
|
+
object_id="blog:publish", relation="execute",
|
|
235
|
+
grantee=GRANTEE, issuer=node_a_hash, hasher=HASHER
|
|
236
|
+
)
|
|
237
|
+
op = Operation(tuple=tup, action=Action.GRANT, hlc=old_hlc).sign(node_a_priv)
|
|
238
|
+
delta = op.to_payload()
|
|
239
|
+
|
|
240
|
+
# Node B's setup
|
|
241
|
+
state_b = StateVector() # Default horizon is 180 days
|
|
242
|
+
keyring_b = Keyring().register_single(node_a_hash, node_a_priv.public_key().public_bytes_raw())
|
|
243
|
+
receiver_b = DeltaReceiver(state_b, keyring_b)
|
|
244
|
+
|
|
245
|
+
# Node B tries to apply the old delta
|
|
246
|
+
import sys
|
|
247
|
+
from io import StringIO
|
|
248
|
+
old_stderr = sys.stderr
|
|
249
|
+
sys.stderr = StringIO()
|
|
250
|
+
|
|
251
|
+
try:
|
|
252
|
+
result = receiver_b.apply_payload(delta, log_rejections=True, now_ms=physical_now_ms())
|
|
253
|
+
stderr_output = sys.stderr.getvalue()
|
|
254
|
+
finally:
|
|
255
|
+
sys.stderr = old_stderr
|
|
256
|
+
|
|
257
|
+
# Verify it was rejected
|
|
258
|
+
self.assertFalse(result, "Stale delta should be rejected")
|
|
259
|
+
|
|
260
|
+
# Verify the rejection reason mentions stale timestamp
|
|
261
|
+
self.assertIn("rejected delta: timestamp is stale", stderr_output,
|
|
262
|
+
"Should log timestamp is stale")
|
|
263
|
+
|
|
264
|
+
# Verify state is empty
|
|
265
|
+
self.assertEqual(len(list(state_b.active_tuples())), 0, "State should be empty")
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
if __name__ == "__main__":
|
|
269
|
+
unittest.main(verbosity=2)
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""
|
|
2
|
+
End-to-end test: RFed sync handles mixed valid/invalid deltas
|
|
3
|
+
|
|
4
|
+
Tests the scenario where RFed storage contains both old-style malformed
|
|
5
|
+
deltas (batched operations) and valid deltas. Verifies that:
|
|
6
|
+
|
|
7
|
+
1. Valid deltas are correctly applied to state
|
|
8
|
+
2. Invalid deltas are rejected (don't corrupt state)
|
|
9
|
+
3. Sync continues processing after rejections
|
|
10
|
+
4. Final state contains only valid grants
|
|
11
|
+
|
|
12
|
+
This simulates the real-world scenario where RFed may have accumulated
|
|
13
|
+
old-style payloads over time.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import unittest
|
|
19
|
+
|
|
20
|
+
from dacar import Action, DeltaReceiver, Keyring, Operation, StateVector, Tuple
|
|
21
|
+
from dacar.hlc import pack, physical_now_ms
|
|
22
|
+
from dacar.namespace import HASH_SIZE, NamespaceHasher, SALT_SIZE
|
|
23
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
24
|
+
from dacar import serialization
|
|
25
|
+
import hashlib
|
|
26
|
+
|
|
27
|
+
HASHER = NamespaceHasher(bytes(range(SALT_SIZE)))
|
|
28
|
+
GRANTEE = bytes([2] * 16) # lille-oe
|
|
29
|
+
HLC = pack(physical_now_ms(), 0)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _op(object_id, issuer_priv, offset=0):
|
|
33
|
+
"""Create a signed operation for testing."""
|
|
34
|
+
issuer_hash = hashlib.sha256(issuer_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
35
|
+
t = Tuple.from_plaintext(
|
|
36
|
+
object_id=object_id, relation="execute", grantee=GRANTEE,
|
|
37
|
+
issuer=issuer_hash, hasher=HASHER,
|
|
38
|
+
)
|
|
39
|
+
base = Operation(tuple=t, action=Action.GRANT, hlc=pack(HLC >> 16, offset))
|
|
40
|
+
return base.sign(issuer_priv)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class E2EMixedValidInvalidDeltasTest(unittest.TestCase):
|
|
44
|
+
"""End-to-end test: sync with mixed valid/invalid deltas."""
|
|
45
|
+
|
|
46
|
+
def test_valid_deltas_applied_invalid_rejected(self):
|
|
47
|
+
"""DeltaReceiver should apply valid deltas and reject invalid ones.
|
|
48
|
+
|
|
49
|
+
This tests the exact scenario from the bug report:
|
|
50
|
+
- Admin machine issued 3 valid grants
|
|
51
|
+
- RFed storage also contained old-style malformed payloads
|
|
52
|
+
- Client sync should result in clean state with only the 3 valid grants
|
|
53
|
+
"""
|
|
54
|
+
# Setup identities
|
|
55
|
+
admin_priv = Ed25519PrivateKey.generate()
|
|
56
|
+
admin_hash = hashlib.sha256(admin_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
57
|
+
|
|
58
|
+
# Create 3 valid operations (the grants from admin machine)
|
|
59
|
+
valid_deltas = [
|
|
60
|
+
_op("blog:publish", admin_priv, 0).to_payload(),
|
|
61
|
+
_op("grib:request", admin_priv, 1).to_payload(),
|
|
62
|
+
_op("sys:command", admin_priv, 2).to_payload(),
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
# Create invalid payloads (old-style batched operations)
|
|
66
|
+
invalid_deltas = [
|
|
67
|
+
# Batch of operations: [[op1_fields...], [op2_fields...]]
|
|
68
|
+
serialization.packb([
|
|
69
|
+
[b"a"*16, b"b"*16, 1, 12345, b"c"*16, [b"d"*16], False, [b"e"*64]],
|
|
70
|
+
[b"f"*16, b"g"*16, 1, 12346, b"h"*16, [b"i"*16], False, [b"j"*64]],
|
|
71
|
+
]),
|
|
72
|
+
# Wrong field types: issuer as array instead of bytes
|
|
73
|
+
serialization.packb([[1]*16, b"b"*16, 1, 12347, b"c"*16, [b"d"*16], False, [b"e"*64]]),
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
# Setup state and keyring
|
|
77
|
+
state = StateVector()
|
|
78
|
+
keyring = Keyring().register_single(admin_hash, admin_priv.public_key().public_bytes_raw())
|
|
79
|
+
receiver = DeltaReceiver(state, keyring)
|
|
80
|
+
|
|
81
|
+
# Simulate sync: process mixed valid/invalid deltas
|
|
82
|
+
applied = 0
|
|
83
|
+
rejected = 0
|
|
84
|
+
|
|
85
|
+
for delta in invalid_deltas + valid_deltas: # Process invalid first
|
|
86
|
+
result = receiver.apply_payload(delta, now_ms=HLC >> 16)
|
|
87
|
+
if result:
|
|
88
|
+
applied += 1
|
|
89
|
+
else:
|
|
90
|
+
rejected += 1
|
|
91
|
+
|
|
92
|
+
# Verify results
|
|
93
|
+
self.assertEqual(applied, 3, f"Should apply 3 valid deltas, got {applied}")
|
|
94
|
+
self.assertEqual(rejected, 2, f"Should reject 2 invalid deltas, got {rejected}")
|
|
95
|
+
|
|
96
|
+
# Verify state has exactly 3 active grants
|
|
97
|
+
active_tuples = list(state.active_tuples())
|
|
98
|
+
self.assertEqual(len(active_tuples), 3, f"Should have 3 active tuples, got {len(active_tuples)}")
|
|
99
|
+
|
|
100
|
+
# Verify each grant has correct properties
|
|
101
|
+
for tup in active_tuples:
|
|
102
|
+
self.assertEqual(tup.grantee, GRANTEE, "Grantee should match lille-oe")
|
|
103
|
+
self.assertEqual(tup.issuer, admin_hash, "Issuer should match admin")
|
|
104
|
+
self.assertEqual(tup.relation_hash, HASHER.hash_relation("execute"),
|
|
105
|
+
"Relation should be 'execute'")
|
|
106
|
+
|
|
107
|
+
# Object should be one of the three we created
|
|
108
|
+
obj_ids = ["blog:publish", "grib:request", "sys:command"]
|
|
109
|
+
matches = 0
|
|
110
|
+
for obj_id in obj_ids:
|
|
111
|
+
obj_hashes, wildcard = HASHER.hash_object(obj_id)
|
|
112
|
+
if tup.object_hashes == obj_hashes and tup.wildcard == wildcard:
|
|
113
|
+
matches += 1
|
|
114
|
+
self.assertEqual(matches, 1, "Each tuple should match exactly one object ID")
|
|
115
|
+
|
|
116
|
+
def test_continues_after_rejection(self):
|
|
117
|
+
"""Processing should continue after encountering invalid deltas."""
|
|
118
|
+
admin_priv = Ed25519PrivateKey.generate()
|
|
119
|
+
admin_hash = hashlib.sha256(admin_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
120
|
+
|
|
121
|
+
# Create valid operations
|
|
122
|
+
valid_deltas = [
|
|
123
|
+
_op("blog:publish", admin_priv, 0).to_payload(),
|
|
124
|
+
_op("grib:request", admin_priv, 1).to_payload(),
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
# Invalid payload at the start
|
|
128
|
+
invalid_deltas = [
|
|
129
|
+
serialization.packb([[1]*16, b"b"*16, 1, 12345, b"c"*16, [b"d"*16], False, [b"e"*64]]),
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
state = StateVector()
|
|
133
|
+
keyring = Keyring().register_single(admin_hash, admin_priv.public_key().public_bytes_raw())
|
|
134
|
+
receiver = DeltaReceiver(state, keyring)
|
|
135
|
+
|
|
136
|
+
# Process invalid first, then valid
|
|
137
|
+
applied = 0
|
|
138
|
+
for delta in invalid_deltas + valid_deltas:
|
|
139
|
+
if receiver.apply_payload(delta, now_ms=HLC >> 16):
|
|
140
|
+
applied += 1
|
|
141
|
+
|
|
142
|
+
# Should still apply both valid deltas despite the invalid one
|
|
143
|
+
self.assertEqual(applied, 2, f"Should apply 2 valid deltas, got {applied}")
|
|
144
|
+
self.assertEqual(len(list(state.active_tuples())), 2, "Should have 2 active tuples")
|
|
145
|
+
|
|
146
|
+
def test_logging_with_rejections(self):
|
|
147
|
+
"""Verify that apply_payload with log_rejections=True logs rejections."""
|
|
148
|
+
admin_priv = Ed25519PrivateKey.generate()
|
|
149
|
+
admin_hash = hashlib.sha256(admin_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
150
|
+
|
|
151
|
+
# Create a valid and an invalid operation
|
|
152
|
+
valid_delta = _op("blog:publish", admin_priv).to_payload()
|
|
153
|
+
invalid_delta = serialization.packb([[1]*16, b"b"*16, 1, 12345, b"c"*16, [b"d"*16], False, [b"e"*64]])
|
|
154
|
+
|
|
155
|
+
state = StateVector()
|
|
156
|
+
keyring = Keyring().register_single(admin_hash, admin_priv.public_key().public_bytes_raw())
|
|
157
|
+
receiver = DeltaReceiver(state, keyring)
|
|
158
|
+
|
|
159
|
+
# Apply invalid delta with logging
|
|
160
|
+
import sys
|
|
161
|
+
from io import StringIO
|
|
162
|
+
old_stderr = sys.stderr
|
|
163
|
+
sys.stderr = StringIO()
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
result = receiver.apply_payload(invalid_delta, log_rejections=True, now_ms=HLC >> 16)
|
|
167
|
+
stderr_output = sys.stderr.getvalue()
|
|
168
|
+
finally:
|
|
169
|
+
sys.stderr = old_stderr
|
|
170
|
+
|
|
171
|
+
# Should be rejected and logged
|
|
172
|
+
self.assertFalse(result, "Invalid delta should be rejected")
|
|
173
|
+
self.assertIn("rejected malformed delta", stderr_output,
|
|
174
|
+
"Should log rejection to stderr")
|
|
175
|
+
self.assertIn("issuer must be a 16-byte binary blob", stderr_output,
|
|
176
|
+
"Should include specific error message")
|
|
177
|
+
|
|
178
|
+
# Valid delta should succeed without logging
|
|
179
|
+
old_stderr = sys.stderr
|
|
180
|
+
sys.stderr = StringIO()
|
|
181
|
+
|
|
182
|
+
try:
|
|
183
|
+
result2 = receiver.apply_payload(valid_delta, log_rejections=True, now_ms=HLC >> 16)
|
|
184
|
+
stderr_output2 = sys.stderr.getvalue()
|
|
185
|
+
finally:
|
|
186
|
+
sys.stderr = old_stderr
|
|
187
|
+
|
|
188
|
+
self.assertTrue(result2, "Valid delta should be applied")
|
|
189
|
+
self.assertEqual(stderr_output2, "", "Valid delta should not log anything")
|
|
190
|
+
|
|
191
|
+
def test_batch_payloads_with_invalid_elements(self):
|
|
192
|
+
"""DeltaReceiver.apply_payloads should handle batch with invalid elements."""
|
|
193
|
+
admin_priv = Ed25519PrivateKey.generate()
|
|
194
|
+
admin_hash = hashlib.sha256(admin_priv.public_key().public_bytes_raw()).digest()[:HASH_SIZE]
|
|
195
|
+
|
|
196
|
+
valid_deltas = [
|
|
197
|
+
_op("blog:publish", admin_priv, 0).to_payload(),
|
|
198
|
+
_op("grib:request", admin_priv, 1).to_payload(),
|
|
199
|
+
]
|
|
200
|
+
invalid_delta = serialization.packb([[1]*16, b"b"*16, 1, 12345, b"c"*16, [b"d"*16], False, [b"e"*64]])
|
|
201
|
+
|
|
202
|
+
# Create batch: [valid1, invalid, valid2]
|
|
203
|
+
batch_payloads = DeltaReceiver.pack_payloads([valid_deltas[0], invalid_delta, valid_deltas[1]])
|
|
204
|
+
|
|
205
|
+
state = StateVector()
|
|
206
|
+
keyring = Keyring().register_single(admin_hash, admin_priv.public_key().public_bytes_raw())
|
|
207
|
+
receiver = DeltaReceiver(state, keyring)
|
|
208
|
+
|
|
209
|
+
# Apply batch - should only apply the valid ones
|
|
210
|
+
applied = receiver.apply_payloads(batch_payloads, now_ms=HLC >> 16)
|
|
211
|
+
|
|
212
|
+
self.assertEqual(applied, 2, f"Should apply 2 valid deltas in batch, got {applied}")
|
|
213
|
+
self.assertEqual(len(list(state.active_tuples())), 2, "Should have 2 active tuples")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
if __name__ == "__main__":
|
|
217
|
+
unittest.main(verbosity=2)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|