altcha 2.0.2__tar.gz → 2.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: altcha
3
- Version: 2.0.2
3
+ Version: 2.2.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) # True
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) + datetime.timedelta(minutes=10),
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) # True
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) + datetime.timedelta(minutes=10),
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)
@@ -1,4 +1,4 @@
1
- # ruff: noqa: F401
1
+ # ruff: noqa: F401, I001 -- imports are grouped by API version, not sorted
2
2
  # ---------------------------------------------------------------------------
3
3
  # V2 API (main / unprefixed)
4
4
  # ---------------------------------------------------------------------------
@@ -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
@@ -1,14 +1,14 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import base64
4
+ import datetime
3
5
  import hashlib
4
6
  import hmac
5
- import base64
6
7
  import json
7
8
  import secrets
8
9
  import time
9
10
  import urllib.parse
10
11
  from typing import Literal, TypedDict, cast, overload
11
- import datetime
12
12
 
13
13
  # Define algorithms
14
14
  SHA1: Literal["SHA-1"] = "SHA-1"
@@ -153,7 +153,7 @@ class Payload:
153
153
  return base64.b64encode(json.dumps(self.to_dict()).encode()).decode()
154
154
 
155
155
  @classmethod
156
- def from_dict(cls, data: PayloadType) -> "Payload":
156
+ def from_dict(cls, data: PayloadType) -> Payload:
157
157
  """Create a Payload from a dictionary."""
158
158
  return cls(
159
159
  algorithm=cast(AlgoType, data["algorithm"]),
@@ -164,7 +164,7 @@ class Payload:
164
164
  )
165
165
 
166
166
  @classmethod
167
- def from_base64(cls, encoded: str) -> "Payload":
167
+ def from_base64(cls, encoded: str) -> Payload:
168
168
  """Create a Payload from a base64 encoded JSON string."""
169
169
  data = cast(PayloadType, json.loads(base64.b64decode(encoded).decode()))
170
170
  return cls.from_dict(data)
