sm-revocation 0.1.1__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.
- sm_revocation/__init__.py +79 -0
- sm_revocation/_wire.py +109 -0
- sm_revocation/adapters.py +95 -0
- sm_revocation/conflicts.py +118 -0
- sm_revocation/issuer.py +154 -0
- sm_revocation/objects.py +146 -0
- sm_revocation/payloads.py +242 -0
- sm_revocation/py.typed +0 -0
- sm_revocation/status.py +110 -0
- sm_revocation/view.py +399 -0
- sm_revocation-0.1.1.dist-info/METADATA +189 -0
- sm_revocation-0.1.1.dist-info/RECORD +14 -0
- sm_revocation-0.1.1.dist-info/WHEEL +4 -0
- sm_revocation-0.1.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""sm-revocation — freshness-bounded revocation feeds for agent meshes on
|
|
2
|
+
intermittent links.
|
|
3
|
+
|
|
4
|
+
An issuer publishes revocations on an ``sm-feed`` feed and re-signs its head on a
|
|
5
|
+
declared cadence. Any carrier can forward entries, heads and pages. A holder's
|
|
6
|
+
``FeedView`` answers one of three things about a subject at a time: ``REVOKED``,
|
|
7
|
+
``NOT_REVOKED(as_of)`` — with ``as_of`` an issuer-signed time the view was provably
|
|
8
|
+
complete to — or ``UNKNOWN(reason)``. Two adapters feed the answers to
|
|
9
|
+
``sm-renewal`` and ``sm-dat``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from importlib.metadata import PackageNotFoundError as _PackageNotFoundError
|
|
15
|
+
from importlib.metadata import version as _dist_version
|
|
16
|
+
|
|
17
|
+
from .adapters import RENEWAL_KINDS, dat_checker, revoked_set
|
|
18
|
+
from .conflicts import (
|
|
19
|
+
CONFLICT_VERSION,
|
|
20
|
+
EQUIVOCATION_VERSION,
|
|
21
|
+
build_conflict,
|
|
22
|
+
conflict_kind,
|
|
23
|
+
verify_conflict,
|
|
24
|
+
verify_equivocation,
|
|
25
|
+
)
|
|
26
|
+
from .issuer import RevocationIssuer
|
|
27
|
+
from .objects import check_entry, check_head
|
|
28
|
+
from .payloads import (
|
|
29
|
+
POLICY_TYPE,
|
|
30
|
+
PROFILE,
|
|
31
|
+
REASONS,
|
|
32
|
+
REVOKE_TYPE,
|
|
33
|
+
SUBJECT_KINDS,
|
|
34
|
+
Record,
|
|
35
|
+
merge,
|
|
36
|
+
policy_payload,
|
|
37
|
+
revoke_payload,
|
|
38
|
+
)
|
|
39
|
+
from .status import NOT_REVOKED, REVOKED, UNKNOWN, UNKNOWN_REASONS, Status, combine
|
|
40
|
+
from .view import SNAPSHOT_VERSION, FeedView, Ingest, state_digest
|
|
41
|
+
|
|
42
|
+
try: # pragma: no cover - trivial branch
|
|
43
|
+
__version__ = _dist_version("sm-revocation")
|
|
44
|
+
except _PackageNotFoundError: # running from a source tree, not installed
|
|
45
|
+
__version__ = "0.0.0.dev0"
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"CONFLICT_VERSION",
|
|
49
|
+
"EQUIVOCATION_VERSION",
|
|
50
|
+
"NOT_REVOKED",
|
|
51
|
+
"POLICY_TYPE",
|
|
52
|
+
"PROFILE",
|
|
53
|
+
"REASONS",
|
|
54
|
+
"RENEWAL_KINDS",
|
|
55
|
+
"REVOKED",
|
|
56
|
+
"REVOKE_TYPE",
|
|
57
|
+
"SNAPSHOT_VERSION",
|
|
58
|
+
"SUBJECT_KINDS",
|
|
59
|
+
"UNKNOWN",
|
|
60
|
+
"UNKNOWN_REASONS",
|
|
61
|
+
"FeedView",
|
|
62
|
+
"Ingest",
|
|
63
|
+
"Record",
|
|
64
|
+
"RevocationIssuer",
|
|
65
|
+
"Status",
|
|
66
|
+
"build_conflict",
|
|
67
|
+
"check_entry",
|
|
68
|
+
"check_head",
|
|
69
|
+
"combine",
|
|
70
|
+
"conflict_kind",
|
|
71
|
+
"dat_checker",
|
|
72
|
+
"merge",
|
|
73
|
+
"policy_payload",
|
|
74
|
+
"revoke_payload",
|
|
75
|
+
"revoked_set",
|
|
76
|
+
"state_digest",
|
|
77
|
+
"verify_conflict",
|
|
78
|
+
"verify_equivocation",
|
|
79
|
+
]
|
sm_revocation/_wire.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Wire conventions (SPEC §3): timestamps, digests, integers, strings, sorting.
|
|
2
|
+
|
|
3
|
+
Every predicate here takes ``Any`` and never raises: the objects it is handed can
|
|
4
|
+
come from an adversary.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import re
|
|
11
|
+
from datetime import UTC, datetime, timedelta, timezone
|
|
12
|
+
from typing import Any, cast
|
|
13
|
+
|
|
14
|
+
import jcs # type: ignore[import-untyped]
|
|
15
|
+
|
|
16
|
+
MAX_INT = 2**53 - 1
|
|
17
|
+
|
|
18
|
+
# SPEC §3: RFC 3339, second precision, UTC, "Z", ASCII digits only. re.ASCII keeps
|
|
19
|
+
# \d-style classes from matching non-ASCII digits; the explicit [0-9] does too.
|
|
20
|
+
_FEED_TIME = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", re.ASCII)
|
|
21
|
+
|
|
22
|
+
# A caller's `at` may be any RFC 3339 instant with an offset, as sm-dat accepts.
|
|
23
|
+
_QUERY_TIME = re.compile(
|
|
24
|
+
r"([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})"
|
|
25
|
+
r"(?:\.([0-9]{1,9}))?([Zz]|[+-][0-9]{2}:[0-9]{2})",
|
|
26
|
+
re.ASCII,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
_DIGEST = re.compile(r"sha256:[0-9a-f]{64}", re.ASCII)
|
|
30
|
+
_DID_KEY = re.compile(r"did:key:z[1-9A-HJ-NP-Za-km-z]+", re.ASCII)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def is_int(value: Any, minimum: int = 0) -> bool:
|
|
34
|
+
"""An integer in ``minimum … 2^53 − 1``. A boolean is never an integer."""
|
|
35
|
+
return isinstance(value, int) and not isinstance(value, bool) and minimum <= value <= MAX_INT
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def is_text(value: Any) -> bool:
|
|
39
|
+
"""A non-empty string that has a UTF-8 encoding (no unpaired surrogates)."""
|
|
40
|
+
if not isinstance(value, str) or not value:
|
|
41
|
+
return False
|
|
42
|
+
try:
|
|
43
|
+
value.encode("utf-8")
|
|
44
|
+
except UnicodeEncodeError:
|
|
45
|
+
return False
|
|
46
|
+
return True
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def is_digest(value: Any) -> bool:
|
|
50
|
+
return isinstance(value, str) and _DIGEST.fullmatch(value) is not None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def is_did_key(value: Any) -> bool:
|
|
54
|
+
return isinstance(value, str) and _DID_KEY.fullmatch(value) is not None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_feed_time(value: Any) -> datetime | None:
|
|
58
|
+
"""A feed timestamp (SPEC §3) as an aware UTC datetime, else ``None``."""
|
|
59
|
+
if not isinstance(value, str) or _FEED_TIME.fullmatch(value) is None:
|
|
60
|
+
return None
|
|
61
|
+
try:
|
|
62
|
+
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
|
|
63
|
+
except ValueError: # 2026-02-30, hour 24, second 60
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def is_feed_time(value: Any) -> bool:
|
|
68
|
+
return parse_feed_time(value) is not None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def parse_query_time(value: Any) -> datetime | None:
|
|
72
|
+
"""A caller's ``at``: any RFC 3339 instant with an offset, else ``None``."""
|
|
73
|
+
if not isinstance(value, str):
|
|
74
|
+
return None
|
|
75
|
+
m = _QUERY_TIME.fullmatch(value)
|
|
76
|
+
if m is None:
|
|
77
|
+
return None
|
|
78
|
+
year, month, day, hour, minute, second, frac, offset = m.groups()
|
|
79
|
+
micro = int((frac or "0").ljust(6, "0")[:6])
|
|
80
|
+
try:
|
|
81
|
+
tz = UTC
|
|
82
|
+
if offset not in ("Z", "z"):
|
|
83
|
+
sign = 1 if offset[0] == "+" else -1
|
|
84
|
+
oh, om = int(offset[1:3]), int(offset[4:6])
|
|
85
|
+
if oh > 23 or om > 59:
|
|
86
|
+
return None
|
|
87
|
+
tz = timezone(sign * timedelta(hours=oh, minutes=om))
|
|
88
|
+
dt = datetime(
|
|
89
|
+
int(year), int(month), int(day), int(hour), int(minute), int(second), micro, tz
|
|
90
|
+
)
|
|
91
|
+
# Converting year 1 or 9999 across an offset can leave datetime's range.
|
|
92
|
+
return dt.astimezone(UTC)
|
|
93
|
+
except (ValueError, OverflowError):
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def sort_key(value: str) -> bytes:
|
|
98
|
+
"""SPEC §3: strings sort by their UTF-8 bytes. Callers pass only ``is_text``."""
|
|
99
|
+
return value.encode("utf-8")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def canonical(value: Any) -> bytes:
|
|
103
|
+
"""RFC 8785 (JCS) bytes. Raises on values with no canonical form; callers that
|
|
104
|
+
hold untrusted values guard it."""
|
|
105
|
+
return cast(bytes, jcs.canonicalize(value))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def digest(value: Any) -> str:
|
|
109
|
+
return "sha256:" + hashlib.sha256(canonical(value)).hexdigest()
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Adapters for the two existing consumers (SPEC §9).
|
|
2
|
+
|
|
3
|
+
Neither imports its consumer: ``revoked_set`` returns the ``frozenset`` that
|
|
4
|
+
``sm-renewal`` takes as ``revoked_credential_hashes``, and ``dat_checker`` returns
|
|
5
|
+
the ``(grant_id, issued_at) -> bool | None`` callable ``sm-dat`` takes as
|
|
6
|
+
``revocation_checker``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable, Iterable, Sequence
|
|
12
|
+
|
|
13
|
+
from ._wire import is_int, parse_query_time
|
|
14
|
+
from .payloads import SUBJECT_KINDS
|
|
15
|
+
from .status import combine
|
|
16
|
+
from .view import FeedView
|
|
17
|
+
|
|
18
|
+
#: The kinds ``sm-renewal`` checks, by the §9.1 convention.
|
|
19
|
+
RENEWAL_KINDS = frozenset({"credential_hash", "manifest_hash"})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def revoked_set(
|
|
23
|
+
view: FeedView,
|
|
24
|
+
kinds: Iterable[str],
|
|
25
|
+
at: str,
|
|
26
|
+
max_staleness_seconds: int,
|
|
27
|
+
) -> frozenset[str] | None:
|
|
28
|
+
"""SPEC §9.1. ``None`` when the view would answer ``UNKNOWN`` for a subject of
|
|
29
|
+
any requested kind that is not revoked at ``at``; otherwise every subject of
|
|
30
|
+
those kinds revoked at or before ``at``.
|
|
31
|
+
|
|
32
|
+
**Never coerce ``None`` to an empty set.** ``sm-renewal`` reads an empty set as
|
|
33
|
+
"complete, fresh, and nothing revoked" — the claim the view refused to make.
|
|
34
|
+
On ``None``, an attester declines and a relying party fails its revocation step.
|
|
35
|
+
"""
|
|
36
|
+
wanted = frozenset(kinds)
|
|
37
|
+
if not wanted or not wanted <= frozenset(SUBJECT_KINDS):
|
|
38
|
+
raise ValueError(f"kinds must be a non-empty subset of {SUBJECT_KINDS}")
|
|
39
|
+
when = parse_query_time(at)
|
|
40
|
+
if when is None:
|
|
41
|
+
raise ValueError("at must be an RFC 3339 timestamp with an offset")
|
|
42
|
+
if not is_int(max_staleness_seconds):
|
|
43
|
+
raise ValueError("max_staleness_seconds must be a non-negative integer")
|
|
44
|
+
for kind in sorted(wanted):
|
|
45
|
+
# The feed-level answer: SPEC §6.7 steps 2–7, which do not depend on the
|
|
46
|
+
# subject, so one probe per kind settles it.
|
|
47
|
+
if view.feed_condition(kind, when, max_staleness_seconds).unknown:
|
|
48
|
+
return None
|
|
49
|
+
return frozenset(
|
|
50
|
+
r.subject for r in view.revoked.values() if r.subject_kind in wanted and r.effective <= when
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
#: ``resolve(grant_id)`` returns the views of that grant's own revocation feeds and
|
|
55
|
+
#: its ``max_revocation_age_seconds``, or ``None`` for a grant it does not know.
|
|
56
|
+
Resolver = Callable[[str], "tuple[Sequence[FeedView], int] | None"]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def dat_checker(resolve: Resolver) -> Callable[[str, str], bool | None]:
|
|
60
|
+
"""SPEC §9.2. ``sm-dat`` calls one checker for every grant in a chain,
|
|
61
|
+
ancestors included, so the checker resolves each grant to its own feeds.
|
|
62
|
+
|
|
63
|
+
``REVOKED`` → ``True``; ``NOT_REVOKED`` → ``False``; ``UNKNOWN``, an unknown
|
|
64
|
+
grant, or a malformed ``issued_at`` → ``None``, which ``sm-dat`` turns into
|
|
65
|
+
``INDETERMINATE(revocation_unknown)``.
|
|
66
|
+
|
|
67
|
+
``issued_at`` is the action's time as the receipt states it. A live verifier
|
|
68
|
+
should bound it by its own clock first (SPEC §9.2, THREATMODEL).
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def check(grant_id: str, issued_at: str) -> bool | None:
|
|
72
|
+
if not isinstance(grant_id, str) or not grant_id:
|
|
73
|
+
return None
|
|
74
|
+
if parse_query_time(issued_at) is None:
|
|
75
|
+
return None
|
|
76
|
+
try:
|
|
77
|
+
resolved = resolve(grant_id)
|
|
78
|
+
except Exception: # noqa: BLE001 — a resolver failure is "cannot say"
|
|
79
|
+
return None
|
|
80
|
+
if resolved is None:
|
|
81
|
+
return None
|
|
82
|
+
views, max_age = resolved
|
|
83
|
+
if not is_int(max_age):
|
|
84
|
+
return None
|
|
85
|
+
try:
|
|
86
|
+
answer = combine(v.status("grant_id", grant_id, issued_at, max_age) for v in views)
|
|
87
|
+
except Exception: # noqa: BLE001 — "cannot say", never an exception into sm-dat
|
|
88
|
+
return None
|
|
89
|
+
if answer.revoked:
|
|
90
|
+
return True
|
|
91
|
+
if answer.not_revoked:
|
|
92
|
+
return False
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
return check
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Evidence of issuer misbehaviour (SPEC §7): forks and signed-time order conflicts.
|
|
2
|
+
|
|
3
|
+
Both kinds are the issuer's own two signatures, so anyone holding the pair can
|
|
4
|
+
re-check it. Neither can be produced by an honest issuer: forks are excluded by
|
|
5
|
+
the linear chain, order conflicts by SPEC §5.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
from ._wire import canonical, is_did_key, is_int
|
|
13
|
+
from .objects import check_head, check_object, kind_of
|
|
14
|
+
|
|
15
|
+
CONFLICT_VERSION = "revocation-conflict/0.1"
|
|
16
|
+
EQUIVOCATION_VERSION = "feed-equivocation/0.1"
|
|
17
|
+
|
|
18
|
+
ConflictKind = Literal["fork", "order"]
|
|
19
|
+
|
|
20
|
+
_CONFLICT_FIELDS = frozenset({"version", "feed_id", "a", "b"})
|
|
21
|
+
_EQUIVOCATION_FIELDS = frozenset({"version", "feed_id", "seq", "head_a", "head_b"})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def binds(obj: dict[str, Any]) -> list[tuple[int, str]]:
|
|
25
|
+
"""The positions a checked object fixes (§7.1). An entry also fixes its
|
|
26
|
+
predecessor's hash through ``prev_hash``."""
|
|
27
|
+
out = [(obj["seq"], obj["entry_hash"])]
|
|
28
|
+
if kind_of(obj) == "entry" and obj["seq"] > 0:
|
|
29
|
+
out.append((obj["seq"] - 1, obj["prev_hash"]))
|
|
30
|
+
return out
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def signed_time(obj: dict[str, Any]) -> str:
|
|
34
|
+
"""An entry's ``issued_at`` or a head's ``generated_at``. Canonical SPEC §3
|
|
35
|
+
timestamps compare correctly as strings."""
|
|
36
|
+
return str(obj["issued_at"] if kind_of(obj) == "entry" else obj["generated_at"])
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def position(obj: dict[str, Any]) -> tuple[int, int]:
|
|
40
|
+
"""``(seq, 0)`` for an entry, ``(seq, 1)`` for a head: a head sits after the
|
|
41
|
+
entry it commits and before the next one."""
|
|
42
|
+
return (obj["seq"], 0 if kind_of(obj) == "entry" else 1)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def conflict_kind(a: dict[str, Any], b: dict[str, Any]) -> ConflictKind | None:
|
|
46
|
+
"""How two checked objects of one feed conflict, if they do (§7.1)."""
|
|
47
|
+
bound_a = dict(binds(a))
|
|
48
|
+
for seq, h in binds(b):
|
|
49
|
+
if seq in bound_a and bound_a[seq] != h:
|
|
50
|
+
return "fork"
|
|
51
|
+
pa, pb = position(a), position(b)
|
|
52
|
+
ta, tb = signed_time(a), signed_time(b)
|
|
53
|
+
if (pa < pb and ta > tb) or (pb < pa and tb > ta):
|
|
54
|
+
return "order"
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _ordered(a: dict[str, Any], b: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
59
|
+
"""A deterministic order for the pair, so equal evidence serialises equally."""
|
|
60
|
+
ka = (position(a), canonical(a))
|
|
61
|
+
kb = (position(b), canonical(b))
|
|
62
|
+
return (a, b) if ka <= kb else (b, a)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def build_conflict(feed_id: str, a: Any, b: Any) -> dict[str, Any] | None:
|
|
66
|
+
"""A ``revocation-conflict/0.1`` proof, or ``None`` unless both objects check
|
|
67
|
+
(§6.2 steps 1–3) under ``feed_id`` and conflict. A proof is never built from an
|
|
68
|
+
object that does not verify."""
|
|
69
|
+
if check_object(a, feed_id, profile=False) or check_object(b, feed_id, profile=False):
|
|
70
|
+
return None
|
|
71
|
+
if conflict_kind(a, b) is None:
|
|
72
|
+
return None
|
|
73
|
+
first, second = _ordered(a, b)
|
|
74
|
+
return {"version": CONFLICT_VERSION, "feed_id": feed_id, "a": first, "b": second}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def verify_conflict(proof: Any) -> tuple[bool, str, ConflictKind | None]:
|
|
78
|
+
"""Re-check a ``revocation-conflict/0.1`` from the issuer's two signatures:
|
|
79
|
+
``(ok, reason, kind)``. Never raises."""
|
|
80
|
+
if not isinstance(proof, dict) or frozenset(proof) != _CONFLICT_FIELDS:
|
|
81
|
+
return False, "shape: field_set", None
|
|
82
|
+
if proof["version"] != CONFLICT_VERSION:
|
|
83
|
+
return False, "shape: version", None
|
|
84
|
+
feed_id = proof["feed_id"]
|
|
85
|
+
if not is_did_key(feed_id):
|
|
86
|
+
return False, "shape: feed_id", None
|
|
87
|
+
for name in ("a", "b"):
|
|
88
|
+
problem = check_object(proof[name], feed_id, profile=False)
|
|
89
|
+
if problem is not None:
|
|
90
|
+
return False, f"{name}: {problem}", None
|
|
91
|
+
kind = conflict_kind(proof["a"], proof["b"])
|
|
92
|
+
if kind is None:
|
|
93
|
+
return False, "no_conflict", None
|
|
94
|
+
return True, "ok", kind
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def verify_equivocation(proof: Any, feed_id: str | None = None) -> tuple[bool, str]:
|
|
98
|
+
"""Accept ``sm-feed``'s ``feed-equivocation/0.1`` (§7.2), checking both heads
|
|
99
|
+
per §6.2 steps 1–3 rather than relying on ``sm-feed``'s verifier alone."""
|
|
100
|
+
if not isinstance(proof, dict) or frozenset(proof) != _EQUIVOCATION_FIELDS:
|
|
101
|
+
return False, "shape: field_set"
|
|
102
|
+
if proof["version"] != EQUIVOCATION_VERSION:
|
|
103
|
+
return False, "shape: version"
|
|
104
|
+
fid = proof["feed_id"]
|
|
105
|
+
if not is_did_key(fid) or (feed_id is not None and fid != feed_id):
|
|
106
|
+
return False, "shape: feed_id"
|
|
107
|
+
if not is_int(proof["seq"]):
|
|
108
|
+
return False, "shape: seq"
|
|
109
|
+
for name in ("head_a", "head_b"):
|
|
110
|
+
problem = check_head(proof[name], fid)
|
|
111
|
+
if problem is not None:
|
|
112
|
+
return False, f"{name}: {problem}"
|
|
113
|
+
a, b = proof["head_a"], proof["head_b"]
|
|
114
|
+
if not (a["seq"] == b["seq"] == proof["seq"]):
|
|
115
|
+
return False, "seq_mismatch"
|
|
116
|
+
if a["entry_hash"] == b["entry_hash"]:
|
|
117
|
+
return False, "no_conflict"
|
|
118
|
+
return True, "ok"
|
sm_revocation/issuer.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""The issuer's side (SPEC §5, §8.1): a revocation feed that keeps its obligations.
|
|
2
|
+
|
|
3
|
+
``RevocationIssuer`` wraps an ``sm-feed`` ``FeedLog``. It appends the genesis
|
|
4
|
+
policy, validates every payload before signing it, serialises every signed time
|
|
5
|
+
through one clamp so the feed's signed times never decrease (§5.3), and computes
|
|
6
|
+
checkpoint digests and snapshots. It reads no clock: every call takes the time.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from sm_arp import Identity
|
|
14
|
+
from sm_feed import FeedLog, build_signed_head, emit_checkpoint
|
|
15
|
+
|
|
16
|
+
from ._wire import parse_feed_time
|
|
17
|
+
from .payloads import Record, merge_into, policy_payload, revoke_payload, sorted_records
|
|
18
|
+
from .view import SNAPSHOT_VERSION, prune, state_digest
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RevocationIssuer:
|
|
22
|
+
"""One revocation feed, keyed to ``identity``.
|
|
23
|
+
|
|
24
|
+
A single instance is the single serialisation point §5.3 requires. Running
|
|
25
|
+
two instances (or replicas) over one key can break the signed-time order while
|
|
26
|
+
every replica is honest, and holders will then treat the feed as misbehaving.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
identity: Identity,
|
|
32
|
+
*,
|
|
33
|
+
heartbeat_seconds: int,
|
|
34
|
+
subject_kinds: list[str],
|
|
35
|
+
issued_at: str,
|
|
36
|
+
) -> None:
|
|
37
|
+
self._identity = identity
|
|
38
|
+
self._log = FeedLog(identity)
|
|
39
|
+
self._last: str | None = None
|
|
40
|
+
self._policy = policy_payload(
|
|
41
|
+
heartbeat_seconds=heartbeat_seconds, subject_kinds=subject_kinds
|
|
42
|
+
)
|
|
43
|
+
self._active: dict[tuple[str, str], Record] = {} # A_prev merged with later revokes
|
|
44
|
+
self._snapshot: dict[str, Any] | None = None
|
|
45
|
+
self._log.append(self._policy, issued_at=self._stamp(issued_at))
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def feed_id(self) -> str:
|
|
49
|
+
return self._log.feed_id
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def policy(self) -> dict[str, Any]:
|
|
53
|
+
return dict(self._policy)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def last_signed_at(self) -> str | None:
|
|
57
|
+
return self._last
|
|
58
|
+
|
|
59
|
+
def _stamp(self, at: str) -> str:
|
|
60
|
+
"""§5.3: a signed time is never earlier than the last one. A clock that
|
|
61
|
+
steps back keeps the last signed time until it passes it."""
|
|
62
|
+
if parse_feed_time(at) is None:
|
|
63
|
+
raise ValueError("times must be RFC 3339, second precision, UTC, 'Z' (SPEC §3)")
|
|
64
|
+
if self._last is not None and at < self._last:
|
|
65
|
+
at = self._last
|
|
66
|
+
self._last = at
|
|
67
|
+
return at
|
|
68
|
+
|
|
69
|
+
# --- entries -----------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
def revoke(
|
|
72
|
+
self,
|
|
73
|
+
*,
|
|
74
|
+
subject_kind: str,
|
|
75
|
+
subject: str,
|
|
76
|
+
effective_at: str,
|
|
77
|
+
issued_at: str,
|
|
78
|
+
reason: str = "unspecified",
|
|
79
|
+
prune_after: str | None = None,
|
|
80
|
+
) -> dict[str, Any]:
|
|
81
|
+
"""Append a ``revocation/revoke``. Raises ``ValueError`` for an uncovered
|
|
82
|
+
kind, a malformed field, or an ``effective_at`` later than the signed time."""
|
|
83
|
+
payload = revoke_payload(
|
|
84
|
+
subject_kind=subject_kind,
|
|
85
|
+
subject=subject,
|
|
86
|
+
effective_at=effective_at,
|
|
87
|
+
reason=reason,
|
|
88
|
+
prune_after=prune_after,
|
|
89
|
+
)
|
|
90
|
+
if subject_kind not in self._policy["subject_kinds"]:
|
|
91
|
+
raise ValueError(f"this feed does not cover {subject_kind!r}")
|
|
92
|
+
if parse_feed_time(issued_at) is None:
|
|
93
|
+
raise ValueError("times must be RFC 3339, second precision, UTC, 'Z' (SPEC §3)")
|
|
94
|
+
stamp = issued_at if self._last is None or issued_at >= self._last else self._last
|
|
95
|
+
if effective_at > stamp:
|
|
96
|
+
raise ValueError("effective_at may not be later than issued_at (no future-dating)")
|
|
97
|
+
entry = self._log.append(payload, issued_at=self._stamp(issued_at))
|
|
98
|
+
merge_into(self._active, Record.from_payload(payload))
|
|
99
|
+
return entry
|
|
100
|
+
|
|
101
|
+
def set_heartbeat(self, heartbeat_seconds: int, *, issued_at: str) -> dict[str, Any]:
|
|
102
|
+
"""Append a later policy. Only ``heartbeat_seconds`` may change (§4.3)."""
|
|
103
|
+
# Validate and stamp before touching state: a refused call must leave the
|
|
104
|
+
# policy the checkpoint digest uses exactly as it was (§8.1).
|
|
105
|
+
policy = policy_payload(
|
|
106
|
+
heartbeat_seconds=heartbeat_seconds, subject_kinds=self._policy["subject_kinds"]
|
|
107
|
+
)
|
|
108
|
+
entry = self._log.append(policy, issued_at=self._stamp(issued_at))
|
|
109
|
+
self._policy = policy
|
|
110
|
+
return entry
|
|
111
|
+
|
|
112
|
+
def checkpoint(self, *, issued_at: str) -> dict[str, Any]:
|
|
113
|
+
"""Append a ``feed/state-checkpoint`` with §8.1's digest, and keep the
|
|
114
|
+
snapshot a late joiner can adopt."""
|
|
115
|
+
stamp = self._stamp(issued_at)
|
|
116
|
+
active = sorted_records(prune(list(self._active.values()), stamp))
|
|
117
|
+
entry = emit_checkpoint(
|
|
118
|
+
self._log, state_digest=state_digest(self._policy, active), issued_at=stamp
|
|
119
|
+
)
|
|
120
|
+
self._active = {r.key: r for r in active}
|
|
121
|
+
self._snapshot = {
|
|
122
|
+
"version": SNAPSHOT_VERSION,
|
|
123
|
+
"feed_id": self.feed_id,
|
|
124
|
+
"checkpoint": entry,
|
|
125
|
+
"policy": dict(self._policy),
|
|
126
|
+
"active": [r.to_json() for r in active],
|
|
127
|
+
}
|
|
128
|
+
return entry
|
|
129
|
+
|
|
130
|
+
# --- heads and pages ---------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
def head(self, *, generated_at: str) -> dict[str, Any]:
|
|
133
|
+
"""A heartbeat (§5.2): the current head re-signed with a newer time."""
|
|
134
|
+
ref = self._log.head_ref()
|
|
135
|
+
assert ref is not None # the genesis policy is always there
|
|
136
|
+
return build_signed_head(
|
|
137
|
+
self._identity,
|
|
138
|
+
seq=ref["seq"],
|
|
139
|
+
entry_hash=ref["entry_hash"],
|
|
140
|
+
generated_at=self._stamp(generated_at),
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def page(
|
|
144
|
+
self, cursor: int | None, *, generated_at: str, limit: int | None = None
|
|
145
|
+
) -> dict[str, Any]:
|
|
146
|
+
"""An ``sm-feed`` page after ``cursor`` with a freshly signed head (§5)."""
|
|
147
|
+
return self._log.page(cursor, generated_at=self._stamp(generated_at), limit=limit)
|
|
148
|
+
|
|
149
|
+
def entries(self) -> list[dict[str, Any]]:
|
|
150
|
+
return self._log.since(None)
|
|
151
|
+
|
|
152
|
+
def snapshot(self) -> dict[str, Any] | None:
|
|
153
|
+
"""The ``revocation-snapshot/0.1`` for the latest checkpoint, if any."""
|
|
154
|
+
return None if self._snapshot is None else dict(self._snapshot)
|