docql 0.2.1__tar.gz → 0.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.
- {docql-0.2.1 → docql-0.4.0}/PKG-INFO +110 -3
- {docql-0.2.1 → docql-0.4.0}/README.md +108 -1
- {docql-0.2.1 → docql-0.4.0}/pyproject.toml +2 -2
- {docql-0.2.1 → docql-0.4.0}/pyproject.toml.orig +2 -2
- {docql-0.2.1 → docql-0.4.0}/src/docql/__init__.py +22 -0
- {docql-0.2.1 → docql-0.4.0}/src/docql/_constants.py +7 -3
- {docql-0.2.1 → docql-0.4.0}/src/docql/_errors.py +12 -0
- {docql-0.2.1 → docql-0.4.0}/src/docql/_jobs.py +2 -1
- {docql-0.2.1 → docql-0.4.0}/src/docql/_response.py +48 -4
- docql-0.4.0/src/docql/_webhooks.py +340 -0
- {docql-0.2.1 → docql-0.4.0}/LICENSE +0 -0
- {docql-0.2.1 → docql-0.4.0}/src/docql/_client.py +0 -0
- {docql-0.2.1 → docql-0.4.0}/src/docql/_request.py +0 -0
- {docql-0.2.1 → docql-0.4.0}/src/docql/_version.py +0 -0
- {docql-0.2.1 → docql-0.4.0}/src/docql/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: docql
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Python client for the DocQL document-extraction API
|
|
5
5
|
Author: Finoniq
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -17,7 +17,7 @@ Requires-Python: >=3.11
|
|
|
17
17
|
Project-URL: Homepage, https://github.com/finoniq/docql-python
|
|
18
18
|
Project-URL: Repository, https://github.com/finoniq/docql-python
|
|
19
19
|
Project-URL: Issues, https://github.com/finoniq/docql-python/issues
|
|
20
|
-
Project-URL: Changelog, https://github.com/finoniq/docql-python/
|
|
20
|
+
Project-URL: Changelog, https://github.com/finoniq/docql-python/blob/main/CHANGELOG.md
|
|
21
21
|
Description-Content-Type: text/markdown
|
|
22
22
|
|
|
23
23
|
# DocQL Python SDK
|
|
@@ -92,6 +92,78 @@ with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
|
92
92
|
- `job.pages_done` stays 0 while DocQL runs OCR, so show progress as
|
|
93
93
|
indeterminate while a running job reports 0 pages done.
|
|
94
94
|
|
|
95
|
+
## Webhooks
|
|
96
|
+
|
|
97
|
+
DocQL signs every webhook delivery with your endpoint's secret, following the
|
|
98
|
+
open Standard Webhooks spec. Verify each delivery with `docql.verify_webhook`
|
|
99
|
+
before you trust it:
|
|
100
|
+
|
|
101
|
+
- Read the raw request bytes before any JSON framework parses them. A body that
|
|
102
|
+
was parsed and serialized again never verifies.
|
|
103
|
+
- Pass the endpoint secret (`whsec_…`). During the 24 h rotation overlap, pass
|
|
104
|
+
both secrets as a list: a delivery signed with either one verifies.
|
|
105
|
+
- The helper does no replay detection. Store each `event.id` and skip one you
|
|
106
|
+
have already seen: the id is the same across retries and resends.
|
|
107
|
+
- `event.type` is an open string. Compare it with `docql.EVENT_JOB_SUCCEEDED`,
|
|
108
|
+
`docql.EVENT_JOB_FAILED`, `docql.EVENT_JOB_CANCELLED` or
|
|
109
|
+
`docql.EVENT_WEBHOOK_TEST`, and ignore a type you do not know. Compare
|
|
110
|
+
`event.status` with the `docql.JOB_STATUS_*` constants.
|
|
111
|
+
- `tolerance=` (seconds, default 300) is the clock difference allowed between
|
|
112
|
+
DocQL and your receiver, either way.
|
|
113
|
+
|
|
114
|
+
A refused delivery raises `docql.WebhookVerificationError`, whose `reason` is
|
|
115
|
+
one of:
|
|
116
|
+
|
|
117
|
+
- `missing_header`: a `webhook-id`, `webhook-timestamp` or `webhook-signature`
|
|
118
|
+
header is absent, empty, or repeated with different values
|
|
119
|
+
- `invalid_timestamp`: `webhook-timestamp` is not 1 to 12 ASCII digits
|
|
120
|
+
- `invalid_signature_header`: `webhook-signature` has no well-formed v1 signature
|
|
121
|
+
- `signature_mismatch`: a wrong secret or a changed body
|
|
122
|
+
- `timestamp_too_old`: the signature is valid but older than the tolerance;
|
|
123
|
+
check your receiver's clock
|
|
124
|
+
- `timestamp_too_new`: the timestamp is further in the future than the tolerance
|
|
125
|
+
- `invalid_payload`: the signed body is not a DocQL webhook event
|
|
126
|
+
|
|
127
|
+
A receiver built on the standard library:
|
|
128
|
+
|
|
129
|
+
<!-- docql:webhook:start -->
|
|
130
|
+
```python
|
|
131
|
+
import os
|
|
132
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
133
|
+
|
|
134
|
+
import docql
|
|
135
|
+
|
|
136
|
+
SECRET = os.environ["DOCQL_WEBHOOK_SECRET"] # whsec_..., from the console
|
|
137
|
+
MAX_BODY = 1024 * 1024
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class Receiver(BaseHTTPRequestHandler):
|
|
141
|
+
def do_POST(self) -> None:
|
|
142
|
+
try:
|
|
143
|
+
length = int(self.headers["Content-Length"])
|
|
144
|
+
except (TypeError, ValueError): # absent or not a number
|
|
145
|
+
length = -1
|
|
146
|
+
if not 0 <= length <= MAX_BODY:
|
|
147
|
+
self.send_response(413 if length > MAX_BODY else 400)
|
|
148
|
+
self.end_headers()
|
|
149
|
+
return
|
|
150
|
+
body = self.rfile.read(length) # the raw bytes, before any JSON parsing
|
|
151
|
+
try:
|
|
152
|
+
event = docql.verify_webhook(body, dict(self.headers), SECRET)
|
|
153
|
+
except docql.WebhookVerificationError as err:
|
|
154
|
+
self.log_error("webhook refused: %s", err.reason)
|
|
155
|
+
self.send_response(400)
|
|
156
|
+
self.end_headers()
|
|
157
|
+
return
|
|
158
|
+
print(f"event {event.type} {event.id}") # store event.id; skip one already seen
|
|
159
|
+
self.send_response(204)
|
|
160
|
+
self.end_headers()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
HTTPServer(("127.0.0.1", int(os.environ.get("PORT", "8000"))), Receiver).serve_forever()
|
|
164
|
+
```
|
|
165
|
+
<!-- docql:webhook:end -->
|
|
166
|
+
|
|
95
167
|
## Configuration
|
|
96
168
|
|
|
97
169
|
| Keyword | Env variable | Default | Notes |
|
|
@@ -133,6 +205,41 @@ binary file object:
|
|
|
133
205
|
- There are no client-side type or size checks — the server is the authority.
|
|
134
206
|
- A stream whose length cannot be measured is sent chunked; an oversized one
|
|
135
207
|
may answer `503` instead of `413`. The API rejects files over 25 MiB.
|
|
208
|
+
- A CSV is recognised only by a file name that ends in `.csv`, in any letter
|
|
209
|
+
case (`sales.csv`, `SALES.CSV`). When you send `bytes` or a stream, pass the
|
|
210
|
+
name with `filename=`. The name is sent exactly as given and never trimmed,
|
|
211
|
+
so `"a.csv "` with a trailing space is refused with `unsupported_file_type`.
|
|
212
|
+
|
|
213
|
+
## Spreadsheets
|
|
214
|
+
|
|
215
|
+
`.xlsx`, `.ods` and `.csv` files are sent like any other file. A refused
|
|
216
|
+
spreadsheet raises `docql.DocQLError`, whose `metadata` is the server's raw
|
|
217
|
+
refusal object. For `spreadsheet_too_large` it holds the measured value under
|
|
218
|
+
its axis key (`cells`, `runes`, `estimated_output_tokens` or `bytes`), plus
|
|
219
|
+
`limit`, `reason` and `request_id`. Find the axis by name, not by key order:
|
|
220
|
+
|
|
221
|
+
<!-- docql:spreadsheet:start -->
|
|
222
|
+
```python
|
|
223
|
+
from pathlib import Path
|
|
224
|
+
|
|
225
|
+
import docql
|
|
226
|
+
from docql import DocQL
|
|
227
|
+
|
|
228
|
+
with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
229
|
+
data = Path("sales.csv").read_bytes()
|
|
230
|
+
try:
|
|
231
|
+
result = client.query_document(data, query="{ region total_sales }", filename="sales.csv")
|
|
232
|
+
print(result.page_count)
|
|
233
|
+
except docql.DocQLError as err:
|
|
234
|
+
if err.reason != docql.REASON_SPREADSHEET_TOO_LARGE:
|
|
235
|
+
raise
|
|
236
|
+
axes = ("cells", "runes", "estimated_output_tokens", "bytes")
|
|
237
|
+
axis = next((k for k in axes if k in err.metadata), None)
|
|
238
|
+
if axis is None:
|
|
239
|
+
raise
|
|
240
|
+
print(f"too large: {axis}={err.metadata[axis]} limit={err.metadata['limit']}")
|
|
241
|
+
```
|
|
242
|
+
<!-- docql:spreadsheet:end -->
|
|
136
243
|
|
|
137
244
|
## Modes
|
|
138
245
|
|
|
@@ -208,7 +315,7 @@ two mean the request was not processed.
|
|
|
208
315
|
## Versioning
|
|
209
316
|
|
|
210
317
|
The SDK follows [Semantic Versioning](https://semver.org/). While the major
|
|
211
|
-
version is 0, a minor release may change the API; pin `docql>=0.
|
|
318
|
+
version is 0, a minor release may change the API; pin `docql>=0.4,<0.5` until
|
|
212
319
|
1.0.
|
|
213
320
|
|
|
214
321
|
## Support
|
|
@@ -70,6 +70,78 @@ with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
|
70
70
|
- `job.pages_done` stays 0 while DocQL runs OCR, so show progress as
|
|
71
71
|
indeterminate while a running job reports 0 pages done.
|
|
72
72
|
|
|
73
|
+
## Webhooks
|
|
74
|
+
|
|
75
|
+
DocQL signs every webhook delivery with your endpoint's secret, following the
|
|
76
|
+
open Standard Webhooks spec. Verify each delivery with `docql.verify_webhook`
|
|
77
|
+
before you trust it:
|
|
78
|
+
|
|
79
|
+
- Read the raw request bytes before any JSON framework parses them. A body that
|
|
80
|
+
was parsed and serialized again never verifies.
|
|
81
|
+
- Pass the endpoint secret (`whsec_…`). During the 24 h rotation overlap, pass
|
|
82
|
+
both secrets as a list: a delivery signed with either one verifies.
|
|
83
|
+
- The helper does no replay detection. Store each `event.id` and skip one you
|
|
84
|
+
have already seen: the id is the same across retries and resends.
|
|
85
|
+
- `event.type` is an open string. Compare it with `docql.EVENT_JOB_SUCCEEDED`,
|
|
86
|
+
`docql.EVENT_JOB_FAILED`, `docql.EVENT_JOB_CANCELLED` or
|
|
87
|
+
`docql.EVENT_WEBHOOK_TEST`, and ignore a type you do not know. Compare
|
|
88
|
+
`event.status` with the `docql.JOB_STATUS_*` constants.
|
|
89
|
+
- `tolerance=` (seconds, default 300) is the clock difference allowed between
|
|
90
|
+
DocQL and your receiver, either way.
|
|
91
|
+
|
|
92
|
+
A refused delivery raises `docql.WebhookVerificationError`, whose `reason` is
|
|
93
|
+
one of:
|
|
94
|
+
|
|
95
|
+
- `missing_header`: a `webhook-id`, `webhook-timestamp` or `webhook-signature`
|
|
96
|
+
header is absent, empty, or repeated with different values
|
|
97
|
+
- `invalid_timestamp`: `webhook-timestamp` is not 1 to 12 ASCII digits
|
|
98
|
+
- `invalid_signature_header`: `webhook-signature` has no well-formed v1 signature
|
|
99
|
+
- `signature_mismatch`: a wrong secret or a changed body
|
|
100
|
+
- `timestamp_too_old`: the signature is valid but older than the tolerance;
|
|
101
|
+
check your receiver's clock
|
|
102
|
+
- `timestamp_too_new`: the timestamp is further in the future than the tolerance
|
|
103
|
+
- `invalid_payload`: the signed body is not a DocQL webhook event
|
|
104
|
+
|
|
105
|
+
A receiver built on the standard library:
|
|
106
|
+
|
|
107
|
+
<!-- docql:webhook:start -->
|
|
108
|
+
```python
|
|
109
|
+
import os
|
|
110
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
111
|
+
|
|
112
|
+
import docql
|
|
113
|
+
|
|
114
|
+
SECRET = os.environ["DOCQL_WEBHOOK_SECRET"] # whsec_..., from the console
|
|
115
|
+
MAX_BODY = 1024 * 1024
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class Receiver(BaseHTTPRequestHandler):
|
|
119
|
+
def do_POST(self) -> None:
|
|
120
|
+
try:
|
|
121
|
+
length = int(self.headers["Content-Length"])
|
|
122
|
+
except (TypeError, ValueError): # absent or not a number
|
|
123
|
+
length = -1
|
|
124
|
+
if not 0 <= length <= MAX_BODY:
|
|
125
|
+
self.send_response(413 if length > MAX_BODY else 400)
|
|
126
|
+
self.end_headers()
|
|
127
|
+
return
|
|
128
|
+
body = self.rfile.read(length) # the raw bytes, before any JSON parsing
|
|
129
|
+
try:
|
|
130
|
+
event = docql.verify_webhook(body, dict(self.headers), SECRET)
|
|
131
|
+
except docql.WebhookVerificationError as err:
|
|
132
|
+
self.log_error("webhook refused: %s", err.reason)
|
|
133
|
+
self.send_response(400)
|
|
134
|
+
self.end_headers()
|
|
135
|
+
return
|
|
136
|
+
print(f"event {event.type} {event.id}") # store event.id; skip one already seen
|
|
137
|
+
self.send_response(204)
|
|
138
|
+
self.end_headers()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
HTTPServer(("127.0.0.1", int(os.environ.get("PORT", "8000"))), Receiver).serve_forever()
|
|
142
|
+
```
|
|
143
|
+
<!-- docql:webhook:end -->
|
|
144
|
+
|
|
73
145
|
## Configuration
|
|
74
146
|
|
|
75
147
|
| Keyword | Env variable | Default | Notes |
|
|
@@ -111,6 +183,41 @@ binary file object:
|
|
|
111
183
|
- There are no client-side type or size checks — the server is the authority.
|
|
112
184
|
- A stream whose length cannot be measured is sent chunked; an oversized one
|
|
113
185
|
may answer `503` instead of `413`. The API rejects files over 25 MiB.
|
|
186
|
+
- A CSV is recognised only by a file name that ends in `.csv`, in any letter
|
|
187
|
+
case (`sales.csv`, `SALES.CSV`). When you send `bytes` or a stream, pass the
|
|
188
|
+
name with `filename=`. The name is sent exactly as given and never trimmed,
|
|
189
|
+
so `"a.csv "` with a trailing space is refused with `unsupported_file_type`.
|
|
190
|
+
|
|
191
|
+
## Spreadsheets
|
|
192
|
+
|
|
193
|
+
`.xlsx`, `.ods` and `.csv` files are sent like any other file. A refused
|
|
194
|
+
spreadsheet raises `docql.DocQLError`, whose `metadata` is the server's raw
|
|
195
|
+
refusal object. For `spreadsheet_too_large` it holds the measured value under
|
|
196
|
+
its axis key (`cells`, `runes`, `estimated_output_tokens` or `bytes`), plus
|
|
197
|
+
`limit`, `reason` and `request_id`. Find the axis by name, not by key order:
|
|
198
|
+
|
|
199
|
+
<!-- docql:spreadsheet:start -->
|
|
200
|
+
```python
|
|
201
|
+
from pathlib import Path
|
|
202
|
+
|
|
203
|
+
import docql
|
|
204
|
+
from docql import DocQL
|
|
205
|
+
|
|
206
|
+
with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
207
|
+
data = Path("sales.csv").read_bytes()
|
|
208
|
+
try:
|
|
209
|
+
result = client.query_document(data, query="{ region total_sales }", filename="sales.csv")
|
|
210
|
+
print(result.page_count)
|
|
211
|
+
except docql.DocQLError as err:
|
|
212
|
+
if err.reason != docql.REASON_SPREADSHEET_TOO_LARGE:
|
|
213
|
+
raise
|
|
214
|
+
axes = ("cells", "runes", "estimated_output_tokens", "bytes")
|
|
215
|
+
axis = next((k for k in axes if k in err.metadata), None)
|
|
216
|
+
if axis is None:
|
|
217
|
+
raise
|
|
218
|
+
print(f"too large: {axis}={err.metadata[axis]} limit={err.metadata['limit']}")
|
|
219
|
+
```
|
|
220
|
+
<!-- docql:spreadsheet:end -->
|
|
114
221
|
|
|
115
222
|
## Modes
|
|
116
223
|
|
|
@@ -186,7 +293,7 @@ two mean the request was not processed.
|
|
|
186
293
|
## Versioning
|
|
187
294
|
|
|
188
295
|
The SDK follows [Semantic Versioning](https://semver.org/). While the major
|
|
189
|
-
version is 0, a minor release may change the API; pin `docql>=0.
|
|
296
|
+
version is 0, a minor release may change the API; pin `docql>=0.4,<0.5` until
|
|
190
297
|
1.0.
|
|
191
298
|
|
|
192
299
|
## Support
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "docql"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.0"
|
|
4
4
|
description = "Python client for the DocQL document-extraction API"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
@@ -24,7 +24,7 @@ name = "Finoniq"
|
|
|
24
24
|
Homepage = "https://github.com/finoniq/docql-python"
|
|
25
25
|
Repository = "https://github.com/finoniq/docql-python"
|
|
26
26
|
Issues = "https://github.com/finoniq/docql-python/issues"
|
|
27
|
-
Changelog = "https://github.com/finoniq/docql-python/
|
|
27
|
+
Changelog = "https://github.com/finoniq/docql-python/blob/main/CHANGELOG.md"
|
|
28
28
|
|
|
29
29
|
[dependency-groups]
|
|
30
30
|
dev = [
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "docql"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.0"
|
|
4
4
|
description = "Python client for the DocQL document-extraction API"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
@@ -22,7 +22,7 @@ classifiers = [
|
|
|
22
22
|
Homepage = "https://github.com/finoniq/docql-python"
|
|
23
23
|
Repository = "https://github.com/finoniq/docql-python"
|
|
24
24
|
Issues = "https://github.com/finoniq/docql-python/issues"
|
|
25
|
-
Changelog = "https://github.com/finoniq/docql-python/
|
|
25
|
+
Changelog = "https://github.com/finoniq/docql-python/blob/main/CHANGELOG.md"
|
|
26
26
|
|
|
27
27
|
[dependency-groups]
|
|
28
28
|
dev = ["pytest>=9.1.1", "mypy>=2.4.0", "ruff>=0.16.10"]
|
|
@@ -13,6 +13,7 @@ from docql._constants import (
|
|
|
13
13
|
REASON_CONCURRENCY_LIMIT_EXCEEDED,
|
|
14
14
|
REASON_CORRUPTED_FILE,
|
|
15
15
|
REASON_DOCUMENT_EXCEEDS_TIME_BUDGET,
|
|
16
|
+
REASON_DOCUMENT_TOO_COMPLEX,
|
|
16
17
|
REASON_IDEMPOTENCY_IN_PROGRESS,
|
|
17
18
|
REASON_IDEMPOTENCY_KEY_CONFLICT,
|
|
18
19
|
REASON_INVALID_API_KEY,
|
|
@@ -26,6 +27,8 @@ from docql._constants import (
|
|
|
26
27
|
REASON_QUEUE_FULL,
|
|
27
28
|
REASON_RATE_LIMIT_EXCEEDED,
|
|
28
29
|
REASON_SERVICE_OVERLOADED,
|
|
30
|
+
REASON_SPREADSHEET_TOO_LARGE,
|
|
31
|
+
REASON_TOO_MANY_PAGES,
|
|
29
32
|
REASON_UNSUPPORTED_FILE_TYPE,
|
|
30
33
|
REASON_UNSUPPORTED_MEDIA_TYPE,
|
|
31
34
|
REASON_UPLOAD_TOO_LARGE,
|
|
@@ -43,6 +46,15 @@ from docql._errors import (
|
|
|
43
46
|
from docql._jobs import Job
|
|
44
47
|
from docql._response import QueryResult
|
|
45
48
|
from docql._version import __version__
|
|
49
|
+
from docql._webhooks import (
|
|
50
|
+
EVENT_JOB_CANCELLED,
|
|
51
|
+
EVENT_JOB_FAILED,
|
|
52
|
+
EVENT_JOB_SUCCEEDED,
|
|
53
|
+
EVENT_WEBHOOK_TEST,
|
|
54
|
+
WebhookEvent,
|
|
55
|
+
WebhookVerificationError,
|
|
56
|
+
verify_webhook,
|
|
57
|
+
)
|
|
46
58
|
|
|
47
59
|
__all__ = [
|
|
48
60
|
"DocQL",
|
|
@@ -51,6 +63,10 @@ __all__ = [
|
|
|
51
63
|
"DocQLException",
|
|
52
64
|
"DocQLTimeoutError",
|
|
53
65
|
"DocQLWaitTimeoutError",
|
|
66
|
+
"EVENT_JOB_CANCELLED",
|
|
67
|
+
"EVENT_JOB_FAILED",
|
|
68
|
+
"EVENT_JOB_SUCCEEDED",
|
|
69
|
+
"EVENT_WEBHOOK_TEST",
|
|
54
70
|
"JOB_STATUS_CANCELLED",
|
|
55
71
|
"JOB_STATUS_FAILED",
|
|
56
72
|
"JOB_STATUS_QUEUED",
|
|
@@ -65,6 +81,7 @@ __all__ = [
|
|
|
65
81
|
"REASON_CONCURRENCY_LIMIT_EXCEEDED",
|
|
66
82
|
"REASON_CORRUPTED_FILE",
|
|
67
83
|
"REASON_DOCUMENT_EXCEEDS_TIME_BUDGET",
|
|
84
|
+
"REASON_DOCUMENT_TOO_COMPLEX",
|
|
68
85
|
"REASON_IDEMPOTENCY_IN_PROGRESS",
|
|
69
86
|
"REASON_IDEMPOTENCY_KEY_CONFLICT",
|
|
70
87
|
"REASON_INVALID_API_KEY",
|
|
@@ -78,10 +95,15 @@ __all__ = [
|
|
|
78
95
|
"REASON_QUEUE_FULL",
|
|
79
96
|
"REASON_RATE_LIMIT_EXCEEDED",
|
|
80
97
|
"REASON_SERVICE_OVERLOADED",
|
|
98
|
+
"REASON_SPREADSHEET_TOO_LARGE",
|
|
99
|
+
"REASON_TOO_MANY_PAGES",
|
|
81
100
|
"REASON_UNSUPPORTED_FILE_TYPE",
|
|
82
101
|
"REASON_UNSUPPORTED_MEDIA_TYPE",
|
|
83
102
|
"REASON_UPLOAD_TOO_LARGE",
|
|
84
103
|
"REASON_UPSTREAM_AUTH_FAILED",
|
|
85
104
|
"REASON_UPSTREAM_UNAVAILABLE",
|
|
105
|
+
"WebhookEvent",
|
|
106
|
+
"WebhookVerificationError",
|
|
86
107
|
"__version__",
|
|
108
|
+
"verify_webhook",
|
|
87
109
|
]
|
|
@@ -35,9 +35,10 @@ ERROR_BODY_READ_LIMIT: Final[int] = 65536
|
|
|
35
35
|
# because an early RST may have discarded the 413 (research Pitfall 4).
|
|
36
36
|
MAX_UPLOAD_BYTES: Final[int] = 26_214_400
|
|
37
37
|
|
|
38
|
-
# Reason constants (D-05, D-09): exactly the
|
|
39
|
-
# contract kit — contract/sdk-cases.json (the sync stub and gateway
|
|
40
|
-
# contract/job-cases.json (the job errors)
|
|
38
|
+
# Reason constants (D-05, D-09, D-12): exactly the 25 non-null reasons of the
|
|
39
|
+
# vendored contract kit — contract/sdk-cases.json (the sync stub and gateway
|
|
40
|
+
# errors), contract/job-cases.json (the job errors) and contract/sheet-cases.json
|
|
41
|
+
# (the kit v5 spreadsheet refusals). The engine's wider class table stays
|
|
41
42
|
# reachable through the open ``reason: str``; adding constants later is
|
|
42
43
|
# backward compatible, removing them is not.
|
|
43
44
|
REASON_INVALID_API_KEY: Final[str] = "invalid_api_key"
|
|
@@ -62,6 +63,9 @@ REASON_QUEUE_FULL: Final[str] = "queue_full"
|
|
|
62
63
|
REASON_IDEMPOTENCY_KEY_CONFLICT: Final[str] = "idempotency_key_conflict"
|
|
63
64
|
REASON_IDEMPOTENCY_IN_PROGRESS: Final[str] = "idempotency_in_progress"
|
|
64
65
|
REASON_JOB_INTERRUPTED: Final[str] = "job_interrupted"
|
|
66
|
+
REASON_DOCUMENT_TOO_COMPLEX: Final[str] = "document_too_complex"
|
|
67
|
+
REASON_SPREADSHEET_TOO_LARGE: Final[str] = "spreadsheet_too_large"
|
|
68
|
+
REASON_TOO_MANY_PAGES: Final[str] = "too_many_pages"
|
|
65
69
|
|
|
66
70
|
# Async jobs (JSDK-01). Status values are open strings (D-09): an unknown status
|
|
67
71
|
# from a future DocQL release is kept verbatim on Job.status, never an error.
|
|
@@ -35,6 +35,15 @@ class DocQLError(DocQLException):
|
|
|
35
35
|
cancel error). ``idempotency_key`` is set on errors from
|
|
36
36
|
``submit_document`` so the caller can retry with the same key; it is a
|
|
37
37
|
field only and never appears in :func:`str` or :func:`repr` (D-08).
|
|
38
|
+
|
|
39
|
+
``metadata`` is the server's raw refusal metadata object, as a dict (D-06).
|
|
40
|
+
For ``spreadsheet_too_large`` it holds the measured value under its axis
|
|
41
|
+
key (``cells``, ``runes``, ``estimated_output_tokens`` or ``bytes``),
|
|
42
|
+
``limit``, ``reason`` and ``request_id``; for ``too_many_pages`` it holds
|
|
43
|
+
``pages`` and ``limit``. Every occurrence of the API key in its keys and
|
|
44
|
+
string values is replaced with ``***``. It is ``{}`` when the answer
|
|
45
|
+
carried no metadata object, and it never appears in :func:`str` or
|
|
46
|
+
:func:`repr`.
|
|
38
47
|
"""
|
|
39
48
|
|
|
40
49
|
def __init__(
|
|
@@ -49,6 +58,7 @@ class DocQLError(DocQLException):
|
|
|
49
58
|
body: str,
|
|
50
59
|
job_id: str | None = None,
|
|
51
60
|
idempotency_key: str | None = None,
|
|
61
|
+
metadata: dict[str, Any] | None = None,
|
|
52
62
|
) -> None:
|
|
53
63
|
super().__init__()
|
|
54
64
|
self.status = status
|
|
@@ -60,6 +70,7 @@ class DocQLError(DocQLException):
|
|
|
60
70
|
self.body = body
|
|
61
71
|
self.job_id = job_id
|
|
62
72
|
self.idempotency_key = idempotency_key
|
|
73
|
+
self.metadata: dict[str, Any] = {} if metadata is None else metadata
|
|
63
74
|
|
|
64
75
|
def __str__(self) -> str:
|
|
65
76
|
if self.reason is not None:
|
|
@@ -106,6 +117,7 @@ class DocQLError(DocQLException):
|
|
|
106
117
|
"body": self.body,
|
|
107
118
|
"job_id": self.job_id,
|
|
108
119
|
"idempotency_key": self.idempotency_key,
|
|
120
|
+
"metadata": self.metadata,
|
|
109
121
|
},
|
|
110
122
|
)
|
|
111
123
|
|
|
@@ -206,7 +206,8 @@ def parse_job(
|
|
|
206
206
|
"""
|
|
207
207
|
try:
|
|
208
208
|
doc: Any = json.loads(body)
|
|
209
|
-
except ValueError:
|
|
209
|
+
except (ValueError, RecursionError):
|
|
210
|
+
# CR-01: a deeply nested body is unusable, never a crash.
|
|
210
211
|
doc = None
|
|
211
212
|
if not isinstance(doc, dict):
|
|
212
213
|
raise _unusable_result(status, headers, body, api_key, "unexpected non-JSON response")
|
|
@@ -50,6 +50,40 @@ def _scrub_and_truncate(text: str, api_key: str) -> str:
|
|
|
50
50
|
return text[:ERROR_BODY_KEEP_CHARS]
|
|
51
51
|
|
|
52
52
|
|
|
53
|
+
def _scrub_deep(value: Any, api_key: str) -> Any:
|
|
54
|
+
"""Replace the key in every string inside ``value``, dict keys included (D-06).
|
|
55
|
+
|
|
56
|
+
Used for the error metadata, which a developer may log or store: a
|
|
57
|
+
reflecting server must never get the key into it. Numbers, booleans and
|
|
58
|
+
None pass through unchanged. The walk uses an explicit stack, so a deeply
|
|
59
|
+
nested body cannot raise RecursionError here (CR-01); when two keys scrub
|
|
60
|
+
to the same text, the later one wins, as before.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def scrub(item: Any) -> Any:
|
|
64
|
+
return item.replace(api_key, "***") if api_key and isinstance(item, str) else item
|
|
65
|
+
|
|
66
|
+
def empty_like(item: Any) -> Any:
|
|
67
|
+
return {} if isinstance(item, dict) else []
|
|
68
|
+
|
|
69
|
+
if not isinstance(value, (dict, list)):
|
|
70
|
+
return scrub(value)
|
|
71
|
+
root = empty_like(value)
|
|
72
|
+
stack: list[tuple[Any, Any]] = [(value, root)]
|
|
73
|
+
while stack:
|
|
74
|
+
source, target = stack.pop()
|
|
75
|
+
pairs = source.items() if isinstance(source, dict) else ((None, v) for v in source)
|
|
76
|
+
for key, item in pairs:
|
|
77
|
+
out = empty_like(item) if isinstance(item, (dict, list)) else scrub(item)
|
|
78
|
+
if isinstance(source, dict):
|
|
79
|
+
target[scrub(key)] = out
|
|
80
|
+
else:
|
|
81
|
+
target.append(out)
|
|
82
|
+
if isinstance(item, (dict, list)):
|
|
83
|
+
stack.append((item, out))
|
|
84
|
+
return root
|
|
85
|
+
|
|
86
|
+
|
|
53
87
|
def parse_retry_after(value: str | None, now: datetime | None = None) -> int | None:
|
|
54
88
|
"""``Retry-After`` as whole seconds, or None when absent/unparsable.
|
|
55
89
|
|
|
@@ -110,7 +144,8 @@ def parse_result(
|
|
|
110
144
|
"""
|
|
111
145
|
try:
|
|
112
146
|
doc: Any = json.loads(body)
|
|
113
|
-
except ValueError:
|
|
147
|
+
except (ValueError, RecursionError):
|
|
148
|
+
# CR-01: a deeply nested body is unusable, never a crash.
|
|
114
149
|
doc = None
|
|
115
150
|
if not isinstance(doc, dict):
|
|
116
151
|
raise _unusable_result(status, headers, body, api_key, "unexpected non-JSON response")
|
|
@@ -146,18 +181,26 @@ def decode_error(
|
|
|
146
181
|
|
|
147
182
|
Classification is by status, never by body shape. An envelope is present
|
|
148
183
|
only when the JSON body is a dict whose ``metadata`` is a dict with a str
|
|
149
|
-
``reason``. Neither the stored ``body`` nor ``
|
|
150
|
-
API key, even when the server echoes it back.
|
|
184
|
+
``reason``. Neither the stored ``body``, ``message`` nor ``metadata`` ever
|
|
185
|
+
contains the API key, even when the server echoes it back.
|
|
186
|
+
|
|
187
|
+
``metadata`` is parsed from the whole bounded body, before the stored body
|
|
188
|
+
is cut, and is filled whenever the body carries a metadata object, for
|
|
189
|
+
every reason (D-06, D-12); otherwise the error keeps the default ``{}``.
|
|
151
190
|
"""
|
|
152
191
|
reason: str | None = None
|
|
153
192
|
message: str | None = None
|
|
154
193
|
request_id: str | None = None
|
|
194
|
+
metadata_out: dict[str, Any] | None = None
|
|
155
195
|
try:
|
|
156
196
|
doc: Any = json.loads(body)
|
|
157
|
-
except ValueError:
|
|
197
|
+
except (ValueError, RecursionError):
|
|
198
|
+
# CR-01: a deeply nested body is unusable, never a crash.
|
|
158
199
|
doc = None
|
|
159
200
|
if isinstance(doc, dict):
|
|
160
201
|
metadata = doc.get("metadata")
|
|
202
|
+
if isinstance(metadata, dict):
|
|
203
|
+
metadata_out = _scrub_deep(metadata, api_key)
|
|
161
204
|
if isinstance(metadata, dict) and isinstance(metadata.get("reason"), str):
|
|
162
205
|
reason = metadata["reason"]
|
|
163
206
|
error_info = doc.get("error_info")
|
|
@@ -182,4 +225,5 @@ def decode_error(
|
|
|
182
225
|
retryable=status in (429, 503),
|
|
183
226
|
message=message,
|
|
184
227
|
body=_scrub_and_truncate(body.decode("utf-8", "replace"), api_key),
|
|
228
|
+
metadata=metadata_out,
|
|
185
229
|
)
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Verify a DocQL webhook delivery (D-06..D-16, D-25..D-29).
|
|
2
|
+
|
|
3
|
+
A receiver has no API key, so the helper is a standalone function, never a
|
|
4
|
+
client method. It checks, in this fixed order: the tolerance, every secret, the
|
|
5
|
+
body type, the presence of the three headers, the timestamp syntax, the ``v1``
|
|
6
|
+
signature entries, the HMAC, the tolerance window and finally the event body.
|
|
7
|
+
Request data (the body and the header names and values) can only produce a
|
|
8
|
+
:class:`WebhookEvent` or a :class:`WebhookVerificationError`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import binascii
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import re
|
|
18
|
+
import time
|
|
19
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from datetime import UTC, datetime
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from docql._errors import DocQLException
|
|
25
|
+
|
|
26
|
+
EVENT_JOB_SUCCEEDED = "job.succeeded"
|
|
27
|
+
EVENT_JOB_FAILED = "job.failed"
|
|
28
|
+
EVENT_JOB_CANCELLED = "job.cancelled"
|
|
29
|
+
EVENT_WEBHOOK_TEST = "webhook.test"
|
|
30
|
+
|
|
31
|
+
DEFAULT_TOLERANCE = 300
|
|
32
|
+
|
|
33
|
+
_SECRET_PREFIX = "whsec_"
|
|
34
|
+
_SECRET_MIN_BYTES = 24
|
|
35
|
+
_SECRET_MAX_BYTES = 64
|
|
36
|
+
_SIGNATURE_BYTES = 32
|
|
37
|
+
_TIMESTAMP_MAX_DIGITS = 12
|
|
38
|
+
# D-29: exactly space, tab, LF and CR; never the Unicode-wide default strip set.
|
|
39
|
+
_SECRET_TRIM = " \t\n\r"
|
|
40
|
+
|
|
41
|
+
_HEADER_ID = "webhook-id"
|
|
42
|
+
_HEADER_TIMESTAMP = "webhook-timestamp"
|
|
43
|
+
_HEADER_SIGNATURE = "webhook-signature"
|
|
44
|
+
|
|
45
|
+
# D-14: the seven reasons and the one fixed sentence each carries. These names
|
|
46
|
+
# never start with REASON_, which is the API error namespace (D-28).
|
|
47
|
+
_WEBHOOK_MESSAGES = {
|
|
48
|
+
"missing_header": (
|
|
49
|
+
"a webhook-id, webhook-timestamp or webhook-signature header is absent, "
|
|
50
|
+
"empty, or repeated with different values"
|
|
51
|
+
),
|
|
52
|
+
"invalid_timestamp": "the webhook-timestamp header is not 1 to 12 ASCII digits",
|
|
53
|
+
"invalid_signature_header": "the webhook-signature header has no well-formed v1 signature",
|
|
54
|
+
"signature_mismatch": "no v1 signature matches any secret (wrong secret or a changed body)",
|
|
55
|
+
"timestamp_too_old": "the webhook-timestamp is older than the tolerance allows",
|
|
56
|
+
"timestamp_too_new": "the webhook-timestamp is further in the future than the tolerance allows",
|
|
57
|
+
"invalid_payload": "the signed body is not a DocQL webhook event",
|
|
58
|
+
}
|
|
59
|
+
_WEBHOOK_REASONS = frozenset(_WEBHOOK_MESSAGES)
|
|
60
|
+
|
|
61
|
+
_EVENT_TIMESTAMP = re.compile(
|
|
62
|
+
r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z", re.ASCII
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class WebhookEvent:
|
|
68
|
+
"""A verified DocQL webhook event (D-08, D-25).
|
|
69
|
+
|
|
70
|
+
``type`` is an open string: compare it with ``EVENT_JOB_SUCCEEDED``,
|
|
71
|
+
``EVENT_JOB_FAILED``, ``EVENT_JOB_CANCELLED`` or ``EVENT_WEBHOOK_TEST``,
|
|
72
|
+
and treat any other value as an event type this SDK does not know yet.
|
|
73
|
+
``timestamp`` is an aware UTC datetime. ``job_id`` and ``status`` are
|
|
74
|
+
``data["job_id"]`` and ``data["status"]`` when they are strings, else None
|
|
75
|
+
(a ``webhook.test`` event has ``data == {}``). ``data`` is the event's raw
|
|
76
|
+
``data`` object, unknown keys included; it is never None.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
id: str
|
|
80
|
+
type: str
|
|
81
|
+
timestamp: datetime
|
|
82
|
+
job_id: str | None
|
|
83
|
+
status: str | None
|
|
84
|
+
data: dict[str, Any]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class WebhookVerificationError(DocQLException):
|
|
88
|
+
"""The delivery failed verification; do not act on it (D-13, D-14).
|
|
89
|
+
|
|
90
|
+
``reason`` is one of ``missing_header``, ``invalid_timestamp``,
|
|
91
|
+
``invalid_signature_header``, ``signature_mismatch``,
|
|
92
|
+
``timestamp_too_old``, ``timestamp_too_new`` or ``invalid_payload``.
|
|
93
|
+
Neither :func:`str` nor :func:`repr` ever holds anything but the reason and
|
|
94
|
+
a fixed sentence: never a secret, the expected signature or a received
|
|
95
|
+
signature. This is not a :class:`DocQLError`, because no API call failed.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, reason: str) -> None:
|
|
99
|
+
self.reason = reason
|
|
100
|
+
super().__init__(f"{reason}: {_WEBHOOK_MESSAGES.get(reason, 'verification failed')}")
|
|
101
|
+
|
|
102
|
+
def __repr__(self) -> str:
|
|
103
|
+
return f"{type(self).__name__}(reason={self.reason!r})"
|
|
104
|
+
|
|
105
|
+
def __reduce__(self) -> tuple[Callable[[str], "WebhookVerificationError"], tuple[str]]:
|
|
106
|
+
return _rebuild_webhook_error, (self.reason,)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _rebuild_webhook_error(reason: str) -> WebhookVerificationError:
|
|
110
|
+
return WebhookVerificationError(reason)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def verify_webhook(
|
|
114
|
+
body: bytes | str,
|
|
115
|
+
headers: Mapping[str, str],
|
|
116
|
+
secrets: str | Sequence[str],
|
|
117
|
+
*,
|
|
118
|
+
tolerance: float = DEFAULT_TOLERANCE,
|
|
119
|
+
) -> WebhookEvent:
|
|
120
|
+
"""Verify one DocQL webhook delivery and return its event.
|
|
121
|
+
|
|
122
|
+
Pass the raw request body exactly as received, before any JSON parsing (a
|
|
123
|
+
``str`` is UTF-8 encoded), the request headers (names match without regard
|
|
124
|
+
to ASCII case) and the endpoint's webhook secret, or a list of secrets
|
|
125
|
+
while a rotation overlaps. ``tolerance`` is the allowed clock skew in
|
|
126
|
+
seconds either way (default 300, inclusive). The helper does not detect
|
|
127
|
+
replays: dedupe on ``event.id``, which stays the same across retries.
|
|
128
|
+
|
|
129
|
+
Raises:
|
|
130
|
+
TypeError: ``tolerance``, ``secrets`` or ``body`` has the wrong type.
|
|
131
|
+
ValueError: ``tolerance`` is not a positive finite number, the secret
|
|
132
|
+
list is empty, or a secret is not ``whsec_`` plus canonical base64
|
|
133
|
+
of 24 to 64 bytes. The message names the position, never the secret.
|
|
134
|
+
WebhookVerificationError: the delivery is not an authentic, timely
|
|
135
|
+
DocQL webhook event; ``reason`` says why.
|
|
136
|
+
"""
|
|
137
|
+
return _verify_at(body, headers, secrets, tolerance=tolerance, now=int(time.time()))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _verify_at(
|
|
141
|
+
body: bytes | str,
|
|
142
|
+
headers: Mapping[str, str],
|
|
143
|
+
secrets: str | Sequence[str],
|
|
144
|
+
*,
|
|
145
|
+
tolerance: float,
|
|
146
|
+
now: int,
|
|
147
|
+
) -> WebhookEvent:
|
|
148
|
+
""":func:`verify_webhook` against a given clock: ``now`` in whole unix seconds (D-12)."""
|
|
149
|
+
_check_tolerance(tolerance)
|
|
150
|
+
keys = _decode_secrets(secrets)
|
|
151
|
+
if not isinstance(body, (bytes, str)):
|
|
152
|
+
raise TypeError(f"body must be bytes or str, not {type(body).__name__!r}")
|
|
153
|
+
if not callable(getattr(headers, "items", None)):
|
|
154
|
+
raise TypeError(f"headers must be a mapping, not {type(headers).__name__!r}")
|
|
155
|
+
|
|
156
|
+
msg_id, timestamp, signature = _read_headers(headers)
|
|
157
|
+
if not (
|
|
158
|
+
1 <= len(timestamp) <= _TIMESTAMP_MAX_DIGITS and timestamp.isascii() and timestamp.isdigit()
|
|
159
|
+
):
|
|
160
|
+
raise WebhookVerificationError("invalid_timestamp")
|
|
161
|
+
entries = _signature_entries(signature)
|
|
162
|
+
if not entries:
|
|
163
|
+
raise WebhookVerificationError("invalid_signature_header")
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
body_bytes = body.encode("utf-8") if isinstance(body, str) else body
|
|
167
|
+
content = msg_id.encode("utf-8") + b"." + timestamp.encode("ascii") + b"." + body_bytes
|
|
168
|
+
except UnicodeEncodeError:
|
|
169
|
+
# A lone surrogate cannot have been signed by the console (D-29 notes).
|
|
170
|
+
raise WebhookVerificationError("signature_mismatch") from None
|
|
171
|
+
if not _any_match(keys, content, entries):
|
|
172
|
+
raise WebhookVerificationError("signature_mismatch")
|
|
173
|
+
|
|
174
|
+
skew = now - int(timestamp)
|
|
175
|
+
if skew > tolerance:
|
|
176
|
+
raise WebhookVerificationError("timestamp_too_old")
|
|
177
|
+
if -skew > tolerance:
|
|
178
|
+
raise WebhookVerificationError("timestamp_too_new")
|
|
179
|
+
|
|
180
|
+
return _parse_event(body_bytes)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _check_tolerance(tolerance: Any) -> None:
|
|
184
|
+
# The client's timeout rule: bool is an int subclass but never a number here.
|
|
185
|
+
if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float)):
|
|
186
|
+
raise TypeError(
|
|
187
|
+
f"webhook tolerance must be a number of seconds, not {type(tolerance).__name__!r}"
|
|
188
|
+
)
|
|
189
|
+
if isinstance(tolerance, float) and not math.isfinite(tolerance):
|
|
190
|
+
raise ValueError("webhook tolerance must be a finite number of seconds")
|
|
191
|
+
if tolerance <= 0:
|
|
192
|
+
raise ValueError("webhook tolerance must be greater than zero")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _decode_secrets(secrets: Any) -> list[bytes]:
|
|
196
|
+
if isinstance(secrets, str):
|
|
197
|
+
items: Sequence[Any] = [secrets]
|
|
198
|
+
elif isinstance(secrets, Sequence) and not isinstance(secrets, (bytes, bytearray)):
|
|
199
|
+
items = secrets
|
|
200
|
+
else:
|
|
201
|
+
raise TypeError(
|
|
202
|
+
f"webhook secrets must be a str or a sequence of str, not {type(secrets).__name__!r}"
|
|
203
|
+
)
|
|
204
|
+
if len(items) == 0:
|
|
205
|
+
raise ValueError("no webhook secrets: pass at least one webhook secret")
|
|
206
|
+
keys = []
|
|
207
|
+
for position, item in enumerate(items, start=1):
|
|
208
|
+
if not isinstance(item, str):
|
|
209
|
+
raise TypeError(
|
|
210
|
+
f"webhook secret {position}: must be a str, not {type(item).__name__!r}"
|
|
211
|
+
)
|
|
212
|
+
keys.append(_decode_secret(position, item))
|
|
213
|
+
return keys
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _decode_secret(position: int, secret: str) -> bytes:
|
|
217
|
+
text = secret.strip(_SECRET_TRIM)
|
|
218
|
+
if not text.startswith(_SECRET_PREFIX):
|
|
219
|
+
raise ValueError(f"webhook secret {position}: does not start with {_SECRET_PREFIX}")
|
|
220
|
+
raw = _canonical_base64(text[len(_SECRET_PREFIX) :])
|
|
221
|
+
if raw is None:
|
|
222
|
+
raise ValueError(f"webhook secret {position}: is not canonical padded base64")
|
|
223
|
+
if not _SECRET_MIN_BYTES <= len(raw) <= _SECRET_MAX_BYTES:
|
|
224
|
+
raise ValueError(
|
|
225
|
+
f"webhook secret {position}: must decode to {_SECRET_MIN_BYTES} to "
|
|
226
|
+
f"{_SECRET_MAX_BYTES} bytes"
|
|
227
|
+
)
|
|
228
|
+
return raw
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _canonical_base64(text: str) -> bytes | None:
|
|
232
|
+
"""The decoded bytes when ``text`` is canonical padded standard base64, else None."""
|
|
233
|
+
try:
|
|
234
|
+
raw = base64.b64decode(text, validate=True)
|
|
235
|
+
except (binascii.Error, ValueError):
|
|
236
|
+
return None
|
|
237
|
+
# b64decode accepts non-zero trailing bits; the re-encode check refuses them.
|
|
238
|
+
if base64.b64encode(raw).decode("ascii") != text:
|
|
239
|
+
return None
|
|
240
|
+
return raw
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _read_headers(headers: Mapping[str, str]) -> tuple[str, str, str]:
|
|
244
|
+
found: dict[str, list[str]] = {_HEADER_ID: [], _HEADER_TIMESTAMP: [], _HEADER_SIGNATURE: []}
|
|
245
|
+
for key, value in headers.items():
|
|
246
|
+
# ASCII-only case fold (D-29): a look-alike such as U+212A never matches.
|
|
247
|
+
if not isinstance(key, str) or not isinstance(value, str) or not key.isascii():
|
|
248
|
+
continue
|
|
249
|
+
values = found.get(key.lower())
|
|
250
|
+
if values is not None and value != "":
|
|
251
|
+
values.append(value)
|
|
252
|
+
if not all(found.values()):
|
|
253
|
+
raise WebhookVerificationError("missing_header")
|
|
254
|
+
ids = set(found[_HEADER_ID])
|
|
255
|
+
timestamps = set(found[_HEADER_TIMESTAMP])
|
|
256
|
+
if len(ids) != 1 or len(timestamps) != 1:
|
|
257
|
+
raise WebhookVerificationError("missing_header")
|
|
258
|
+
return ids.pop(), timestamps.pop(), " ".join(found[_HEADER_SIGNATURE])
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _signature_entries(signature: str) -> list[bytes]:
|
|
262
|
+
entries = []
|
|
263
|
+
# Split on U+0020 only: a tab or newline stays inside a piece and spoils it.
|
|
264
|
+
for piece in signature.split(" "):
|
|
265
|
+
if not piece.startswith("v1,"):
|
|
266
|
+
continue
|
|
267
|
+
raw = _canonical_base64(piece[3:])
|
|
268
|
+
if raw is not None and len(raw) == _SIGNATURE_BYTES:
|
|
269
|
+
entries.append(raw)
|
|
270
|
+
return entries
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _any_match(keys: list[bytes], content: bytes, entries: list[bytes]) -> bool:
|
|
274
|
+
for key in keys:
|
|
275
|
+
expected = hmac.new(key, content, hashlib.sha256).digest()
|
|
276
|
+
for entry in entries:
|
|
277
|
+
if hmac.compare_digest(expected, entry):
|
|
278
|
+
return True
|
|
279
|
+
return False
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _reject_constant(name: str) -> Any:
|
|
283
|
+
raise ValueError(f"{name} is not JSON")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _parse_event(body: bytes) -> WebhookEvent:
|
|
287
|
+
try:
|
|
288
|
+
doc: Any = json.loads(body.decode("utf-8"), parse_constant=_reject_constant)
|
|
289
|
+
except (ValueError, RecursionError):
|
|
290
|
+
raise WebhookVerificationError("invalid_payload") from None
|
|
291
|
+
if not isinstance(doc, dict):
|
|
292
|
+
raise WebhookVerificationError("invalid_payload")
|
|
293
|
+
event_id = doc.get("id")
|
|
294
|
+
event_type = doc.get("type")
|
|
295
|
+
data = doc.get("data")
|
|
296
|
+
if not isinstance(event_id, str) or not event_id:
|
|
297
|
+
raise WebhookVerificationError("invalid_payload")
|
|
298
|
+
if not isinstance(event_type, str) or not event_type:
|
|
299
|
+
raise WebhookVerificationError("invalid_payload")
|
|
300
|
+
if not isinstance(data, dict):
|
|
301
|
+
raise WebhookVerificationError("invalid_payload")
|
|
302
|
+
job_id = data.get("job_id")
|
|
303
|
+
status = data.get("status")
|
|
304
|
+
return WebhookEvent(
|
|
305
|
+
id=event_id,
|
|
306
|
+
type=event_type,
|
|
307
|
+
timestamp=_parse_timestamp(doc.get("timestamp")),
|
|
308
|
+
job_id=job_id if isinstance(job_id, str) else None,
|
|
309
|
+
status=status if isinstance(status, str) else None,
|
|
310
|
+
data=data,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _parse_timestamp(value: Any) -> datetime:
|
|
315
|
+
"""``YYYY-MM-DDTHH:MM:SS[.fraction]Z`` as an aware UTC datetime.
|
|
316
|
+
|
|
317
|
+
The fraction keeps at most microseconds (truncated). The lenient ISO parser
|
|
318
|
+
is never used alone: it also takes dates without a time, offsets and
|
|
319
|
+
compact forms.
|
|
320
|
+
"""
|
|
321
|
+
match = _EVENT_TIMESTAMP.fullmatch(value) if isinstance(value, str) else None
|
|
322
|
+
if match is None:
|
|
323
|
+
raise WebhookVerificationError("invalid_payload")
|
|
324
|
+
year, month, day, hour, minute, second = (int(part) for part in match.groups()[:6])
|
|
325
|
+
fraction = match.group(7) or ""
|
|
326
|
+
try:
|
|
327
|
+
# datetime itself range-checks month, day (February 30), hour 0-23,
|
|
328
|
+
# minute 0-59 and second 0-59 (no leap second).
|
|
329
|
+
return datetime(
|
|
330
|
+
year,
|
|
331
|
+
month,
|
|
332
|
+
day,
|
|
333
|
+
hour,
|
|
334
|
+
minute,
|
|
335
|
+
second,
|
|
336
|
+
int(fraction[:6].ljust(6, "0")),
|
|
337
|
+
tzinfo=UTC,
|
|
338
|
+
)
|
|
339
|
+
except ValueError:
|
|
340
|
+
raise WebhookVerificationError("invalid_payload") from None
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|