@@ -561,17 +561,18 @@ def verify_solution(
561
561
  except ValueError: # Guard against malformed expires
562
562
  return False, "Altcha payload expired"
563
563
 
564
- options = ChallengeOptions(
565
- algorithm=cast(AlgoType, p["algorithm"]),
566
- hmac_key=hmac_key,
567
- number=cast(int, p["number"]),
568
- salt=cast(str, p["salt"]),
569
- )
570
- expected_challenge = create_challenge(options)
564
+ # Hash the submitted salt verbatim (plus the splicing delimiter). Re-parsing
565
+ # and re-serializing its params would collapse duplicate keys differently
566
+ # from the expiry check above, letting a forged salt pass as unexpired.
567
+ algorithm = cast(AlgoType, p["algorithm"])
568
+ salt = cast(str, p["salt"])
569
+ if not salt.endswith("&"):
570
+ salt += "&"
571
+ expected_challenge = hash_hex(algorithm, (salt + str(p["number"])).encode())
572
+ expected_signature = hmac_hex(algorithm, expected_challenge.encode(), hmac_key)
571
573
 
572
574
  return (
573
- expected_challenge.challenge == p["challenge"]
574
- and expected_challenge.signature == p["signature"]
575
+ expected_challenge == p["challenge"] and expected_signature == p["signature"]
575
576
  ), None
576
577
 
577
578
 
@@ -770,8 +771,7 @@ def solve_challenge(
770
771
  max_number = 1000000
771
772
  challenge_str = challenge
772
773
 
773
- if start < 0:
774
- start = 0
774
+ start = max(start, 0)
775
775
 
776
776
  start_time = time.time()
777
777
  for n in range(start, max_number + 1):
@@ -1,16 +1,18 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import base64
4
+ import datetime
3
5
  import hashlib
4
6
  import hmac as _hmac_module
5
- import base64
6
7
  import json
7
8
  import re
8
9
  import secrets
9
10
  import struct
10
11
  import time
12
+ import urllib.error
11
13
  import urllib.parse
14
+ import urllib.request
12
15
  from typing import Callable, Literal
13
- import datetime
14
16
 
15
17
  # ---------------------------------------------------------------------------
16
18
  # Types
@@ -366,8 +368,10 @@ def derive_key_scrypt(
366
368
 
367
369
 
368
370
  try:
369
- from argon2.low_level import Type as _Argon2Type # type: ignore
370
- from argon2.low_level import hash_secret_raw as _argon2_hash_secret_raw # type: ignore
371
+ from argon2.low_level import ( # type: ignore
372
+ Type as _Argon2Type,
373
+ hash_secret_raw as _argon2_hash_secret_raw,
374
+ )
371
375
 
372
376
  def derive_key_argon2id(
373
377
  parameters: ChallengeParameters, salt: bytes, password: bytes
@@ -663,7 +667,8 @@ def verify_solution(
663
667
  verified=valid,
664
668
  )
665
669
 
666
- # 4b. Slow path: re-derive the key from the counter and compare.
670
+ # 4b. Slow path: re-derive the key from the counter and compare, and
671
+ # require it to satisfy the signed key prefix.
667
672
  if derive_key is None:
668
673
  derive_key = _select_derive_key(params.algorithm)
669
674
 
@@ -672,7 +677,9 @@ def verify_solution(
672
677
  password = _make_password(nonce_bytes, solution.counter)
673
678
  recomputed = derive_key(params, salt_bytes, password)
674
679
  recomputed_hex = recomputed.hex()
675
- invalid = not _constant_time_equal(recomputed_hex, solution.derived_key)
680
+ key_matches = _constant_time_equal(recomputed_hex, solution.derived_key)
681
+ prefix_matches = recomputed_hex.startswith(params.key_prefix)
682
+ invalid = not (key_matches and prefix_matches)
676
683
 
677
684
  return VerifySolutionResult(
678
685
  expired=False,
@@ -714,6 +721,14 @@ class ServerSignaturePayload:
714
721
  self.verification_data = verification_data
715
722
  self.verified = verified
716
723
 
724
+ def to_dict(self) -> dict:
725
+ return {
726
+ "algorithm": self.algorithm,
727
+ "signature": self.signature,
728
+ "verificationData": self.verification_data,
729
+ "verified": self.verified,
730
+ }
731
+
717
732
  @classmethod
718
733
  def from_dict(cls, d: dict) -> ServerSignaturePayload:
719
734
  return cls(
@@ -793,7 +808,7 @@ def parse_verification_data(
793
808
  else:
794
809
  result[key] = value.strip()
795
810
  return result
796
- except Exception:
811
+ except (ValueError, TypeError, AttributeError):
797
812
  return None
798
813
 
799
814
 
@@ -859,3 +874,141 @@ def verify_server_signature(
859
874
  verified=verified,
860
875
  verification_data=verification_data if verified else None,
861
876
  )
877
+
878
+
879
+ # ---------------------------------------------------------------------------
880
+ # Remote (Sentinel API) verification
881
+ # ---------------------------------------------------------------------------
882
+
883
+
884
+ class VerifyServerResult:
885
+ """
886
+ Result of a remote Sentinel verification via :func:`verify_server`.
887
+
888
+ Attributes:
889
+ verified: ``True`` if Sentinel confirmed the payload is valid.
890
+ reason: Failure reason (e.g. an error code or exception message), if any.
891
+ api_key: The API key associated with the payload, if returned.
892
+ verification_data: Parsed verification data, if returned.
893
+ """
894
+
895
+ def __init__(
896
+ self,
897
+ verified: bool,
898
+ reason: str | None = None,
899
+ api_key: str | None = None,
900
+ verification_data: dict | None = None,
901
+ ):
902
+ self.verified = verified
903
+ self.reason = reason
904
+ self.api_key = api_key
905
+ self.verification_data = verification_data
906
+
907
+ @classmethod
908
+ def from_dict(cls, d: dict) -> VerifyServerResult:
909
+ return cls(
910
+ verified=bool(d.get("verified", False)),
911
+ reason=d.get("reason"),
912
+ api_key=d.get("apiKey"),
913
+ verification_data=d.get("verificationData"),
914
+ )
915
+
916
+
917
+ def _default_http_post(
918
+ url: str, data: bytes, headers: dict[str, str], timeout: float
919
+ ) -> tuple[int, bytes]:
920
+ """Minimal stdlib HTTP POST, used as the default transport for :func:`verify_server`."""
921
+ req = urllib.request.Request(url, data=data, method="POST", headers=headers)
922
+ try:
923
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
924
+ return resp.status, resp.read()
925
+ except urllib.error.HTTPError as e:
926
+ return e.code, e.read()
927
+
928
+
929
+ def _sleep_backoff(attempt: int, delay: float, backoff: str) -> None:
930
+ wait = delay if backoff == "fixed" else delay * (2**attempt)
931
+ time.sleep(wait)
932
+
933
+
934
+ def verify_server(
935
+ payload: str | ServerSignaturePayload | dict,
936
+ url: str,
937
+ secret: str | None = None,
938
+ *,
939
+ headers: dict[str, str] | None = None,
940
+ timeout: float = 10.0,
941
+ retries: int = 0,
942
+ retry_delay: float = 0.3,
943
+ retry_backoff: Literal["fixed", "exponential"] = "exponential",
944
+ http_post: Callable[[str, bytes, dict[str, str], float], tuple[int, bytes]]
945
+ | None = None,
946
+ ) -> VerifyServerResult:
947
+ """
948
+ Verify a payload remotely via the ALTCHA Sentinel ``/v1/verify/signature`` API.
949
+
950
+ Instead of verifying the HMAC signature locally (see :func:`verify_server_signature`),
951
+ this POSTs the payload to Sentinel and trusts its response. Avoids managing the HMAC
952
+ secret on your server, at the cost of a network round-trip.
953
+
954
+ Args:
955
+ payload: The payload to verify, as received from ``POST /v1/verify`` — a base64
956
+ string, a :class:`ServerSignaturePayload`, or an already-decoded dict.
957
+ url: Full URL of the Sentinel ``/v1/verify/signature`` endpoint.
958
+ secret: API key secret. If given, Sentinel checks it against the payload's API key.
959
+ headers: Additional headers to send with the request.
960
+ timeout: Per-attempt request timeout in seconds. Defaults to ``10``.
961
+ retries: Number of retry attempts after the first try. Defaults to ``0``.
962
+ retry_delay: Base delay in seconds between retries. Defaults to ``0.3``.
963
+ retry_backoff: ``'fixed'`` or ``'exponential'`` backoff applied to *retry_delay*.
964
+ http_post: Transport override — ``(url, body, headers, timeout) -> (status, body)``.
965
+ Defaults to a stdlib ``urllib.request``-based implementation. Swap in another
966
+ HTTP client (e.g. ``requests``, ``httpx``) here if preferred.
967
+
968
+ Returns:
969
+ A :class:`VerifyServerResult` describing the outcome. Failures (HTTP errors, network
970
+ errors, or a negative Sentinel verdict) are reported via ``verified=False`` with a
971
+ ``reason``, never raised as exceptions.
972
+ """
973
+ if isinstance(payload, ServerSignaturePayload):
974
+ payload_value: str | dict = payload.to_dict()
975
+ else:
976
+ payload_value = payload
977
+
978
+ body: dict = {"payload": payload_value}
979
+ if secret is not None:
980
+ body["secret"] = secret
981
+ data = json.dumps(body).encode()
982
+
983
+ req_headers = {"Content-Type": "application/json", **(headers or {})}
984
+ post = http_post or _default_http_post
985
+
986
+ attempts = retries + 1
987
+ for attempt in range(attempts):
988
+ try:
989
+ status, resp_body = post(url, data, req_headers, timeout)
990
+ except Exception as e: # noqa: BLE001 -- custom transports may raise anything
991
+ if attempt >= attempts - 1:
992
+ return VerifyServerResult(
993
+ verified=False, reason=str(e) or type(e).__name__
994
+ )
995
+ _sleep_backoff(attempt, retry_delay, retry_backoff)
996
+ continue
997
+
998
+ if status == 400:
999
+ try:
1000
+ err_data = json.loads(resp_body.decode())
1001
+ except ValueError:
1002
+ err_data = None
1003
+ reason = (err_data or {}).get("error") or f"HTTP_{status}"
1004
+ return VerifyServerResult(verified=False, reason=reason)
1005
+
1006
+ if not (200 <= status < 300):
1007
+ if attempt >= attempts - 1:
1008
+ return VerifyServerResult(verified=False, reason=f"HTTP_{status}")
1009
+ _sleep_backoff(attempt, retry_delay, retry_backoff)
1010
+ continue
1011
+
1012
+ return VerifyServerResult.from_dict(json.loads(resp_body.decode()))
1013
+
1014
+ 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.2
3
+ Version: 2.2.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) # True
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) + datetime.timedelta(minutes=10),
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)
@@ -1,10 +1,15 @@
1
- from setuptools import setup, find_packages # type: ignore[import-untyped]
1
+ from pathlib import Path
2
+
3
+ from setuptools import ( # type: ignore[import-not-found, import-untyped, unused-ignore]
4
+ find_packages,
5
+ setup,
6
+ )
2
7
 
3
8
  setup(
4
9
  name="altcha",
5
- version="2.0.2",
10
+ version="2.2.0",
6
11
  description="A library for creating and verifying challenges for ALTCHA.",
7
- long_description=open("README.md").read(),
12
+ long_description=Path("README.md").read_text(encoding="utf-8"),
8
13
  long_description_content_type="text/markdown",
9
14
  author="Daniel Regeci",
10
15
  author_email="536331+ovx@users.noreply.github.com",
@@ -1,10 +1,12 @@
1
+ import base64
1
2
  import datetime
2
3
  import hashlib
3
4
  import hmac
5
+ import json
4
6
  import time
5
7
  import unittest
6
- import base64
7
- import json
8
+ from collections.abc import Callable
9
+
8
10
  from altcha.altcha import (
9
11
  ChallengeOptions,
10
12
  Payload,
@@ -277,6 +279,44 @@ class TestALTCHA(unittest.TestCase):
277
279
  result, _ = verify_solution(payload_encoded, self.hmac_key, check_expires=False)
278
280
  self.assertFalse(result)
279
281
 
282
+ def _expired_payload_with_salt(
283
+ self, salt_for: Callable[[str, str], str]
284
+ ) -> Payload:
285
+ options = ChallengeOptions(
286
+ algorithm="SHA-256",
287
+ max_number=1000,
288
+ hmac_key=self.hmac_key,
289
+ expires=datetime.datetime.now(datetime.timezone.utc)
290
+ - datetime.timedelta(minutes=1),
291
+ number=123,
292
+ )
293
+ challenge = create_challenge(options)
294
+ base, query = challenge.salt.split("?", 1)
295
+ original = query.split("expires=")[1].rstrip("&")
296
+ return Payload(
297
+ algorithm="SHA-256",
298
+ challenge=challenge.challenge,
299
+ number=123,
300
+ salt=salt_for(base, original),
301
+ signature=challenge.signature,
302
+ )
303
+
304
+ def test_verify_solution_duplicate_expires_rejected(self):
305
+ future = str(int(time.time()) + 3600)
306
+ payload = self._expired_payload_with_salt(
307
+ lambda base, orig: f"{base}?expires={future}&expires={orig}&"
308
+ )
309
+ result, _ = verify_solution(payload, self.hmac_key, check_expires=True)
310
+ self.assertFalse(result)
311
+
312
+ def test_verify_solution_reencoded_salt_rejected(self):
313
+ # A percent-encoded variant of the issued salt must not verify.
314
+ payload = self._expired_payload_with_salt(
315
+ lambda base, orig: f"{base}?expires=%{ord(orig[0]):02X}{orig[1:]}&"
316
+ )
317
+ result, _ = verify_solution(payload, self.hmac_key, check_expires=False)
318
+ self.assertFalse(result)
319
+
280
320
  def test_valid_signature(self):
281
321
  expire_time = int(time.time()) + 600 # 10 minutes from now
282
322
  verification_data = (
@@ -400,13 +440,13 @@ class TestALTCHA(unittest.TestCase):
400
440
  self.assertEqual(solution.number, 100, "Solution be 100")
401
441
 
402
442
  def test_hash_hex(self):
403
- result = hash_hex("SHA-256", "testdata".encode())
404
- self.assertEqual(result, hashlib.sha256("testdata".encode()).hexdigest())
443
+ result = hash_hex("SHA-256", b"testdata")
444
+ self.assertEqual(result, hashlib.sha256(b"testdata").hexdigest())
405
445
 
406
446
  def test_hmac_hex(self):
407
- result = hmac_hex("SHA-256", "testdata".encode(), self.hmac_key)
447
+ result = hmac_hex("SHA-256", b"testdata", self.hmac_key)
408
448
  expected = hmac.new(
409
- self.hmac_key.encode(), "testdata".encode(), hashlib.sha256
449
+ self.hmac_key.encode(), b"testdata", hashlib.sha256
410
450
  ).hexdigest()
411
451
  self.assertEqual(result, expected)
412
452
 
@@ -1,8 +1,13 @@
1
1
  import datetime
2
+ import json
2
3
  import struct
3
4
  import unittest
5
+ import unittest.mock
6
+ from typing import cast
4
7
 
5
8
  from altcha.v2 import (
9
+ DEFAULT_HMAC_ALGORITHM,
10
+ Challenge,
6
11
  ChallengeParameters,
7
12
  Payload,
8
13
  ServerSignaturePayload,
@@ -10,17 +15,18 @@ from altcha.v2 import (
10
15
  _canonical_json,
11
16
  _hmac_v2,
12
17
  _make_password,
18
+ _sign_challenge_v2,
13
19
  create_challenge,
14
20
  derive_key_pbkdf2,
15
21
  derive_key_scrypt,
16
22
  derive_key_sha,
17
23
  parse_verification_data,
18
24
  solve_challenge,
25
+ verify_server,
19
26
  verify_server_signature,
20
27
  verify_solution,
21
28
  )
22
29
 
23
-
24
30
  HMAC_KEY = "test-secret"
25
31
 
26
32
 
@@ -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)
@@ -382,14 +424,12 @@ class TestParseVerificationData(unittest.TestCase):
382
424
  assert result is not None
383
425
  self.assertEqual(result["classification"], "GOOD")
384
426
 
385
- def test_invalid_returns_none(self):
386
- # parse_qsl is very permissive, so simulate a truly broken input
387
- result = (
388
- parse_verification_data.__wrapped__("")
389
- if hasattr(parse_verification_data, "__wrapped__")
390
- else parse_verification_data("")
391
- )
392
- self.assertIsNotNone(result) # empty string is valid (empty dict)
427
+ def test_empty_string_returns_empty_dict(self):
428
+ self.assertEqual(parse_verification_data(""), {})
429
+
430
+ def test_unparseable_input_returns_none(self):
431
+ # bytes parse into bytes pairs, which the str-based coercion rejects
432
+ self.assertIsNone(parse_verification_data(cast(str, b"verified=true")))
393
433
 
394
434
 
395
435
  class TestVerifyServerSignature(unittest.TestCase):
@@ -464,5 +504,148 @@ class TestVerifyServerSignature(unittest.TestCase):
464
504
  self.assertTrue(result.invalid_signature)
465
505
 
466
506
 
507
+ class TestVerifyServer(unittest.TestCase):
508
+ URL = "https://sentinel.example.com/v1/verify/signature"
509
+
510
+ def setUp(self):
511
+ self._sleep_calls: list[float] = []
512
+ self._sleep_patcher = unittest.mock.patch(
513
+ "altcha.v2.time.sleep", side_effect=self._sleep_calls.append
514
+ )
515
+ self._sleep_patcher.start()
516
+ self.addCleanup(self._sleep_patcher.stop)
517
+
518
+ def test_success(self):
519
+ result_data = {
520
+ "apiKey": "key_1",
521
+ "verificationData": {"verified": True},
522
+ "verified": True,
523
+ }
524
+ calls = []
525
+
526
+ def post(url, data, headers, timeout):
527
+ calls.append((url, data, headers, timeout))
528
+ return 200, json.dumps(result_data).encode()
529
+
530
+ result = verify_server("payload", self.URL, http_post=post)
531
+ self.assertTrue(result.verified)
532
+ self.assertEqual(result.api_key, "key_1")
533
+ self.assertEqual(result.verification_data, {"verified": True})
534
+ self.assertIsNone(result.reason)
535
+ self.assertEqual(len(calls), 1)
536
+
537
+ def test_secret_included_in_body(self):
538
+ calls = []
539
+
540
+ def post(url, data, headers, timeout):
541
+ calls.append(data)
542
+ return 200, json.dumps({"verified": True}).encode()
543
+
544
+ verify_server("payload", self.URL, secret="sec_123", http_post=post)
545
+ self.assertEqual(
546
+ json.loads(calls[0]), {"payload": "payload", "secret": "sec_123"}
547
+ )
548
+
549
+ def test_secret_omitted_when_not_given(self):
550
+ calls = []
551
+
552
+ def post(url, data, headers, timeout):
553
+ calls.append(data)
554
+ return 200, json.dumps({"verified": True}).encode()
555
+
556
+ verify_server("payload", self.URL, http_post=post)
557
+ self.assertEqual(json.loads(calls[0]), {"payload": "payload"})
558
+
559
+ def test_400_is_terminal_not_retried(self):
560
+ calls = []
561
+
562
+ def post(url, data, headers, timeout):
563
+ calls.append(1)
564
+ return 400, json.dumps({"error": "INVALID_PAYLOAD"}).encode()
565
+
566
+ result = verify_server("payload", self.URL, retries=3, http_post=post)
567
+ self.assertFalse(result.verified)
568
+ self.assertEqual(result.reason, "INVALID_PAYLOAD")
569
+ self.assertEqual(len(calls), 1)
570
+
571
+ def test_network_error_retried_then_fails(self):
572
+ calls = []
573
+
574
+ def post(url, data, headers, timeout):
575
+ calls.append(1)
576
+ raise OSError("fetch failed")
577
+
578
+ result = verify_server("payload", self.URL, retries=2, http_post=post)
579
+ self.assertFalse(result.verified)
580
+ self.assertEqual(result.reason, "fetch failed")
581
+ self.assertEqual(len(calls), 3)
582
+
583
+ def test_network_error_then_success(self):
584
+ calls = []
585
+
586
+ def post(url, data, headers, timeout):
587
+ calls.append(1)
588
+ if len(calls) < 2:
589
+ raise OSError("fetch failed")
590
+ return 200, json.dumps({"verified": True}).encode()
591
+
592
+ result = verify_server("payload", self.URL, retries=2, http_post=post)
593
+ self.assertTrue(result.verified)
594
+ self.assertEqual(len(calls), 2)
595
+
596
+ def test_server_signature_payload_serialized(self):
597
+ payload = ServerSignaturePayload(
598
+ algorithm="SHA-256",
599
+ signature="sig",
600
+ verification_data="verified=true",
601
+ verified=True,
602
+ )
603
+ calls = []
604
+
605
+ def post(url, data, headers, timeout):
606
+ calls.append(data)
607
+ return 200, json.dumps({"verified": True}).encode()
608
+
609
+ verify_server(payload, self.URL, http_post=post)
610
+ sent = json.loads(calls[0])
611
+ self.assertEqual(
612
+ sent["payload"],
613
+ {
614
+ "algorithm": "SHA-256",
615
+ "signature": "sig",
616
+ "verificationData": "verified=true",
617
+ "verified": True,
618
+ },
619
+ )
620
+
621
+ def test_fixed_backoff(self):
622
+ def post(url, data, headers, timeout):
623
+ raise OSError("fail")
624
+
625
+ verify_server(
626
+ "payload",
627
+ self.URL,
628
+ retries=2,
629
+ retry_delay=0.5,
630
+ retry_backoff="fixed",
631
+ http_post=post,
632
+ )
633
+ self.assertEqual(self._sleep_calls, [0.5, 0.5])
634
+
635
+ def test_exponential_backoff(self):
636
+ def post(url, data, headers, timeout):
637
+ raise OSError("fail")
638
+
639
+ verify_server(
640
+ "payload",
641
+ self.URL,
642
+ retries=2,
643
+ retry_delay=0.5,
644
+ retry_backoff="exponential",
645
+ http_post=post,
646
+ )
647
+ self.assertEqual(self._sleep_calls, [0.5, 1.0])
648
+
649
+
467
650
  if __name__ == "__main__":
468
651
  unittest.main()
File without changes
File without changes
@@ -6,27 +6,27 @@ from ``altcha.altcha`` continues to work unchanged.
6
6
  """
7
7
 
8
8
  from .v1 import (
9
+ DEFAULT_ALGORITHM as DEFAULT_ALGORITHM,
10
+ DEFAULT_MAX_NUMBER as DEFAULT_MAX_NUMBER,
11
+ DEFAULT_SALT_LENGTH as DEFAULT_SALT_LENGTH,
12
+ SHA1 as SHA1,
13
+ SHA256 as SHA256,
14
+ SHA512 as SHA512,
9
15
  AlgoType as AlgoType,
10
- ChallengeOptions as ChallengeOptions,
11
16
  Challenge as Challenge,
17
+ ChallengeOptions as ChallengeOptions,
12
18
  Payload as Payload,
13
19
  PayloadType as PayloadType,
14
20
  ServerSignaturePayload as ServerSignaturePayload,
15
21
  ServerSignatureVerificationData as ServerSignatureVerificationData,
16
22
  Solution as Solution,
17
- DEFAULT_MAX_NUMBER as DEFAULT_MAX_NUMBER,
18
- DEFAULT_SALT_LENGTH as DEFAULT_SALT_LENGTH,
19
- DEFAULT_ALGORITHM as DEFAULT_ALGORITHM,
20
- SHA1 as SHA1,
21
- SHA256 as SHA256,
22
- SHA512 as SHA512,
23
- hash_hex as hash_hex,
24
- hash_algorithm as hash_algorithm,
25
- hmac_hex as hmac_hex,
26
23
  create_challenge as create_challenge,
27
- verify_solution as verify_solution,
28
24
  extract_params as extract_params,
25
+ hash_algorithm as hash_algorithm,
26
+ hash_hex as hash_hex,
27
+ hmac_hex as hmac_hex,
28
+ solve_challenge as solve_challenge,
29
29
  verify_fields_hash as verify_fields_hash,
30
30
  verify_server_signature as verify_server_signature,
31
- solve_challenge as solve_challenge,
31
+ verify_solution as verify_solution,
32
32
  )
File without changes
File without changes