correct-hooks 0.1.0__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- correct_hooks-0.2.0/PKG-INFO +96 -0
- correct_hooks-0.2.0/README.md +83 -0
- {correct_hooks-0.1.0 → correct_hooks-0.2.0}/pyproject.toml +1 -1
- {correct_hooks-0.1.0 → correct_hooks-0.2.0}/pyproject.toml.orig +1 -1
- {correct_hooks-0.1.0 → correct_hooks-0.2.0}/src/correct_hooks/__init__.py +239 -177
- correct_hooks-0.1.0/PKG-INFO +0 -13
- correct_hooks-0.1.0/README.md +0 -0
- correct_hooks-0.1.0/src/correct_hooks/py.typed +0 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: correct-hooks
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Asymmetric signing, verification, and key management for webhooks
|
|
5
|
+
Author: Phillip Diffley
|
|
6
|
+
Author-email: Phillip Diffley <7283778+pdiffley@users.noreply.github.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Requires-Dist: cryptography>=50.0.2
|
|
9
|
+
Requires-Dist: httpx>=0.28.1
|
|
10
|
+
Requires-Dist: pydantic>=2.13.5
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# Correct Hook
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
### Webhook Producers
|
|
18
|
+
|
|
19
|
+
#### Key generation
|
|
20
|
+
To sign requests, you first need to generate a secret signing key. The key serializes to a json string which should be stored in your secret manager.
|
|
21
|
+
|
|
22
|
+
The secret signing key should be treated as an opaque blob, and you should never edit it's contents.
|
|
23
|
+
```python
|
|
24
|
+
from correct_hooks import generate_secret_signing_key
|
|
25
|
+
|
|
26
|
+
secret_signing_key = generate_secret_signing_key()
|
|
27
|
+
secret_signing_key_json = secret_signing_key.model_dump_json()
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
#### Public key generation
|
|
31
|
+
For your webhook consumers to verify your signatures, they need the public verifying key set for your signing keys.
|
|
32
|
+
|
|
33
|
+
`create_public_verifying_key_set` creates a public verifying key set from a list of your secret keys.
|
|
34
|
+
You should serialize the public verifying key set to a json string and serve it from a public GET endpoint. Document this endpoint's url
|
|
35
|
+
for your webhook consumers. Initial deployments can serve the public verifying key set directly. Moderate and large scale deployments may
|
|
36
|
+
want to put this endpoint behind a CDN.
|
|
37
|
+
```python
|
|
38
|
+
from correct_hooks import create_public_verifying_key_set
|
|
39
|
+
|
|
40
|
+
public_verifying_key_set = create_public_verifying_key_set([secret_signing_key])
|
|
41
|
+
public_verifying_key_set_json = public_verifying_key_set.model_dump_json()
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
#### Sign a request
|
|
45
|
+
|
|
46
|
+
Sign the request data and set the headers `correct-hooks-signature-components` and `correct-hooks-signature` to
|
|
47
|
+
the returned values. See [SignArgs](https://github.com/handlewithcarecollective/correct-hooks/blob/accffd39544b64392a8d7edcb5b42ea03fd2e2d5/python/correct_hooks/src/correct_hooks/__init__.py#L82) for argument details.
|
|
48
|
+
```python
|
|
49
|
+
from correct_hooks import (sign, SignArgs)
|
|
50
|
+
|
|
51
|
+
signature_headers = sign(SignArgs(
|
|
52
|
+
webhook_id=webhook_id,
|
|
53
|
+
recipient_id=recipient_id,
|
|
54
|
+
target_url=target_url,
|
|
55
|
+
method=method,
|
|
56
|
+
request_body=request_body,
|
|
57
|
+
secret_signing_key=secret_signing_key,
|
|
58
|
+
))
|
|
59
|
+
correct_hooks_signature_components = signature_headers.correct_hooks_signature_components
|
|
60
|
+
correct_hooks_signature = signature_headers.correct_hooks_signature
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Webhook Consumers
|
|
64
|
+
|
|
65
|
+
#### Create a verifier
|
|
66
|
+
Create a Verifier with the webhook producer's public verifying key set url. You should create a Verifier once when your backend instance starts and reuse it for all requests to that instance.
|
|
67
|
+
|
|
68
|
+
See [VerifyConfig](https://github.com/handlewithcarecollective/correct-hooks/blob/accffd39544b64392a8d7edcb5b42ea03fd2e2d5/python/correct_hooks/src/correct_hooks/__init__.py#L285) for argument details.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from correct_hooks import (Verifier, VerifierConfig)
|
|
72
|
+
|
|
73
|
+
verifier = Verifier(VerifierConfig(
|
|
74
|
+
recipient_id=recipient_id,
|
|
75
|
+
public_verifying_key_set_url=AnyUrl(public_verifying_key_set_url),
|
|
76
|
+
))
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
#### Verify a request
|
|
80
|
+
Verify a request with the Verifier. Any error indicates that the signature is invalid and that the request should be immediately rejected.
|
|
81
|
+
|
|
82
|
+
See [VerifyArgs](https://github.com/handlewithcarecollective/correct-hooks/blob/accffd39544b64392a8d7edcb5b42ea03fd2e2d5/python/correct_hooks/src/correct_hooks/__init__.py#L130) for argument details.
|
|
83
|
+
```python
|
|
84
|
+
from correct_hooks import VerifyArgs
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
verified_data = await verifier.verify(
|
|
88
|
+
target_url=target_url,
|
|
89
|
+
method=method,
|
|
90
|
+
correct_hooks_signature_components=signature_headers.correct_hooks_signature_components,
|
|
91
|
+
correct_hooks_signature=signature_headers.correct_hooks_signature,
|
|
92
|
+
request_body=request_body,
|
|
93
|
+
)
|
|
94
|
+
except Exception:
|
|
95
|
+
return HTTPStatus.FORBIDDEN
|
|
96
|
+
```
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Correct Hook
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Webhook Producers
|
|
5
|
+
|
|
6
|
+
#### Key generation
|
|
7
|
+
To sign requests, you first need to generate a secret signing key. The key serializes to a json string which should be stored in your secret manager.
|
|
8
|
+
|
|
9
|
+
The secret signing key should be treated as an opaque blob, and you should never edit it's contents.
|
|
10
|
+
```python
|
|
11
|
+
from correct_hooks import generate_secret_signing_key
|
|
12
|
+
|
|
13
|
+
secret_signing_key = generate_secret_signing_key()
|
|
14
|
+
secret_signing_key_json = secret_signing_key.model_dump_json()
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
#### Public key generation
|
|
18
|
+
For your webhook consumers to verify your signatures, they need the public verifying key set for your signing keys.
|
|
19
|
+
|
|
20
|
+
`create_public_verifying_key_set` creates a public verifying key set from a list of your secret keys.
|
|
21
|
+
You should serialize the public verifying key set to a json string and serve it from a public GET endpoint. Document this endpoint's url
|
|
22
|
+
for your webhook consumers. Initial deployments can serve the public verifying key set directly. Moderate and large scale deployments may
|
|
23
|
+
want to put this endpoint behind a CDN.
|
|
24
|
+
```python
|
|
25
|
+
from correct_hooks import create_public_verifying_key_set
|
|
26
|
+
|
|
27
|
+
public_verifying_key_set = create_public_verifying_key_set([secret_signing_key])
|
|
28
|
+
public_verifying_key_set_json = public_verifying_key_set.model_dump_json()
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
#### Sign a request
|
|
32
|
+
|
|
33
|
+
Sign the request data and set the headers `correct-hooks-signature-components` and `correct-hooks-signature` to
|
|
34
|
+
the returned values. See [SignArgs](https://github.com/handlewithcarecollective/correct-hooks/blob/accffd39544b64392a8d7edcb5b42ea03fd2e2d5/python/correct_hooks/src/correct_hooks/__init__.py#L82) for argument details.
|
|
35
|
+
```python
|
|
36
|
+
from correct_hooks import (sign, SignArgs)
|
|
37
|
+
|
|
38
|
+
signature_headers = sign(SignArgs(
|
|
39
|
+
webhook_id=webhook_id,
|
|
40
|
+
recipient_id=recipient_id,
|
|
41
|
+
target_url=target_url,
|
|
42
|
+
method=method,
|
|
43
|
+
request_body=request_body,
|
|
44
|
+
secret_signing_key=secret_signing_key,
|
|
45
|
+
))
|
|
46
|
+
correct_hooks_signature_components = signature_headers.correct_hooks_signature_components
|
|
47
|
+
correct_hooks_signature = signature_headers.correct_hooks_signature
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Webhook Consumers
|
|
51
|
+
|
|
52
|
+
#### Create a verifier
|
|
53
|
+
Create a Verifier with the webhook producer's public verifying key set url. You should create a Verifier once when your backend instance starts and reuse it for all requests to that instance.
|
|
54
|
+
|
|
55
|
+
See [VerifyConfig](https://github.com/handlewithcarecollective/correct-hooks/blob/accffd39544b64392a8d7edcb5b42ea03fd2e2d5/python/correct_hooks/src/correct_hooks/__init__.py#L285) for argument details.
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from correct_hooks import (Verifier, VerifierConfig)
|
|
59
|
+
|
|
60
|
+
verifier = Verifier(VerifierConfig(
|
|
61
|
+
recipient_id=recipient_id,
|
|
62
|
+
public_verifying_key_set_url=AnyUrl(public_verifying_key_set_url),
|
|
63
|
+
))
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
#### Verify a request
|
|
67
|
+
Verify a request with the Verifier. Any error indicates that the signature is invalid and that the request should be immediately rejected.
|
|
68
|
+
|
|
69
|
+
See [VerifyArgs](https://github.com/handlewithcarecollective/correct-hooks/blob/accffd39544b64392a8d7edcb5b42ea03fd2e2d5/python/correct_hooks/src/correct_hooks/__init__.py#L130) for argument details.
|
|
70
|
+
```python
|
|
71
|
+
from correct_hooks import VerifyArgs
|
|
72
|
+
|
|
73
|
+
try:
|
|
74
|
+
verified_data = await verifier.verify(
|
|
75
|
+
target_url=target_url,
|
|
76
|
+
method=method,
|
|
77
|
+
correct_hooks_signature_components=signature_headers.correct_hooks_signature_components,
|
|
78
|
+
correct_hooks_signature=signature_headers.correct_hooks_signature,
|
|
79
|
+
request_body=request_body,
|
|
80
|
+
)
|
|
81
|
+
except Exception:
|
|
82
|
+
return HTTPStatus.FORBIDDEN
|
|
83
|
+
```
|
|
@@ -4,13 +4,14 @@ import asyncio
|
|
|
4
4
|
import base64
|
|
5
5
|
import time
|
|
6
6
|
import uuid
|
|
7
|
+
from typing import Any
|
|
7
8
|
|
|
8
9
|
import httpx
|
|
9
10
|
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
10
11
|
Ed25519PrivateKey,
|
|
11
12
|
Ed25519PublicKey,
|
|
12
13
|
)
|
|
13
|
-
from pydantic import BaseModel, ConfigDict, Field
|
|
14
|
+
from pydantic import UUID4, AnyUrl, BaseModel, ConfigDict, Field
|
|
14
15
|
from pydantic.alias_generators import to_camel
|
|
15
16
|
|
|
16
17
|
SIGNATURE_VERSION = "v1"
|
|
@@ -19,6 +20,20 @@ SIGNATURE_VERSION = "v1"
|
|
|
19
20
|
_DEFAULT_SIGNATURE_TTL_SECONDS = 300
|
|
20
21
|
_DEFAULT_PUBLIC_VERIFYING_KEY_SET_TTL_SECONDS = 300
|
|
21
22
|
|
|
23
|
+
VALID_HTTP_METHODS = frozenset(
|
|
24
|
+
{
|
|
25
|
+
"GET",
|
|
26
|
+
"HEAD",
|
|
27
|
+
"POST",
|
|
28
|
+
"PUT",
|
|
29
|
+
"DELETE",
|
|
30
|
+
"CONNECT",
|
|
31
|
+
"OPTIONS",
|
|
32
|
+
"TRACE",
|
|
33
|
+
"PATCH",
|
|
34
|
+
}
|
|
35
|
+
)
|
|
36
|
+
|
|
22
37
|
|
|
23
38
|
class CamelCaseBaseModel(BaseModel):
|
|
24
39
|
model_config = ConfigDict(
|
|
@@ -35,7 +50,7 @@ class SecretSigningKey(CamelCaseBaseModel):
|
|
|
35
50
|
Must be kept secret and should only be held by the signer.
|
|
36
51
|
"""
|
|
37
52
|
|
|
38
|
-
kid:
|
|
53
|
+
kid: UUID4 = Field(strict=False)
|
|
39
54
|
kty: str
|
|
40
55
|
crv: str
|
|
41
56
|
x: str
|
|
@@ -43,7 +58,9 @@ class SecretSigningKey(CamelCaseBaseModel):
|
|
|
43
58
|
|
|
44
59
|
|
|
45
60
|
class _PublicJwk(CamelCaseBaseModel):
|
|
46
|
-
|
|
61
|
+
model_config = ConfigDict(extra="forbid")
|
|
62
|
+
|
|
63
|
+
kid: UUID4 = Field(strict=False)
|
|
47
64
|
kty: str
|
|
48
65
|
crv: str
|
|
49
66
|
x: str
|
|
@@ -56,16 +73,42 @@ class PublicVerifyingKeySet(CamelCaseBaseModel):
|
|
|
56
73
|
|
|
57
74
|
|
|
58
75
|
class _SignatureComponents(CamelCaseBaseModel):
|
|
59
|
-
|
|
60
|
-
|
|
76
|
+
webhook_id: UUID4 = Field(strict=False)
|
|
77
|
+
key_id: UUID4 = Field(strict=False)
|
|
61
78
|
signed_at: int
|
|
62
|
-
key_id: uuid.UUID = Field(strict=False)
|
|
63
79
|
|
|
64
80
|
|
|
65
81
|
class InvalidKeyFound(Exception):
|
|
66
82
|
pass
|
|
67
83
|
|
|
68
84
|
|
|
85
|
+
class SignArgs(CamelCaseBaseModel):
|
|
86
|
+
"""The arguments to the `sign` function."""
|
|
87
|
+
|
|
88
|
+
webhook_id: UUID4 = Field(strict=False)
|
|
89
|
+
"""An id for the webhook.
|
|
90
|
+
|
|
91
|
+
This id should be unique for the event triggering the webhook, and should
|
|
92
|
+
be reused for any delivery retries.
|
|
93
|
+
"""
|
|
94
|
+
recipient_id: UUID4 = Field(strict=False)
|
|
95
|
+
"""The webhook consumer's id.
|
|
96
|
+
|
|
97
|
+
This id must be controlled by the webhook producer and not taken as an input from the webhook consumer.
|
|
98
|
+
"""
|
|
99
|
+
target_url: str
|
|
100
|
+
"""The url the webhook is being sent to.
|
|
101
|
+
|
|
102
|
+
Must be the exact url string provided by the webhook consumer.
|
|
103
|
+
"""
|
|
104
|
+
method: str
|
|
105
|
+
"""The HTTP method the webhook will be sent with."""
|
|
106
|
+
request_body: bytes
|
|
107
|
+
"""The exact body of the webhook request as bytes."""
|
|
108
|
+
secret_signing_key: SecretSigningKey
|
|
109
|
+
"""The `SecretSigningKey` the signature will be signed with."""
|
|
110
|
+
|
|
111
|
+
|
|
69
112
|
class SignatureData(CamelCaseBaseModel):
|
|
70
113
|
"""Header values to set on the webhook request.
|
|
71
114
|
You must set the request headers `correct-hooks-signature-components` and `correct-hooks-signature` to these values.
|
|
@@ -79,7 +122,7 @@ class SignatureData(CamelCaseBaseModel):
|
|
|
79
122
|
"""Set the header `correct-hooks-signature` to this value."""
|
|
80
123
|
|
|
81
124
|
|
|
82
|
-
class
|
|
125
|
+
class InvalidArgs(Exception):
|
|
83
126
|
pass
|
|
84
127
|
|
|
85
128
|
|
|
@@ -87,10 +130,28 @@ class InvalidSigningKey(Exception):
|
|
|
87
130
|
pass
|
|
88
131
|
|
|
89
132
|
|
|
133
|
+
class VerifyArgs(CamelCaseBaseModel):
|
|
134
|
+
"""The arguments to `Verifier.verify` and `Verifier.verify_with_time`."""
|
|
135
|
+
|
|
136
|
+
target_url: str
|
|
137
|
+
"""The url your endpoint is receiving requests at.
|
|
138
|
+
|
|
139
|
+
`target_url` needs to be the exact string given to the webhook provider,
|
|
140
|
+
"""
|
|
141
|
+
method: str
|
|
142
|
+
"""The HTTP method the request was sent with. Can be extracted from the request."""
|
|
143
|
+
correct_hooks_signature_components: str
|
|
144
|
+
"""The value from the request's `correct-hooks-signature-components` header."""
|
|
145
|
+
correct_hooks_signature: str
|
|
146
|
+
"""The value from the request's `correct-hooks-signature` header."""
|
|
147
|
+
request_body: bytes
|
|
148
|
+
"""The raw unparsed request body as bytes."""
|
|
149
|
+
|
|
150
|
+
|
|
90
151
|
class VerifiedData(CamelCaseBaseModel):
|
|
91
152
|
"""Validated request data."""
|
|
92
153
|
|
|
93
|
-
webhook_id:
|
|
154
|
+
webhook_id: UUID4
|
|
94
155
|
"""The validated `webhook_id` for the request. These id's can be put in a shared cache
|
|
95
156
|
by the webhook consumer and checked against for the highest level of replay protection.
|
|
96
157
|
"""
|
|
@@ -157,21 +218,19 @@ def create_public_verifying_key_set(
|
|
|
157
218
|
public_jwks = PublicVerifyingKeySet(keys=[])
|
|
158
219
|
for private_key in secret_signing_keys:
|
|
159
220
|
try:
|
|
160
|
-
public_key = _PublicJwk
|
|
221
|
+
public_key = _PublicJwk(
|
|
222
|
+
kid=private_key.kid,
|
|
223
|
+
kty="OKP",
|
|
224
|
+
crv="Ed25519",
|
|
225
|
+
x=private_key.x,
|
|
226
|
+
)
|
|
161
227
|
public_jwks.keys.append(public_key)
|
|
162
228
|
except Exception as e:
|
|
163
229
|
raise InvalidKeyFound from e
|
|
164
230
|
return public_jwks
|
|
165
231
|
|
|
166
232
|
|
|
167
|
-
def sign(
|
|
168
|
-
*,
|
|
169
|
-
webhook_id: str,
|
|
170
|
-
target_url: str,
|
|
171
|
-
method: str,
|
|
172
|
-
request_body: bytes,
|
|
173
|
-
secret_signing_key: SecretSigningKey,
|
|
174
|
-
) -> SignatureData:
|
|
233
|
+
def sign(args: SignArgs) -> SignatureData:
|
|
175
234
|
"""Creates a signature for a webhook request and returns the signature headers that should be set on the request.
|
|
176
235
|
|
|
177
236
|
You must set the request headers `correct-hooks-signature-components` and `correct-hooks-signature` to these values.
|
|
@@ -182,43 +241,44 @@ def sign(
|
|
|
182
241
|
`sign` should be called every time a webhook delivery is attempted. The signed headers should not be reused
|
|
183
242
|
between retried delivery attempts.
|
|
184
243
|
|
|
185
|
-
Args:
|
|
186
|
-
webhook_id: An id for the webhook.
|
|
187
|
-
This id should be unique for the event triggering the webhook, and should
|
|
188
|
-
be reused for any delivery retries.
|
|
189
|
-
target_url: The url the webhook is being sent to.
|
|
190
|
-
Must be the exact url string provided by the webhook consumer.
|
|
191
|
-
method: The method the webhook is being sent with. Only `"POST"` is supported.
|
|
192
|
-
request_body: The exact body of the webhook request in bytes.
|
|
193
|
-
secret_signing_key: The `SecretSigningKey` the signature will be signed with.
|
|
194
|
-
|
|
195
244
|
Raises:
|
|
196
|
-
|
|
245
|
+
InvalidArgs
|
|
197
246
|
InvalidSigningKey
|
|
198
247
|
"""
|
|
199
|
-
if method != "POST":
|
|
200
|
-
raise InvalidMethod()
|
|
201
248
|
|
|
202
|
-
|
|
249
|
+
try:
|
|
250
|
+
AnyUrl(args.target_url)
|
|
251
|
+
except ValueError as e:
|
|
252
|
+
raise InvalidArgs from e
|
|
253
|
+
|
|
254
|
+
if not is_valid_http_method(args.method):
|
|
255
|
+
raise InvalidArgs
|
|
256
|
+
|
|
257
|
+
key_id = args.secret_signing_key.kid
|
|
203
258
|
signed_at = _seconds_since_unix_epoch()
|
|
204
259
|
|
|
205
260
|
signature_components = _SignatureComponents(
|
|
206
|
-
|
|
207
|
-
webhook_id=webhook_id,
|
|
208
|
-
signed_at=signed_at,
|
|
261
|
+
webhook_id=args.webhook_id,
|
|
209
262
|
key_id=key_id,
|
|
263
|
+
signed_at=signed_at,
|
|
210
264
|
)
|
|
211
265
|
|
|
212
266
|
encoded_signature_components = _encode_signature_components(signature_components)
|
|
213
267
|
signature_components_header = _version_header_value(encoded_signature_components)
|
|
214
268
|
|
|
215
269
|
try:
|
|
216
|
-
secret_key_bytes = decode_base64(secret_signing_key.d)
|
|
270
|
+
secret_key_bytes = decode_base64(args.secret_signing_key.d)
|
|
217
271
|
signing_key = Ed25519PrivateKey.from_private_bytes(secret_key_bytes)
|
|
218
272
|
except Exception as e:
|
|
219
273
|
raise InvalidSigningKey from e
|
|
220
274
|
|
|
221
|
-
signature_message = _construct_signature_message(
|
|
275
|
+
signature_message = _construct_signature_message(
|
|
276
|
+
signature_components,
|
|
277
|
+
args.recipient_id,
|
|
278
|
+
args.target_url,
|
|
279
|
+
args.method,
|
|
280
|
+
args.request_body,
|
|
281
|
+
)
|
|
222
282
|
|
|
223
283
|
signature = signing_key.sign(signature_message)
|
|
224
284
|
signature_base64 = _encode_base64(signature)
|
|
@@ -230,6 +290,32 @@ def sign(
|
|
|
230
290
|
)
|
|
231
291
|
|
|
232
292
|
|
|
293
|
+
class VerifierConfig(CamelCaseBaseModel):
|
|
294
|
+
"""Arguments for creating a `Verifier`."""
|
|
295
|
+
|
|
296
|
+
recipient_id: UUID4 = Field(strict=False)
|
|
297
|
+
"""Your webhook consumer id."""
|
|
298
|
+
public_verifying_key_set_url: AnyUrl = Field(strict=False)
|
|
299
|
+
"""The url serving the webhook provider's verfiying key set.
|
|
300
|
+
|
|
301
|
+
The webhook provider should give you this url.
|
|
302
|
+
"""
|
|
303
|
+
signature_ttl_seconds: int = Field(default=_DEFAULT_SIGNATURE_TTL_SECONDS)
|
|
304
|
+
"""How long a signature is considered valid. Defaults to 300 seconds (5 minutes).
|
|
305
|
+
|
|
306
|
+
In most cases, the default parameter should be used.
|
|
307
|
+
This parameter should not be set to a value larger than 300 (may be enforced in the future).
|
|
308
|
+
"""
|
|
309
|
+
public_verifying_key_set_ttl_seconds: int = Field(
|
|
310
|
+
default=_DEFAULT_PUBLIC_VERIFYING_KEY_SET_TTL_SECONDS
|
|
311
|
+
)
|
|
312
|
+
"""How long a retrieved `public_verifying_key_set` can be used before it is considered stale. Defaults to 300 seconds (5 minutes).
|
|
313
|
+
|
|
314
|
+
In most cases, the default parameter should be used.
|
|
315
|
+
This parameter should not be set to a value larger than 300 (may be enforced in the future).
|
|
316
|
+
"""
|
|
317
|
+
|
|
318
|
+
|
|
233
319
|
class Verifier:
|
|
234
320
|
"""Verifier for signed webhook requests
|
|
235
321
|
|
|
@@ -238,66 +324,27 @@ class Verifier:
|
|
|
238
324
|
Ideally you should create one `Verifier` when your backend instance starts and reuse it for all requests sent to that backend instance.
|
|
239
325
|
"""
|
|
240
326
|
|
|
241
|
-
def __init__(
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
public_verifying_key_set_url
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
Args:
|
|
251
|
-
public_verifying_key_set_url: The url serving the webhook provider's verfiying key set.
|
|
252
|
-
The webhook provider should give you this url.
|
|
253
|
-
signature_ttl_seconds: How long a signature is considered valid. Defaults to 300 seconds (5 minutes).
|
|
254
|
-
In most cases, the default parameter should be used.
|
|
255
|
-
This parameter should not be set to a value larger than 300 (may be enforced in the future).
|
|
256
|
-
public_verifying_key_set_ttl_seconds: How long a retrieved `public_verifying_key_set` can be used before it is considered stale. Defaults to 300 seconds (5 minutes).
|
|
257
|
-
In most cases, the default parameter should be used.
|
|
258
|
-
This parameter should not be set to a value larger than 300 (may be enforced in the future).
|
|
259
|
-
"""
|
|
260
|
-
self._public_verifying_key_set_url = public_verifying_key_set_url
|
|
261
|
-
if signature_ttl_seconds is not None:
|
|
262
|
-
self._signature_ttl_seconds = signature_ttl_seconds
|
|
263
|
-
else:
|
|
264
|
-
self._signature_ttl_seconds = _DEFAULT_SIGNATURE_TTL_SECONDS
|
|
265
|
-
if public_verifying_key_set_ttl_seconds is not None:
|
|
266
|
-
self._public_verifying_key_set_ttl_seconds = public_verifying_key_set_ttl_seconds
|
|
267
|
-
else:
|
|
268
|
-
self._public_verifying_key_set_ttl_seconds = (
|
|
269
|
-
_DEFAULT_PUBLIC_VERIFYING_KEY_SET_TTL_SECONDS
|
|
270
|
-
)
|
|
327
|
+
def __init__(self, config: VerifierConfig) -> None:
|
|
328
|
+
"""Create a new `Verifier`."""
|
|
329
|
+
self._recipient_id = config.recipient_id
|
|
330
|
+
self._public_verifying_key_set_url = config.public_verifying_key_set_url
|
|
331
|
+
self._signature_ttl_seconds = config.signature_ttl_seconds
|
|
332
|
+
self._public_verifying_key_set_ttl_seconds = (
|
|
333
|
+
config.public_verifying_key_set_ttl_seconds
|
|
334
|
+
)
|
|
271
335
|
|
|
272
336
|
self._public_verifying_key_set = PublicVerifyingKeySet(keys=[])
|
|
273
337
|
self._public_verifying_key_set_refreshed_at = 0
|
|
274
338
|
self._public_verifying_key_set_refresh_id = uuid.uuid4()
|
|
275
339
|
self._public_verifying_key_set_refresh_lock = asyncio.Lock()
|
|
276
340
|
|
|
277
|
-
async def verify(
|
|
278
|
-
self,
|
|
279
|
-
*,
|
|
280
|
-
target_url: str,
|
|
281
|
-
method: str,
|
|
282
|
-
correct_hooks_signature_components: str,
|
|
283
|
-
correct_hooks_signature: str,
|
|
284
|
-
request_body: bytes,
|
|
285
|
-
) -> VerifiedData:
|
|
341
|
+
async def verify(self, args: VerifyArgs) -> VerifiedData:
|
|
286
342
|
"""Verifies a request and returns validated information from the Correct Hooks request headers.
|
|
287
343
|
|
|
288
344
|
This function confirms that the provided request signature is valid, that the signature has not expired, and that the request was sent to the intended endpoint.
|
|
289
345
|
|
|
290
346
|
Any raised error indicates that the signature could not be verified and the request should be rejected with a 4xx error
|
|
291
347
|
|
|
292
|
-
Args:
|
|
293
|
-
target_url: The url the webhook should be sent to.
|
|
294
|
-
`target_url` needs to be the exact string given to the webhook provider,
|
|
295
|
-
preferably retrieved from an environment variable or hardcoded.
|
|
296
|
-
method: The method the request was sent with. Only `"POST"` is supported.
|
|
297
|
-
correct_hooks_signature_components: The value from the request's `correct-hooks-signature-components` header.
|
|
298
|
-
correct_hooks_signature: The value from the request's `correct-hooks-signature` header.
|
|
299
|
-
request_body: The unparsed request body in bytes.
|
|
300
|
-
|
|
301
348
|
Raises:
|
|
302
349
|
PublicVerifyingKeyNotFound
|
|
303
350
|
PublicVerifyingKeyRetrievalFailed
|
|
@@ -306,22 +353,13 @@ class Verifier:
|
|
|
306
353
|
"""
|
|
307
354
|
now = _seconds_since_unix_epoch()
|
|
308
355
|
return await self.verify_with_time(
|
|
309
|
-
|
|
310
|
-
method=method,
|
|
311
|
-
correct_hooks_signature_components=correct_hooks_signature_components,
|
|
312
|
-
correct_hooks_signature=correct_hooks_signature,
|
|
313
|
-
request_body=request_body,
|
|
356
|
+
args=args,
|
|
314
357
|
now=now,
|
|
315
358
|
)
|
|
316
359
|
|
|
317
360
|
async def verify_with_time(
|
|
318
361
|
self,
|
|
319
|
-
|
|
320
|
-
target_url: str,
|
|
321
|
-
method: str,
|
|
322
|
-
correct_hooks_signature_components: str,
|
|
323
|
-
correct_hooks_signature: str,
|
|
324
|
-
request_body: bytes,
|
|
362
|
+
args: VerifyArgs,
|
|
325
363
|
now: int,
|
|
326
364
|
) -> VerifiedData:
|
|
327
365
|
"""The same as `Verifier.verify` but with the current time provided by the caller, which
|
|
@@ -341,11 +379,8 @@ class Verifier:
|
|
|
341
379
|
pass
|
|
342
380
|
try:
|
|
343
381
|
return verify_with_time(
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
correct_hooks_signature_components=correct_hooks_signature_components,
|
|
347
|
-
correct_hooks_signature=correct_hooks_signature,
|
|
348
|
-
request_body=request_body,
|
|
382
|
+
args=args,
|
|
383
|
+
recipient_id=self._recipient_id,
|
|
349
384
|
signature_ttl_seconds=self._signature_ttl_seconds,
|
|
350
385
|
public_verifying_key_set=self._public_verifying_key_set,
|
|
351
386
|
now=now,
|
|
@@ -356,44 +391,24 @@ class Verifier:
|
|
|
356
391
|
except Exception: # noqa
|
|
357
392
|
raise PublicVerifyingKeyRetrievalFailed()
|
|
358
393
|
return verify_with_time(
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
correct_hooks_signature_components=correct_hooks_signature_components,
|
|
362
|
-
correct_hooks_signature=correct_hooks_signature,
|
|
363
|
-
request_body=request_body,
|
|
394
|
+
args=args,
|
|
395
|
+
recipient_id=self._recipient_id,
|
|
364
396
|
signature_ttl_seconds=self._signature_ttl_seconds,
|
|
365
397
|
public_verifying_key_set=self._public_verifying_key_set,
|
|
366
398
|
now=now,
|
|
367
399
|
)
|
|
368
400
|
|
|
369
|
-
def verify_sync(
|
|
370
|
-
self,
|
|
371
|
-
*,
|
|
372
|
-
target_url: str,
|
|
373
|
-
method: str,
|
|
374
|
-
correct_hooks_signature_components: str,
|
|
375
|
-
correct_hooks_signature: str,
|
|
376
|
-
request_body: bytes,
|
|
377
|
-
) -> VerifiedData:
|
|
401
|
+
def verify_sync(self, args: VerifyArgs) -> VerifiedData:
|
|
378
402
|
"""A synchronous version of `Verifier.verify`."""
|
|
379
403
|
now = _seconds_since_unix_epoch()
|
|
380
404
|
return self.verify_with_time_sync(
|
|
381
|
-
|
|
382
|
-
method=method,
|
|
383
|
-
correct_hooks_signature_components=correct_hooks_signature_components,
|
|
384
|
-
correct_hooks_signature=correct_hooks_signature,
|
|
385
|
-
request_body=request_body,
|
|
405
|
+
args=args,
|
|
386
406
|
now=now,
|
|
387
407
|
)
|
|
388
408
|
|
|
389
409
|
def verify_with_time_sync(
|
|
390
410
|
self,
|
|
391
|
-
|
|
392
|
-
target_url: str,
|
|
393
|
-
method: str,
|
|
394
|
-
correct_hooks_signature_components: str,
|
|
395
|
-
correct_hooks_signature: str,
|
|
396
|
-
request_body: bytes,
|
|
411
|
+
args: VerifyArgs,
|
|
397
412
|
now: int,
|
|
398
413
|
) -> VerifiedData:
|
|
399
414
|
"""A synchronous version of `Verifier.verify_with_time`."""
|
|
@@ -408,11 +423,8 @@ class Verifier:
|
|
|
408
423
|
pass
|
|
409
424
|
try:
|
|
410
425
|
return verify_with_time(
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
correct_hooks_signature_components=correct_hooks_signature_components,
|
|
414
|
-
correct_hooks_signature=correct_hooks_signature,
|
|
415
|
-
request_body=request_body,
|
|
426
|
+
args=args,
|
|
427
|
+
recipient_id=self._recipient_id,
|
|
416
428
|
signature_ttl_seconds=self._signature_ttl_seconds,
|
|
417
429
|
public_verifying_key_set=self._public_verifying_key_set,
|
|
418
430
|
now=now,
|
|
@@ -423,11 +435,8 @@ class Verifier:
|
|
|
423
435
|
except Exception: # noqa
|
|
424
436
|
raise PublicVerifyingKeyRetrievalFailed()
|
|
425
437
|
result = verify_with_time(
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
correct_hooks_signature_components=correct_hooks_signature_components,
|
|
429
|
-
correct_hooks_signature=correct_hooks_signature,
|
|
430
|
-
request_body=request_body,
|
|
438
|
+
args=args,
|
|
439
|
+
recipient_id=self._recipient_id,
|
|
431
440
|
signature_ttl_seconds=self._signature_ttl_seconds,
|
|
432
441
|
public_verifying_key_set=self._public_verifying_key_set,
|
|
433
442
|
now=now,
|
|
@@ -439,52 +448,61 @@ class Verifier:
|
|
|
439
448
|
if self._public_verifying_key_set_refresh_id != old_refresh_id:
|
|
440
449
|
return
|
|
441
450
|
async with httpx.AsyncClient() as client:
|
|
442
|
-
response = await client.get(self._public_verifying_key_set_url)
|
|
451
|
+
response = await client.get(str(self._public_verifying_key_set_url))
|
|
443
452
|
if response.status_code != 200:
|
|
444
453
|
raise PublicVerifyingKeyRetrievalFailed()
|
|
445
|
-
|
|
446
|
-
response.content
|
|
447
|
-
|
|
454
|
+
try:
|
|
455
|
+
key_set = _parse_public_verifying_key_set(response.content)
|
|
456
|
+
except Exception as e:
|
|
457
|
+
raise PublicVerifyingKeyRetrievalFailed() from e
|
|
458
|
+
self._public_verifying_key_set = key_set
|
|
448
459
|
self._public_verifying_key_set_refreshed_at = _seconds_since_unix_epoch()
|
|
449
460
|
self._public_verifying_key_set_refresh_id = uuid.uuid4()
|
|
450
461
|
|
|
451
462
|
def _refresh_jwks_sync(self) -> None:
|
|
452
463
|
new_refresh_time = _seconds_since_unix_epoch()
|
|
453
464
|
with httpx.Client() as client:
|
|
454
|
-
response = client.get(self._public_verifying_key_set_url)
|
|
465
|
+
response = client.get(str(self._public_verifying_key_set_url))
|
|
455
466
|
if response.status_code != 200:
|
|
456
467
|
raise PublicVerifyingKeyRetrievalFailed()
|
|
457
|
-
|
|
458
|
-
response.content
|
|
459
|
-
|
|
468
|
+
try:
|
|
469
|
+
key_set = _parse_public_verifying_key_set(response.content)
|
|
470
|
+
except Exception as e:
|
|
471
|
+
raise PublicVerifyingKeyRetrievalFailed() from e
|
|
472
|
+
self._public_verifying_key_set = key_set
|
|
460
473
|
self._public_verifying_key_set_refreshed_at = new_refresh_time
|
|
461
474
|
|
|
462
475
|
|
|
463
476
|
def verify_with_time(
|
|
464
477
|
*,
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
correct_hooks_signature_components: str,
|
|
468
|
-
correct_hooks_signature: str,
|
|
469
|
-
request_body: bytes,
|
|
478
|
+
args: VerifyArgs,
|
|
479
|
+
recipient_id: uuid.UUID,
|
|
470
480
|
signature_ttl_seconds: int,
|
|
471
481
|
public_verifying_key_set: PublicVerifyingKeySet,
|
|
472
482
|
now: int,
|
|
473
483
|
) -> VerifiedData:
|
|
474
484
|
"""This function is only public for internal testing purposes and will be made private in a future version of this library."""
|
|
475
|
-
if method != "POST":
|
|
476
|
-
raise InvalidSignature()
|
|
477
485
|
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
486
|
+
try:
|
|
487
|
+
signature_components_encoded = _split_versioned_header(
|
|
488
|
+
args.correct_hooks_signature_components
|
|
489
|
+
).get(SIGNATURE_VERSION)
|
|
490
|
+
except Exception as e:
|
|
491
|
+
raise InvalidSignature() from e
|
|
481
492
|
if signature_components_encoded is None:
|
|
482
493
|
raise InvalidSignature()
|
|
494
|
+
|
|
483
495
|
try:
|
|
484
496
|
signature_components = _decode_signature_components(signature_components_encoded)
|
|
485
497
|
except Exception as e:
|
|
486
498
|
raise InvalidSignature() from e
|
|
487
499
|
|
|
500
|
+
if (
|
|
501
|
+
now > signature_components.signed_at + signature_ttl_seconds
|
|
502
|
+
or now + signature_ttl_seconds < signature_components.signed_at
|
|
503
|
+
):
|
|
504
|
+
raise InvalidSignature()
|
|
505
|
+
|
|
488
506
|
verifying_key_jwk = next(
|
|
489
507
|
(
|
|
490
508
|
key
|
|
@@ -503,11 +521,20 @@ def verify_with_time(
|
|
|
503
521
|
except Exception as e:
|
|
504
522
|
raise InvalidPublicVerifyingKey() from e
|
|
505
523
|
|
|
506
|
-
signature_message = _construct_signature_message(
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
524
|
+
signature_message = _construct_signature_message(
|
|
525
|
+
signature_components,
|
|
526
|
+
recipient_id,
|
|
527
|
+
args.target_url,
|
|
528
|
+
args.method,
|
|
529
|
+
args.request_body,
|
|
510
530
|
)
|
|
531
|
+
|
|
532
|
+
try:
|
|
533
|
+
signature_encoded = _split_versioned_header(args.correct_hooks_signature).get(
|
|
534
|
+
SIGNATURE_VERSION
|
|
535
|
+
)
|
|
536
|
+
except Exception as e:
|
|
537
|
+
raise InvalidSignature() from e
|
|
511
538
|
if signature_encoded is None:
|
|
512
539
|
raise InvalidSignature()
|
|
513
540
|
|
|
@@ -521,23 +548,20 @@ def verify_with_time(
|
|
|
521
548
|
except Exception as e:
|
|
522
549
|
raise InvalidSignature() from e
|
|
523
550
|
|
|
524
|
-
if (
|
|
525
|
-
now > signature_components.signed_at + signature_ttl_seconds
|
|
526
|
-
or now + signature_ttl_seconds < signature_components.signed_at
|
|
527
|
-
):
|
|
528
|
-
raise InvalidSignature()
|
|
529
|
-
|
|
530
|
-
if target_url != signature_components.target_url:
|
|
531
|
-
raise InvalidSignature()
|
|
532
|
-
|
|
533
551
|
return VerifiedData(webhook_id=signature_components.webhook_id)
|
|
534
552
|
|
|
535
553
|
|
|
536
554
|
def _construct_signature_message(
|
|
537
|
-
signature_components: _SignatureComponents,
|
|
555
|
+
signature_components: _SignatureComponents,
|
|
556
|
+
recipient_id: uuid.UUID,
|
|
557
|
+
target_url: str,
|
|
558
|
+
method: str,
|
|
559
|
+
request_body: bytes,
|
|
538
560
|
) -> bytes:
|
|
539
561
|
encoded_signature_components = _encode_signature_components(signature_components)
|
|
540
|
-
|
|
562
|
+
recipient_id_base64 = _encode_base64_from_string(str(recipient_id))
|
|
563
|
+
target_url_base64 = _encode_base64_from_string(target_url)
|
|
564
|
+
signature_components_bytes = f"{encoded_signature_components}.{recipient_id_base64}.{target_url_base64},{method}.".encode()
|
|
541
565
|
return signature_components_bytes + request_body
|
|
542
566
|
|
|
543
567
|
|
|
@@ -551,17 +575,18 @@ def _split_versioned_header(header: str) -> dict[str, str]:
|
|
|
551
575
|
parts = versioned_value.split(",")
|
|
552
576
|
if len(parts) < 2:
|
|
553
577
|
continue
|
|
578
|
+
if parts[0] in split_headers:
|
|
579
|
+
raise InvalidSignature()
|
|
554
580
|
split_headers[parts[0]] = parts[1]
|
|
555
581
|
return split_headers
|
|
556
582
|
|
|
557
583
|
|
|
558
584
|
def _encode_signature_components(signature_components: _SignatureComponents) -> str:
|
|
559
|
-
|
|
560
|
-
webhook_id_base64 = _encode_base64_from_string(signature_components.webhook_id)
|
|
561
|
-
signed_at_base64 = _encode_base64_from_string(str(signature_components.signed_at))
|
|
585
|
+
webhook_id_base64 = _encode_base64_from_string(str(signature_components.webhook_id))
|
|
562
586
|
key_id_base64 = _encode_base64_from_string(str(signature_components.key_id))
|
|
587
|
+
signed_at_base64 = _encode_base64_from_string(str(signature_components.signed_at))
|
|
563
588
|
encoded_signature_components = (
|
|
564
|
-
f"{
|
|
589
|
+
f"{webhook_id_base64}.{key_id_base64}.{signed_at_base64}"
|
|
565
590
|
)
|
|
566
591
|
return encoded_signature_components
|
|
567
592
|
|
|
@@ -570,17 +595,54 @@ def _decode_signature_components(
|
|
|
570
595
|
encoded_signature_components: str,
|
|
571
596
|
) -> _SignatureComponents:
|
|
572
597
|
components = list(encoded_signature_components.split("."))
|
|
573
|
-
if len(components) !=
|
|
598
|
+
if len(components) != 3:
|
|
574
599
|
raise ValueError("Invalid component count")
|
|
575
|
-
|
|
576
|
-
|
|
600
|
+
webhook_id = uuid.UUID(_decode_base64_to_string(components[0]))
|
|
601
|
+
key_id = uuid.UUID(_decode_base64_to_string(components[1]))
|
|
577
602
|
signed_at = int(_decode_base64_to_string(components[2]))
|
|
578
|
-
key_id = uuid.UUID(_decode_base64_to_string(components[3]))
|
|
579
603
|
return _SignatureComponents(
|
|
580
|
-
|
|
604
|
+
webhook_id=webhook_id,
|
|
605
|
+
key_id=key_id,
|
|
606
|
+
signed_at=signed_at,
|
|
581
607
|
)
|
|
582
608
|
|
|
583
609
|
|
|
610
|
+
class _PublicVerifyingKeySetPartialParse(CamelCaseBaseModel):
|
|
611
|
+
model_config = ConfigDict(extra="forbid")
|
|
612
|
+
|
|
613
|
+
keys: list[dict[str, Any]]
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _parse_public_verifying_key_set(content: bytes) -> PublicVerifyingKeySet:
|
|
617
|
+
try:
|
|
618
|
+
partially_parsed_key_set = _PublicVerifyingKeySetPartialParse.model_validate_json(
|
|
619
|
+
content
|
|
620
|
+
)
|
|
621
|
+
except Exception as e:
|
|
622
|
+
raise PublicVerifyingKeyRetrievalFailed() from e
|
|
623
|
+
|
|
624
|
+
# Keys that are not an exact match for PublicJwk fields give an error and are excluded.
|
|
625
|
+
parsed_keys: list[_PublicJwk] = []
|
|
626
|
+
for jwk in partially_parsed_key_set.keys:
|
|
627
|
+
try:
|
|
628
|
+
parsed_keys.append(_PublicJwk.model_validate(jwk))
|
|
629
|
+
except Exception: # noqa
|
|
630
|
+
continue
|
|
631
|
+
|
|
632
|
+
# Duplicate key ids in a key set are not allowed
|
|
633
|
+
key_ids: set[UUID4] = set()
|
|
634
|
+
for key in parsed_keys:
|
|
635
|
+
if key.kid in key_ids:
|
|
636
|
+
raise PublicVerifyingKeyRetrievalFailed()
|
|
637
|
+
key_ids.add(key.kid)
|
|
638
|
+
|
|
639
|
+
return PublicVerifyingKeySet(keys=parsed_keys)
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def is_valid_http_method(method: str) -> bool:
|
|
643
|
+
return method in VALID_HTTP_METHODS
|
|
644
|
+
|
|
645
|
+
|
|
584
646
|
def _encode_base64(data: bytes) -> str:
|
|
585
647
|
return base64.urlsafe_b64encode(data).decode("utf-8").rstrip("=")
|
|
586
648
|
|
correct_hooks-0.1.0/PKG-INFO
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: correct-hooks
|
|
3
|
-
Version: 0.1.0
|
|
4
|
-
Summary: Asymmetric signing, verification, and key management for webhooks
|
|
5
|
-
Author: Phillip Diffley
|
|
6
|
-
Author-email: Phillip Diffley <7283778+pdiffley@users.noreply.github.com>
|
|
7
|
-
License-Expression: MIT
|
|
8
|
-
Requires-Dist: cryptography>=50.0.2
|
|
9
|
-
Requires-Dist: httpx>=0.28.1
|
|
10
|
-
Requires-Dist: pydantic>=2.13.5
|
|
11
|
-
Requires-Python: >=3.11
|
|
12
|
-
Description-Content-Type: text/markdown
|
|
13
|
-
|
correct_hooks-0.1.0/README.md
DELETED
|
File without changes
|
|
File without changes
|