docql 0.3.0__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.3.0 → docql-0.4.0}/PKG-INFO +79 -4
- {docql-0.3.0 → docql-0.4.0}/README.md +77 -2
- {docql-0.3.0 → docql-0.4.0}/pyproject.toml +2 -2
- {docql-0.3.0 → docql-0.4.0}/pyproject.toml.orig +2 -2
- {docql-0.3.0 → docql-0.4.0}/src/docql/__init__.py +16 -0
- {docql-0.3.0 → docql-0.4.0}/src/docql/_jobs.py +2 -1
- {docql-0.3.0 → docql-0.4.0}/src/docql/_response.py +30 -10
- docql-0.4.0/src/docql/_webhooks.py +340 -0
- {docql-0.3.0 → docql-0.4.0}/LICENSE +0 -0
- {docql-0.3.0 → docql-0.4.0}/src/docql/_client.py +0 -0
- {docql-0.3.0 → docql-0.4.0}/src/docql/_constants.py +0 -0
- {docql-0.3.0 → docql-0.4.0}/src/docql/_errors.py +0 -0
- {docql-0.3.0 → docql-0.4.0}/src/docql/_request.py +0 -0
- {docql-0.3.0 → docql-0.4.0}/src/docql/_version.py +0 -0
- {docql-0.3.0 → 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 |
|
|
@@ -161,7 +233,10 @@ with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
|
161
233
|
except docql.DocQLError as err:
|
|
162
234
|
if err.reason != docql.REASON_SPREADSHEET_TOO_LARGE:
|
|
163
235
|
raise
|
|
164
|
-
|
|
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
|
|
165
240
|
print(f"too large: {axis}={err.metadata[axis]} limit={err.metadata['limit']}")
|
|
166
241
|
```
|
|
167
242
|
<!-- docql:spreadsheet:end -->
|
|
@@ -240,7 +315,7 @@ two mean the request was not processed.
|
|
|
240
315
|
## Versioning
|
|
241
316
|
|
|
242
317
|
The SDK follows [Semantic Versioning](https://semver.org/). While the major
|
|
243
|
-
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
|
|
244
319
|
1.0.
|
|
245
320
|
|
|
246
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 |
|
|
@@ -139,7 +211,10 @@ with DocQL() as client: # reads DOCQL_API_KEY and DOCQL_API_URL
|
|
|
139
211
|
except docql.DocQLError as err:
|
|
140
212
|
if err.reason != docql.REASON_SPREADSHEET_TOO_LARGE:
|
|
141
213
|
raise
|
|
142
|
-
|
|
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
|
|
143
218
|
print(f"too large: {axis}={err.metadata[axis]} limit={err.metadata['limit']}")
|
|
144
219
|
```
|
|
145
220
|
<!-- docql:spreadsheet:end -->
|
|
@@ -218,7 +293,7 @@ two mean the request was not processed.
|
|
|
218
293
|
## Versioning
|
|
219
294
|
|
|
220
295
|
The SDK follows [Semantic Versioning](https://semver.org/). While the major
|
|
221
|
-
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
|
|
222
297
|
1.0.
|
|
223
298
|
|
|
224
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"]
|
|
@@ -46,6 +46,15 @@ from docql._errors import (
|
|
|
46
46
|
from docql._jobs import Job
|
|
47
47
|
from docql._response import QueryResult
|
|
48
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
|
+
)
|
|
49
58
|
|
|
50
59
|
__all__ = [
|
|
51
60
|
"DocQL",
|
|
@@ -54,6 +63,10 @@ __all__ = [
|
|
|
54
63
|
"DocQLException",
|
|
55
64
|
"DocQLTimeoutError",
|
|
56
65
|
"DocQLWaitTimeoutError",
|
|
66
|
+
"EVENT_JOB_CANCELLED",
|
|
67
|
+
"EVENT_JOB_FAILED",
|
|
68
|
+
"EVENT_JOB_SUCCEEDED",
|
|
69
|
+
"EVENT_WEBHOOK_TEST",
|
|
57
70
|
"JOB_STATUS_CANCELLED",
|
|
58
71
|
"JOB_STATUS_FAILED",
|
|
59
72
|
"JOB_STATUS_QUEUED",
|
|
@@ -89,5 +102,8 @@ __all__ = [
|
|
|
89
102
|
"REASON_UPLOAD_TOO_LARGE",
|
|
90
103
|
"REASON_UPSTREAM_AUTH_FAILED",
|
|
91
104
|
"REASON_UPSTREAM_UNAVAILABLE",
|
|
105
|
+
"WebhookEvent",
|
|
106
|
+
"WebhookVerificationError",
|
|
92
107
|
"__version__",
|
|
108
|
+
"verify_webhook",
|
|
93
109
|
]
|
|
@@ -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")
|
|
@@ -55,15 +55,33 @@ def _scrub_deep(value: Any, api_key: str) -> Any:
|
|
|
55
55
|
|
|
56
56
|
Used for the error metadata, which a developer may log or store: a
|
|
57
57
|
reflecting server must never get the key into it. Numbers, booleans and
|
|
58
|
-
None pass through unchanged.
|
|
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.
|
|
59
61
|
"""
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
return
|
|
66
|
-
|
|
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
|
|
67
85
|
|
|
68
86
|
|
|
69
87
|
def parse_retry_after(value: str | None, now: datetime | None = None) -> int | None:
|
|
@@ -126,7 +144,8 @@ def parse_result(
|
|
|
126
144
|
"""
|
|
127
145
|
try:
|
|
128
146
|
doc: Any = json.loads(body)
|
|
129
|
-
except ValueError:
|
|
147
|
+
except (ValueError, RecursionError):
|
|
148
|
+
# CR-01: a deeply nested body is unusable, never a crash.
|
|
130
149
|
doc = None
|
|
131
150
|
if not isinstance(doc, dict):
|
|
132
151
|
raise _unusable_result(status, headers, body, api_key, "unexpected non-JSON response")
|
|
@@ -175,7 +194,8 @@ def decode_error(
|
|
|
175
194
|
metadata_out: dict[str, Any] | None = None
|
|
176
195
|
try:
|
|
177
196
|
doc: Any = json.loads(body)
|
|
178
|
-
except ValueError:
|
|
197
|
+
except (ValueError, RecursionError):
|
|
198
|
+
# CR-01: a deeply nested body is unusable, never a crash.
|
|
179
199
|
doc = None
|
|
180
200
|
if isinstance(doc, dict):
|
|
181
201
|
metadata = doc.get("metadata")
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|