altcha 2.3.0__tar.gz → 2.4.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.3.0 → altcha-2.4.0}/CHANGELOG.md +25 -0
- {altcha-2.3.0/altcha.egg-info → altcha-2.4.0}/PKG-INFO +116 -11
- {altcha-2.3.0 → altcha-2.4.0}/README.md +115 -10
- {altcha-2.3.0 → altcha-2.4.0}/altcha/v2.py +101 -32
- {altcha-2.3.0 → altcha-2.4.0/altcha.egg-info}/PKG-INFO +116 -11
- {altcha-2.3.0 → altcha-2.4.0}/setup.py +1 -1
- {altcha-2.3.0 → altcha-2.4.0}/tests/test_altcha_v2.py +102 -2
- {altcha-2.3.0 → altcha-2.4.0}/LICENSE +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/MANIFEST.in +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/altcha/__init__.py +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/altcha/altcha.py +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/altcha/py.typed +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/altcha/v1.py +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/altcha.egg-info/SOURCES.txt +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/altcha.egg-info/dependency_links.txt +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/altcha.egg-info/top_level.txt +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/setup.cfg +0 -0
- {altcha-2.3.0 → altcha-2.4.0}/tests/test_altcha.py +0 -0
|
@@ -4,6 +4,31 @@ All notable changes to this project are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
6
6
|
|
|
7
|
+
## [2.4.0] - 2026-11-17
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `verify_server` supports Sentinel v2's `POST /v2/verify/signature`. Pass the ID and
|
|
12
|
+
secret of a `restricted` or `full` API key as `api_key` and `secret`: they are sent as
|
|
13
|
+
HTTP Basic credentials and `secret` is left out of the body. `api_key` without `secret`
|
|
14
|
+
raises `ValueError`. Sentinel v1 (`/v1/verify/signature`) works as before when `api_key`
|
|
15
|
+
is omitted.
|
|
16
|
+
- `ServerSignaturePayload` carries the optional `apiKey` and `id` fields (`api_key`, `id`)
|
|
17
|
+
and keeps them in `to_dict`, so a payload object passed to `verify_server` still names
|
|
18
|
+
its signing key.
|
|
19
|
+
|
|
20
|
+
### Changed
|
|
21
|
+
|
|
22
|
+
- `verify_server` no longer retries `4xx` responses (e.g. `401`/`403` for missing or wrong
|
|
23
|
+
credentials, `429`); they return `verified=False` at once. For error responses, `reason`
|
|
24
|
+
is the body's `code`, else its `error`, else `HTTP_<status>`; `5xx` responses that
|
|
25
|
+
exhaust the retries report it too (was always `HTTP_<status>`).
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
|
|
29
|
+
- `verify_server` returns `reason='INVALID_RESPONSE'` (after retrying) instead of raising
|
|
30
|
+
when a `2xx` response body is not a JSON object.
|
|
31
|
+
|
|
7
32
|
## [2.3.0] - 2026-10-04
|
|
8
33
|
|
|
9
34
|
Aligns the v2 API (`altcha.v2`) with the reference JavaScript implementation
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: altcha
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.4.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
|
|
@@ -254,17 +254,99 @@ Returns `VerifySolutionResult` with fields:
|
|
|
254
254
|
|
|
255
255
|
#### `verify_fields_hash(form_data, fields, fields_hash, algorithm) → bool`
|
|
256
256
|
|
|
257
|
-
Verifies the hash of specific form fields.
|
|
257
|
+
Verifies the hash of specific form fields: the hex hash (`algorithm`, e.g. `'SHA-256'`) of
|
|
258
|
+
the values of `fields` in `form_data`, joined with `\n`, must equal `fields_hash`.
|
|
258
259
|
|
|
259
|
-
#### `verify_server_signature(payload,
|
|
260
|
+
#### `verify_server_signature(payload, hmac_secret, *, hmac_algorithm) → VerifyServerSignatureResult`
|
|
260
261
|
|
|
261
|
-
Verifies an ALTCHA server signature.
|
|
262
|
+
Verifies an ALTCHA server signature locally, e.g. the `payload` of Sentinel's
|
|
263
|
+
`POST /v2/verify` (or `/v1/verify`) response, with the secret of the API key that signed
|
|
264
|
+
it. Sentinel v1 and v2 sign the same way, so this works for both. To have Sentinel check
|
|
265
|
+
the payload instead, use `verify_server` (below).
|
|
262
266
|
|
|
263
|
-
|
|
267
|
+
```python
|
|
268
|
+
from altcha import verify_fields_hash, verify_server_signature
|
|
269
|
+
|
|
270
|
+
result = verify_server_signature(payload, API_KEY_SECRET)
|
|
271
|
+
|
|
272
|
+
if result.verified:
|
|
273
|
+
data = result.verification_data
|
|
274
|
+
# Detect tampering with the submitted form fields
|
|
275
|
+
if data.get("fields") and not verify_fields_hash(
|
|
276
|
+
form_data, data["fields"], data["fieldsHash"], "SHA-256"
|
|
277
|
+
):
|
|
278
|
+
...
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
| Parameter | Type | Default | Description |
|
|
282
|
+
|---|---|---|---|
|
|
283
|
+
| `payload` | `str` \| `ServerSignaturePayload` | — | Base64-encoded JSON string or `ServerSignaturePayload` object. Its `algorithm` (hash of `verificationData`) must be `'SHA-1'`, `'SHA-256'`, `'SHA-384'` or `'SHA-512'`. |
|
|
284
|
+
| `hmac_secret` | `str` \| `bytes` | — | Secret used to verify the HMAC signature (the API key secret for Sentinel). Raises `ValueError` if empty. |
|
|
285
|
+
| `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
|
|
286
|
+
|
|
287
|
+
Returns `VerifyServerSignatureResult` with fields:
|
|
264
288
|
|
|
265
|
-
|
|
289
|
+
| Field | Type | Description |
|
|
290
|
+
|---|---|---|
|
|
291
|
+
| `verified` | `bool` | `True` if the signature is valid, the payload has not expired, and `verified` is `true` in both the payload and the signed verification data. |
|
|
292
|
+
| `expired` | `bool` | `True` if the signed `expire` is in the past. |
|
|
293
|
+
| `invalid_signature` | `bool` | `True` if the signature does not match, or the payload is malformed. |
|
|
294
|
+
| `invalid_solution` | `bool` | `True` if `verified` is not `true` in the payload or in the signed verification data. |
|
|
295
|
+
| `time` | `float` | Time taken for verification in milliseconds. |
|
|
296
|
+
| `verification_data` | `dict \| None` | The signed verification data, parsed with `parse_verification_data`; `None` unless `verified`. |
|
|
297
|
+
|
|
298
|
+
`parse_verification_data(data)` turns the URL-encoded verification data into a flat dict:
|
|
299
|
+
|
|
300
|
+
- Keys stay as signed, e.g. `data["challenge.algorithm"]` and `data["device.edk"]`
|
|
301
|
+
(`verify_server` returns these nested instead).
|
|
302
|
+
- `'true'`/`'false'` become `bool`, all-digit values `int` (including e.g. a
|
|
303
|
+
`params.zip` of `01234`, which becomes `1234`), and `digits.digits` values `float`.
|
|
304
|
+
- `fields` and `reasons` become lists.
|
|
305
|
+
- Keys with empty values are left out.
|
|
306
|
+
|
|
307
|
+
Unlike Sentinel v2's `/v2/verify/signature` (via `verify_server`), local verification does
|
|
308
|
+
not prevent reuse: a valid payload verifies again until `expire`. Reject repeated `id`s
|
|
309
|
+
yourself if that matters.
|
|
310
|
+
|
|
311
|
+
#### `verify_server(payload, url, secret, *, api_key, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
|
|
312
|
+
|
|
313
|
+
Verifies a payload remotely via the ALTCHA Sentinel verify signature API, instead of
|
|
266
314
|
checking the HMAC signature locally. Avoids managing the HMAC secret on your server, at the
|
|
267
|
-
cost of a network round-trip.
|
|
315
|
+
cost of a network round-trip. Both Sentinel v2 (`POST /v2/verify/signature`) and Sentinel v1
|
|
316
|
+
(`POST /v1/verify/signature`) are supported; they differ in how the request is authenticated.
|
|
317
|
+
|
|
318
|
+
##### Sentinel v2
|
|
319
|
+
|
|
320
|
+
```python
|
|
321
|
+
from altcha import verify_server
|
|
322
|
+
|
|
323
|
+
result = verify_server(
|
|
324
|
+
payload, # the payload received from POST /v2/verify
|
|
325
|
+
url="https://sentinel.example.com/v2/verify/signature",
|
|
326
|
+
api_key=SENTINEL_API_KEY, # id of a restricted or full API key (key_...)
|
|
327
|
+
secret=SENTINEL_API_KEY_SECRET, # its secret (sec_...)
|
|
328
|
+
timeout=10,
|
|
329
|
+
retries=2,
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
if result.verified:
|
|
333
|
+
...
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
- `api_key` and `secret` are the ID and secret of a `restricted` or `full` API key of the
|
|
337
|
+
account that owns the payload's (public) API key. They are sent as
|
|
338
|
+
`Authorization: Basic base64(api_key:secret)`; an `Authorization` header in `headers` is
|
|
339
|
+
replaced. `api_key` without `secret` raises `ValueError` before any request is sent.
|
|
340
|
+
- The request body is `{"payload": ...}`; `secret` is not sent in the body (Sentinel v2
|
|
341
|
+
rejects it).
|
|
342
|
+
- Without credentials, Sentinel v2 answers `401` and `reason` is `'API_KEY_REQUIRED'`. A
|
|
343
|
+
payload signed by a key of another account gets `reason='API_KEY_NOT_ALLOWED'`.
|
|
344
|
+
- `verification_data` is the signed verification data as a nested dict, with keys split on
|
|
345
|
+
`.`: `result.verification_data["challenge"]["algorithm"]` (v1's `challengeAlgorithm`),
|
|
346
|
+
`result.verification_data["device"]["edk"]`. `fields` and `reasons` are lists; `id`,
|
|
347
|
+
`fieldsHash`, `device.edk` and `params.*` stay strings.
|
|
348
|
+
|
|
349
|
+
##### Sentinel v1
|
|
268
350
|
|
|
269
351
|
```python
|
|
270
352
|
from altcha import verify_server
|
|
@@ -281,11 +363,20 @@ if result.verified:
|
|
|
281
363
|
...
|
|
282
364
|
```
|
|
283
365
|
|
|
366
|
+
- `/v1/verify/signature` takes no credentials: omit `api_key`. `secret` (the payload's API
|
|
367
|
+
key secret) is optional and sent in the body as `{"payload": ..., "secret": ...}`; Sentinel
|
|
368
|
+
answers `reason='WRONG_API_KEY_SECRET'` when it is not the payload key's secret.
|
|
369
|
+
- This also applies to the `/v1/verify/signature` alias Sentinel v2 serves with
|
|
370
|
+
`[server] v1_compat = true`.
|
|
371
|
+
|
|
372
|
+
##### Parameters
|
|
373
|
+
|
|
284
374
|
| Parameter | Type | Default | Description |
|
|
285
375
|
|---|---|---|---|
|
|
286
376
|
| `payload` | `str` \| `ServerSignaturePayload` \| `dict` | — | The payload to verify. |
|
|
287
|
-
| `url` | `str` | — | Full URL of the Sentinel `/v1/verify/signature`
|
|
288
|
-
| `secret` | `str` | `None` | API key secret
|
|
377
|
+
| `url` | `str` | — | Full URL of the Sentinel endpoint: `/v2/verify/signature` (v2) or `/v1/verify/signature` (v1). |
|
|
378
|
+
| `secret` | `str` | `None` | v2: secret of `api_key`, required with it. v1: API key secret sent in the body and checked against the payload's API key. |
|
|
379
|
+
| `api_key` | `str` | `None` | v2 only: ID of a `restricted` or `full` API key, sent with `secret` as HTTP Basic credentials. |
|
|
289
380
|
| `headers` | `dict` | `None` | Additional headers to send with the request. |
|
|
290
381
|
| `timeout` | `float` | `10` | Per-attempt request timeout in seconds. |
|
|
291
382
|
| `retries` | `int` | `0` | Number of retry attempts after the first try. |
|
|
@@ -293,14 +384,22 @@ if result.verified:
|
|
|
293
384
|
| `retry_backoff` | `str` | `'exponential'` | `'fixed'` or `'exponential'` backoff. |
|
|
294
385
|
| `http_post` | callable | stdlib `urllib` | Transport override: `(url, body, headers, timeout) -> (status, body)`. |
|
|
295
386
|
|
|
387
|
+
##### Errors and retries
|
|
388
|
+
|
|
389
|
+
Failures never raise; they return `verified=False` with a `reason`. `4xx` responses (bad
|
|
390
|
+
payload, missing or wrong credentials, rate limit) are definitive and returned at once.
|
|
391
|
+
Network errors, other error statuses (e.g. `5xx`) and invalid response bodies are retried up
|
|
392
|
+
to `retries` times. For an error response, `reason` is the `code` of Sentinel's error body
|
|
393
|
+
(v2: `{"code", "error", "statusCode"}`), else its `error` (v1), else `'HTTP_<status>'`.
|
|
394
|
+
|
|
296
395
|
Returns `VerifyServerResult` with fields:
|
|
297
396
|
|
|
298
397
|
| Field | Type | Description |
|
|
299
398
|
|---|---|---|
|
|
300
399
|
| `verified` | `bool` | `True` if Sentinel confirmed the payload is valid. |
|
|
301
|
-
| `reason` | `str \| None` |
|
|
400
|
+
| `reason` | `str \| None` | Why verification failed: Sentinel's `reason` (e.g. `'PAYLOAD_ALREADY_USED'`, `'INVALID_PAYLOAD'`, `'API_KEY_NOT_ALLOWED'` (v2), `'WRONG_API_KEY_SECRET'` (v1)), the error code of an HTTP error response, `'INVALID_RESPONSE'`, or a network error message. |
|
|
302
401
|
| `api_key` | `str \| None` | The API key associated with the payload, if returned. |
|
|
303
|
-
| `verification_data` | `dict \| None` |
|
|
402
|
+
| `verification_data` | `dict \| None` | Verification data returned by Sentinel (nested dict), if returned. |
|
|
304
403
|
|
|
305
404
|
---
|
|
306
405
|
|
|
@@ -323,6 +422,12 @@ Creates a new v1 challenge.
|
|
|
323
422
|
| `expires` | `datetime` | `None` | Optional expiration time. |
|
|
324
423
|
| `params` | `dict` | `None` | Optional URL-encoded query parameters appended to the salt. |
|
|
325
424
|
|
|
425
|
+
#### `verify_server_signature_v1(payload, hmac_key) → (bool, ServerSignatureVerificationData | None, str | None)`
|
|
426
|
+
|
|
427
|
+
Verifies a server signature with the v1 API. Returns `(verified, data, error)`, where `data`
|
|
428
|
+
exposes the known fields (`classification`, `expire`, `fields`, `fieldsHash`, `score`, …)
|
|
429
|
+
as attributes. Prefer `verify_server_signature`.
|
|
430
|
+
|
|
326
431
|
#### `verify_solution_v1(payload, hmac_secret, check_expires) → (bool, str | None)`
|
|
327
432
|
|
|
328
433
|
Verifies a v1 solution payload.
|
|
@@ -231,17 +231,99 @@ Returns `VerifySolutionResult` with fields:
|
|
|
231
231
|
|
|
232
232
|
#### `verify_fields_hash(form_data, fields, fields_hash, algorithm) → bool`
|
|
233
233
|
|
|
234
|
-
Verifies the hash of specific form fields.
|
|
234
|
+
Verifies the hash of specific form fields: the hex hash (`algorithm`, e.g. `'SHA-256'`) of
|
|
235
|
+
the values of `fields` in `form_data`, joined with `\n`, must equal `fields_hash`.
|
|
235
236
|
|
|
236
|
-
#### `verify_server_signature(payload,
|
|
237
|
+
#### `verify_server_signature(payload, hmac_secret, *, hmac_algorithm) → VerifyServerSignatureResult`
|
|
237
238
|
|
|
238
|
-
Verifies an ALTCHA server signature.
|
|
239
|
+
Verifies an ALTCHA server signature locally, e.g. the `payload` of Sentinel's
|
|
240
|
+
`POST /v2/verify` (or `/v1/verify`) response, with the secret of the API key that signed
|
|
241
|
+
it. Sentinel v1 and v2 sign the same way, so this works for both. To have Sentinel check
|
|
242
|
+
the payload instead, use `verify_server` (below).
|
|
239
243
|
|
|
240
|
-
|
|
244
|
+
```python
|
|
245
|
+
from altcha import verify_fields_hash, verify_server_signature
|
|
246
|
+
|
|
247
|
+
result = verify_server_signature(payload, API_KEY_SECRET)
|
|
248
|
+
|
|
249
|
+
if result.verified:
|
|
250
|
+
data = result.verification_data
|
|
251
|
+
# Detect tampering with the submitted form fields
|
|
252
|
+
if data.get("fields") and not verify_fields_hash(
|
|
253
|
+
form_data, data["fields"], data["fieldsHash"], "SHA-256"
|
|
254
|
+
):
|
|
255
|
+
...
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
| Parameter | Type | Default | Description |
|
|
259
|
+
|---|---|---|---|
|
|
260
|
+
| `payload` | `str` \| `ServerSignaturePayload` | — | Base64-encoded JSON string or `ServerSignaturePayload` object. Its `algorithm` (hash of `verificationData`) must be `'SHA-1'`, `'SHA-256'`, `'SHA-384'` or `'SHA-512'`. |
|
|
261
|
+
| `hmac_secret` | `str` \| `bytes` | — | Secret used to verify the HMAC signature (the API key secret for Sentinel). Raises `ValueError` if empty. |
|
|
262
|
+
| `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
|
|
263
|
+
|
|
264
|
+
Returns `VerifyServerSignatureResult` with fields:
|
|
241
265
|
|
|
242
|
-
|
|
266
|
+
| Field | Type | Description |
|
|
267
|
+
|---|---|---|
|
|
268
|
+
| `verified` | `bool` | `True` if the signature is valid, the payload has not expired, and `verified` is `true` in both the payload and the signed verification data. |
|
|
269
|
+
| `expired` | `bool` | `True` if the signed `expire` is in the past. |
|
|
270
|
+
| `invalid_signature` | `bool` | `True` if the signature does not match, or the payload is malformed. |
|
|
271
|
+
| `invalid_solution` | `bool` | `True` if `verified` is not `true` in the payload or in the signed verification data. |
|
|
272
|
+
| `time` | `float` | Time taken for verification in milliseconds. |
|
|
273
|
+
| `verification_data` | `dict \| None` | The signed verification data, parsed with `parse_verification_data`; `None` unless `verified`. |
|
|
274
|
+
|
|
275
|
+
`parse_verification_data(data)` turns the URL-encoded verification data into a flat dict:
|
|
276
|
+
|
|
277
|
+
- Keys stay as signed, e.g. `data["challenge.algorithm"]` and `data["device.edk"]`
|
|
278
|
+
(`verify_server` returns these nested instead).
|
|
279
|
+
- `'true'`/`'false'` become `bool`, all-digit values `int` (including e.g. a
|
|
280
|
+
`params.zip` of `01234`, which becomes `1234`), and `digits.digits` values `float`.
|
|
281
|
+
- `fields` and `reasons` become lists.
|
|
282
|
+
- Keys with empty values are left out.
|
|
283
|
+
|
|
284
|
+
Unlike Sentinel v2's `/v2/verify/signature` (via `verify_server`), local verification does
|
|
285
|
+
not prevent reuse: a valid payload verifies again until `expire`. Reject repeated `id`s
|
|
286
|
+
yourself if that matters.
|
|
287
|
+
|
|
288
|
+
#### `verify_server(payload, url, secret, *, api_key, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
|
|
289
|
+
|
|
290
|
+
Verifies a payload remotely via the ALTCHA Sentinel verify signature API, instead of
|
|
243
291
|
checking the HMAC signature locally. Avoids managing the HMAC secret on your server, at the
|
|
244
|
-
cost of a network round-trip.
|
|
292
|
+
cost of a network round-trip. Both Sentinel v2 (`POST /v2/verify/signature`) and Sentinel v1
|
|
293
|
+
(`POST /v1/verify/signature`) are supported; they differ in how the request is authenticated.
|
|
294
|
+
|
|
295
|
+
##### Sentinel v2
|
|
296
|
+
|
|
297
|
+
```python
|
|
298
|
+
from altcha import verify_server
|
|
299
|
+
|
|
300
|
+
result = verify_server(
|
|
301
|
+
payload, # the payload received from POST /v2/verify
|
|
302
|
+
url="https://sentinel.example.com/v2/verify/signature",
|
|
303
|
+
api_key=SENTINEL_API_KEY, # id of a restricted or full API key (key_...)
|
|
304
|
+
secret=SENTINEL_API_KEY_SECRET, # its secret (sec_...)
|
|
305
|
+
timeout=10,
|
|
306
|
+
retries=2,
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
if result.verified:
|
|
310
|
+
...
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
- `api_key` and `secret` are the ID and secret of a `restricted` or `full` API key of the
|
|
314
|
+
account that owns the payload's (public) API key. They are sent as
|
|
315
|
+
`Authorization: Basic base64(api_key:secret)`; an `Authorization` header in `headers` is
|
|
316
|
+
replaced. `api_key` without `secret` raises `ValueError` before any request is sent.
|
|
317
|
+
- The request body is `{"payload": ...}`; `secret` is not sent in the body (Sentinel v2
|
|
318
|
+
rejects it).
|
|
319
|
+
- Without credentials, Sentinel v2 answers `401` and `reason` is `'API_KEY_REQUIRED'`. A
|
|
320
|
+
payload signed by a key of another account gets `reason='API_KEY_NOT_ALLOWED'`.
|
|
321
|
+
- `verification_data` is the signed verification data as a nested dict, with keys split on
|
|
322
|
+
`.`: `result.verification_data["challenge"]["algorithm"]` (v1's `challengeAlgorithm`),
|
|
323
|
+
`result.verification_data["device"]["edk"]`. `fields` and `reasons` are lists; `id`,
|
|
324
|
+
`fieldsHash`, `device.edk` and `params.*` stay strings.
|
|
325
|
+
|
|
326
|
+
##### Sentinel v1
|
|
245
327
|
|
|
246
328
|
```python
|
|
247
329
|
from altcha import verify_server
|
|
@@ -258,11 +340,20 @@ if result.verified:
|
|
|
258
340
|
...
|
|
259
341
|
```
|
|
260
342
|
|
|
343
|
+
- `/v1/verify/signature` takes no credentials: omit `api_key`. `secret` (the payload's API
|
|
344
|
+
key secret) is optional and sent in the body as `{"payload": ..., "secret": ...}`; Sentinel
|
|
345
|
+
answers `reason='WRONG_API_KEY_SECRET'` when it is not the payload key's secret.
|
|
346
|
+
- This also applies to the `/v1/verify/signature` alias Sentinel v2 serves with
|
|
347
|
+
`[server] v1_compat = true`.
|
|
348
|
+
|
|
349
|
+
##### Parameters
|
|
350
|
+
|
|
261
351
|
| Parameter | Type | Default | Description |
|
|
262
352
|
|---|---|---|---|
|
|
263
353
|
| `payload` | `str` \| `ServerSignaturePayload` \| `dict` | — | The payload to verify. |
|
|
264
|
-
| `url` | `str` | — | Full URL of the Sentinel `/v1/verify/signature`
|
|
265
|
-
| `secret` | `str` | `None` | API key secret
|
|
354
|
+
| `url` | `str` | — | Full URL of the Sentinel endpoint: `/v2/verify/signature` (v2) or `/v1/verify/signature` (v1). |
|
|
355
|
+
| `secret` | `str` | `None` | v2: secret of `api_key`, required with it. v1: API key secret sent in the body and checked against the payload's API key. |
|
|
356
|
+
| `api_key` | `str` | `None` | v2 only: ID of a `restricted` or `full` API key, sent with `secret` as HTTP Basic credentials. |
|
|
266
357
|
| `headers` | `dict` | `None` | Additional headers to send with the request. |
|
|
267
358
|
| `timeout` | `float` | `10` | Per-attempt request timeout in seconds. |
|
|
268
359
|
| `retries` | `int` | `0` | Number of retry attempts after the first try. |
|
|
@@ -270,14 +361,22 @@ if result.verified:
|
|
|
270
361
|
| `retry_backoff` | `str` | `'exponential'` | `'fixed'` or `'exponential'` backoff. |
|
|
271
362
|
| `http_post` | callable | stdlib `urllib` | Transport override: `(url, body, headers, timeout) -> (status, body)`. |
|
|
272
363
|
|
|
364
|
+
##### Errors and retries
|
|
365
|
+
|
|
366
|
+
Failures never raise; they return `verified=False` with a `reason`. `4xx` responses (bad
|
|
367
|
+
payload, missing or wrong credentials, rate limit) are definitive and returned at once.
|
|
368
|
+
Network errors, other error statuses (e.g. `5xx`) and invalid response bodies are retried up
|
|
369
|
+
to `retries` times. For an error response, `reason` is the `code` of Sentinel's error body
|
|
370
|
+
(v2: `{"code", "error", "statusCode"}`), else its `error` (v1), else `'HTTP_<status>'`.
|
|
371
|
+
|
|
273
372
|
Returns `VerifyServerResult` with fields:
|
|
274
373
|
|
|
275
374
|
| Field | Type | Description |
|
|
276
375
|
|---|---|---|
|
|
277
376
|
| `verified` | `bool` | `True` if Sentinel confirmed the payload is valid. |
|
|
278
|
-
| `reason` | `str \| None` |
|
|
377
|
+
| `reason` | `str \| None` | Why verification failed: Sentinel's `reason` (e.g. `'PAYLOAD_ALREADY_USED'`, `'INVALID_PAYLOAD'`, `'API_KEY_NOT_ALLOWED'` (v2), `'WRONG_API_KEY_SECRET'` (v1)), the error code of an HTTP error response, `'INVALID_RESPONSE'`, or a network error message. |
|
|
279
378
|
| `api_key` | `str \| None` | The API key associated with the payload, if returned. |
|
|
280
|
-
| `verification_data` | `dict \| None` |
|
|
379
|
+
| `verification_data` | `dict \| None` | Verification data returned by Sentinel (nested dict), if returned. |
|
|
281
380
|
|
|
282
381
|
---
|
|
283
382
|
|
|
@@ -300,6 +399,12 @@ Creates a new v1 challenge.
|
|
|
300
399
|
| `expires` | `datetime` | `None` | Optional expiration time. |
|
|
301
400
|
| `params` | `dict` | `None` | Optional URL-encoded query parameters appended to the salt. |
|
|
302
401
|
|
|
402
|
+
#### `verify_server_signature_v1(payload, hmac_key) → (bool, ServerSignatureVerificationData | None, str | None)`
|
|
403
|
+
|
|
404
|
+
Verifies a server signature with the v1 API. Returns `(verified, data, error)`, where `data`
|
|
405
|
+
exposes the known fields (`classification`, `expire`, `fields`, `fieldsHash`, `score`, …)
|
|
406
|
+
as attributes. Prefer `verify_server_signature`.
|
|
407
|
+
|
|
303
408
|
#### `verify_solution_v1(payload, hmac_secret, check_expires) → (bool, str | None)`
|
|
304
409
|
|
|
305
410
|
Verifies a v1 solution payload.
|
|
@@ -895,6 +895,9 @@ class ServerSignaturePayload:
|
|
|
895
895
|
signature: HMAC signature of the hashed verification data.
|
|
896
896
|
verification_data: URL-encoded query string of verification attributes.
|
|
897
897
|
verified: Whether the server marked the payload as verified.
|
|
898
|
+
api_key: ID of the API key that signed the payload (Sentinel's ``apiKey``),
|
|
899
|
+
if present. Not covered by the signature.
|
|
900
|
+
id: Payload ID (Sentinel's ``id``), if present. Not covered by the signature.
|
|
898
901
|
"""
|
|
899
902
|
|
|
900
903
|
def __init__(
|
|
@@ -903,19 +906,28 @@ class ServerSignaturePayload:
|
|
|
903
906
|
signature: str,
|
|
904
907
|
verification_data: str,
|
|
905
908
|
verified: bool,
|
|
909
|
+
api_key: str | None = None,
|
|
910
|
+
id: str | None = None,
|
|
906
911
|
):
|
|
907
912
|
self.algorithm = algorithm
|
|
908
913
|
self.signature = signature
|
|
909
914
|
self.verification_data = verification_data
|
|
910
915
|
self.verified = verified
|
|
916
|
+
self.api_key = api_key
|
|
917
|
+
self.id = id
|
|
911
918
|
|
|
912
919
|
def to_dict(self) -> dict:
|
|
913
|
-
|
|
920
|
+
d: dict = {
|
|
914
921
|
"algorithm": self.algorithm,
|
|
915
922
|
"signature": self.signature,
|
|
916
923
|
"verificationData": self.verification_data,
|
|
917
924
|
"verified": self.verified,
|
|
918
925
|
}
|
|
926
|
+
if self.api_key is not None:
|
|
927
|
+
d["apiKey"] = self.api_key
|
|
928
|
+
if self.id is not None:
|
|
929
|
+
d["id"] = self.id
|
|
930
|
+
return d
|
|
919
931
|
|
|
920
932
|
@classmethod
|
|
921
933
|
def from_dict(cls, d: dict) -> ServerSignaturePayload:
|
|
@@ -924,6 +936,8 @@ class ServerSignaturePayload:
|
|
|
924
936
|
signature=d["signature"],
|
|
925
937
|
verification_data=d["verificationData"],
|
|
926
938
|
verified=bool(d.get("verified", False)),
|
|
939
|
+
api_key=d.get("apiKey"),
|
|
940
|
+
id=d.get("id"),
|
|
927
941
|
)
|
|
928
942
|
|
|
929
943
|
@classmethod
|
|
@@ -1106,9 +1120,14 @@ class VerifyServerResult:
|
|
|
1106
1120
|
|
|
1107
1121
|
Attributes:
|
|
1108
1122
|
verified: ``True`` if Sentinel confirmed the payload is valid.
|
|
1109
|
-
reason:
|
|
1123
|
+
reason: Why verification failed, if it did: Sentinel's ``reason`` (e.g.
|
|
1124
|
+
``'PAYLOAD_ALREADY_USED'``, ``'INVALID_PAYLOAD'``, ``'API_KEY_NOT_ALLOWED'``
|
|
1125
|
+
(v2) or ``'WRONG_API_KEY_SECRET'`` (v1)), the ``code`` (else ``error``) of an
|
|
1126
|
+
HTTP error response (e.g. ``'API_KEY_REQUIRED'``), ``'HTTP_<status>'``,
|
|
1127
|
+
``'INVALID_RESPONSE'`` or a network error message.
|
|
1110
1128
|
api_key: The API key associated with the payload, if returned.
|
|
1111
|
-
verification_data:
|
|
1129
|
+
verification_data: The verification data returned by Sentinel, as a nested
|
|
1130
|
+
dict (``{'challenge': {'algorithm': ...}}``), if returned.
|
|
1112
1131
|
"""
|
|
1113
1132
|
|
|
1114
1133
|
def __init__(
|
|
@@ -1150,11 +1169,34 @@ def _sleep_backoff(attempt: int, delay: float, backoff: str) -> None:
|
|
|
1150
1169
|
time.sleep(wait)
|
|
1151
1170
|
|
|
1152
1171
|
|
|
1172
|
+
def _decode_json(body: bytes) -> object:
|
|
1173
|
+
"""Decode a JSON response body, or return ``None`` if it is not valid JSON."""
|
|
1174
|
+
try:
|
|
1175
|
+
return json.loads(body.decode())
|
|
1176
|
+
except (ValueError, RecursionError):
|
|
1177
|
+
return None
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
def _error_reason(status: int, body: bytes) -> str:
|
|
1181
|
+
"""
|
|
1182
|
+
The ``code`` of a Sentinel error body (v2: ``{code, error, statusCode}``), else its
|
|
1183
|
+
``error`` (v1 sends only ``error``), else ``'HTTP_<status>'``.
|
|
1184
|
+
"""
|
|
1185
|
+
data = _decode_json(body)
|
|
1186
|
+
if isinstance(data, dict):
|
|
1187
|
+
for key in ("code", "error"):
|
|
1188
|
+
value = data.get(key)
|
|
1189
|
+
if isinstance(value, str) and value:
|
|
1190
|
+
return value
|
|
1191
|
+
return f"HTTP_{status}"
|
|
1192
|
+
|
|
1193
|
+
|
|
1153
1194
|
def verify_server(
|
|
1154
1195
|
payload: str | ServerSignaturePayload | dict,
|
|
1155
1196
|
url: str,
|
|
1156
1197
|
secret: str | None = None,
|
|
1157
1198
|
*,
|
|
1199
|
+
api_key: str | None = None,
|
|
1158
1200
|
headers: dict[str, str] | None = None,
|
|
1159
1201
|
timeout: float = 10.0,
|
|
1160
1202
|
retries: int = 0,
|
|
@@ -1164,20 +1206,39 @@ def verify_server(
|
|
|
1164
1206
|
| None = None,
|
|
1165
1207
|
) -> VerifyServerResult:
|
|
1166
1208
|
"""
|
|
1167
|
-
Verify a payload remotely via the ALTCHA Sentinel
|
|
1209
|
+
Verify a payload remotely via the ALTCHA Sentinel verify signature API.
|
|
1168
1210
|
|
|
1169
1211
|
Instead of verifying the HMAC signature locally (see :func:`verify_server_signature`),
|
|
1170
1212
|
this POSTs the payload to Sentinel and trusts its response. Avoids managing the HMAC
|
|
1171
1213
|
secret on your server, at the cost of a network round-trip.
|
|
1172
1214
|
|
|
1215
|
+
Supports both Sentinel versions; they differ in how the request is authenticated:
|
|
1216
|
+
|
|
1217
|
+
- Sentinel v2 (``/v2/verify/signature``): pass *api_key* and *secret*, the ID and
|
|
1218
|
+
secret of a ``restricted`` or ``full`` API key of the account that owns the
|
|
1219
|
+
payload's API key. They are sent as HTTP Basic credentials, and nothing else
|
|
1220
|
+
besides the payload is sent in the body.
|
|
1221
|
+
- Sentinel v1 (``/v1/verify/signature``, also the ``/v1`` alias Sentinel v2 serves
|
|
1222
|
+
with ``v1_compat``): omit *api_key*. *secret* is optional and sent in the body;
|
|
1223
|
+
Sentinel checks it against the payload's API key.
|
|
1224
|
+
|
|
1173
1225
|
Args:
|
|
1174
|
-
payload: The payload to verify, as received from ``POST /
|
|
1175
|
-
string, a :class:`ServerSignaturePayload`, or an
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1226
|
+
payload: The payload to verify, as received from ``POST /v2/verify`` (or
|
|
1227
|
+
``/v1/verify``) — a base64 string, a :class:`ServerSignaturePayload`, or an
|
|
1228
|
+
already-decoded dict.
|
|
1229
|
+
url: Full URL of the Sentinel ``/v2/verify/signature`` or
|
|
1230
|
+
``/v1/verify/signature`` endpoint.
|
|
1231
|
+
secret: API key secret. With *api_key* (Sentinel v2), the secret of that key,
|
|
1232
|
+
sent as the Basic password; required. Without *api_key* (Sentinel v1),
|
|
1233
|
+
optional and sent as ``secret`` in the body.
|
|
1234
|
+
api_key: Sentinel v2: ID (``key_…``) of a ``restricted`` or ``full`` API key,
|
|
1235
|
+
sent with *secret* as ``Authorization: Basic base64(api_key:secret)``.
|
|
1236
|
+
headers: Additional headers to send with the request. An ``Authorization``
|
|
1237
|
+
header is replaced when *api_key* is set.
|
|
1179
1238
|
timeout: Per-attempt request timeout in seconds. Defaults to ``10``.
|
|
1180
|
-
retries: Number of retry attempts after the first try.
|
|
1239
|
+
retries: Number of retry attempts after the first try. Network errors, non-4xx
|
|
1240
|
+
error statuses and invalid response bodies are retried; 4xx responses are
|
|
1241
|
+
not. Defaults to ``0``.
|
|
1181
1242
|
retry_delay: Base delay in seconds between retries. Defaults to ``0.3``.
|
|
1182
1243
|
retry_backoff: ``'fixed'`` or ``'exponential'`` backoff applied to *retry_delay*.
|
|
1183
1244
|
http_post: Transport override — ``(url, body, headers, timeout) -> (status, body)``.
|
|
@@ -1188,18 +1249,31 @@ def verify_server(
|
|
|
1188
1249
|
A :class:`VerifyServerResult` describing the outcome. Failures (HTTP errors, network
|
|
1189
1250
|
errors, or a negative Sentinel verdict) are reported via ``verified=False`` with a
|
|
1190
1251
|
``reason``, never raised as exceptions.
|
|
1252
|
+
|
|
1253
|
+
Raises:
|
|
1254
|
+
ValueError: If *api_key* is set without *secret*.
|
|
1191
1255
|
"""
|
|
1256
|
+
if api_key and not secret:
|
|
1257
|
+
raise ValueError("secret is required when api_key is set")
|
|
1258
|
+
|
|
1192
1259
|
if isinstance(payload, ServerSignaturePayload):
|
|
1193
1260
|
payload_value: str | dict = payload.to_dict()
|
|
1194
1261
|
else:
|
|
1195
1262
|
payload_value = payload
|
|
1196
1263
|
|
|
1197
1264
|
body: dict = {"payload": payload_value}
|
|
1198
|
-
|
|
1265
|
+
# Sentinel v2 rejects `secret` in the body (400); only Sentinel v1 reads it.
|
|
1266
|
+
if not api_key and secret is not None:
|
|
1199
1267
|
body["secret"] = secret
|
|
1200
1268
|
data = json.dumps(body).encode()
|
|
1201
1269
|
|
|
1202
1270
|
req_headers = {"Content-Type": "application/json", **(headers or {})}
|
|
1271
|
+
if api_key:
|
|
1272
|
+
credentials = base64.b64encode(f"{api_key}:{secret}".encode()).decode()
|
|
1273
|
+
req_headers = {
|
|
1274
|
+
k: v for k, v in req_headers.items() if k.lower() != "authorization"
|
|
1275
|
+
}
|
|
1276
|
+
req_headers["Authorization"] = f"Basic {credentials}"
|
|
1203
1277
|
post = http_post or _default_http_post
|
|
1204
1278
|
|
|
1205
1279
|
attempts = retries + 1
|
|
@@ -1207,27 +1281,22 @@ def verify_server(
|
|
|
1207
1281
|
try:
|
|
1208
1282
|
status, resp_body = post(url, data, req_headers, timeout)
|
|
1209
1283
|
except Exception as e: # noqa: BLE001 -- custom transports may raise anything
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
)
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
return VerifyServerResult(verified=False, reason=reason)
|
|
1224
|
-
|
|
1225
|
-
if not (200 <= status < 300):
|
|
1226
|
-
if attempt >= attempts - 1:
|
|
1227
|
-
return VerifyServerResult(verified=False, reason=f"HTTP_{status}")
|
|
1228
|
-
_sleep_backoff(attempt, retry_delay, retry_backoff)
|
|
1229
|
-
continue
|
|
1284
|
+
reason = str(e) or type(e).__name__
|
|
1285
|
+
else:
|
|
1286
|
+
if 200 <= status < 300:
|
|
1287
|
+
resp_data = _decode_json(resp_body)
|
|
1288
|
+
if isinstance(resp_data, dict):
|
|
1289
|
+
return VerifyServerResult.from_dict(resp_data)
|
|
1290
|
+
reason = "INVALID_RESPONSE"
|
|
1291
|
+
else:
|
|
1292
|
+
reason = _error_reason(status, resp_body)
|
|
1293
|
+
# A 4xx (bad payload, missing or wrong credentials, rate limit) fails
|
|
1294
|
+
# the same way again.
|
|
1295
|
+
if 400 <= status < 500:
|
|
1296
|
+
return VerifyServerResult(verified=False, reason=reason)
|
|
1230
1297
|
|
|
1231
|
-
|
|
1298
|
+
if attempt >= attempts - 1:
|
|
1299
|
+
return VerifyServerResult(verified=False, reason=reason)
|
|
1300
|
+
_sleep_backoff(attempt, retry_delay, retry_backoff)
|
|
1232
1301
|
|
|
1233
1302
|
return VerifyServerResult(verified=False, reason="NETWORK_ERROR")
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: altcha
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.4.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
|
|
@@ -254,17 +254,99 @@ Returns `VerifySolutionResult` with fields:
|
|
|
254
254
|
|
|
255
255
|
#### `verify_fields_hash(form_data, fields, fields_hash, algorithm) → bool`
|
|
256
256
|
|
|
257
|
-
Verifies the hash of specific form fields.
|
|
257
|
+
Verifies the hash of specific form fields: the hex hash (`algorithm`, e.g. `'SHA-256'`) of
|
|
258
|
+
the values of `fields` in `form_data`, joined with `\n`, must equal `fields_hash`.
|
|
258
259
|
|
|
259
|
-
#### `verify_server_signature(payload,
|
|
260
|
+
#### `verify_server_signature(payload, hmac_secret, *, hmac_algorithm) → VerifyServerSignatureResult`
|
|
260
261
|
|
|
261
|
-
Verifies an ALTCHA server signature.
|
|
262
|
+
Verifies an ALTCHA server signature locally, e.g. the `payload` of Sentinel's
|
|
263
|
+
`POST /v2/verify` (or `/v1/verify`) response, with the secret of the API key that signed
|
|
264
|
+
it. Sentinel v1 and v2 sign the same way, so this works for both. To have Sentinel check
|
|
265
|
+
the payload instead, use `verify_server` (below).
|
|
262
266
|
|
|
263
|
-
|
|
267
|
+
```python
|
|
268
|
+
from altcha import verify_fields_hash, verify_server_signature
|
|
269
|
+
|
|
270
|
+
result = verify_server_signature(payload, API_KEY_SECRET)
|
|
271
|
+
|
|
272
|
+
if result.verified:
|
|
273
|
+
data = result.verification_data
|
|
274
|
+
# Detect tampering with the submitted form fields
|
|
275
|
+
if data.get("fields") and not verify_fields_hash(
|
|
276
|
+
form_data, data["fields"], data["fieldsHash"], "SHA-256"
|
|
277
|
+
):
|
|
278
|
+
...
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
| Parameter | Type | Default | Description |
|
|
282
|
+
|---|---|---|---|
|
|
283
|
+
| `payload` | `str` \| `ServerSignaturePayload` | — | Base64-encoded JSON string or `ServerSignaturePayload` object. Its `algorithm` (hash of `verificationData`) must be `'SHA-1'`, `'SHA-256'`, `'SHA-384'` or `'SHA-512'`. |
|
|
284
|
+
| `hmac_secret` | `str` \| `bytes` | — | Secret used to verify the HMAC signature (the API key secret for Sentinel). Raises `ValueError` if empty. |
|
|
285
|
+
| `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
|
|
286
|
+
|
|
287
|
+
Returns `VerifyServerSignatureResult` with fields:
|
|
264
288
|
|
|
265
|
-
|
|
289
|
+
| Field | Type | Description |
|
|
290
|
+
|---|---|---|
|
|
291
|
+
| `verified` | `bool` | `True` if the signature is valid, the payload has not expired, and `verified` is `true` in both the payload and the signed verification data. |
|
|
292
|
+
| `expired` | `bool` | `True` if the signed `expire` is in the past. |
|
|
293
|
+
| `invalid_signature` | `bool` | `True` if the signature does not match, or the payload is malformed. |
|
|
294
|
+
| `invalid_solution` | `bool` | `True` if `verified` is not `true` in the payload or in the signed verification data. |
|
|
295
|
+
| `time` | `float` | Time taken for verification in milliseconds. |
|
|
296
|
+
| `verification_data` | `dict \| None` | The signed verification data, parsed with `parse_verification_data`; `None` unless `verified`. |
|
|
297
|
+
|
|
298
|
+
`parse_verification_data(data)` turns the URL-encoded verification data into a flat dict:
|
|
299
|
+
|
|
300
|
+
- Keys stay as signed, e.g. `data["challenge.algorithm"]` and `data["device.edk"]`
|
|
301
|
+
(`verify_server` returns these nested instead).
|
|
302
|
+
- `'true'`/`'false'` become `bool`, all-digit values `int` (including e.g. a
|
|
303
|
+
`params.zip` of `01234`, which becomes `1234`), and `digits.digits` values `float`.
|
|
304
|
+
- `fields` and `reasons` become lists.
|
|
305
|
+
- Keys with empty values are left out.
|
|
306
|
+
|
|
307
|
+
Unlike Sentinel v2's `/v2/verify/signature` (via `verify_server`), local verification does
|
|
308
|
+
not prevent reuse: a valid payload verifies again until `expire`. Reject repeated `id`s
|
|
309
|
+
yourself if that matters.
|
|
310
|
+
|
|
311
|
+
#### `verify_server(payload, url, secret, *, api_key, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
|
|
312
|
+
|
|
313
|
+
Verifies a payload remotely via the ALTCHA Sentinel verify signature API, instead of
|
|
266
314
|
checking the HMAC signature locally. Avoids managing the HMAC secret on your server, at the
|
|
267
|
-
cost of a network round-trip.
|
|
315
|
+
cost of a network round-trip. Both Sentinel v2 (`POST /v2/verify/signature`) and Sentinel v1
|
|
316
|
+
(`POST /v1/verify/signature`) are supported; they differ in how the request is authenticated.
|
|
317
|
+
|
|
318
|
+
##### Sentinel v2
|
|
319
|
+
|
|
320
|
+
```python
|
|
321
|
+
from altcha import verify_server
|
|
322
|
+
|
|
323
|
+
result = verify_server(
|
|
324
|
+
payload, # the payload received from POST /v2/verify
|
|
325
|
+
url="https://sentinel.example.com/v2/verify/signature",
|
|
326
|
+
api_key=SENTINEL_API_KEY, # id of a restricted or full API key (key_...)
|
|
327
|
+
secret=SENTINEL_API_KEY_SECRET, # its secret (sec_...)
|
|
328
|
+
timeout=10,
|
|
329
|
+
retries=2,
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
if result.verified:
|
|
333
|
+
...
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
- `api_key` and `secret` are the ID and secret of a `restricted` or `full` API key of the
|
|
337
|
+
account that owns the payload's (public) API key. They are sent as
|
|
338
|
+
`Authorization: Basic base64(api_key:secret)`; an `Authorization` header in `headers` is
|
|
339
|
+
replaced. `api_key` without `secret` raises `ValueError` before any request is sent.
|
|
340
|
+
- The request body is `{"payload": ...}`; `secret` is not sent in the body (Sentinel v2
|
|
341
|
+
rejects it).
|
|
342
|
+
- Without credentials, Sentinel v2 answers `401` and `reason` is `'API_KEY_REQUIRED'`. A
|
|
343
|
+
payload signed by a key of another account gets `reason='API_KEY_NOT_ALLOWED'`.
|
|
344
|
+
- `verification_data` is the signed verification data as a nested dict, with keys split on
|
|
345
|
+
`.`: `result.verification_data["challenge"]["algorithm"]` (v1's `challengeAlgorithm`),
|
|
346
|
+
`result.verification_data["device"]["edk"]`. `fields` and `reasons` are lists; `id`,
|
|
347
|
+
`fieldsHash`, `device.edk` and `params.*` stay strings.
|
|
348
|
+
|
|
349
|
+
##### Sentinel v1
|
|
268
350
|
|
|
269
351
|
```python
|
|
270
352
|
from altcha import verify_server
|
|
@@ -281,11 +363,20 @@ if result.verified:
|
|
|
281
363
|
...
|
|
282
364
|
```
|
|
283
365
|
|
|
366
|
+
- `/v1/verify/signature` takes no credentials: omit `api_key`. `secret` (the payload's API
|
|
367
|
+
key secret) is optional and sent in the body as `{"payload": ..., "secret": ...}`; Sentinel
|
|
368
|
+
answers `reason='WRONG_API_KEY_SECRET'` when it is not the payload key's secret.
|
|
369
|
+
- This also applies to the `/v1/verify/signature` alias Sentinel v2 serves with
|
|
370
|
+
`[server] v1_compat = true`.
|
|
371
|
+
|
|
372
|
+
##### Parameters
|
|
373
|
+
|
|
284
374
|
| Parameter | Type | Default | Description |
|
|
285
375
|
|---|---|---|---|
|
|
286
376
|
| `payload` | `str` \| `ServerSignaturePayload` \| `dict` | — | The payload to verify. |
|
|
287
|
-
| `url` | `str` | — | Full URL of the Sentinel `/v1/verify/signature`
|
|
288
|
-
| `secret` | `str` | `None` | API key secret
|
|
377
|
+
| `url` | `str` | — | Full URL of the Sentinel endpoint: `/v2/verify/signature` (v2) or `/v1/verify/signature` (v1). |
|
|
378
|
+
| `secret` | `str` | `None` | v2: secret of `api_key`, required with it. v1: API key secret sent in the body and checked against the payload's API key. |
|
|
379
|
+
| `api_key` | `str` | `None` | v2 only: ID of a `restricted` or `full` API key, sent with `secret` as HTTP Basic credentials. |
|
|
289
380
|
| `headers` | `dict` | `None` | Additional headers to send with the request. |
|
|
290
381
|
| `timeout` | `float` | `10` | Per-attempt request timeout in seconds. |
|
|
291
382
|
| `retries` | `int` | `0` | Number of retry attempts after the first try. |
|
|
@@ -293,14 +384,22 @@ if result.verified:
|
|
|
293
384
|
| `retry_backoff` | `str` | `'exponential'` | `'fixed'` or `'exponential'` backoff. |
|
|
294
385
|
| `http_post` | callable | stdlib `urllib` | Transport override: `(url, body, headers, timeout) -> (status, body)`. |
|
|
295
386
|
|
|
387
|
+
##### Errors and retries
|
|
388
|
+
|
|
389
|
+
Failures never raise; they return `verified=False` with a `reason`. `4xx` responses (bad
|
|
390
|
+
payload, missing or wrong credentials, rate limit) are definitive and returned at once.
|
|
391
|
+
Network errors, other error statuses (e.g. `5xx`) and invalid response bodies are retried up
|
|
392
|
+
to `retries` times. For an error response, `reason` is the `code` of Sentinel's error body
|
|
393
|
+
(v2: `{"code", "error", "statusCode"}`), else its `error` (v1), else `'HTTP_<status>'`.
|
|
394
|
+
|
|
296
395
|
Returns `VerifyServerResult` with fields:
|
|
297
396
|
|
|
298
397
|
| Field | Type | Description |
|
|
299
398
|
|---|---|---|
|
|
300
399
|
| `verified` | `bool` | `True` if Sentinel confirmed the payload is valid. |
|
|
301
|
-
| `reason` | `str \| None` |
|
|
400
|
+
| `reason` | `str \| None` | Why verification failed: Sentinel's `reason` (e.g. `'PAYLOAD_ALREADY_USED'`, `'INVALID_PAYLOAD'`, `'API_KEY_NOT_ALLOWED'` (v2), `'WRONG_API_KEY_SECRET'` (v1)), the error code of an HTTP error response, `'INVALID_RESPONSE'`, or a network error message. |
|
|
302
401
|
| `api_key` | `str \| None` | The API key associated with the payload, if returned. |
|
|
303
|
-
| `verification_data` | `dict \| None` |
|
|
402
|
+
| `verification_data` | `dict \| None` | Verification data returned by Sentinel (nested dict), if returned. |
|
|
304
403
|
|
|
305
404
|
---
|
|
306
405
|
|
|
@@ -323,6 +422,12 @@ Creates a new v1 challenge.
|
|
|
323
422
|
| `expires` | `datetime` | `None` | Optional expiration time. |
|
|
324
423
|
| `params` | `dict` | `None` | Optional URL-encoded query parameters appended to the salt. |
|
|
325
424
|
|
|
425
|
+
#### `verify_server_signature_v1(payload, hmac_key) → (bool, ServerSignatureVerificationData | None, str | None)`
|
|
426
|
+
|
|
427
|
+
Verifies a server signature with the v1 API. Returns `(verified, data, error)`, where `data`
|
|
428
|
+
exposes the known fields (`classification`, `expire`, `fields`, `fieldsHash`, `score`, …)
|
|
429
|
+
as attributes. Prefer `verify_server_signature`.
|
|
430
|
+
|
|
326
431
|
#### `verify_solution_v1(payload, hmac_secret, check_expires) → (bool, str | None)`
|
|
327
432
|
|
|
328
433
|
Verifies a v1 solution payload.
|
|
@@ -7,7 +7,7 @@ from setuptools import ( # type: ignore[import-not-found, import-untyped, unuse
|
|
|
7
7
|
|
|
8
8
|
setup(
|
|
9
9
|
name="altcha",
|
|
10
|
-
version="2.
|
|
10
|
+
version="2.4.0",
|
|
11
11
|
description="A library for creating and verifying challenges for ALTCHA.",
|
|
12
12
|
long_description=Path("README.md").read_text(encoding="utf-8"),
|
|
13
13
|
long_description_content_type="text/markdown",
|
|
@@ -882,6 +882,7 @@ class TestVerifyServerSignature(unittest.TestCase):
|
|
|
882
882
|
|
|
883
883
|
class TestVerifyServer(unittest.TestCase):
|
|
884
884
|
URL = "https://sentinel.example.com/v1/verify/signature"
|
|
885
|
+
URL_V2 = "https://sentinel.example.com/v2/verify/signature"
|
|
885
886
|
|
|
886
887
|
def setUp(self):
|
|
887
888
|
self._sleep_calls: list[float] = []
|
|
@@ -914,14 +915,106 @@ class TestVerifyServer(unittest.TestCase):
|
|
|
914
915
|
calls = []
|
|
915
916
|
|
|
916
917
|
def post(url, data, headers, timeout):
|
|
917
|
-
calls.append(data)
|
|
918
|
+
calls.append((data, headers))
|
|
918
919
|
return 200, json.dumps({"verified": True}).encode()
|
|
919
920
|
|
|
920
921
|
verify_server("payload", self.URL, secret="sec_123", http_post=post)
|
|
921
922
|
self.assertEqual(
|
|
922
|
-
json.loads(calls[0]), {"payload": "payload", "secret": "sec_123"}
|
|
923
|
+
json.loads(calls[0][0]), {"payload": "payload", "secret": "sec_123"}
|
|
924
|
+
)
|
|
925
|
+
self.assertNotIn("Authorization", calls[0][1])
|
|
926
|
+
|
|
927
|
+
def test_v2_api_key_sent_as_basic_auth_without_body_secret(self):
|
|
928
|
+
calls = []
|
|
929
|
+
|
|
930
|
+
def post(url, data, headers, timeout):
|
|
931
|
+
calls.append((url, data, headers))
|
|
932
|
+
return 200, json.dumps({"verified": True}).encode()
|
|
933
|
+
|
|
934
|
+
verify_server(
|
|
935
|
+
"payload",
|
|
936
|
+
self.URL_V2,
|
|
937
|
+
secret="sec_123",
|
|
938
|
+
api_key="key_restricted",
|
|
939
|
+
headers={"authorization": "Bearer other", "X-Extra": "1"},
|
|
940
|
+
http_post=post,
|
|
941
|
+
)
|
|
942
|
+
url, data, headers = calls[0]
|
|
943
|
+
self.assertEqual(url, self.URL_V2)
|
|
944
|
+
self.assertEqual(json.loads(data), {"payload": "payload"})
|
|
945
|
+
self.assertEqual(
|
|
946
|
+
headers,
|
|
947
|
+
{
|
|
948
|
+
"Content-Type": "application/json",
|
|
949
|
+
"X-Extra": "1",
|
|
950
|
+
"Authorization": "Basic "
|
|
951
|
+
+ base64.b64encode(b"key_restricted:sec_123").decode(),
|
|
952
|
+
},
|
|
923
953
|
)
|
|
924
954
|
|
|
955
|
+
def test_v2_api_key_without_secret_raises(self):
|
|
956
|
+
def post(url, data, headers, timeout):
|
|
957
|
+
raise AssertionError("no request expected")
|
|
958
|
+
|
|
959
|
+
for secret in (None, ""):
|
|
960
|
+
with self.subTest(secret=secret), self.assertRaises(ValueError):
|
|
961
|
+
verify_server(
|
|
962
|
+
"payload",
|
|
963
|
+
self.URL_V2,
|
|
964
|
+
secret=secret,
|
|
965
|
+
api_key="key_restricted",
|
|
966
|
+
http_post=post,
|
|
967
|
+
)
|
|
968
|
+
|
|
969
|
+
def test_4xx_is_terminal_with_error_code(self):
|
|
970
|
+
for status in (400, 401, 403, 429):
|
|
971
|
+
calls = []
|
|
972
|
+
|
|
973
|
+
def post(url, data, headers, timeout, status=status, calls=calls):
|
|
974
|
+
calls.append(1)
|
|
975
|
+
body = {"code": "API_KEY_REQUIRED", "error": "API key required."}
|
|
976
|
+
return status, json.dumps({**body, "statusCode": status}).encode()
|
|
977
|
+
|
|
978
|
+
with self.subTest(status=status):
|
|
979
|
+
result = verify_server(
|
|
980
|
+
"payload", self.URL_V2, retries=3, http_post=post
|
|
981
|
+
)
|
|
982
|
+
self.assertFalse(result.verified)
|
|
983
|
+
self.assertEqual(result.reason, "API_KEY_REQUIRED")
|
|
984
|
+
self.assertEqual(len(calls), 1)
|
|
985
|
+
|
|
986
|
+
def test_5xx_retried_then_fails_with_error_code(self):
|
|
987
|
+
calls = []
|
|
988
|
+
|
|
989
|
+
def post(url, data, headers, timeout):
|
|
990
|
+
calls.append(1)
|
|
991
|
+
return 503, json.dumps({"code": "UNAVAILABLE", "error": "x"}).encode()
|
|
992
|
+
|
|
993
|
+
result = verify_server("payload", self.URL_V2, retries=2, http_post=post)
|
|
994
|
+
self.assertFalse(result.verified)
|
|
995
|
+
self.assertEqual(result.reason, "UNAVAILABLE")
|
|
996
|
+
self.assertEqual(len(calls), 3)
|
|
997
|
+
|
|
998
|
+
def test_error_without_json_body_reports_status(self):
|
|
999
|
+
def post(url, data, headers, timeout):
|
|
1000
|
+
return 502, b"Bad Gateway"
|
|
1001
|
+
|
|
1002
|
+
result = verify_server("payload", self.URL_V2, http_post=post)
|
|
1003
|
+
self.assertFalse(result.verified)
|
|
1004
|
+
self.assertEqual(result.reason, "HTTP_502")
|
|
1005
|
+
|
|
1006
|
+
def test_invalid_success_body_retried(self):
|
|
1007
|
+
responses = [b"<html>", b"[]", json.dumps({"verified": True}).encode()]
|
|
1008
|
+
|
|
1009
|
+
def post(url, data, headers, timeout):
|
|
1010
|
+
return 200, responses.pop(0)
|
|
1011
|
+
|
|
1012
|
+
result = verify_server("payload", self.URL_V2, retries=1, http_post=post)
|
|
1013
|
+
self.assertFalse(result.verified)
|
|
1014
|
+
self.assertEqual(result.reason, "INVALID_RESPONSE")
|
|
1015
|
+
result = verify_server("payload", self.URL_V2, http_post=post)
|
|
1016
|
+
self.assertTrue(result.verified)
|
|
1017
|
+
|
|
925
1018
|
def test_secret_omitted_when_not_given(self):
|
|
926
1019
|
calls = []
|
|
927
1020
|
|
|
@@ -975,6 +1068,8 @@ class TestVerifyServer(unittest.TestCase):
|
|
|
975
1068
|
signature="sig",
|
|
976
1069
|
verification_data="verified=true",
|
|
977
1070
|
verified=True,
|
|
1071
|
+
api_key="key_1",
|
|
1072
|
+
id="543713f0",
|
|
978
1073
|
)
|
|
979
1074
|
calls = []
|
|
980
1075
|
|
|
@@ -991,8 +1086,13 @@ class TestVerifyServer(unittest.TestCase):
|
|
|
991
1086
|
"signature": "sig",
|
|
992
1087
|
"verificationData": "verified=true",
|
|
993
1088
|
"verified": True,
|
|
1089
|
+
"apiKey": "key_1",
|
|
1090
|
+
"id": "543713f0",
|
|
994
1091
|
},
|
|
995
1092
|
)
|
|
1093
|
+
self.assertEqual(
|
|
1094
|
+
ServerSignaturePayload.from_dict(sent["payload"]).api_key, "key_1"
|
|
1095
|
+
)
|
|
996
1096
|
|
|
997
1097
|
def test_fixed_backoff(self):
|
|
998
1098
|
def post(url, data, headers, timeout):
|
|
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
|
|
File without changes
|