altcha 2.0.2__tar.gz → 2.1.0__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.
- {altcha-2.0.2/altcha.egg-info → altcha-2.1.0}/PKG-INFO +48 -5
- {altcha-2.0.2 → altcha-2.1.0}/README.md +47 -4
- {altcha-2.0.2 → altcha-2.1.0}/altcha/__init__.py +2 -0
- {altcha-2.0.2 → altcha-2.1.0}/altcha/v2.py +153 -2
- {altcha-2.0.2 → altcha-2.1.0/altcha.egg-info}/PKG-INFO +48 -5
- {altcha-2.0.2 → altcha-2.1.0}/setup.py +1 -1
- {altcha-2.0.2 → altcha-2.1.0}/tests/test_altcha_v2.py +185 -0
- {altcha-2.0.2 → altcha-2.1.0}/LICENSE +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/MANIFEST.in +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/altcha/altcha.py +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/altcha/py.typed +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/altcha/v1.py +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/altcha.egg-info/SOURCES.txt +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/altcha.egg-info/dependency_links.txt +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/altcha.egg-info/top_level.txt +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/setup.cfg +0 -0
- {altcha-2.0.2 → altcha-2.1.0}/tests/test_altcha.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: altcha
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: A library for creating and verifying challenges for ALTCHA.
|
|
5
5
|
Home-page: https://github.com/altcha-org/altcha-lib-py
|
|
6
6
|
Author: Daniel Regeci
|
|
@@ -95,7 +95,7 @@ payload_b64 = Payload(challenge, solution).to_base64()
|
|
|
95
95
|
|
|
96
96
|
# Server: verify
|
|
97
97
|
result = verify_solution(payload_b64, HMAC_SECRET)
|
|
98
|
-
print(result.verified)
|
|
98
|
+
print(result.verified) # True
|
|
99
99
|
```
|
|
100
100
|
|
|
101
101
|
### Deterministic mode
|
|
@@ -136,7 +136,8 @@ import datetime
|
|
|
136
136
|
challenge = create_challenge(
|
|
137
137
|
algorithm="PBKDF2/SHA-256",
|
|
138
138
|
cost=5_000,
|
|
139
|
-
expires_at=datetime.datetime.now(datetime.timezone.utc)
|
|
139
|
+
expires_at=datetime.datetime.now(datetime.timezone.utc)
|
|
140
|
+
+ datetime.timedelta(minutes=10),
|
|
140
141
|
hmac_secret=HMAC_SECRET,
|
|
141
142
|
)
|
|
142
143
|
```
|
|
@@ -146,8 +147,8 @@ challenge = create_challenge(
|
|
|
146
147
|
Pass your own `derive_key` function to use a custom or third-party KDF:
|
|
147
148
|
|
|
148
149
|
```python
|
|
149
|
-
def my_derive_key(parameters, salt: bytes, password: bytes) -> bytes:
|
|
150
|
-
|
|
150
|
+
def my_derive_key(parameters, salt: bytes, password: bytes) -> bytes: ...
|
|
151
|
+
|
|
151
152
|
|
|
152
153
|
challenge = create_challenge(
|
|
153
154
|
algorithm="MY-ALGO",
|
|
@@ -256,6 +257,48 @@ Verifies the hash of specific form fields.
|
|
|
256
257
|
|
|
257
258
|
Verifies an ALTCHA server signature.
|
|
258
259
|
|
|
260
|
+
#### `verify_server(payload, url, secret, *, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
|
|
261
|
+
|
|
262
|
+
Verifies a payload remotely via the ALTCHA Sentinel `/v1/verify/signature` API, instead of
|
|
263
|
+
checking the HMAC signature locally. Avoids managing the HMAC secret on your server, at the
|
|
264
|
+
cost of a network round-trip.
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
from altcha import verify_server
|
|
268
|
+
|
|
269
|
+
result = verify_server(
|
|
270
|
+
payload, # the payload received from POST /v1/verify
|
|
271
|
+
url="https://sentinel.example.com/v1/verify/signature",
|
|
272
|
+
secret=API_KEY_SECRET, # optional, checked against the payload's API key
|
|
273
|
+
timeout=10,
|
|
274
|
+
retries=2,
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
if result.verified:
|
|
278
|
+
...
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
| Parameter | Type | Default | Description |
|
|
282
|
+
|---|---|---|---|
|
|
283
|
+
| `payload` | `str` \| `ServerSignaturePayload` \| `dict` | — | The payload to verify. |
|
|
284
|
+
| `url` | `str` | — | Full URL of the Sentinel `/v1/verify/signature` endpoint. |
|
|
285
|
+
| `secret` | `str` | `None` | API key secret, checked against the payload's API key. |
|
|
286
|
+
| `headers` | `dict` | `None` | Additional headers to send with the request. |
|
|
287
|
+
| `timeout` | `float` | `10` | Per-attempt request timeout in seconds. |
|
|
288
|
+
| `retries` | `int` | `0` | Number of retry attempts after the first try. |
|
|
289
|
+
| `retry_delay` | `float` | `0.3` | Base delay in seconds between retries. |
|
|
290
|
+
| `retry_backoff` | `str` | `'exponential'` | `'fixed'` or `'exponential'` backoff. |
|
|
291
|
+
| `http_post` | callable | stdlib `urllib` | Transport override: `(url, body, headers, timeout) -> (status, body)`. |
|
|
292
|
+
|
|
293
|
+
Returns `VerifyServerResult` with fields:
|
|
294
|
+
|
|
295
|
+
| Field | Type | Description |
|
|
296
|
+
|---|---|---|
|
|
297
|
+
| `verified` | `bool` | `True` if Sentinel confirmed the payload is valid. |
|
|
298
|
+
| `reason` | `str \| None` | Failure reason, if any. |
|
|
299
|
+
| `api_key` | `str \| None` | The API key associated with the payload, if returned. |
|
|
300
|
+
| `verification_data` | `dict \| None` | Parsed verification data, if returned. |
|
|
301
|
+
|
|
259
302
|
---
|
|
260
303
|
|
|
261
304
|
### V1 (legacy)
|
|
@@ -72,7 +72,7 @@ payload_b64 = Payload(challenge, solution).to_base64()
|
|
|
72
72
|
|
|
73
73
|
# Server: verify
|
|
74
74
|
result = verify_solution(payload_b64, HMAC_SECRET)
|
|
75
|
-
print(result.verified)
|
|
75
|
+
print(result.verified) # True
|
|
76
76
|
```
|
|
77
77
|
|
|
78
78
|
### Deterministic mode
|
|
@@ -113,7 +113,8 @@ import datetime
|
|
|
113
113
|
challenge = create_challenge(
|
|
114
114
|
algorithm="PBKDF2/SHA-256",
|
|
115
115
|
cost=5_000,
|
|
116
|
-
expires_at=datetime.datetime.now(datetime.timezone.utc)
|
|
116
|
+
expires_at=datetime.datetime.now(datetime.timezone.utc)
|
|
117
|
+
+ datetime.timedelta(minutes=10),
|
|
117
118
|
hmac_secret=HMAC_SECRET,
|
|
118
119
|
)
|
|
119
120
|
```
|
|
@@ -123,8 +124,8 @@ challenge = create_challenge(
|
|
|
123
124
|
Pass your own `derive_key` function to use a custom or third-party KDF:
|
|
124
125
|
|
|
125
126
|
```python
|
|
126
|
-
def my_derive_key(parameters, salt: bytes, password: bytes) -> bytes:
|
|
127
|
-
|
|
127
|
+
def my_derive_key(parameters, salt: bytes, password: bytes) -> bytes: ...
|
|
128
|
+
|
|
128
129
|
|
|
129
130
|
challenge = create_challenge(
|
|
130
131
|
algorithm="MY-ALGO",
|
|
@@ -233,6 +234,48 @@ Verifies the hash of specific form fields.
|
|
|
233
234
|
|
|
234
235
|
Verifies an ALTCHA server signature.
|
|
235
236
|
|
|
237
|
+
#### `verify_server(payload, url, secret, *, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
|
|
238
|
+
|
|
239
|
+
Verifies a payload remotely via the ALTCHA Sentinel `/v1/verify/signature` API, instead of
|
|
240
|
+
checking the HMAC signature locally. Avoids managing the HMAC secret on your server, at the
|
|
241
|
+
cost of a network round-trip.
|
|
242
|
+
|
|
243
|
+
```python
|
|
244
|
+
from altcha import verify_server
|
|
245
|
+
|
|
246
|
+
result = verify_server(
|
|
247
|
+
payload, # the payload received from POST /v1/verify
|
|
248
|
+
url="https://sentinel.example.com/v1/verify/signature",
|
|
249
|
+
secret=API_KEY_SECRET, # optional, checked against the payload's API key
|
|
250
|
+
timeout=10,
|
|
251
|
+
retries=2,
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
if result.verified:
|
|
255
|
+
...
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
| Parameter | Type | Default | Description |
|
|
259
|
+
|---|---|---|---|
|
|
260
|
+
| `payload` | `str` \| `ServerSignaturePayload` \| `dict` | — | The payload to verify. |
|
|
261
|
+
| `url` | `str` | — | Full URL of the Sentinel `/v1/verify/signature` endpoint. |
|
|
262
|
+
| `secret` | `str` | `None` | API key secret, checked against the payload's API key. |
|
|
263
|
+
| `headers` | `dict` | `None` | Additional headers to send with the request. |
|
|
264
|
+
| `timeout` | `float` | `10` | Per-attempt request timeout in seconds. |
|
|
265
|
+
| `retries` | `int` | `0` | Number of retry attempts after the first try. |
|
|
266
|
+
| `retry_delay` | `float` | `0.3` | Base delay in seconds between retries. |
|
|
267
|
+
| `retry_backoff` | `str` | `'exponential'` | `'fixed'` or `'exponential'` backoff. |
|
|
268
|
+
| `http_post` | callable | stdlib `urllib` | Transport override: `(url, body, headers, timeout) -> (status, body)`. |
|
|
269
|
+
|
|
270
|
+
Returns `VerifyServerResult` with fields:
|
|
271
|
+
|
|
272
|
+
| Field | Type | Description |
|
|
273
|
+
|---|---|---|
|
|
274
|
+
| `verified` | `bool` | `True` if Sentinel confirmed the payload is valid. |
|
|
275
|
+
| `reason` | `str \| None` | Failure reason, if any. |
|
|
276
|
+
| `api_key` | `str \| None` | The API key associated with the payload, if returned. |
|
|
277
|
+
| `verification_data` | `dict \| None` | Parsed verification data, if returned. |
|
|
278
|
+
|
|
236
279
|
---
|
|
237
280
|
|
|
238
281
|
### V1 (legacy)
|
|
@@ -11,6 +11,8 @@ from .v2 import ServerSignaturePayload as ServerSignaturePayload
|
|
|
11
11
|
from .v2 import VerifyServerSignatureResult as VerifyServerSignatureResult
|
|
12
12
|
from .v2 import parse_verification_data as parse_verification_data
|
|
13
13
|
from .v2 import verify_server_signature as verify_server_signature
|
|
14
|
+
from .v2 import VerifyServerResult as VerifyServerResult
|
|
15
|
+
from .v2 import verify_server as verify_server
|
|
14
16
|
from .v2 import create_challenge as create_challenge
|
|
15
17
|
from .v2 import solve_challenge as solve_challenge
|
|
16
18
|
from .v2 import verify_solution as verify_solution
|
|
@@ -8,7 +8,9 @@ import re
|
|
|
8
8
|
import secrets
|
|
9
9
|
import struct
|
|
10
10
|
import time
|
|
11
|
+
import urllib.error
|
|
11
12
|
import urllib.parse
|
|
13
|
+
import urllib.request
|
|
12
14
|
from typing import Callable, Literal
|
|
13
15
|
import datetime
|
|
14
16
|
|
|
@@ -663,7 +665,8 @@ def verify_solution(
|
|
|
663
665
|
verified=valid,
|
|
664
666
|
)
|
|
665
667
|
|
|
666
|
-
# 4b. Slow path: re-derive the key from the counter and compare
|
|
668
|
+
# 4b. Slow path: re-derive the key from the counter and compare, and
|
|
669
|
+
# require it to satisfy the signed key prefix.
|
|
667
670
|
if derive_key is None:
|
|
668
671
|
derive_key = _select_derive_key(params.algorithm)
|
|
669
672
|
|
|
@@ -672,7 +675,9 @@ def verify_solution(
|
|
|
672
675
|
password = _make_password(nonce_bytes, solution.counter)
|
|
673
676
|
recomputed = derive_key(params, salt_bytes, password)
|
|
674
677
|
recomputed_hex = recomputed.hex()
|
|
675
|
-
|
|
678
|
+
key_matches = _constant_time_equal(recomputed_hex, solution.derived_key)
|
|
679
|
+
prefix_matches = recomputed_hex.startswith(params.key_prefix)
|
|
680
|
+
invalid = not (key_matches and prefix_matches)
|
|
676
681
|
|
|
677
682
|
return VerifySolutionResult(
|
|
678
683
|
expired=False,
|
|
@@ -714,6 +719,14 @@ class ServerSignaturePayload:
|
|
|
714
719
|
self.verification_data = verification_data
|
|
715
720
|
self.verified = verified
|
|
716
721
|
|
|
722
|
+
def to_dict(self) -> dict:
|
|
723
|
+
return {
|
|
724
|
+
"algorithm": self.algorithm,
|
|
725
|
+
"signature": self.signature,
|
|
726
|
+
"verificationData": self.verification_data,
|
|
727
|
+
"verified": self.verified,
|
|
728
|
+
}
|
|
729
|
+
|
|
717
730
|
@classmethod
|
|
718
731
|
def from_dict(cls, d: dict) -> ServerSignaturePayload:
|
|
719
732
|
return cls(
|
|
@@ -859,3 +872,141 @@ def verify_server_signature(
|
|
|
859
872
|
verified=verified,
|
|
860
873
|
verification_data=verification_data if verified else None,
|
|
861
874
|
)
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
# ---------------------------------------------------------------------------
|
|
878
|
+
# Remote (Sentinel API) verification
|
|
879
|
+
# ---------------------------------------------------------------------------
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
class VerifyServerResult:
|
|
883
|
+
"""
|
|
884
|
+
Result of a remote Sentinel verification via :func:`verify_server`.
|
|
885
|
+
|
|
886
|
+
Attributes:
|
|
887
|
+
verified: ``True`` if Sentinel confirmed the payload is valid.
|
|
888
|
+
reason: Failure reason (e.g. an error code or exception message), if any.
|
|
889
|
+
api_key: The API key associated with the payload, if returned.
|
|
890
|
+
verification_data: Parsed verification data, if returned.
|
|
891
|
+
"""
|
|
892
|
+
|
|
893
|
+
def __init__(
|
|
894
|
+
self,
|
|
895
|
+
verified: bool,
|
|
896
|
+
reason: str | None = None,
|
|
897
|
+
api_key: str | None = None,
|
|
898
|
+
verification_data: dict | None = None,
|
|
899
|
+
):
|
|
900
|
+
self.verified = verified
|
|
901
|
+
self.reason = reason
|
|
902
|
+
self.api_key = api_key
|
|
903
|
+
self.verification_data = verification_data
|
|
904
|
+
|
|
905
|
+
@classmethod
|
|
906
|
+
def from_dict(cls, d: dict) -> VerifyServerResult:
|
|
907
|
+
return cls(
|
|
908
|
+
verified=bool(d.get("verified", False)),
|
|
909
|
+
reason=d.get("reason"),
|
|
910
|
+
api_key=d.get("apiKey"),
|
|
911
|
+
verification_data=d.get("verificationData"),
|
|
912
|
+
)
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
def _default_http_post(
|
|
916
|
+
url: str, data: bytes, headers: dict[str, str], timeout: float
|
|
917
|
+
) -> tuple[int, bytes]:
|
|
918
|
+
"""Minimal stdlib HTTP POST, used as the default transport for :func:`verify_server`."""
|
|
919
|
+
req = urllib.request.Request(url, data=data, method="POST", headers=headers)
|
|
920
|
+
try:
|
|
921
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
922
|
+
return resp.status, resp.read()
|
|
923
|
+
except urllib.error.HTTPError as e:
|
|
924
|
+
return e.code, e.read()
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
def _sleep_backoff(attempt: int, delay: float, backoff: str) -> None:
|
|
928
|
+
wait = delay if backoff == "fixed" else delay * (2**attempt)
|
|
929
|
+
time.sleep(wait)
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def verify_server(
|
|
933
|
+
payload: str | ServerSignaturePayload | dict,
|
|
934
|
+
url: str,
|
|
935
|
+
secret: str | None = None,
|
|
936
|
+
*,
|
|
937
|
+
headers: dict[str, str] | None = None,
|
|
938
|
+
timeout: float = 10.0,
|
|
939
|
+
retries: int = 0,
|
|
940
|
+
retry_delay: float = 0.3,
|
|
941
|
+
retry_backoff: Literal["fixed", "exponential"] = "exponential",
|
|
942
|
+
http_post: Callable[[str, bytes, dict[str, str], float], tuple[int, bytes]]
|
|
943
|
+
| None = None,
|
|
944
|
+
) -> VerifyServerResult:
|
|
945
|
+
"""
|
|
946
|
+
Verify a payload remotely via the ALTCHA Sentinel ``/v1/verify/signature`` API.
|
|
947
|
+
|
|
948
|
+
Instead of verifying the HMAC signature locally (see :func:`verify_server_signature`),
|
|
949
|
+
this POSTs the payload to Sentinel and trusts its response. Avoids managing the HMAC
|
|
950
|
+
secret on your server, at the cost of a network round-trip.
|
|
951
|
+
|
|
952
|
+
Args:
|
|
953
|
+
payload: The payload to verify, as received from ``POST /v1/verify`` — a base64
|
|
954
|
+
string, a :class:`ServerSignaturePayload`, or an already-decoded dict.
|
|
955
|
+
url: Full URL of the Sentinel ``/v1/verify/signature`` endpoint.
|
|
956
|
+
secret: API key secret. If given, Sentinel checks it against the payload's API key.
|
|
957
|
+
headers: Additional headers to send with the request.
|
|
958
|
+
timeout: Per-attempt request timeout in seconds. Defaults to ``10``.
|
|
959
|
+
retries: Number of retry attempts after the first try. Defaults to ``0``.
|
|
960
|
+
retry_delay: Base delay in seconds between retries. Defaults to ``0.3``.
|
|
961
|
+
retry_backoff: ``'fixed'`` or ``'exponential'`` backoff applied to *retry_delay*.
|
|
962
|
+
http_post: Transport override — ``(url, body, headers, timeout) -> (status, body)``.
|
|
963
|
+
Defaults to a stdlib ``urllib.request``-based implementation. Swap in another
|
|
964
|
+
HTTP client (e.g. ``requests``, ``httpx``) here if preferred.
|
|
965
|
+
|
|
966
|
+
Returns:
|
|
967
|
+
A :class:`VerifyServerResult` describing the outcome. Failures (HTTP errors, network
|
|
968
|
+
errors, or a negative Sentinel verdict) are reported via ``verified=False`` with a
|
|
969
|
+
``reason``, never raised as exceptions.
|
|
970
|
+
"""
|
|
971
|
+
if isinstance(payload, ServerSignaturePayload):
|
|
972
|
+
payload_value: str | dict = payload.to_dict()
|
|
973
|
+
else:
|
|
974
|
+
payload_value = payload
|
|
975
|
+
|
|
976
|
+
body: dict = {"payload": payload_value}
|
|
977
|
+
if secret is not None:
|
|
978
|
+
body["secret"] = secret
|
|
979
|
+
data = json.dumps(body).encode()
|
|
980
|
+
|
|
981
|
+
req_headers = {"Content-Type": "application/json", **(headers or {})}
|
|
982
|
+
post = http_post or _default_http_post
|
|
983
|
+
|
|
984
|
+
attempts = retries + 1
|
|
985
|
+
for attempt in range(attempts):
|
|
986
|
+
try:
|
|
987
|
+
status, resp_body = post(url, data, req_headers, timeout)
|
|
988
|
+
except Exception as e:
|
|
989
|
+
if attempt >= attempts - 1:
|
|
990
|
+
return VerifyServerResult(
|
|
991
|
+
verified=False, reason=str(e) or type(e).__name__
|
|
992
|
+
)
|
|
993
|
+
_sleep_backoff(attempt, retry_delay, retry_backoff)
|
|
994
|
+
continue
|
|
995
|
+
|
|
996
|
+
if status == 400:
|
|
997
|
+
try:
|
|
998
|
+
err_data = json.loads(resp_body.decode())
|
|
999
|
+
except Exception:
|
|
1000
|
+
err_data = None
|
|
1001
|
+
reason = (err_data or {}).get("error") or f"HTTP_{status}"
|
|
1002
|
+
return VerifyServerResult(verified=False, reason=reason)
|
|
1003
|
+
|
|
1004
|
+
if not (200 <= status < 300):
|
|
1005
|
+
if attempt >= attempts - 1:
|
|
1006
|
+
return VerifyServerResult(verified=False, reason=f"HTTP_{status}")
|
|
1007
|
+
_sleep_backoff(attempt, retry_delay, retry_backoff)
|
|
1008
|
+
continue
|
|
1009
|
+
|
|
1010
|
+
return VerifyServerResult.from_dict(json.loads(resp_body.decode()))
|
|
1011
|
+
|
|
1012
|
+
return VerifyServerResult(verified=False, reason="NETWORK_ERROR")
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: altcha
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: A library for creating and verifying challenges for ALTCHA.
|
|
5
5
|
Home-page: https://github.com/altcha-org/altcha-lib-py
|
|
6
6
|
Author: Daniel Regeci
|
|
@@ -95,7 +95,7 @@ payload_b64 = Payload(challenge, solution).to_base64()
|
|
|
95
95
|
|
|
96
96
|
# Server: verify
|
|
97
97
|
result = verify_solution(payload_b64, HMAC_SECRET)
|
|
98
|
-
print(result.verified)
|
|
98
|
+
print(result.verified) # True
|
|
99
99
|
```
|
|
100
100
|
|
|
101
101
|
### Deterministic mode
|
|
@@ -136,7 +136,8 @@ import datetime
|
|
|
136
136
|
challenge = create_challenge(
|
|
137
137
|
algorithm="PBKDF2/SHA-256",
|
|
138
138
|
cost=5_000,
|
|
139
|
-
expires_at=datetime.datetime.now(datetime.timezone.utc)
|
|
139
|
+
expires_at=datetime.datetime.now(datetime.timezone.utc)
|
|
140
|
+
+ datetime.timedelta(minutes=10),
|
|
140
141
|
hmac_secret=HMAC_SECRET,
|
|
141
142
|
)
|
|
142
143
|
```
|
|
@@ -146,8 +147,8 @@ challenge = create_challenge(
|
|
|
146
147
|
Pass your own `derive_key` function to use a custom or third-party KDF:
|
|
147
148
|
|
|
148
149
|
```python
|
|
149
|
-
def my_derive_key(parameters, salt: bytes, password: bytes) -> bytes:
|
|
150
|
-
|
|
150
|
+
def my_derive_key(parameters, salt: bytes, password: bytes) -> bytes: ...
|
|
151
|
+
|
|
151
152
|
|
|
152
153
|
challenge = create_challenge(
|
|
153
154
|
algorithm="MY-ALGO",
|
|
@@ -256,6 +257,48 @@ Verifies the hash of specific form fields.
|
|
|
256
257
|
|
|
257
258
|
Verifies an ALTCHA server signature.
|
|
258
259
|
|
|
260
|
+
#### `verify_server(payload, url, secret, *, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
|
|
261
|
+
|
|
262
|
+
Verifies a payload remotely via the ALTCHA Sentinel `/v1/verify/signature` API, instead of
|
|
263
|
+
checking the HMAC signature locally. Avoids managing the HMAC secret on your server, at the
|
|
264
|
+
cost of a network round-trip.
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
from altcha import verify_server
|
|
268
|
+
|
|
269
|
+
result = verify_server(
|
|
270
|
+
payload, # the payload received from POST /v1/verify
|
|
271
|
+
url="https://sentinel.example.com/v1/verify/signature",
|
|
272
|
+
secret=API_KEY_SECRET, # optional, checked against the payload's API key
|
|
273
|
+
timeout=10,
|
|
274
|
+
retries=2,
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
if result.verified:
|
|
278
|
+
...
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
| Parameter | Type | Default | Description |
|
|
282
|
+
|---|---|---|---|
|
|
283
|
+
| `payload` | `str` \| `ServerSignaturePayload` \| `dict` | — | The payload to verify. |
|
|
284
|
+
| `url` | `str` | — | Full URL of the Sentinel `/v1/verify/signature` endpoint. |
|
|
285
|
+
| `secret` | `str` | `None` | API key secret, checked against the payload's API key. |
|
|
286
|
+
| `headers` | `dict` | `None` | Additional headers to send with the request. |
|
|
287
|
+
| `timeout` | `float` | `10` | Per-attempt request timeout in seconds. |
|
|
288
|
+
| `retries` | `int` | `0` | Number of retry attempts after the first try. |
|
|
289
|
+
| `retry_delay` | `float` | `0.3` | Base delay in seconds between retries. |
|
|
290
|
+
| `retry_backoff` | `str` | `'exponential'` | `'fixed'` or `'exponential'` backoff. |
|
|
291
|
+
| `http_post` | callable | stdlib `urllib` | Transport override: `(url, body, headers, timeout) -> (status, body)`. |
|
|
292
|
+
|
|
293
|
+
Returns `VerifyServerResult` with fields:
|
|
294
|
+
|
|
295
|
+
| Field | Type | Description |
|
|
296
|
+
|---|---|---|
|
|
297
|
+
| `verified` | `bool` | `True` if Sentinel confirmed the payload is valid. |
|
|
298
|
+
| `reason` | `str \| None` | Failure reason, if any. |
|
|
299
|
+
| `api_key` | `str \| None` | The API key associated with the payload, if returned. |
|
|
300
|
+
| `verification_data` | `dict \| None` | Parsed verification data, if returned. |
|
|
301
|
+
|
|
259
302
|
---
|
|
260
303
|
|
|
261
304
|
### V1 (legacy)
|
|
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages # type: ignore[import-untyped]
|
|
|
2
2
|
|
|
3
3
|
setup(
|
|
4
4
|
name="altcha",
|
|
5
|
-
version="2.0
|
|
5
|
+
version="2.1.0",
|
|
6
6
|
description="A library for creating and verifying challenges for ALTCHA.",
|
|
7
7
|
long_description=open("README.md").read(),
|
|
8
8
|
long_description_content_type="text/markdown",
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import datetime
|
|
2
|
+
import json
|
|
2
3
|
import struct
|
|
3
4
|
import unittest
|
|
5
|
+
import unittest.mock
|
|
4
6
|
|
|
5
7
|
from altcha.v2 import (
|
|
8
|
+
DEFAULT_HMAC_ALGORITHM,
|
|
9
|
+
Challenge,
|
|
6
10
|
ChallengeParameters,
|
|
7
11
|
Payload,
|
|
8
12
|
ServerSignaturePayload,
|
|
@@ -10,12 +14,14 @@ from altcha.v2 import (
|
|
|
10
14
|
_canonical_json,
|
|
11
15
|
_hmac_v2,
|
|
12
16
|
_make_password,
|
|
17
|
+
_sign_challenge_v2,
|
|
13
18
|
create_challenge,
|
|
14
19
|
derive_key_pbkdf2,
|
|
15
20
|
derive_key_scrypt,
|
|
16
21
|
derive_key_sha,
|
|
17
22
|
parse_verification_data,
|
|
18
23
|
solve_challenge,
|
|
24
|
+
verify_server,
|
|
19
25
|
verify_server_signature,
|
|
20
26
|
verify_solution,
|
|
21
27
|
)
|
|
@@ -307,6 +313,42 @@ class TestVerifySolution(unittest.TestCase):
|
|
|
307
313
|
self.assertFalse(result.verified)
|
|
308
314
|
self.assertTrue(result.invalid_solution)
|
|
309
315
|
|
|
316
|
+
def test_slow_path_enforces_key_prefix(self):
|
|
317
|
+
# Regression test: the fallback (no key signature) verification path must
|
|
318
|
+
# reject a solution whose derived key is genuinely correct for its counter
|
|
319
|
+
# but does not satisfy the challenge's key_prefix. Previously only
|
|
320
|
+
# derived_key == KDF(counter) was checked, letting a client submit any
|
|
321
|
+
# counter after a single KDF execution and skip the prefix search entirely.
|
|
322
|
+
ch = create_challenge("SHA-256", cost=10, hmac_secret=HMAC_KEY)
|
|
323
|
+
|
|
324
|
+
# Learn the honest KDF output for counter 0 with exactly one hash
|
|
325
|
+
# computation: solve a probe copy of the challenge whose key_prefix is ""
|
|
326
|
+
# (matches immediately, no search).
|
|
327
|
+
probe_params = ChallengeParameters(
|
|
328
|
+
**{**ch.parameters.__dict__, "key_prefix": ""}
|
|
329
|
+
)
|
|
330
|
+
probe_ch = Challenge(parameters=probe_params, signature=None)
|
|
331
|
+
honest = solve_challenge(probe_ch)
|
|
332
|
+
assert honest is not None
|
|
333
|
+
self.assertEqual(honest.counter, 0)
|
|
334
|
+
|
|
335
|
+
# Pick a key_prefix the honest key is guaranteed not to satisfy: a byte
|
|
336
|
+
# can't be both 0x00 and 0xff.
|
|
337
|
+
mismatched_prefix = "ff" if honest.derived_key.startswith("00") else "00"
|
|
338
|
+
ch.parameters.key_prefix = mismatched_prefix
|
|
339
|
+
signed = _sign_challenge_v2(
|
|
340
|
+
DEFAULT_HMAC_ALGORITHM, ch.parameters, None, HMAC_KEY
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
# Submit the honestly-derived key/counter pair (one KDF execution, no
|
|
344
|
+
# prefix search) against the challenge whose signed key_prefix it does
|
|
345
|
+
# not satisfy.
|
|
346
|
+
bad_sol = Solution(counter=honest.counter, derived_key=honest.derived_key)
|
|
347
|
+
payload = Payload(signed, bad_sol).to_base64()
|
|
348
|
+
result = verify_solution(payload, HMAC_KEY)
|
|
349
|
+
self.assertFalse(result.verified)
|
|
350
|
+
self.assertTrue(result.invalid_solution)
|
|
351
|
+
|
|
310
352
|
def test_payload_object(self):
|
|
311
353
|
ch = create_challenge("SHA-256", cost=1, counter=2, hmac_secret=HMAC_KEY)
|
|
312
354
|
sol = solve_challenge(ch)
|
|
@@ -464,5 +506,148 @@ class TestVerifyServerSignature(unittest.TestCase):
|
|
|
464
506
|
self.assertTrue(result.invalid_signature)
|
|
465
507
|
|
|
466
508
|
|
|
509
|
+
class TestVerifyServer(unittest.TestCase):
|
|
510
|
+
URL = "https://sentinel.example.com/v1/verify/signature"
|
|
511
|
+
|
|
512
|
+
def setUp(self):
|
|
513
|
+
self._sleep_calls: list[float] = []
|
|
514
|
+
self._sleep_patcher = unittest.mock.patch(
|
|
515
|
+
"altcha.v2.time.sleep", side_effect=self._sleep_calls.append
|
|
516
|
+
)
|
|
517
|
+
self._sleep_patcher.start()
|
|
518
|
+
self.addCleanup(self._sleep_patcher.stop)
|
|
519
|
+
|
|
520
|
+
def test_success(self):
|
|
521
|
+
result_data = {
|
|
522
|
+
"apiKey": "key_1",
|
|
523
|
+
"verificationData": {"verified": True},
|
|
524
|
+
"verified": True,
|
|
525
|
+
}
|
|
526
|
+
calls = []
|
|
527
|
+
|
|
528
|
+
def post(url, data, headers, timeout):
|
|
529
|
+
calls.append((url, data, headers, timeout))
|
|
530
|
+
return 200, json.dumps(result_data).encode()
|
|
531
|
+
|
|
532
|
+
result = verify_server("payload", self.URL, http_post=post)
|
|
533
|
+
self.assertTrue(result.verified)
|
|
534
|
+
self.assertEqual(result.api_key, "key_1")
|
|
535
|
+
self.assertEqual(result.verification_data, {"verified": True})
|
|
536
|
+
self.assertIsNone(result.reason)
|
|
537
|
+
self.assertEqual(len(calls), 1)
|
|
538
|
+
|
|
539
|
+
def test_secret_included_in_body(self):
|
|
540
|
+
calls = []
|
|
541
|
+
|
|
542
|
+
def post(url, data, headers, timeout):
|
|
543
|
+
calls.append(data)
|
|
544
|
+
return 200, json.dumps({"verified": True}).encode()
|
|
545
|
+
|
|
546
|
+
verify_server("payload", self.URL, secret="sec_123", http_post=post)
|
|
547
|
+
self.assertEqual(
|
|
548
|
+
json.loads(calls[0]), {"payload": "payload", "secret": "sec_123"}
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
def test_secret_omitted_when_not_given(self):
|
|
552
|
+
calls = []
|
|
553
|
+
|
|
554
|
+
def post(url, data, headers, timeout):
|
|
555
|
+
calls.append(data)
|
|
556
|
+
return 200, json.dumps({"verified": True}).encode()
|
|
557
|
+
|
|
558
|
+
verify_server("payload", self.URL, http_post=post)
|
|
559
|
+
self.assertEqual(json.loads(calls[0]), {"payload": "payload"})
|
|
560
|
+
|
|
561
|
+
def test_400_is_terminal_not_retried(self):
|
|
562
|
+
calls = []
|
|
563
|
+
|
|
564
|
+
def post(url, data, headers, timeout):
|
|
565
|
+
calls.append(1)
|
|
566
|
+
return 400, json.dumps({"error": "INVALID_PAYLOAD"}).encode()
|
|
567
|
+
|
|
568
|
+
result = verify_server("payload", self.URL, retries=3, http_post=post)
|
|
569
|
+
self.assertFalse(result.verified)
|
|
570
|
+
self.assertEqual(result.reason, "INVALID_PAYLOAD")
|
|
571
|
+
self.assertEqual(len(calls), 1)
|
|
572
|
+
|
|
573
|
+
def test_network_error_retried_then_fails(self):
|
|
574
|
+
calls = []
|
|
575
|
+
|
|
576
|
+
def post(url, data, headers, timeout):
|
|
577
|
+
calls.append(1)
|
|
578
|
+
raise OSError("fetch failed")
|
|
579
|
+
|
|
580
|
+
result = verify_server("payload", self.URL, retries=2, http_post=post)
|
|
581
|
+
self.assertFalse(result.verified)
|
|
582
|
+
self.assertEqual(result.reason, "fetch failed")
|
|
583
|
+
self.assertEqual(len(calls), 3)
|
|
584
|
+
|
|
585
|
+
def test_network_error_then_success(self):
|
|
586
|
+
calls = []
|
|
587
|
+
|
|
588
|
+
def post(url, data, headers, timeout):
|
|
589
|
+
calls.append(1)
|
|
590
|
+
if len(calls) < 2:
|
|
591
|
+
raise OSError("fetch failed")
|
|
592
|
+
return 200, json.dumps({"verified": True}).encode()
|
|
593
|
+
|
|
594
|
+
result = verify_server("payload", self.URL, retries=2, http_post=post)
|
|
595
|
+
self.assertTrue(result.verified)
|
|
596
|
+
self.assertEqual(len(calls), 2)
|
|
597
|
+
|
|
598
|
+
def test_server_signature_payload_serialized(self):
|
|
599
|
+
payload = ServerSignaturePayload(
|
|
600
|
+
algorithm="SHA-256",
|
|
601
|
+
signature="sig",
|
|
602
|
+
verification_data="verified=true",
|
|
603
|
+
verified=True,
|
|
604
|
+
)
|
|
605
|
+
calls = []
|
|
606
|
+
|
|
607
|
+
def post(url, data, headers, timeout):
|
|
608
|
+
calls.append(data)
|
|
609
|
+
return 200, json.dumps({"verified": True}).encode()
|
|
610
|
+
|
|
611
|
+
verify_server(payload, self.URL, http_post=post)
|
|
612
|
+
sent = json.loads(calls[0])
|
|
613
|
+
self.assertEqual(
|
|
614
|
+
sent["payload"],
|
|
615
|
+
{
|
|
616
|
+
"algorithm": "SHA-256",
|
|
617
|
+
"signature": "sig",
|
|
618
|
+
"verificationData": "verified=true",
|
|
619
|
+
"verified": True,
|
|
620
|
+
},
|
|
621
|
+
)
|
|
622
|
+
|
|
623
|
+
def test_fixed_backoff(self):
|
|
624
|
+
def post(url, data, headers, timeout):
|
|
625
|
+
raise OSError("fail")
|
|
626
|
+
|
|
627
|
+
verify_server(
|
|
628
|
+
"payload",
|
|
629
|
+
self.URL,
|
|
630
|
+
retries=2,
|
|
631
|
+
retry_delay=0.5,
|
|
632
|
+
retry_backoff="fixed",
|
|
633
|
+
http_post=post,
|
|
634
|
+
)
|
|
635
|
+
self.assertEqual(self._sleep_calls, [0.5, 0.5])
|
|
636
|
+
|
|
637
|
+
def test_exponential_backoff(self):
|
|
638
|
+
def post(url, data, headers, timeout):
|
|
639
|
+
raise OSError("fail")
|
|
640
|
+
|
|
641
|
+
verify_server(
|
|
642
|
+
"payload",
|
|
643
|
+
self.URL,
|
|
644
|
+
retries=2,
|
|
645
|
+
retry_delay=0.5,
|
|
646
|
+
retry_backoff="exponential",
|
|
647
|
+
http_post=post,
|
|
648
|
+
)
|
|
649
|
+
self.assertEqual(self._sleep_calls, [0.5, 1.0])
|
|
650
|
+
|
|
651
|
+
|
|
467
652
|
if __name__ == "__main__":
|
|
468
653
|
unittest.main()
|
|
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
|