variantgate 0.9.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.
- variantgate/__init__.py +127 -0
- variantgate/__main__.py +5 -0
- variantgate/_ed25519.py +92 -0
- variantgate/_http.py +123 -0
- variantgate/_version.py +3 -0
- variantgate/cancel_window.py +93 -0
- variantgate/canonical.py +73 -0
- variantgate/cli.py +242 -0
- variantgate/client.py +298 -0
- variantgate/errors.py +169 -0
- variantgate/guard.py +132 -0
- variantgate/mandate.py +80 -0
- variantgate/on_behalf.py +57 -0
- variantgate/plans.py +78 -0
- variantgate/preview.py +199 -0
- variantgate/py.typed +0 -0
- variantgate/receipts.py +212 -0
- variantgate/run_links.py +39 -0
- variantgate/runs.py +26 -0
- variantgate/source_limits.py +122 -0
- variantgate/sources.py +119 -0
- variantgate/types.py +132 -0
- variantgate/webhooks.py +91 -0
- variantgate-0.9.0.dist-info/METADATA +293 -0
- variantgate-0.9.0.dist-info/RECORD +27 -0
- variantgate-0.9.0.dist-info/WHEEL +4 -0
- variantgate-0.9.0.dist-info/entry_points.txt +2 -0
variantgate/__init__.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Ask a person before your agent acts.
|
|
2
|
+
|
|
3
|
+
A small client for the VariantGate approvals API. It reads
|
|
4
|
+
``VARIANTGATE_API_URL`` and ``VARIANTGATE_KEY`` from the environment and
|
|
5
|
+
fails closed: an error, a timeout, or any answer but an approval means the
|
|
6
|
+
action does not happen.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Any, Optional
|
|
10
|
+
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .cancel_window import in_cancel_window
|
|
13
|
+
from .client import DEFAULT_API_URL, MAX_WAIT_SECONDS, ApprovalClient
|
|
14
|
+
from .errors import (
|
|
15
|
+
ApprovalApiError,
|
|
16
|
+
ChangedApprovalError,
|
|
17
|
+
ConfigurationError,
|
|
18
|
+
NotApprovedError,
|
|
19
|
+
OnBehalfLockedError,
|
|
20
|
+
OutOfScopeError,
|
|
21
|
+
PlanLockedError,
|
|
22
|
+
RunLinkedError,
|
|
23
|
+
RunStoppedError,
|
|
24
|
+
VariantGateError,
|
|
25
|
+
approved_version,
|
|
26
|
+
describe,
|
|
27
|
+
)
|
|
28
|
+
from .guard import Approved, RequireApproval
|
|
29
|
+
from .mandate import MandateAnswer, is_granted
|
|
30
|
+
from .preview import (
|
|
31
|
+
DiffPreview,
|
|
32
|
+
EmailPreview,
|
|
33
|
+
Preview,
|
|
34
|
+
RecordsPreview,
|
|
35
|
+
SqlPreview,
|
|
36
|
+
TextPreview,
|
|
37
|
+
preview_problem,
|
|
38
|
+
)
|
|
39
|
+
from .receipts import (
|
|
40
|
+
RECEIPT_LEEWAY_SECONDS,
|
|
41
|
+
ReceiptClaims,
|
|
42
|
+
ReceiptError,
|
|
43
|
+
canonical_json,
|
|
44
|
+
details_digest,
|
|
45
|
+
verify_receipt,
|
|
46
|
+
)
|
|
47
|
+
from .source_limits import MAX_SOURCES
|
|
48
|
+
from .sources import Sources
|
|
49
|
+
from .types import (
|
|
50
|
+
Approval,
|
|
51
|
+
Decision,
|
|
52
|
+
MandateView,
|
|
53
|
+
Outcome,
|
|
54
|
+
Source,
|
|
55
|
+
SourceKind,
|
|
56
|
+
Status,
|
|
57
|
+
is_allowed,
|
|
58
|
+
is_changed,
|
|
59
|
+
)
|
|
60
|
+
from .webhooks import WEBHOOK_TOLERANCE_SECONDS, WebhookVerificationError, verify_webhook
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"DEFAULT_API_URL",
|
|
64
|
+
"MAX_SOURCES",
|
|
65
|
+
"MAX_WAIT_SECONDS",
|
|
66
|
+
"RECEIPT_LEEWAY_SECONDS",
|
|
67
|
+
"WEBHOOK_TOLERANCE_SECONDS",
|
|
68
|
+
"Approval",
|
|
69
|
+
"ApprovalApiError",
|
|
70
|
+
"ApprovalClient",
|
|
71
|
+
"Approved",
|
|
72
|
+
"ChangedApprovalError",
|
|
73
|
+
"ConfigurationError",
|
|
74
|
+
"Decision",
|
|
75
|
+
"DiffPreview",
|
|
76
|
+
"EmailPreview",
|
|
77
|
+
"MandateAnswer",
|
|
78
|
+
"MandateView",
|
|
79
|
+
"NotApprovedError",
|
|
80
|
+
"OnBehalfLockedError",
|
|
81
|
+
"OutOfScopeError",
|
|
82
|
+
"Outcome",
|
|
83
|
+
"PlanLockedError",
|
|
84
|
+
"Preview",
|
|
85
|
+
"ReceiptClaims",
|
|
86
|
+
"ReceiptError",
|
|
87
|
+
"RecordsPreview",
|
|
88
|
+
"RequireApproval",
|
|
89
|
+
"RunLinkedError",
|
|
90
|
+
"RunStoppedError",
|
|
91
|
+
"Source",
|
|
92
|
+
"SourceKind",
|
|
93
|
+
"Sources",
|
|
94
|
+
"SqlPreview",
|
|
95
|
+
"Status",
|
|
96
|
+
"TextPreview",
|
|
97
|
+
"VariantGateError",
|
|
98
|
+
"WebhookVerificationError",
|
|
99
|
+
"__version__",
|
|
100
|
+
"approved_version",
|
|
101
|
+
"canonical_json",
|
|
102
|
+
"describe",
|
|
103
|
+
"details_digest",
|
|
104
|
+
"in_cancel_window",
|
|
105
|
+
"is_allowed",
|
|
106
|
+
"is_changed",
|
|
107
|
+
"is_granted",
|
|
108
|
+
"preview_problem",
|
|
109
|
+
"require_approval",
|
|
110
|
+
"verify_receipt",
|
|
111
|
+
"verify_webhook",
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def require_approval(
|
|
116
|
+
action: Any, summary: Any, *, agent: Optional[str] = None, **request: Any
|
|
117
|
+
) -> RequireApproval:
|
|
118
|
+
"""Runs the wrapped code only after an explicit approval.
|
|
119
|
+
|
|
120
|
+
Use it as a decorator or a ``with`` block. The client is made from the
|
|
121
|
+
environment when the code runs, not when it is imported. Anything but an
|
|
122
|
+
approval raises ``NotApprovedError`` and the code does not run. So does an
|
|
123
|
+
approval of a changed version (``ChangedApprovalError``), unless a ``with``
|
|
124
|
+
block passes ``accept_changes=True`` and acts on ``approved.decision``'s
|
|
125
|
+
``approved_summary`` and ``approved_amount``.
|
|
126
|
+
"""
|
|
127
|
+
return RequireApproval(lambda: ApprovalClient(agent), action, summary, **request)
|
variantgate/__main__.py
ADDED
variantgate/_ed25519.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Checking an Ed25519 signature (RFC 8032), in plain Python.
|
|
2
|
+
|
|
3
|
+
Only verification lives here: VariantGate signs, tools check. It follows the
|
|
4
|
+
RFC's reference code and section 5.1.7, with the cofactorless check
|
|
5
|
+
``[S]B == R + [k]A``. A signature whose ``S`` is not below the group order,
|
|
6
|
+
and a point whose encoding is not canonical or not on the curve, are
|
|
7
|
+
refused. It is not constant time, which a check of public data does not need.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
Point = tuple[int, int, int, int]
|
|
14
|
+
"""A point in extended coordinates (X, Y, Z, T) with x = X/Z, y = Y/Z, xy = T/Z."""
|
|
15
|
+
|
|
16
|
+
P = 2**255 - 19
|
|
17
|
+
L = 2**252 + 27742317777372353535851937790883648493
|
|
18
|
+
"""The order of the group the base point makes."""
|
|
19
|
+
|
|
20
|
+
_D = -121665 * pow(121666, P - 2, P) % P
|
|
21
|
+
_SQRT_M1 = pow(2, (P - 1) // 4, P)
|
|
22
|
+
_BASE_X = 15112221349535400772501151409588531511454012693041857206046113283949847762202
|
|
23
|
+
_BASE_Y = 4 * pow(5, P - 2, P) % P
|
|
24
|
+
BASE: Point = (_BASE_X, _BASE_Y, 1, _BASE_X * _BASE_Y % P)
|
|
25
|
+
_IDENTITY: Point = (0, 1, 1, 0)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _add(a: Point, b: Point) -> Point:
|
|
29
|
+
first = (a[1] - a[0]) * (b[1] - b[0]) % P
|
|
30
|
+
second = (a[1] + a[0]) * (b[1] + b[0]) % P
|
|
31
|
+
third = 2 * a[3] * b[3] * _D % P
|
|
32
|
+
fourth = 2 * a[2] * b[2] % P
|
|
33
|
+
e, f, g, h = second - first, fourth - third, fourth + third, second + first
|
|
34
|
+
return (e * f % P, g * h % P, f * g % P, e * h % P)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def multiply(scalar: int, point: Point) -> Point:
|
|
38
|
+
"""``scalar`` times ``point``, by double and add."""
|
|
39
|
+
result = _IDENTITY
|
|
40
|
+
while scalar > 0:
|
|
41
|
+
if scalar & 1:
|
|
42
|
+
result = _add(result, point)
|
|
43
|
+
point = _add(point, point)
|
|
44
|
+
scalar >>= 1
|
|
45
|
+
return result
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def encode(point: Point) -> bytes:
|
|
49
|
+
"""The 32-byte encoding: y, little-endian, with the low bit of x on top."""
|
|
50
|
+
z_inverse = pow(point[2], P - 2, P)
|
|
51
|
+
x, y = point[0] * z_inverse % P, point[1] * z_inverse % P
|
|
52
|
+
return (y | ((x & 1) << 255)).to_bytes(32, "little")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _recover_x(y: int, sign: int) -> Optional[int]:
|
|
56
|
+
if y >= P:
|
|
57
|
+
return None
|
|
58
|
+
x2 = (y * y - 1) * pow(_D * y * y + 1, P - 2, P) % P
|
|
59
|
+
if x2 == 0:
|
|
60
|
+
return None if sign else 0
|
|
61
|
+
x = pow(x2, (P + 3) // 8, P)
|
|
62
|
+
if (x * x - x2) % P != 0:
|
|
63
|
+
x = x * _SQRT_M1 % P
|
|
64
|
+
if (x * x - x2) % P != 0:
|
|
65
|
+
return None
|
|
66
|
+
return P - x if (x & 1) != sign else x
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _decode(data: bytes) -> Optional[Point]:
|
|
70
|
+
y = int.from_bytes(data, "little")
|
|
71
|
+
sign, y = y >> 255, y & ((1 << 255) - 1)
|
|
72
|
+
x = _recover_x(y, sign)
|
|
73
|
+
if x is None:
|
|
74
|
+
return None
|
|
75
|
+
return (x, y, 1, x * y % P)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def hash_to_scalar(data: bytes) -> int:
|
|
79
|
+
"""SHA-512 of ``data`` as a little-endian number modulo ``L``."""
|
|
80
|
+
return int.from_bytes(hashlib.sha512(data).digest(), "little") % L
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def verify(public_key: bytes, message: bytes, signature: bytes) -> bool:
|
|
84
|
+
"""True only when ``signature`` is ``public_key``'s signature of ``message``."""
|
|
85
|
+
if len(public_key) != 32 or len(signature) != 64:
|
|
86
|
+
return False
|
|
87
|
+
signer, commitment = _decode(public_key), _decode(signature[:32])
|
|
88
|
+
s = int.from_bytes(signature[32:], "little")
|
|
89
|
+
if signer is None or commitment is None or s >= L:
|
|
90
|
+
return False
|
|
91
|
+
k = hash_to_scalar(signature[:32] + public_key + message)
|
|
92
|
+
return encode(multiply(s, BASE)) == encode(_add(commitment, multiply(k, signer)))
|
variantgate/_http.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""One call to the API, with every way it can fail turned into an error."""
|
|
2
|
+
|
|
3
|
+
import http.client
|
|
4
|
+
import json
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.request
|
|
7
|
+
from typing import Any, Optional
|
|
8
|
+
|
|
9
|
+
from ._version import __version__
|
|
10
|
+
from .errors import (
|
|
11
|
+
ApprovalApiError,
|
|
12
|
+
OnBehalfLockedError,
|
|
13
|
+
OutOfScopeError,
|
|
14
|
+
PlanLockedError,
|
|
15
|
+
RunLinkedError,
|
|
16
|
+
RunStoppedError,
|
|
17
|
+
)
|
|
18
|
+
from .types import Decision
|
|
19
|
+
|
|
20
|
+
USER_AGENT = f"variantgate-python/{__version__}"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def call(
|
|
24
|
+
url: str,
|
|
25
|
+
key: str,
|
|
26
|
+
method: str,
|
|
27
|
+
body: Optional[dict[str, Any]],
|
|
28
|
+
timeout: float,
|
|
29
|
+
) -> Decision:
|
|
30
|
+
"""Sends one call and returns the request the API answered with."""
|
|
31
|
+
return _decision(*_send(url, key, method, body, timeout))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def call_object(
|
|
35
|
+
url: str,
|
|
36
|
+
key: str,
|
|
37
|
+
method: str,
|
|
38
|
+
body: Optional[dict[str, Any]],
|
|
39
|
+
timeout: float,
|
|
40
|
+
) -> dict[str, Any]:
|
|
41
|
+
"""Sends one call and returns the JSON object the API answered with."""
|
|
42
|
+
return _object(*_send(url, key, method, body, timeout))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _send(
|
|
46
|
+
url: str, key: str, method: str, body: Optional[dict[str, Any]], timeout: float
|
|
47
|
+
) -> tuple[int, bytes]:
|
|
48
|
+
"""Sends one call and returns the status and body of a successful answer."""
|
|
49
|
+
data = None if body is None else json.dumps(body).encode("utf-8")
|
|
50
|
+
request = urllib.request.Request(
|
|
51
|
+
url,
|
|
52
|
+
data=data,
|
|
53
|
+
method=method,
|
|
54
|
+
headers={
|
|
55
|
+
"accept": "application/json",
|
|
56
|
+
"authorization": f"Bearer {key}",
|
|
57
|
+
"content-type": "application/json",
|
|
58
|
+
"user-agent": USER_AGENT,
|
|
59
|
+
},
|
|
60
|
+
)
|
|
61
|
+
try:
|
|
62
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
63
|
+
return response.status, response.read()
|
|
64
|
+
except urllib.error.HTTPError as error:
|
|
65
|
+
raise _refusal(error.code, error.read()) from None
|
|
66
|
+
except (OSError, http.client.HTTPException) as error:
|
|
67
|
+
message = str(getattr(error, "reason", None) or error) or type(error).__name__
|
|
68
|
+
raise ApprovalApiError(message, "network", 0) from error
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _parse(raw: bytes) -> Any:
|
|
72
|
+
try:
|
|
73
|
+
return json.loads(raw.decode("utf-8"))
|
|
74
|
+
except ValueError:
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _decision(status: int, raw: bytes) -> Decision:
|
|
79
|
+
"""The request in a successful answer. Anything unexpected is refused."""
|
|
80
|
+
parsed = _parse(raw)
|
|
81
|
+
looks_right = (
|
|
82
|
+
isinstance(parsed, dict)
|
|
83
|
+
and isinstance(parsed.get("id"), str)
|
|
84
|
+
and isinstance(parsed.get("status"), str)
|
|
85
|
+
)
|
|
86
|
+
if not looks_right:
|
|
87
|
+
raise ApprovalApiError(
|
|
88
|
+
"the API sent an answer that is not a request", "invalid_response", status
|
|
89
|
+
)
|
|
90
|
+
decision: Decision = parsed
|
|
91
|
+
return decision
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _object(status: int, raw: bytes) -> dict[str, Any]:
|
|
95
|
+
"""Any JSON object the API answered with. Anything else is refused."""
|
|
96
|
+
parsed = _parse(raw)
|
|
97
|
+
if not isinstance(parsed, dict):
|
|
98
|
+
raise ApprovalApiError(
|
|
99
|
+
"the API sent an answer that is not an object", "invalid_response", status
|
|
100
|
+
)
|
|
101
|
+
answer: dict[str, Any] = parsed
|
|
102
|
+
return answer
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _refusal(status: int, raw: bytes) -> ApprovalApiError:
|
|
106
|
+
parsed = _parse(raw)
|
|
107
|
+
detail = parsed.get("error") if isinstance(parsed, dict) else None
|
|
108
|
+
if not isinstance(detail, dict):
|
|
109
|
+
detail = {}
|
|
110
|
+
message = detail.get("message")
|
|
111
|
+
code = detail.get("code")
|
|
112
|
+
text = message if isinstance(message, str) else f"the API answered {status}"
|
|
113
|
+
if code == OutOfScopeError.CODE:
|
|
114
|
+
return OutOfScopeError(text, status)
|
|
115
|
+
if code == OnBehalfLockedError.CODE:
|
|
116
|
+
return OnBehalfLockedError(text, status)
|
|
117
|
+
if code == PlanLockedError.CODE:
|
|
118
|
+
return PlanLockedError(text, status)
|
|
119
|
+
if code == RunLinkedError.CODE:
|
|
120
|
+
return RunLinkedError(text, status)
|
|
121
|
+
if code == RunStoppedError.CODE:
|
|
122
|
+
return RunStoppedError(text, status)
|
|
123
|
+
return ApprovalApiError(text, code if isinstance(code, str) else "unknown", status)
|
variantgate/_version.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Cancel windows: an approval that waits a few minutes before the agent may act.
|
|
2
|
+
|
|
3
|
+
While a request is in its window the API says ``approved`` with ``allowed``
|
|
4
|
+
false, and ``acts_at`` says when it goes ahead. Until then any member of the
|
|
5
|
+
workspace may cancel it, which turns it ``denied``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
import re
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import TYPE_CHECKING, Any, Optional, cast
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from .types import Decision
|
|
15
|
+
|
|
16
|
+
_FRACTION = re.compile(r"\.(\d+)")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def parse_time(text: Any) -> Optional[float]:
|
|
20
|
+
"""An RFC 3339 time from the API as a timestamp, or ``None`` if unreadable."""
|
|
21
|
+
try:
|
|
22
|
+
normal = _FRACTION.sub(lambda m: "." + m.group(1)[:6].ljust(6, "0"), str(text))
|
|
23
|
+
return datetime.fromisoformat(normal.replace("Z", "+00:00")).timestamp()
|
|
24
|
+
except ValueError:
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def in_cancel_window(decision: "Decision") -> bool:
|
|
29
|
+
"""True while a request is approved but still in its cancel window.
|
|
30
|
+
|
|
31
|
+
Read from what the API says, not from this machine's clock: until the
|
|
32
|
+
API itself says ``allowed``, the agent must not act.
|
|
33
|
+
"""
|
|
34
|
+
return (
|
|
35
|
+
decision.get("status") == "approved"
|
|
36
|
+
and decision.get("allowed") is not True
|
|
37
|
+
and decision.get("paused") is False
|
|
38
|
+
and isinstance(decision.get("acts_at"), str)
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def window_ends(decision: "Decision") -> float:
|
|
43
|
+
"""How long a request in its window is worth waiting for.
|
|
44
|
+
|
|
45
|
+
The API's answer decides when the window is over, never this machine's
|
|
46
|
+
clock, so a readable window is waited out until the API says so; only
|
|
47
|
+
the caller's own timeout ends it sooner. 0 if the time cannot be read.
|
|
48
|
+
"""
|
|
49
|
+
at = parse_time(decision.get("acts_at"))
|
|
50
|
+
return 0.0 if at is None else math.inf
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _when(decision: "Decision") -> str:
|
|
54
|
+
"""When a request in its window goes ahead, such as ``14:32 UTC``."""
|
|
55
|
+
at = parse_time(decision.get("acts_at"))
|
|
56
|
+
if at is None:
|
|
57
|
+
return "the end of its cancel window"
|
|
58
|
+
return datetime.fromtimestamp(at, timezone.utc).strftime("%H:%M UTC")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def describe_window(decision: "Decision") -> str:
|
|
62
|
+
"""A request in its cancel window, in a few words."""
|
|
63
|
+
return (
|
|
64
|
+
f"approved, but it goes ahead only at {_when(decision)}, after its cancel window, "
|
|
65
|
+
"and a person can still cancel it until then"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def kept_window(after: "Decision", before: "Decision") -> "Decision":
|
|
70
|
+
"""A request taken back from its window, still saying when it would have gone ahead.
|
|
71
|
+
|
|
72
|
+
The API's answer to a withdrawal no longer carries ``acts_at``, so it is
|
|
73
|
+
kept from ``before``.
|
|
74
|
+
"""
|
|
75
|
+
if after.get("status") != "withdrawn" or not in_cancel_window(before):
|
|
76
|
+
return after
|
|
77
|
+
kept = dict(after)
|
|
78
|
+
kept["acts_at"] = after.get("acts_at") or before.get("acts_at")
|
|
79
|
+
return cast("Decision", kept)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def withdrawn_from_window(decision: "Decision") -> bool:
|
|
83
|
+
"""True when the agent took this request back from its cancel window."""
|
|
84
|
+
return decision.get("status") == "withdrawn" and isinstance(decision.get("acts_at"), str)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def describe_withdrawn(decision: "Decision") -> str:
|
|
88
|
+
"""A request taken back from its window, in a few words."""
|
|
89
|
+
return (
|
|
90
|
+
f"withdrawn: it would have gone ahead only at {_when(decision)}, after its "
|
|
91
|
+
"cancel window, and the wait ended first, so it was taken back and nothing "
|
|
92
|
+
"goes ahead"
|
|
93
|
+
)
|
variantgate/canonical.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""One exact JSON text for a value, so two programs can hash the same details.
|
|
2
|
+
|
|
3
|
+
The API, the TypeScript SDK and this module write the same text: object keys
|
|
4
|
+
sorted by UTF-16 code unit, no whitespace, and strings escaped the way
|
|
5
|
+
JavaScript's ``JSON.stringify`` escapes them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
_MAX_SAFE_INTEGER = 2**53
|
|
16
|
+
_LONE_SURROGATE = re.compile("[\ud800-\udfff]")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _string(text: str) -> str:
|
|
20
|
+
written = json.dumps(text, ensure_ascii=False)
|
|
21
|
+
return _LONE_SURROGATE.sub(lambda match: f"\\u{ord(match.group()):04x}", written)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _number(number: float) -> str:
|
|
25
|
+
if not math.isfinite(number):
|
|
26
|
+
raise ValueError("JSON has no NaN or infinity")
|
|
27
|
+
if number.is_integer() and abs(number) < _MAX_SAFE_INTEGER:
|
|
28
|
+
return str(int(number))
|
|
29
|
+
return repr(number)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _object(value: Mapping[Any, Any]) -> str:
|
|
33
|
+
for key in value:
|
|
34
|
+
if not isinstance(key, str):
|
|
35
|
+
raise TypeError(f"JSON object keys are strings, not {type(key).__name__}")
|
|
36
|
+
keys = sorted(value, key=lambda key: key.encode("utf-16-be"))
|
|
37
|
+
return "{" + ",".join(f"{_string(key)}:{canonical_json(value[key])}" for key in keys) + "}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def canonical_json(value: Any) -> str:
|
|
41
|
+
"""``value`` as canonical JSON text.
|
|
42
|
+
|
|
43
|
+
Objects (any mapping with string keys), lists and tuples, strings,
|
|
44
|
+
booleans, ``None``, integers and floats are written; anything else raises
|
|
45
|
+
``TypeError``, and NaN or infinity raises ``ValueError``. A whole float
|
|
46
|
+
below 2**53 is written as an integer, so ``1.0`` is ``1`` and ``-0.0`` is
|
|
47
|
+
``0``.
|
|
48
|
+
|
|
49
|
+
A number JavaScript cannot hold exactly (an integer of 2**53 or more, or
|
|
50
|
+
a float such as ``1e-7`` or ``1e16`` that the languages print
|
|
51
|
+
differently) may make a receipt check fail, never pass. Keep such values,
|
|
52
|
+
and money, in strings.
|
|
53
|
+
"""
|
|
54
|
+
if value is None:
|
|
55
|
+
return "null"
|
|
56
|
+
if isinstance(value, bool):
|
|
57
|
+
return "true" if value else "false"
|
|
58
|
+
if isinstance(value, int):
|
|
59
|
+
return str(value)
|
|
60
|
+
if isinstance(value, float):
|
|
61
|
+
return _number(value)
|
|
62
|
+
if isinstance(value, str):
|
|
63
|
+
return _string(value)
|
|
64
|
+
if isinstance(value, Mapping):
|
|
65
|
+
return _object(value)
|
|
66
|
+
if isinstance(value, (list, tuple)):
|
|
67
|
+
return "[" + ",".join(canonical_json(item) for item in value) + "]"
|
|
68
|
+
raise TypeError(f"{type(value).__name__} is not JSON")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def details_digest(details: Any) -> str:
|
|
72
|
+
"""The lowercase hex SHA-256 of ``details``' canonical JSON, as UTF-8."""
|
|
73
|
+
return hashlib.sha256(canonical_json(details).encode()).hexdigest()
|