dacar 1.0.0__py3-none-any.whl
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/__init__.py +113 -0
- dacar/challenge.py +340 -0
- dacar/cli/__init__.py +346 -0
- dacar/cli/__main__.py +8 -0
- dacar/cli/commands.py +772 -0
- dacar/cli/store.py +662 -0
- dacar/config.py +139 -0
- dacar/crdt.py +330 -0
- dacar/delta.py +114 -0
- dacar/engine.py +161 -0
- dacar/hlc.py +81 -0
- dacar/namespace.py +125 -0
- dacar/naming.py +38 -0
- dacar/operation.py +237 -0
- dacar/serialization.py +27 -0
- dacar/threshold.py +75 -0
- dacar/transport/__init__.py +43 -0
- dacar/transport/lxmf_sync.py +156 -0
- dacar/transport/rns_challenge.py +206 -0
- dacar/transport/rns_identity.py +63 -0
- dacar/tuple.py +118 -0
- dacar/verifier.py +131 -0
- dacar-1.0.0.dist-info/METADATA +228 -0
- dacar-1.0.0.dist-info/RECORD +27 -0
- dacar-1.0.0.dist-info/WHEEL +5 -0
- dacar-1.0.0.dist-info/entry_points.txt +2 -0
- dacar-1.0.0.dist-info/top_level.txt +1 -0
dacar/__init__.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Dacar: Decentralized Access Control for Reticulum.
|
|
2
|
+
|
|
3
|
+
Python implementation of Dacar, a Decentralized Access Control system for
|
|
4
|
+
Reticulum: a tuple-based, offline-first authorization policy plane built on an
|
|
5
|
+
LWW-Element-Set CRDT, designed for delay-tolerant mesh networks.
|
|
6
|
+
|
|
7
|
+
Object and relation labels are stored only as salted HMAC-SHA256 hashes
|
|
8
|
+
(§3.3 Namespace Label Privacy), Threshold Groups may act as N-of-M Issuers
|
|
9
|
+
(§4.1), and the state is bounded by Time-Horizon Tombstone Pruning (§9).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from dacar.hlc import Clock, MAX_HLC, MAX_LOGICAL, MAX_PHYSICAL, pack, unpack
|
|
13
|
+
from dacar.namespace import (
|
|
14
|
+
DEFAULT_SALT,
|
|
15
|
+
HASH_SIZE,
|
|
16
|
+
MAX_LEGACY_SALTS,
|
|
17
|
+
SALT_SIZE,
|
|
18
|
+
DELIMITER,
|
|
19
|
+
WILDCARD,
|
|
20
|
+
NamespaceHasher,
|
|
21
|
+
covers,
|
|
22
|
+
split,
|
|
23
|
+
)
|
|
24
|
+
from dacar.tuple import MAX_SEGMENTS, Tuple
|
|
25
|
+
from dacar.threshold import ThresholdGroup, group_id
|
|
26
|
+
from dacar.operation import HLC_BYTES, SIGNATURE_SIZE, Action, Operation
|
|
27
|
+
from dacar.verifier import IssuerKeyset, KeyResolver, Keyring, verify_operation
|
|
28
|
+
from dacar.config import Config, DEFAULT_DELETION_HORIZON_DAYS, NullPrivacySaltWarning
|
|
29
|
+
from dacar.crdt import StateVector, TrustedLocalOnlyWarning
|
|
30
|
+
from dacar.delta import DeltaReceiver
|
|
31
|
+
from dacar.naming import (
|
|
32
|
+
APP_NAME,
|
|
33
|
+
CHALLENGE_ASPECTS,
|
|
34
|
+
CHALLENGE_DESTINATION,
|
|
35
|
+
RFED_TOPIC,
|
|
36
|
+
LXMF_DELIVERY_TITLE,
|
|
37
|
+
)
|
|
38
|
+
from dacar.engine import ADMIN_RELATION, DEFAULT_MAX_DEPTH, DEFAULT_MAX_VISITED, Engine
|
|
39
|
+
from dacar.challenge import (
|
|
40
|
+
NONCE_SIZE,
|
|
41
|
+
AuthoritativeServer,
|
|
42
|
+
Challenge,
|
|
43
|
+
ChallengeClient,
|
|
44
|
+
Receipt,
|
|
45
|
+
Transport,
|
|
46
|
+
Verdict,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
# HLC (§5.1)
|
|
51
|
+
"Clock",
|
|
52
|
+
"MAX_HLC",
|
|
53
|
+
"MAX_LOGICAL",
|
|
54
|
+
"MAX_PHYSICAL",
|
|
55
|
+
"pack",
|
|
56
|
+
"unpack",
|
|
57
|
+
# Namespace Label Privacy (§3.3)
|
|
58
|
+
"DEFAULT_SALT",
|
|
59
|
+
"HASH_SIZE",
|
|
60
|
+
"MAX_LEGACY_SALTS",
|
|
61
|
+
"SALT_SIZE",
|
|
62
|
+
"DELIMITER",
|
|
63
|
+
"WILDCARD",
|
|
64
|
+
"NamespaceHasher",
|
|
65
|
+
"covers",
|
|
66
|
+
"split",
|
|
67
|
+
# Tuple (§3.1, §6.1)
|
|
68
|
+
"MAX_SEGMENTS",
|
|
69
|
+
"Tuple",
|
|
70
|
+
# Threshold Groups (§4.1)
|
|
71
|
+
"ThresholdGroup",
|
|
72
|
+
"group_id",
|
|
73
|
+
# Operations (§5.2, §5.3)
|
|
74
|
+
"HLC_BYTES",
|
|
75
|
+
"SIGNATURE_SIZE",
|
|
76
|
+
"Action",
|
|
77
|
+
"Operation",
|
|
78
|
+
# Verify-on-ingest (§11.2.4)
|
|
79
|
+
"IssuerKeyset",
|
|
80
|
+
"KeyResolver",
|
|
81
|
+
"Keyring",
|
|
82
|
+
"verify_operation",
|
|
83
|
+
# Transport-agnostic Delta receive boundary (§11)
|
|
84
|
+
"DeltaReceiver",
|
|
85
|
+
# RNS naming conventions (§8, §11)
|
|
86
|
+
"APP_NAME",
|
|
87
|
+
"CHALLENGE_ASPECTS",
|
|
88
|
+
"CHALLENGE_DESTINATION",
|
|
89
|
+
"RFED_TOPIC",
|
|
90
|
+
"LXMF_DELIVERY_TITLE",
|
|
91
|
+
# Config (§4, §10) + state (§6)
|
|
92
|
+
"Config",
|
|
93
|
+
"DEFAULT_DELETION_HORIZON_DAYS",
|
|
94
|
+
"NullPrivacySaltWarning",
|
|
95
|
+
"StateVector",
|
|
96
|
+
"TrustedLocalOnlyWarning",
|
|
97
|
+
# Engine (§7)
|
|
98
|
+
"ADMIN_RELATION",
|
|
99
|
+
"DEFAULT_MAX_DEPTH",
|
|
100
|
+
"DEFAULT_MAX_VISITED",
|
|
101
|
+
"Engine",
|
|
102
|
+
# Challenge (§8)
|
|
103
|
+
"NONCE_SIZE",
|
|
104
|
+
"AuthoritativeServer",
|
|
105
|
+
"Challenge",
|
|
106
|
+
"ChallengeClient",
|
|
107
|
+
"Receipt",
|
|
108
|
+
"Transport",
|
|
109
|
+
"Verdict",
|
|
110
|
+
]
|
|
111
|
+
|
|
112
|
+
__version__ = "1.0.0"
|
|
113
|
+
__spec_version__ = "1.0-RC7"
|
dacar/challenge.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Strict Consistency Challenge / Freshness Receipts (§8).
|
|
2
|
+
|
|
3
|
+
For destructive operations, eventual consistency is dangerous. A node performs
|
|
4
|
+
a local pre-check, then challenges a configured Authoritative Identity over an
|
|
5
|
+
RNS link (App Name ``dacar``, Aspects ``auth``, ``v1``) for a signed verdict
|
|
6
|
+
evaluated against the server's absolute-latest CRDT state.
|
|
7
|
+
|
|
8
|
+
To preserve Namespace Label Privacy (§3.3), the Challenge payload carries only
|
|
9
|
+
*hashed* hypotheses — never plaintext. The client hashes the request across its
|
|
10
|
+
Primary Salt and all Legacy Salts (§10); the server matches each by its
|
|
11
|
+
``salt_id_tag`` and evaluates directly in hash space.
|
|
12
|
+
|
|
13
|
+
Canonical challenge wire format (§8.3)::
|
|
14
|
+
|
|
15
|
+
[ nonce(32),
|
|
16
|
+
[ [ salt_id_tag(16), grantee_hash(16), allow_relation_hash(16),
|
|
17
|
+
deny_relation_hash(16), [object_segment_hashes] ],
|
|
18
|
+
... ] ]
|
|
19
|
+
|
|
20
|
+
Each entry is fully self-contained for one salt and carries *both* the allow and
|
|
21
|
+
deny relation hashes so the Authority can apply the deny-beats-allow rule
|
|
22
|
+
(§7.3) without recovering plaintext. Requests are exact, so the §3.3 wildcard
|
|
23
|
+
flag is not set on an entry; the array length conveys the segment count.
|
|
24
|
+
|
|
25
|
+
The RNS transport is abstracted behind a ``transport`` callable
|
|
26
|
+
(``challenge_payload -> receipt_payload | None``), so the cryptographic and
|
|
27
|
+
verdict logic is fully testable without a live network. A transport that returns
|
|
28
|
+
``None`` or raises is a partition -> immediately DENIED (§8).
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import os
|
|
34
|
+
from dataclasses import dataclass, replace
|
|
35
|
+
from enum import IntEnum
|
|
36
|
+
from typing import Any, Callable, List, Optional, Sequence, Tuple as _Tuple
|
|
37
|
+
|
|
38
|
+
from cryptography.exceptions import InvalidSignature
|
|
39
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
40
|
+
Ed25519PrivateKey,
|
|
41
|
+
Ed25519PublicKey,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
from dacar import serialization
|
|
45
|
+
from dacar.config import Config
|
|
46
|
+
from dacar.crdt import StateVector
|
|
47
|
+
from dacar.engine import Engine, Hypothesis
|
|
48
|
+
from dacar.hlc import MAX_HLC, Clock
|
|
49
|
+
from dacar.namespace import HASH_SIZE, NamespaceHasher
|
|
50
|
+
|
|
51
|
+
#: Cryptographically secure challenge nonces are 32 bytes.
|
|
52
|
+
NONCE_SIZE = 32
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Verdict(IntEnum):
|
|
56
|
+
"""The binary verdict carried by a Freshness Receipt."""
|
|
57
|
+
|
|
58
|
+
DENY = 0x00
|
|
59
|
+
ALLOW = 0x01
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _as_public_key(public_key: Any) -> Ed25519PublicKey:
|
|
63
|
+
if isinstance(public_key, Ed25519PublicKey):
|
|
64
|
+
return public_key
|
|
65
|
+
if isinstance(public_key, (bytes, bytearray, memoryview)):
|
|
66
|
+
return Ed25519PublicKey.from_public_bytes(bytes(public_key))
|
|
67
|
+
raise TypeError(f"unsupported public key type: {type(public_key)!r}")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _expect_blob(value: Any, length: int, name: str) -> bytes:
|
|
71
|
+
if not isinstance(value, (bytes, bytearray)) or len(value) != length:
|
|
72
|
+
raise ValueError(f"{name} must be a {length}-byte binary blob")
|
|
73
|
+
return bytes(value)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class Challenge:
|
|
78
|
+
"""The complete evaluation context sent to the Authoritative Identity.
|
|
79
|
+
|
|
80
|
+
Plaintext is held only on the client; :meth:`to_payload` emits hashed
|
|
81
|
+
hypotheses across the supplied salts.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
object: str
|
|
85
|
+
relation: str
|
|
86
|
+
grantee: bytes #: 16-byte RNS.Identity hash.
|
|
87
|
+
nonce: bytes #: 32-byte locally generated nonce.
|
|
88
|
+
hashers: _Tuple[NamespaceHasher, ...] #: salts to hypothesize over.
|
|
89
|
+
|
|
90
|
+
def __post_init__(self) -> None:
|
|
91
|
+
if len(self.grantee) != HASH_SIZE:
|
|
92
|
+
raise ValueError(f"grantee must be {HASH_SIZE} bytes")
|
|
93
|
+
if len(self.nonce) != NONCE_SIZE:
|
|
94
|
+
raise ValueError(f"nonce must be {NONCE_SIZE} bytes")
|
|
95
|
+
if not self.hashers:
|
|
96
|
+
raise ValueError("at least one salt hasher is required")
|
|
97
|
+
object.__setattr__(self, "grantee", bytes(self.grantee))
|
|
98
|
+
object.__setattr__(self, "nonce", bytes(self.nonce))
|
|
99
|
+
object.__setattr__(self, "hashers", tuple(self.hashers))
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def generate(
|
|
103
|
+
cls,
|
|
104
|
+
object_id: str,
|
|
105
|
+
relation: str,
|
|
106
|
+
grantee: bytes,
|
|
107
|
+
hashers: Sequence[NamespaceHasher],
|
|
108
|
+
*,
|
|
109
|
+
nonce: Optional[bytes] = None,
|
|
110
|
+
) -> "Challenge":
|
|
111
|
+
"""Build a Challenge with a fresh (or supplied) cryptographically secure nonce."""
|
|
112
|
+
return cls(
|
|
113
|
+
object_id,
|
|
114
|
+
relation,
|
|
115
|
+
grantee,
|
|
116
|
+
nonce if nonce is not None else os.urandom(NONCE_SIZE),
|
|
117
|
+
tuple(hashers),
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def to_payload(self) -> bytes:
|
|
121
|
+
"""Serialize the hashed multi-salt challenge (§8.3)."""
|
|
122
|
+
entries = []
|
|
123
|
+
for hasher in self.hashers:
|
|
124
|
+
obj_hashes, _wildcard = hasher.hash_object(self.object)
|
|
125
|
+
entries.append(
|
|
126
|
+
[
|
|
127
|
+
hasher.id_tag,
|
|
128
|
+
self.grantee,
|
|
129
|
+
hasher.hash_relation(self.relation),
|
|
130
|
+
hasher.hash_relation("-" + self.relation),
|
|
131
|
+
list(obj_hashes),
|
|
132
|
+
]
|
|
133
|
+
)
|
|
134
|
+
return serialization.packb([self.nonce, entries])
|
|
135
|
+
|
|
136
|
+
@classmethod
|
|
137
|
+
def from_payload(cls, data: bytes) -> "_ChallengeDecoded":
|
|
138
|
+
"""Decode a challenge payload into ``(nonce, grantee, hypotheses)``.
|
|
139
|
+
|
|
140
|
+
Plaintext is intentionally unrecoverable; the caller (the Authority)
|
|
141
|
+
receives per-salt hashed hypotheses directly. ``hypotheses`` is a list of
|
|
142
|
+
``(object_hashes, allow_relation_hash, deny_relation_hash)`` plus the
|
|
143
|
+
``salt_id_tag`` needed to bind each to a configured salt.
|
|
144
|
+
"""
|
|
145
|
+
fields = serialization.unpackb(data)
|
|
146
|
+
if not isinstance(fields, (list, tuple)) or len(fields) != 2:
|
|
147
|
+
raise ValueError("challenge payload must be a 2-element MessagePack array")
|
|
148
|
+
nonce, entries = fields
|
|
149
|
+
nonce = _expect_blob(nonce, NONCE_SIZE, "nonce")
|
|
150
|
+
if not isinstance(entries, (list, tuple)):
|
|
151
|
+
raise ValueError("challenge entries must be an array")
|
|
152
|
+
decoded: List[_DecodedEntry] = []
|
|
153
|
+
grantee: Optional[bytes] = None
|
|
154
|
+
for entry in entries:
|
|
155
|
+
if not isinstance(entry, (list, tuple)) or len(entry) != 5:
|
|
156
|
+
raise ValueError("each challenge entry must be a 5-element array")
|
|
157
|
+
salt_id_tag, grantee_hash, allow_rh, deny_rh, obj_hashes = entry
|
|
158
|
+
salt_id_tag = _expect_blob(salt_id_tag, HASH_SIZE, "salt_id_tag")
|
|
159
|
+
grantee_hash = _expect_blob(grantee_hash, HASH_SIZE, "grantee_hash")
|
|
160
|
+
allow_rh = _expect_blob(allow_rh, HASH_SIZE, "allow_relation_hash")
|
|
161
|
+
deny_rh = _expect_blob(deny_rh, HASH_SIZE, "deny_relation_hash")
|
|
162
|
+
if not isinstance(obj_hashes, (list, tuple)):
|
|
163
|
+
raise ValueError("object_segment_hashes must be an array")
|
|
164
|
+
obj_hashes = tuple(_expect_blob(h, HASH_SIZE, "object segment hash") for h in obj_hashes)
|
|
165
|
+
if grantee is None:
|
|
166
|
+
grantee = grantee_hash
|
|
167
|
+
elif grantee != grantee_hash:
|
|
168
|
+
raise ValueError("all challenge entries must share one grantee")
|
|
169
|
+
decoded.append(
|
|
170
|
+
_DecodedEntry(salt_id_tag, grantee_hash, allow_rh, deny_rh, obj_hashes)
|
|
171
|
+
)
|
|
172
|
+
if grantee is None:
|
|
173
|
+
raise ValueError("challenge must carry at least one entry")
|
|
174
|
+
return _ChallengeDecoded(nonce, grantee, decoded)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@dataclass(frozen=True)
|
|
178
|
+
class _ChallengeDecoded:
|
|
179
|
+
"""Decoded challenge: nonce, grantee, and per-salt hashed entries."""
|
|
180
|
+
|
|
181
|
+
nonce: bytes
|
|
182
|
+
grantee: bytes
|
|
183
|
+
entries: _Tuple[_DecodedEntry, ...]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass(frozen=True)
|
|
187
|
+
class _DecodedEntry:
|
|
188
|
+
salt_id_tag: bytes
|
|
189
|
+
grantee_hash: bytes
|
|
190
|
+
allow_relation_hash: bytes
|
|
191
|
+
deny_relation_hash: bytes
|
|
192
|
+
object_hashes: _Tuple[bytes, ...]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@dataclass(frozen=True)
|
|
196
|
+
class Receipt:
|
|
197
|
+
"""The Authoritative Identity's signed verdict (§8.5)."""
|
|
198
|
+
|
|
199
|
+
verdict: Verdict
|
|
200
|
+
server_hlc: int
|
|
201
|
+
nonce: bytes
|
|
202
|
+
signature: bytes = b""
|
|
203
|
+
|
|
204
|
+
def __post_init__(self) -> None:
|
|
205
|
+
if not isinstance(self.verdict, Verdict):
|
|
206
|
+
raise TypeError("verdict must be a Verdict")
|
|
207
|
+
if not 0 <= self.server_hlc <= MAX_HLC:
|
|
208
|
+
raise ValueError("server_hlc must fit in 64 bits")
|
|
209
|
+
if len(self.nonce) != NONCE_SIZE:
|
|
210
|
+
raise ValueError(f"nonce must be {NONCE_SIZE} bytes")
|
|
211
|
+
if self.signature and len(self.signature) != 64:
|
|
212
|
+
raise ValueError("signature must be 64 bytes")
|
|
213
|
+
|
|
214
|
+
def preimage(self) -> bytes:
|
|
215
|
+
"""The unpadded concatenation of the fields preceding the signature."""
|
|
216
|
+
return bytes([int(self.verdict)]) + self.server_hlc.to_bytes(8, "big") + self.nonce
|
|
217
|
+
|
|
218
|
+
def sign(self, private_key: Ed25519PrivateKey) -> "Receipt":
|
|
219
|
+
return replace(self, signature=private_key.sign(self.preimage()))
|
|
220
|
+
|
|
221
|
+
def verify(self, public_key: Any) -> bool:
|
|
222
|
+
if len(self.signature) != 64:
|
|
223
|
+
return False
|
|
224
|
+
try:
|
|
225
|
+
_as_public_key(public_key).verify(self.signature, self.preimage())
|
|
226
|
+
return True
|
|
227
|
+
except InvalidSignature:
|
|
228
|
+
return False
|
|
229
|
+
|
|
230
|
+
def to_payload(self) -> bytes:
|
|
231
|
+
if len(self.signature) != 64:
|
|
232
|
+
raise ValueError("Receipt must be signed before payload serialization")
|
|
233
|
+
return serialization.packb([int(self.verdict), self.server_hlc, self.nonce, self.signature])
|
|
234
|
+
|
|
235
|
+
@classmethod
|
|
236
|
+
def from_payload(cls, data: bytes) -> "Receipt":
|
|
237
|
+
fields = serialization.unpackb(data)
|
|
238
|
+
if not isinstance(fields, (list, tuple)) or len(fields) != 4:
|
|
239
|
+
raise ValueError("receipt payload must be a 4-element MessagePack array")
|
|
240
|
+
verdict, server_hlc, nonce, signature = fields
|
|
241
|
+
if verdict not in (int(Verdict.ALLOW), int(Verdict.DENY)):
|
|
242
|
+
raise ValueError(f"unknown verdict byte {verdict!r}")
|
|
243
|
+
if not isinstance(server_hlc, int) or not 0 <= server_hlc <= MAX_HLC:
|
|
244
|
+
raise ValueError("server_hlc must be a uint64 integer")
|
|
245
|
+
return cls(
|
|
246
|
+
Verdict(verdict),
|
|
247
|
+
server_hlc,
|
|
248
|
+
_expect_blob(nonce, NONCE_SIZE, "nonce"),
|
|
249
|
+
_expect_blob(signature, 64, "signature"),
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
#: Transport callable type: challenge payload -> receipt payload (or None).
|
|
254
|
+
Transport = Callable[[bytes], Optional[bytes]]
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _build_hypotheses(
|
|
258
|
+
config: Config, decoded: _ChallengeDecoded
|
|
259
|
+
) -> List[Hypothesis]:
|
|
260
|
+
"""Bind each decoded entry to a configured salt via its salt_id_tag (§8.4)."""
|
|
261
|
+
by_tag = {h.id_tag: h for h in config.hashers}
|
|
262
|
+
hyps: List[Hypothesis] = []
|
|
263
|
+
for entry in decoded.entries:
|
|
264
|
+
hasher = by_tag.get(entry.salt_id_tag)
|
|
265
|
+
if hasher is None:
|
|
266
|
+
continue # unknown salt -> hypothesis unusable, skip
|
|
267
|
+
hyps.append(
|
|
268
|
+
(hasher, entry.object_hashes, entry.allow_relation_hash, entry.deny_relation_hash)
|
|
269
|
+
)
|
|
270
|
+
return hyps
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class AuthoritativeServer:
|
|
274
|
+
"""The Authoritative Identity: evaluates requests and signs Freshness Receipts."""
|
|
275
|
+
|
|
276
|
+
def __init__(
|
|
277
|
+
self,
|
|
278
|
+
config: Config,
|
|
279
|
+
state: StateVector,
|
|
280
|
+
private_key: Ed25519PrivateKey,
|
|
281
|
+
*,
|
|
282
|
+
clock: Optional[Clock] = None,
|
|
283
|
+
) -> None:
|
|
284
|
+
self._engine = Engine(config, state)
|
|
285
|
+
self._state = state
|
|
286
|
+
self._config = config
|
|
287
|
+
self._private_key = private_key
|
|
288
|
+
self._clock = clock if clock is not None else Clock()
|
|
289
|
+
|
|
290
|
+
def handle(self, challenge_payload: bytes) -> bytes:
|
|
291
|
+
"""Evaluate a hashed Challenge and return a signed Receipt payload (§8.4)."""
|
|
292
|
+
decoded = Challenge.from_payload(challenge_payload)
|
|
293
|
+
hypotheses = _build_hypotheses(self._config, decoded)
|
|
294
|
+
if hypotheses:
|
|
295
|
+
allowed = self._engine.evaluate_hashes(decoded.grantee, hypotheses)
|
|
296
|
+
else:
|
|
297
|
+
allowed = False # no recognizable salt -> cannot prove allowance
|
|
298
|
+
verdict = Verdict.ALLOW if allowed else Verdict.DENY
|
|
299
|
+
receipt = Receipt(verdict, self._clock.now(), decoded.nonce).sign(self._private_key)
|
|
300
|
+
return receipt.to_payload()
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class ChallengeClient:
|
|
304
|
+
"""The requesting node: performs the local pre-check and challenge exchange."""
|
|
305
|
+
|
|
306
|
+
def __init__(
|
|
307
|
+
self,
|
|
308
|
+
config: Config,
|
|
309
|
+
state: StateVector,
|
|
310
|
+
authoritative_public_key: Any,
|
|
311
|
+
transport: Transport,
|
|
312
|
+
) -> None:
|
|
313
|
+
if config.authoritative_identity is None:
|
|
314
|
+
raise ValueError("Strict Consistency requires an Authoritative Identity (§8)")
|
|
315
|
+
self._engine = Engine(config, state)
|
|
316
|
+
self._state = state
|
|
317
|
+
self._config = config
|
|
318
|
+
self._public_key = _as_public_key(authoritative_public_key)
|
|
319
|
+
self._transport = transport
|
|
320
|
+
|
|
321
|
+
def authorize(self, object_id: str, relation: str, grantee: bytes) -> bool:
|
|
322
|
+
"""Run the full §8 flow. Returns True only on a verified server ALLOW."""
|
|
323
|
+
# §8.1 Local pre-check: denied locally -> fail immediately.
|
|
324
|
+
if not self._engine.evaluate(object_id, relation, grantee):
|
|
325
|
+
return False
|
|
326
|
+
# §8.2/§8.3 Challenge across Primary + Legacy salts.
|
|
327
|
+
challenge = Challenge.generate(
|
|
328
|
+
object_id, relation, grantee, self._config.hashers
|
|
329
|
+
)
|
|
330
|
+
try:
|
|
331
|
+
receipt_payload = self._transport(challenge.to_payload())
|
|
332
|
+
except Exception:
|
|
333
|
+
return False # partition penalty (§8)
|
|
334
|
+
if receipt_payload is None:
|
|
335
|
+
return False # partition penalty (§8)
|
|
336
|
+
receipt = Receipt.from_payload(receipt_payload)
|
|
337
|
+
# §8.5 Verify the nonce matches exactly and the signature is valid.
|
|
338
|
+
if receipt.nonce != challenge.nonce or not receipt.verify(self._public_key):
|
|
339
|
+
return False # invalid sig / nonce -> treated as DENY
|
|
340
|
+
return receipt.verdict == Verdict.ALLOW
|