Skip to main content

ocre/runtime/
webhooks.rs

1//! [`once`]: a webhook event's effect runs once, however many times it is delivered.
2
3use crate::{Db, Error, Result, config::Environment, params, webhooks::UrlHost};
4
5/// A delivery left `processing` this long (seconds) is taken over by the
6/// next one: the invocation that claimed it died before finishing.
7pub const STALE_AFTER: i64 = 300;
8
9/// What [`once`] did with a delivery.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum Delivery<T> {
12    /// The effect ran (first delivery, or a retry after a failure) and returned this.
13    Processed(T),
14    /// Already processed, or being processed by another invocation: nothing ran.
15    Duplicate,
16}
17
18/// Runs `effect` for the event `event_id` of `source` unless it already ran.
19///
20/// The delivery is claimed with one insert into `webhook_events` (unique on
21/// `source, event_id`), with the raw `payload` kept for the log. When the
22/// effect succeeds the event is marked `processed`, and later deliveries of
23/// the same id get [`Delivery::Duplicate`]: answer them 200 so the provider
24/// stops retrying. When it fails, the event is marked `failed` with the
25/// error and the error is returned, so the handler answers 500 and the
26/// provider's retry runs the effect again. A delivery still `processing`
27/// after [`STALE_AFTER`] seconds is taken over.
28///
29/// Two to three D1 writes per delivery. Recording and effect are separate
30/// statements: an effect made of D1 writes should be idempotent itself
31/// (`INSERT ... ON CONFLICT DO NOTHING`, `UPDATE ... WHERE status = 'pending'`)
32/// to stay correct if the invocation dies between them.
33///
34/// # Errors
35///
36/// The effect's error, or a D1 error (the table is missing: run
37/// `ocre g webhook` and `ocre migrate`).
38pub async fn once<T, F, Fut>(db: &Db, source: &str, event_id: &str, payload: &[u8], effect: F) -> Result<Delivery<T>>
39where
40    F: FnOnce() -> Fut,
41    Fut: Future<Output = Result<T>>,
42{
43    let now = crate::now();
44    let claimed = db
45        .execute(
46            "INSERT INTO webhook_events (source, event_id, payload, status, received_at) \
47             VALUES (?1, ?2, ?3, 'processing', ?4) \
48             ON CONFLICT (source, event_id) DO UPDATE SET status = 'processing', attempts = attempts + 1, \
49             received_at = ?4 \
50             WHERE webhook_events.status = 'failed' \
51             OR (webhook_events.status = 'processing' AND webhook_events.received_at < ?5)",
52            params![source, event_id, String::from_utf8_lossy(payload).into_owned(), now, now - STALE_AFTER],
53        )
54        .await?;
55    if claimed == 0 {
56        return Ok(Delivery::Duplicate);
57    }
58    match effect().await {
59        Ok(value) => {
60            db.execute(
61                "UPDATE webhook_events SET status = 'processed', error = NULL, processed_at = ?3 \
62                 WHERE source = ?1 AND event_id = ?2",
63                params![source, event_id, crate::now()],
64            )
65            .await?;
66            Ok(Delivery::Processed(value))
67        }
68        Err(err) => {
69            db.execute(
70                "UPDATE webhook_events SET status = 'failed', error = ?3 WHERE source = ?1 AND event_id = ?2",
71                params![source, event_id, err.to_string()],
72            )
73            .await?;
74            Err(err)
75        }
76    }
77}
78
79/// The answer of [`post_signed`]: status and body.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct Answer {
82    /// HTTP status.
83    pub status: u16,
84    /// Body, as text.
85    pub text: String,
86}
87
88/// POSTs `body` as JSON to `url`, signed: the HMAC-SHA256 of the body with
89/// `secret` in `X-Signature` (lowercase hex, see [`sign`](crate::webhooks::sign)),
90/// and `Authorization: Bearer <bearer>` when given (API keys of services
91/// such as RunPod). One subrequest. Any status is an answer: check
92/// `status` (a service's 4xx is not an error of the call).
93///
94/// # Errors
95///
96/// [`Error::Internal`](crate::Error::Internal) when the request cannot be
97/// built or the service cannot be reached.
98pub fn post_signed(
99    url: &str,
100    secret: &[u8],
101    bearer: Option<&str>,
102    body: &serde_json::Value,
103) -> impl Future<Output = Result<Answer>> + Send + use<> {
104    let url = url.to_owned();
105    let body = body.to_string();
106    let signature = crate::webhooks::sign(secret, body.as_bytes());
107    let bearer = bearer.map(str::to_owned);
108    worker::send::SendFuture::new(async move {
109        let headers = worker::Headers::new();
110        headers.set("Content-Type", "application/json")?;
111        headers.set("X-Signature", &signature)?;
112        if let Some(bearer) = bearer {
113            headers.set("Authorization", &format!("Bearer {bearer}"))?;
114        }
115        let mut init = worker::RequestInit::new();
116        init.with_method(worker::Method::Post).with_headers(headers).with_body(Some(body.into()));
117        let mut response = worker::Fetch::Request(worker::Request::new_with_init(&url, &init)?).send().await?;
118        Ok(Answer { status: response.status_code(), text: response.text().await? })
119    })
120}
121
122/// Checks that `url` may receive webhooks: `http(s)`, no credentials, and a host that is not (and does not resolve to) a private address.
123///
124/// Call it when a user saves an endpoint URL, to answer the form with the
125/// reason; [`deliver`] calls it again before each delivery in release
126/// builds, since a name can point elsewhere later. A host name is
127/// resolved with DNS over HTTPS (Cloudflare's resolver, `A` and `AAAA`
128/// records: two subrequests), as a Worker has no resolver of its own. A
129/// DNS change between the check and the delivery (DNS rebinding) is not
130/// caught; Workers cannot reach private networks anyway, so the check
131/// mainly keeps the app from calling itself or its own services.
132///
133/// # Errors
134///
135/// [`Error::BadRequest`](crate::Error::BadRequest) (400) with the reason
136/// ("must start with https:// or http://", "is a private address", "was
137/// not found"), or [`Error::Internal`](crate::Error::Internal) when the
138/// resolver cannot be reached.
139///
140/// # Examples
141///
142/// ```no_run
143/// use ocre::{Result, webhooks};
144///
145/// async fn save_endpoint(url: &str) -> Result<()> {
146///     webhooks::check_public_url(url).await?; // 400 "The webhook URL's host 10.0.0.5 is a private address"
147///     Ok(())
148/// }
149/// ```
150pub fn check_public_url(url: &str) -> impl Future<Output = Result<()>> + Send + use<> {
151    let url = url.to_owned();
152    async move {
153        let name = match crate::webhooks::url_host(&url)? {
154            UrlHost::Ip(ip) => {
155                let shown = ip.to_string();
156                return crate::webhooks::refused_addresses(&shown, &[ip]).map_or(Ok(()), Err);
157            }
158            UrlHost::Name(name) => name,
159        };
160        let mut addresses = Vec::new();
161        for kind in ["A", "AAAA"] {
162            let answer = crate::http::Request::get("https://cloudflare-dns.com/dns-query")
163                .query(&[("name", &name), ("type", kind)])
164                .header("accept", "application/dns-json")
165                .timeout(std::time::Duration::from_secs(5))
166                .send()
167                .await?
168                .error_for_status()?;
169            addresses.extend(crate::webhooks::dns_addresses(&answer.json()?));
170        }
171        crate::webhooks::refused_addresses(&name, &addresses).map_or(Ok(()), Err)
172    }
173}
174
175/// POSTs `payload` as JSON to the endpoint `url`, signed as a [Standard Webhooks](https://www.standardwebhooks.com) delivery, and returns the answer.
176///
177/// Headers: `webhook-id` (`id`, the event's id, the same on every retry so
178/// receivers can deduplicate), `webhook-timestamp` (now) and
179/// `webhook-signature` (`v1,<base64>` with `secret`, see
180/// [`sign_standard`](crate::webhooks::sign_standard)); receivers verify it
181/// with the Standard Webhooks libraries or [`verify_standard`](crate::webhooks::verify_standard).
182/// Waits at most [`DELIVERY_TIMEOUT`](crate::webhooks::DELIVERY_TIMEOUT)
183/// and never follows a redirect (a 3xx is the answer). In release builds
184/// the URL is checked first ([`check_public_url`]); debug builds deliver to
185/// any host, so request tests can run a receiver on `127.0.0.1`.
186///
187/// Any status is an answer: retry on a non-2xx from a job. One subrequest,
188/// plus two DNS lookups in release builds for a host name.
189///
190/// # Errors
191///
192/// [`Error::BadRequest`](crate::Error::BadRequest) when the URL is refused;
193/// [`Error::Internal`](crate::Error::Internal) when `secret` is not a
194/// `whsec_` secret, `payload` is not serializable, or the endpoint cannot
195/// be reached or does not answer in time.
196pub fn deliver(
197    url: &str,
198    secret: &str,
199    id: &str,
200    payload: &serde_json::Value,
201) -> impl Future<Output = Result<crate::http::Response>> + Send + use<> {
202    let body = serde_json::to_vec(payload).map_err(|err| Error::internal(format!("webhook payload: {err}")));
203    let request = body.and_then(|body| crate::webhooks::delivery_request(url, secret, id, body, crate::now()));
204    let url = url.to_owned();
205    async move {
206        let request = request?;
207        if !Environment::current().is_development() {
208            check_public_url(&url).await?;
209        }
210        request.send().await
211    }
212}