omniwebhook 0.1.0__py3-none-any.whl
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.
- omniwebhook/__init__.py +182 -0
- omniwebhook/adapters/__init__.py +1 -0
- omniwebhook/adapters/clock.py +20 -0
- omniwebhook/adapters/crypto.py +25 -0
- omniwebhook/adapters/dns/__init__.py +0 -0
- omniwebhook/adapters/dns/system.py +51 -0
- omniwebhook/adapters/ledger/__init__.py +0 -0
- omniwebhook/adapters/ledger/memory.py +35 -0
- omniwebhook/adapters/schemes/__init__.py +0 -0
- omniwebhook/adapters/schemes/body_signature.py +83 -0
- omniwebhook/adapters/schemes/creem.py +13 -0
- omniwebhook/adapters/schemes/event_keys.py +37 -0
- omniwebhook/adapters/schemes/github.py +15 -0
- omniwebhook/adapters/schemes/hmac_body.py +29 -0
- omniwebhook/adapters/schemes/mercadopago.py +86 -0
- omniwebhook/adapters/schemes/scheme_verifier.py +116 -0
- omniwebhook/adapters/schemes/standard/__init__.py +79 -0
- omniwebhook/adapters/schemes/standard/native_signer.py +14 -0
- omniwebhook/adapters/schemes/standard/reference_signer.py +16 -0
- omniwebhook/adapters/schemes/standard/secret.py +31 -0
- omniwebhook/adapters/schemes/standard/signer.py +14 -0
- omniwebhook/adapters/schemes/standard/standard_signer.py +42 -0
- omniwebhook/adapters/schemes/stripe.py +61 -0
- omniwebhook/adapters/stores/__init__.py +0 -0
- omniwebhook/adapters/stores/firestore.py +174 -0
- omniwebhook/adapters/stores/memory.py +71 -0
- omniwebhook/adapters/stores/postgres.py +187 -0
- omniwebhook/adapters/tokens.py +26 -0
- omniwebhook/adapters/transport/__init__.py +0 -0
- omniwebhook/adapters/transport/http_client.py +94 -0
- omniwebhook/adapters/transport/httpx_transport.py +48 -0
- omniwebhook/adapters/transport/threaded.py +13 -0
- omniwebhook/application/__init__.py +1 -0
- omniwebhook/application/ports.py +180 -0
- omniwebhook/application/receive_webhook.py +199 -0
- omniwebhook/application/send_webhook.py +305 -0
- omniwebhook/domain/__init__.py +1 -0
- omniwebhook/domain/blanks.py +10 -0
- omniwebhook/domain/delivery.py +43 -0
- omniwebhook/domain/destination.py +118 -0
- omniwebhook/domain/errors.py +15 -0
- omniwebhook/domain/event_key.py +11 -0
- omniwebhook/domain/fields.py +31 -0
- omniwebhook/domain/freshness.py +10 -0
- omniwebhook/domain/incoming_request.py +29 -0
- omniwebhook/domain/ip_address.py +146 -0
- omniwebhook/domain/message.py +43 -0
- omniwebhook/domain/reception.py +26 -0
- omniwebhook/domain/reservation.py +9 -0
- omniwebhook/domain/retry.py +109 -0
- omniwebhook/domain/signature_pairs.py +22 -0
- omniwebhook/domain/spec_version.py +5 -0
- omniwebhook/domain/timestamp.py +24 -0
- omniwebhook/domain/verification.py +24 -0
- omniwebhook/entrypoints/__init__.py +1 -0
- omniwebhook/entrypoints/asgi.py +18 -0
- omniwebhook/entrypoints/receiver.py +55 -0
- omniwebhook/entrypoints/requests.py +27 -0
- omniwebhook/entrypoints/sender.py +94 -0
- omniwebhook/entrypoints/starlette.py +19 -0
- omniwebhook/firestore.py +9 -0
- omniwebhook/httpx.py +5 -0
- omniwebhook/postgres.py +23 -0
- omniwebhook/py.typed +0 -0
- omniwebhook/standard.py +26 -0
- omniwebhook/starlette.py +5 -0
- omniwebhook-0.1.0.dist-info/METADATA +129 -0
- omniwebhook-0.1.0.dist-info/RECORD +70 -0
- omniwebhook-0.1.0.dist-info/WHEEL +4 -0
- omniwebhook-0.1.0.dist-info/licenses/LICENSE +21 -0
omniwebhook/__init__.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Webhooks firmados que se emiten y se reciben igual en cualquier stack."""
|
|
2
|
+
|
|
3
|
+
from omniwebhook.adapters.clock import system_clock
|
|
4
|
+
from omniwebhook.adapters.dns.system import AsyncSystemDnsResolver, SystemDnsResolver
|
|
5
|
+
from omniwebhook.adapters.ledger.memory import AsyncMemoryDeliveryLedger, MemoryDeliveryLedger
|
|
6
|
+
from omniwebhook.adapters.schemes.creem import creem_scheme
|
|
7
|
+
from omniwebhook.adapters.schemes.github import github_scheme
|
|
8
|
+
from omniwebhook.adapters.schemes.hmac_body import hmac_body_scheme
|
|
9
|
+
from omniwebhook.adapters.schemes.mercadopago import mercadopago_scheme
|
|
10
|
+
from omniwebhook.adapters.schemes.stripe import stripe_scheme
|
|
11
|
+
from omniwebhook.adapters.stores.memory import AsyncMemoryIdempotencyStore, MemoryIdempotencyStore
|
|
12
|
+
from omniwebhook.adapters.tokens import random_message_id, random_tokens
|
|
13
|
+
from omniwebhook.adapters.transport.http_client import HttpClientTransport
|
|
14
|
+
from omniwebhook.adapters.transport.threaded import ThreadedTransport
|
|
15
|
+
from omniwebhook.application.ports import (
|
|
16
|
+
AsyncDeliveryLedger,
|
|
17
|
+
AsyncDnsResolver,
|
|
18
|
+
AsyncHttpTransport,
|
|
19
|
+
AsyncIdempotencyStore,
|
|
20
|
+
AttemptRecord,
|
|
21
|
+
ClaimRequest,
|
|
22
|
+
Clock,
|
|
23
|
+
CompleteRequest,
|
|
24
|
+
DeliveryLedger,
|
|
25
|
+
DnsResolver,
|
|
26
|
+
HttpTransport,
|
|
27
|
+
IdempotencyStore,
|
|
28
|
+
MessageSigner,
|
|
29
|
+
RandomSource,
|
|
30
|
+
ReleaseRequest,
|
|
31
|
+
Timer,
|
|
32
|
+
TokenGenerator,
|
|
33
|
+
TransportFailure,
|
|
34
|
+
TransportRequest,
|
|
35
|
+
TransportResponse,
|
|
36
|
+
Verifier,
|
|
37
|
+
)
|
|
38
|
+
from omniwebhook.application.receive_webhook import (
|
|
39
|
+
AsyncEventHandler,
|
|
40
|
+
AsyncReceiveWebhook,
|
|
41
|
+
EventHandler,
|
|
42
|
+
ReceiveWebhook,
|
|
43
|
+
Reception,
|
|
44
|
+
VerifiedEvent,
|
|
45
|
+
)
|
|
46
|
+
from omniwebhook.application.send_webhook import (
|
|
47
|
+
DEFAULT_CONTENT_TYPE,
|
|
48
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
49
|
+
AsyncSendWebhook,
|
|
50
|
+
Delivery,
|
|
51
|
+
Endpoint,
|
|
52
|
+
SendWebhook,
|
|
53
|
+
)
|
|
54
|
+
from omniwebhook.domain.delivery import (
|
|
55
|
+
AttemptOutcome,
|
|
56
|
+
DeliveryClass,
|
|
57
|
+
DeliveryFailure,
|
|
58
|
+
DeliveryState,
|
|
59
|
+
classify_delivery,
|
|
60
|
+
)
|
|
61
|
+
from omniwebhook.domain.destination import (
|
|
62
|
+
DestinationProblem,
|
|
63
|
+
DestinationVerdict,
|
|
64
|
+
InspectedDestination,
|
|
65
|
+
evaluate_destination,
|
|
66
|
+
inspect_destination,
|
|
67
|
+
)
|
|
68
|
+
from omniwebhook.domain.errors import ConfigurationError
|
|
69
|
+
from omniwebhook.domain.freshness import DEFAULT_TOLERANCE_SECONDS
|
|
70
|
+
from omniwebhook.domain.incoming_request import Field, IncomingRequest
|
|
71
|
+
from omniwebhook.domain.ip_address import is_blocked_address
|
|
72
|
+
from omniwebhook.domain.message import NotSigned, OutgoingMessage, Signed, Signing, SigningProblem
|
|
73
|
+
from omniwebhook.domain.reception import ReceptionOutcome, http_status_for
|
|
74
|
+
from omniwebhook.domain.reservation import DEFAULT_LEASE_SECONDS, DEFAULT_RETENTION_SECONDS, ClaimOutcome
|
|
75
|
+
from omniwebhook.domain.retry import (
|
|
76
|
+
DEFAULT_JITTER_RATIO,
|
|
77
|
+
DEFAULT_MAX_DELAY_SECONDS,
|
|
78
|
+
DEFAULT_RETRY_SCHEDULE,
|
|
79
|
+
NextAttempt,
|
|
80
|
+
RetryPolicy,
|
|
81
|
+
next_attempt,
|
|
82
|
+
)
|
|
83
|
+
from omniwebhook.domain.spec_version import SPEC_VERSION
|
|
84
|
+
from omniwebhook.domain.verification import Rejected, Rejection, Verification, Verified
|
|
85
|
+
from omniwebhook.entrypoints.asgi import incoming_request_from_scope
|
|
86
|
+
from omniwebhook.entrypoints.receiver import create_async_receiver, create_receiver
|
|
87
|
+
from omniwebhook.entrypoints.requests import incoming_request
|
|
88
|
+
from omniwebhook.entrypoints.sender import create_async_sender, create_sender
|
|
89
|
+
|
|
90
|
+
__all__ = [
|
|
91
|
+
"DEFAULT_CONTENT_TYPE",
|
|
92
|
+
"DEFAULT_JITTER_RATIO",
|
|
93
|
+
"DEFAULT_LEASE_SECONDS",
|
|
94
|
+
"DEFAULT_MAX_DELAY_SECONDS",
|
|
95
|
+
"DEFAULT_RETENTION_SECONDS",
|
|
96
|
+
"DEFAULT_RETRY_SCHEDULE",
|
|
97
|
+
"DEFAULT_TIMEOUT_SECONDS",
|
|
98
|
+
"DEFAULT_TOLERANCE_SECONDS",
|
|
99
|
+
"SPEC_VERSION",
|
|
100
|
+
"AsyncDeliveryLedger",
|
|
101
|
+
"AsyncDnsResolver",
|
|
102
|
+
"AsyncEventHandler",
|
|
103
|
+
"AsyncHttpTransport",
|
|
104
|
+
"AsyncIdempotencyStore",
|
|
105
|
+
"AsyncMemoryDeliveryLedger",
|
|
106
|
+
"AsyncMemoryIdempotencyStore",
|
|
107
|
+
"AsyncReceiveWebhook",
|
|
108
|
+
"AsyncSendWebhook",
|
|
109
|
+
"AsyncSystemDnsResolver",
|
|
110
|
+
"AttemptOutcome",
|
|
111
|
+
"AttemptRecord",
|
|
112
|
+
"ClaimOutcome",
|
|
113
|
+
"ClaimRequest",
|
|
114
|
+
"Clock",
|
|
115
|
+
"CompleteRequest",
|
|
116
|
+
"ConfigurationError",
|
|
117
|
+
"Delivery",
|
|
118
|
+
"DeliveryClass",
|
|
119
|
+
"DeliveryFailure",
|
|
120
|
+
"DeliveryLedger",
|
|
121
|
+
"DeliveryState",
|
|
122
|
+
"DestinationProblem",
|
|
123
|
+
"DestinationVerdict",
|
|
124
|
+
"DnsResolver",
|
|
125
|
+
"Endpoint",
|
|
126
|
+
"EventHandler",
|
|
127
|
+
"Field",
|
|
128
|
+
"HttpClientTransport",
|
|
129
|
+
"HttpTransport",
|
|
130
|
+
"IdempotencyStore",
|
|
131
|
+
"IncomingRequest",
|
|
132
|
+
"InspectedDestination",
|
|
133
|
+
"MemoryDeliveryLedger",
|
|
134
|
+
"MemoryIdempotencyStore",
|
|
135
|
+
"MessageSigner",
|
|
136
|
+
"NextAttempt",
|
|
137
|
+
"NotSigned",
|
|
138
|
+
"OutgoingMessage",
|
|
139
|
+
"RandomSource",
|
|
140
|
+
"ReceiveWebhook",
|
|
141
|
+
"Reception",
|
|
142
|
+
"ReceptionOutcome",
|
|
143
|
+
"Rejected",
|
|
144
|
+
"Rejection",
|
|
145
|
+
"ReleaseRequest",
|
|
146
|
+
"RetryPolicy",
|
|
147
|
+
"SendWebhook",
|
|
148
|
+
"Signed",
|
|
149
|
+
"Signing",
|
|
150
|
+
"SigningProblem",
|
|
151
|
+
"SystemDnsResolver",
|
|
152
|
+
"ThreadedTransport",
|
|
153
|
+
"Timer",
|
|
154
|
+
"TokenGenerator",
|
|
155
|
+
"TransportFailure",
|
|
156
|
+
"TransportRequest",
|
|
157
|
+
"TransportResponse",
|
|
158
|
+
"Verification",
|
|
159
|
+
"Verified",
|
|
160
|
+
"VerifiedEvent",
|
|
161
|
+
"Verifier",
|
|
162
|
+
"classify_delivery",
|
|
163
|
+
"create_async_receiver",
|
|
164
|
+
"create_async_sender",
|
|
165
|
+
"create_receiver",
|
|
166
|
+
"create_sender",
|
|
167
|
+
"creem_scheme",
|
|
168
|
+
"evaluate_destination",
|
|
169
|
+
"github_scheme",
|
|
170
|
+
"hmac_body_scheme",
|
|
171
|
+
"http_status_for",
|
|
172
|
+
"incoming_request",
|
|
173
|
+
"incoming_request_from_scope",
|
|
174
|
+
"inspect_destination",
|
|
175
|
+
"is_blocked_address",
|
|
176
|
+
"mercadopago_scheme",
|
|
177
|
+
"next_attempt",
|
|
178
|
+
"random_message_id",
|
|
179
|
+
"random_tokens",
|
|
180
|
+
"stripe_scheme",
|
|
181
|
+
"system_clock",
|
|
182
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Implementaciones de los puertos: esquemas de firma, almacenes y transporte."""
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""El reloj y el cronómetro del sistema."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SystemClock:
|
|
7
|
+
"""El reloj del sistema, en segundos."""
|
|
8
|
+
|
|
9
|
+
def now(self) -> int:
|
|
10
|
+
return int(time.time())
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MonotonicTimer:
|
|
14
|
+
"""Un cronómetro que no retrocede aunque cambie la hora del sistema."""
|
|
15
|
+
|
|
16
|
+
def now_ms(self) -> int:
|
|
17
|
+
return time.monotonic_ns() // 1_000_000
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
system_clock = SystemClock()
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Primitivas criptográficas sobre la biblioteca estándar."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def utf8(text: str) -> bytes | None:
|
|
8
|
+
"""El texto en UTF-8, o `None` si no se puede codificar."""
|
|
9
|
+
try:
|
|
10
|
+
return text.encode("utf-8")
|
|
11
|
+
except UnicodeEncodeError:
|
|
12
|
+
return None
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def hmac_sha256(key: bytes, message: bytes) -> bytes:
|
|
16
|
+
return hmac.new(key, message, hashlib.sha256).digest()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def sha256_hex(message: bytes) -> str:
|
|
20
|
+
return hashlib.sha256(message).hexdigest()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def equal_in_constant_time(a: str, b: str) -> bool:
|
|
24
|
+
"""Compara dos textos sin cortar en la primera diferencia (sección 4.3)."""
|
|
25
|
+
return hmac.compare_digest(a.encode("utf-8", "surrogatepass"), b.encode("utf-8", "surrogatepass"))
|
|
File without changes
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Resuelve nombres con el sistema operativo. Un nombre que no existe da una lista vacía."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import socket
|
|
5
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
6
|
+
from typing import Any, Final
|
|
7
|
+
|
|
8
|
+
AddressInfo = Sequence[tuple[Any, Any, Any, str, tuple[Any, ...]]]
|
|
9
|
+
"""Lo que devuelve `socket.getaddrinfo`."""
|
|
10
|
+
|
|
11
|
+
_NOT_FOUND: Final = frozenset(
|
|
12
|
+
code for code in (socket.EAI_NONAME, getattr(socket, "EAI_NODATA", None)) if code is not None
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _addresses(found: AddressInfo) -> list[str]:
|
|
17
|
+
return list(dict.fromkeys(str(entry[4][0]) for entry in found))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _system_lookup(host: str) -> AddressInfo:
|
|
21
|
+
return socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def _async_system_lookup(host: str) -> AddressInfo:
|
|
25
|
+
return await asyncio.get_running_loop().getaddrinfo(host, None, type=socket.SOCK_STREAM)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SystemDnsResolver:
|
|
29
|
+
def __init__(self, *, lookup: Callable[[str], AddressInfo] = _system_lookup) -> None:
|
|
30
|
+
self._lookup = lookup
|
|
31
|
+
|
|
32
|
+
def resolve(self, host: str) -> list[str]:
|
|
33
|
+
try:
|
|
34
|
+
return _addresses(self._lookup(host))
|
|
35
|
+
except socket.gaierror as error:
|
|
36
|
+
if error.errno in _NOT_FOUND:
|
|
37
|
+
return []
|
|
38
|
+
raise
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class AsyncSystemDnsResolver:
|
|
42
|
+
def __init__(self, *, lookup: Callable[[str], Awaitable[AddressInfo]] = _async_system_lookup) -> None:
|
|
43
|
+
self._lookup = lookup
|
|
44
|
+
|
|
45
|
+
async def resolve(self, host: str) -> list[str]:
|
|
46
|
+
try:
|
|
47
|
+
return _addresses(await self._lookup(host))
|
|
48
|
+
except socket.gaierror as error:
|
|
49
|
+
if error.errno in _NOT_FOUND:
|
|
50
|
+
return []
|
|
51
|
+
raise
|
|
File without changes
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Registro de entregas en memoria. Sirve para tests y para un único proceso."""
|
|
2
|
+
|
|
3
|
+
from omniwebhook.application.ports import AttemptRecord
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MemoryDeliveryLedger:
|
|
7
|
+
def __init__(self) -> None:
|
|
8
|
+
self._records: list[AttemptRecord] = []
|
|
9
|
+
|
|
10
|
+
def record(self, attempt: AttemptRecord) -> None:
|
|
11
|
+
self._records.append(attempt)
|
|
12
|
+
|
|
13
|
+
def attempts(self) -> list[AttemptRecord]:
|
|
14
|
+
"""Todos los intentos, en el orden en que se registraron."""
|
|
15
|
+
return list(self._records)
|
|
16
|
+
|
|
17
|
+
def attempts_of(self, message_id: str, endpoint_id: str) -> list[AttemptRecord]:
|
|
18
|
+
"""Los intentos de un mensaje hacia un destino."""
|
|
19
|
+
return [r for r in self._records if r.message_id == message_id and r.endpoint_id == endpoint_id]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AsyncMemoryDeliveryLedger:
|
|
23
|
+
"""El mismo registro para código asincrónico. Registrar no espera, así que no bloquea."""
|
|
24
|
+
|
|
25
|
+
def __init__(self) -> None:
|
|
26
|
+
self._ledger = MemoryDeliveryLedger()
|
|
27
|
+
|
|
28
|
+
async def record(self, attempt: AttemptRecord) -> None:
|
|
29
|
+
self._ledger.record(attempt)
|
|
30
|
+
|
|
31
|
+
def attempts(self) -> list[AttemptRecord]:
|
|
32
|
+
return self._ledger.attempts()
|
|
33
|
+
|
|
34
|
+
def attempts_of(self, message_id: str, endpoint_id: str) -> list[AttemptRecord]:
|
|
35
|
+
return self._ledger.attempts_of(message_id, endpoint_id)
|
|
File without changes
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Esquemas que firman sólo el cuerpo y mandan la firma en una cabecera."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from omniwebhook.adapters.crypto import hmac_sha256
|
|
9
|
+
from omniwebhook.adapters.schemes.event_keys import body_fingerprint, json_id_key
|
|
10
|
+
from omniwebhook.adapters.schemes.scheme_verifier import Reading, ReadProblem, scheme_verifier, text_key
|
|
11
|
+
from omniwebhook.application.ports import Verifier
|
|
12
|
+
from omniwebhook.domain.errors import ConfigurationError
|
|
13
|
+
from omniwebhook.domain.event_key import event_key
|
|
14
|
+
from omniwebhook.domain.fields import pick_singles
|
|
15
|
+
from omniwebhook.domain.incoming_request import IncomingRequest, field_values
|
|
16
|
+
|
|
17
|
+
SignatureEncoding = Literal["hex", "base64"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
21
|
+
class BodySignatureFormat:
|
|
22
|
+
name: str
|
|
23
|
+
"""El nombre del esquema en la clave del evento."""
|
|
24
|
+
header: str
|
|
25
|
+
"""La cabecera que trae la firma."""
|
|
26
|
+
prefix: str = ""
|
|
27
|
+
"""Un texto fijo antes de la firma."""
|
|
28
|
+
encoding: SignatureEncoding = "hex"
|
|
29
|
+
id_header: str | None = None
|
|
30
|
+
"""La cabecera que identifica el evento, si el emisor manda una."""
|
|
31
|
+
fallback_key: Literal["json-id", "fingerprint"] = "fingerprint"
|
|
32
|
+
"""De dónde sale la clave del evento cuando no hay cabecera que lo identifique."""
|
|
33
|
+
|
|
34
|
+
def __post_init__(self) -> None:
|
|
35
|
+
for option, value in (("name", self.name), ("header", self.header)):
|
|
36
|
+
if not isinstance(value, str) or value.strip() == "":
|
|
37
|
+
raise ConfigurationError(f"{option} no puede estar vacío")
|
|
38
|
+
if self.encoding not in ("hex", "base64"):
|
|
39
|
+
raise ConfigurationError('encoding tiene que ser "hex" o "base64"')
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class _BodySignature:
|
|
44
|
+
format: BodySignatureFormat
|
|
45
|
+
|
|
46
|
+
def key_of(self, secret: str) -> bytes | None:
|
|
47
|
+
return text_key(secret)
|
|
48
|
+
|
|
49
|
+
def read(self, request: IncomingRequest) -> Reading | ReadProblem:
|
|
50
|
+
fmt = self.format
|
|
51
|
+
fields = pick_singles(
|
|
52
|
+
{"signature": field_values(request.headers, fmt.header)},
|
|
53
|
+
{"id": [] if fmt.id_header is None else field_values(request.headers, fmt.id_header)},
|
|
54
|
+
)
|
|
55
|
+
if isinstance(fields, str):
|
|
56
|
+
return fields
|
|
57
|
+
signature = fields.required["signature"]
|
|
58
|
+
if not signature.startswith(fmt.prefix):
|
|
59
|
+
return "malformed"
|
|
60
|
+
|
|
61
|
+
received = signature[len(fmt.prefix) :]
|
|
62
|
+
identifier = fields.optional["id"]
|
|
63
|
+
|
|
64
|
+
def key() -> str:
|
|
65
|
+
if identifier is not None:
|
|
66
|
+
return event_key(fmt.name, identifier)
|
|
67
|
+
derive = json_id_key if fmt.fallback_key == "json-id" else body_fingerprint
|
|
68
|
+
return derive(fmt.name, request.body)
|
|
69
|
+
|
|
70
|
+
return Reading(
|
|
71
|
+
timestamp=None,
|
|
72
|
+
received=[received.lower() if fmt.encoding == "hex" else received],
|
|
73
|
+
event_key=key,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def expected(self, key: bytes, reading: Reading, request: IncomingRequest) -> str:
|
|
77
|
+
mac = hmac_sha256(key, request.body)
|
|
78
|
+
return mac.hex() if self.format.encoding == "hex" else base64.b64encode(mac).decode("ascii")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def body_signature_verifier(fmt: BodySignatureFormat, *, secrets: Sequence[str]) -> Verifier:
|
|
82
|
+
"""Arma el verificador de un formato que firma sólo el cuerpo. No lleva marca de tiempo."""
|
|
83
|
+
return scheme_verifier(_BodySignature(fmt), secrets=secrets)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""El formato de firma de Creem (sección 5.5)."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
from omniwebhook.adapters.schemes.body_signature import BodySignatureFormat, body_signature_verifier
|
|
6
|
+
from omniwebhook.application.ports import Verifier
|
|
7
|
+
|
|
8
|
+
_FORMAT = BodySignatureFormat(name="creem", header="creem-signature", fallback_key="json-id")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def creem_scheme(*, secrets: Sequence[str]) -> Verifier:
|
|
12
|
+
"""Verifica el formato de firma de Creem."""
|
|
13
|
+
return body_signature_verifier(_FORMAT, secrets=secrets)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Claves de evento que salen del cuerpo (sección 4.6)."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import NoReturn
|
|
5
|
+
|
|
6
|
+
from omniwebhook.adapters.crypto import sha256_hex
|
|
7
|
+
from omniwebhook.domain.event_key import event_key, fingerprint_key
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def body_fingerprint(scheme: str, body: bytes) -> str:
|
|
11
|
+
"""La clave de un evento sin identificador: la huella de su cuerpo."""
|
|
12
|
+
return fingerprint_key(scheme, sha256_hex(body))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def json_id_key(scheme: str, body: bytes) -> str:
|
|
16
|
+
"""La clave de un evento cuyo identificador viaja en el campo `id` del cuerpo.
|
|
17
|
+
|
|
18
|
+
Si el cuerpo no es un objeto JSON con un `id` de texto no vacío, se usa la huella.
|
|
19
|
+
"""
|
|
20
|
+
identifier = _json_id(body)
|
|
21
|
+
return body_fingerprint(scheme, body) if identifier is None else event_key(scheme, identifier)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _not_json(constant: str) -> NoReturn:
|
|
25
|
+
raise ValueError(f"{constant} no es JSON")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _json_id(body: bytes) -> str | None:
|
|
29
|
+
try:
|
|
30
|
+
# Los números no interesan; leerlos como decimales evita el tope de dígitos de los enteros.
|
|
31
|
+
data = json.loads(body.decode("utf-8"), parse_constant=_not_json, parse_int=float)
|
|
32
|
+
except (ValueError, RecursionError):
|
|
33
|
+
return None
|
|
34
|
+
if not isinstance(data, dict):
|
|
35
|
+
return None
|
|
36
|
+
identifier = data.get("id")
|
|
37
|
+
return identifier if isinstance(identifier, str) and identifier else None
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""El formato de firma de GitHub (sección 5.4)."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
from omniwebhook.adapters.schemes.body_signature import BodySignatureFormat, body_signature_verifier
|
|
6
|
+
from omniwebhook.application.ports import Verifier
|
|
7
|
+
|
|
8
|
+
_FORMAT = BodySignatureFormat(
|
|
9
|
+
name="github", header="x-hub-signature-256", prefix="sha256=", id_header="x-github-delivery"
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def github_scheme(*, secrets: Sequence[str]) -> Verifier:
|
|
14
|
+
"""Verifica el formato de firma de GitHub."""
|
|
15
|
+
return body_signature_verifier(_FORMAT, secrets=secrets)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Un esquema genérico para emisores que firman sólo el cuerpo (sección 5.6)."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
from omniwebhook.adapters.schemes.body_signature import (
|
|
6
|
+
BodySignatureFormat,
|
|
7
|
+
SignatureEncoding,
|
|
8
|
+
body_signature_verifier,
|
|
9
|
+
)
|
|
10
|
+
from omniwebhook.application.ports import Verifier
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def hmac_body_scheme(
|
|
14
|
+
*,
|
|
15
|
+
secrets: Sequence[str],
|
|
16
|
+
header: str,
|
|
17
|
+
prefix: str = "",
|
|
18
|
+
encoding: SignatureEncoding = "hex",
|
|
19
|
+
name: str = "hmac-body",
|
|
20
|
+
id_header: str | None = None,
|
|
21
|
+
) -> Verifier:
|
|
22
|
+
"""Verifica a un emisor que firma sólo el cuerpo con HMAC-SHA256.
|
|
23
|
+
|
|
24
|
+
`header` es la cabecera que trae la firma y `prefix` un texto fijo antes de ella.
|
|
25
|
+
`name` es el nombre del esquema en la clave del evento. Sin `id_header`, la clave es
|
|
26
|
+
la huella del cuerpo.
|
|
27
|
+
"""
|
|
28
|
+
fmt = BodySignatureFormat(name=name, header=header, prefix=prefix, encoding=encoding, id_header=id_header)
|
|
29
|
+
return body_signature_verifier(fmt, secrets=secrets)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""El formato de firma de Mercado Pago (sección 5.3)."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
from omniwebhook.adapters.crypto import hmac_sha256
|
|
7
|
+
from omniwebhook.adapters.schemes.scheme_verifier import Reading, ReadProblem, scheme_verifier, text_key
|
|
8
|
+
from omniwebhook.application.ports import Clock, Verifier
|
|
9
|
+
from omniwebhook.domain.event_key import event_key
|
|
10
|
+
from omniwebhook.domain.fields import pick_singles
|
|
11
|
+
from omniwebhook.domain.freshness import DEFAULT_TOLERANCE_SECONDS
|
|
12
|
+
from omniwebhook.domain.incoming_request import IncomingRequest, field_values
|
|
13
|
+
from omniwebhook.domain.signature_pairs import pair_values, parse_pairs
|
|
14
|
+
from omniwebhook.domain.timestamp import SECONDS_OR_MILLIS_DIGITS, parse_timestamp, to_seconds
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
18
|
+
class _MercadoPagoReading(Reading):
|
|
19
|
+
manifest: str
|
|
20
|
+
"""Lo que se firma: `id:…;request-id:…;ts:…;`, sin las partes que falten."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _MercadoPago:
|
|
24
|
+
def key_of(self, secret: str) -> bytes | None:
|
|
25
|
+
return text_key(secret)
|
|
26
|
+
|
|
27
|
+
def read(self, request: IncomingRequest) -> _MercadoPagoReading | ReadProblem:
|
|
28
|
+
fields = pick_singles(
|
|
29
|
+
{"signature": field_values(request.headers, "x-signature")},
|
|
30
|
+
{
|
|
31
|
+
"request_id": field_values(request.headers, "x-request-id"),
|
|
32
|
+
"data_id": field_values(request.query, "data.id"),
|
|
33
|
+
},
|
|
34
|
+
)
|
|
35
|
+
if isinstance(fields, str):
|
|
36
|
+
return fields
|
|
37
|
+
|
|
38
|
+
pairs = parse_pairs(fields.required["signature"], lowercase_keys=True)
|
|
39
|
+
times = pair_values(pairs, "ts")
|
|
40
|
+
signatures = pair_values(pairs, "v1")
|
|
41
|
+
if len(times) > 1 or len(signatures) > 1:
|
|
42
|
+
return "ambiguous"
|
|
43
|
+
if not times or not signatures:
|
|
44
|
+
return "malformed"
|
|
45
|
+
raw_timestamp = times[0]
|
|
46
|
+
raw = parse_timestamp(raw_timestamp, SECONDS_OR_MILLIS_DIGITS)
|
|
47
|
+
if raw is None:
|
|
48
|
+
return "malformed"
|
|
49
|
+
|
|
50
|
+
request_id = fields.optional["request_id"]
|
|
51
|
+
data_id = fields.optional["data_id"]
|
|
52
|
+
data_id = None if data_id is None else data_id.lower()
|
|
53
|
+
parts = (
|
|
54
|
+
"" if data_id is None else f"id:{data_id};",
|
|
55
|
+
"" if request_id is None else f"request-id:{request_id};",
|
|
56
|
+
f"ts:{raw_timestamp};",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def key() -> str:
|
|
60
|
+
if data_id is None and request_id is None:
|
|
61
|
+
return event_key("mercadopago", f"ts:{raw_timestamp}")
|
|
62
|
+
return event_key("mercadopago", f"{data_id or ''}:{request_id or ''}")
|
|
63
|
+
|
|
64
|
+
return _MercadoPagoReading(
|
|
65
|
+
manifest="".join(parts),
|
|
66
|
+
timestamp=to_seconds(raw),
|
|
67
|
+
received=[signatures[0].lower()],
|
|
68
|
+
event_key=key,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def expected(self, key: bytes, reading: _MercadoPagoReading, request: IncomingRequest) -> str:
|
|
72
|
+
return hmac_sha256(key, reading.manifest.encode("utf-8", "surrogatepass")).hex()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def mercadopago_scheme(
|
|
76
|
+
*,
|
|
77
|
+
secrets: Sequence[str],
|
|
78
|
+
tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
|
|
79
|
+
clock: Clock | None = None,
|
|
80
|
+
) -> Verifier:
|
|
81
|
+
"""Verifica el formato de firma de Mercado Pago.
|
|
82
|
+
|
|
83
|
+
La firma no cubre el cuerpo: conviene tratar el aviso como una señal de cambio y
|
|
84
|
+
consultar el recurso al emisor antes de actuar.
|
|
85
|
+
"""
|
|
86
|
+
return scheme_verifier(_MercadoPago(), secrets=secrets, clock=clock, tolerance_seconds=tolerance_seconds)
|