atomic-integration-proxy 0.4.3

OAuth/catalog integration proxy (pinned OpenAPI catalog, connections owned by Atomic agents, Atomic v2 request signatures, delegations and frame capabilities) used by Atomic Server and LocalThought
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! `POST /webhooks/{endpointId}`: the provider-facing receiver (Webhook
//! Deliveries §4.2.1–§4.4, Webhook Subscriptions §5.3).
//!
//! In order, before any body byte is read: the endpoint id's shape, a
//! `Content-Length` over the verification cap (413), and the endpoint's
//! hook, profile and secret, looked up under a bounded database slot. Then
//! the body is read, at most the cap, under a bounded read slot and a read
//! timeout; the signature is verified over the exact bytes; only then is
//! the body scanned for depth and parsed; revocations are applied; the
//! delivery is routed and stored in one transaction. A 2xx goes out only
//! after that transaction committed, or when nothing is to be kept. Every
//! wait is bounded: a slot not free in time is a 503.

use std::collections::BTreeMap;

use axum::{
    body::Body,
    extract::{ConnectInfo, Path, State},
    http::{header, HeaderMap, StatusCode},
    response::{IntoResponse, Response},
};

use super::metadata::{Deliveries, EventType};
use super::store::Delivery;
use super::verify::{single_header, verify};
use crate::AppState;

/// Nesting deeper than this is not parsed (`delivery.maxJsonDepth`).
pub const MAX_JSON_DEPTH: usize = 64;

fn answer(status: StatusCode) -> Response {
    status.into_response()
}

/// An endpoint id: 43 characters of base64url (256 random bits).
fn endpoint_shaped(id: &str) -> bool {
    id.len() == 43
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

/// Logs refused deliveries at most once per ten seconds, with how many.
fn log_refused(reason: &str, platform: &str) {
    use std::sync::atomic::{AtomicU64, Ordering};
    static LAST: AtomicU64 = AtomicU64::new(0);
    static REFUSED: AtomicU64 = AtomicU64::new(0);
    let refused = REFUSED.fetch_add(1, Ordering::Relaxed) + 1;
    let now = crate::now_secs();
    let last = LAST.load(Ordering::Relaxed);
    if now >= last + 10
        && LAST
            .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
    {
        REFUSED.store(0, Ordering::Relaxed);
        tracing::info!(reason, platform, refused, "webhook deliveries refused");
    }
}

async fn slot<'a>(
    semaphore: &'a tokio::sync::Semaphore,
    wait: std::time::Duration,
) -> Option<tokio::sync::SemaphorePermit<'a>> {
    tokio::time::timeout(wait, semaphore.acquire())
        .await
        .ok()?
        .ok()
}

enum ReadError {
    TooLarge,
    Broken,
}

/// Reads a body up to `cap` bytes, telling a body over the cap from a broken
/// upload.
async fn read_capped(mut body: Body, cap: usize) -> Result<Vec<u8>, ReadError> {
    use axum::body::HttpBody as _;
    let mut buffer = Vec::new();
    while let Some(frame) =
        std::future::poll_fn(|cx| std::pin::Pin::new(&mut body).poll_frame(cx)).await
    {
        let frame = frame.map_err(|_| ReadError::Broken)?;
        if let Ok(data) = frame.into_data() {
            if buffer.len() + data.len() > cap {
                return Err(ReadError::TooLarge);
            }
            buffer.extend_from_slice(&data);
        }
    }
    Ok(buffer)
}

/// One body being read for an endpoint, counted until dropped.
struct EndpointRead<'a> {
    gate: &'a super::IngressGate,
    endpoint: String,
}

impl<'a> EndpointRead<'a> {
    fn take(gate: &'a super::IngressGate, endpoint: &str) -> Option<Self> {
        let mut reading = gate.reading.lock().unwrap_or_else(|e| e.into_inner());
        let count = reading.entry(endpoint.to_owned()).or_insert(0);
        if *count >= gate.reads_per_endpoint {
            return None;
        }
        *count += 1;
        Some(Self {
            gate,
            endpoint: endpoint.to_owned(),
        })
    }
}

impl Drop for EndpointRead<'_> {
    fn drop(&mut self) {
        let mut reading = self.gate.reading.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(count) = reading.get_mut(&self.endpoint) {
            *count -= 1;
            if *count == 0 {
                reading.remove(&self.endpoint);
            }
        }
    }
}

/// The rate limits count refusals only (see [`super::limits`]). A network
/// over its limit gets `429` for ids that are malformed or name no endpoint,
/// after the lookup, and may have at most `INGRESS_BLOCKED_WAITERS`
/// requests waiting for or holding the lookup slot; beyond that its requests get `429`
/// at once, a real delivery included. A sender that points a provider's
/// hooks at junk URLs makes the provider's own addresses collect refusals,
/// so that queue is where the provider's real deliveries can still lose
/// (SECURITY.md, rate limits). The per-endpoint limit counts that endpoint's
/// failed verifications.
pub async fn receive(
    State(state): State<AppState>,
    Path(endpoint_id): Path<String>,
    peer: Option<ConnectInfo<std::net::SocketAddr>>,
    headers: HeaderMap,
    body: Body,
) -> Response {
    let Some(webhooks) = state.webhooks.clone() else {
        return answer(StatusCode::NOT_FOUND);
    };
    let network = crate::client_addr::client_network(
        state.trust_forwarded_for,
        &headers,
        peer.map(|ConnectInfo(peer)| peer),
    );
    let mut verified = false;
    let response = receive_checked(
        &state,
        &webhooks,
        &network,
        endpoint_id,
        headers,
        body,
        &mut verified,
    )
    .await;
    let status = response.status();
    // A refusal the sender caused counts against its network. Not 429 (a
    // limit already answered), and not 400 or 408, which a provider's own
    // broken or slow upload causes.
    if !verified
        && status.is_client_error()
        && !matches!(
            status,
            StatusCode::TOO_MANY_REQUESTS | StatusCode::BAD_REQUEST | StatusCode::REQUEST_TIMEOUT
        )
    {
        let _ = webhooks
            .limits
            .ingress_per_network
            .take(&network, std::time::Instant::now());
    }
    response
}

/// `404` for an id that names no endpoint, or `429` once its network has
/// been refused too often.
fn no_endpoint(webhooks: &super::Webhooks, network: &str) -> Response {
    match webhooks
        .limits
        .ingress_per_network
        .blocked(network, std::time::Instant::now())
    {
        Some(retry) => super::limits::too_many(retry),
        None => answer(StatusCode::NOT_FOUND),
    }
}

async fn receive_checked(
    state: &AppState,
    webhooks: &std::sync::Arc<super::Webhooks>,
    network: &str,
    endpoint_id: String,
    headers: HeaderMap,
    body: Body,
    verified: &mut bool,
) -> Response {
    if !endpoint_shaped(&endpoint_id) {
        return no_endpoint(webhooks, network);
    }
    let cap = webhooks.store.policy().max_verified_bytes as usize;
    let declared = headers
        .get(header::CONTENT_LENGTH)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse::<u64>().ok());
    if declared.is_some_and(|length| length > cap as u64) {
        return answer(StatusCode::PAYLOAD_TOO_LARGE);
    }
    let gate = &webhooks.gate;
    let hook = {
        // A network over its refusal limit may queue for the lookup slot
        // only while fewer than `INGRESS_BLOCKED_WAITERS` of its kind wait
        // for or hold it (the permit is kept through the lookup);
        // beyond that it gets `429` at once. The lookup semaphore is fair, so
        // those few cannot jump ahead of other networks' requests, and a
        // real delivery from a blocked network (a provider whose addresses
        // also carry junk) can still wait for the slot like any other.
        let blocked = webhooks
            .limits
            .ingress_per_network
            .blocked(network, std::time::Instant::now());
        let _queued = match blocked {
            Some(retry) => match gate.blocked_waiters.try_acquire() {
                Ok(permit) => Some(permit),
                Err(_) => return super::limits::too_many(retry),
            },
            None => None,
        };
        let permit = match slot(&gate.lookups, gate.wait).await {
            Some(permit) => permit,
            None => return answer(StatusCode::SERVICE_UNAVAILABLE),
        };
        let _slot = permit;
        match webhooks.store.hook_by_endpoint(&endpoint_id).await {
            Ok(Some(hook)) => hook,
            Ok(None) => return no_endpoint(webhooks, network),
            Err(_) => return answer(StatusCode::SERVICE_UNAVAILABLE),
        }
    };
    let Some(deliveries) = super::provider::deliveries(state, &hook.platform) else {
        return answer(StatusCode::NOT_FOUND);
    };
    let profile_name = if hook.dedicated {
        deliveries.dedicated.as_ref().map(|d| d.profile.clone())
    } else {
        deliveries.shared_profile.clone()
    };
    let Some(profile) = profile_name.and_then(|name| deliveries.profiles.get(&name).cloned())
    else {
        return answer(StatusCode::NOT_FOUND);
    };
    let secret = if hook.dedicated {
        hook.secret_envelope.as_deref().and_then(|envelope| {
            state
                .security
                .as_ref()?
                .open(envelope, &super::hook_secret_aad(&hook.hook_id))
        })
    } else {
        webhooks.shared_secret(&hook.platform).map(<[u8]>::to_vec)
    };
    let Some(secret) = secret else {
        // No secret, no delivery (Webhook Deliveries §4.2).
        log_refused("no-secret", &hook.platform);
        return answer(StatusCode::UNAUTHORIZED);
    };
    // Only now is the body read: at most the cap, within the read timeout,
    // and only by a bounded number of requests at once.
    let body = {
        let Some(_endpoint_slot) = EndpointRead::take(gate, &endpoint_id) else {
            return answer(StatusCode::SERVICE_UNAVAILABLE);
        };
        let Some(_slot) = slot(&gate.reads, gate.wait).await else {
            return answer(StatusCode::SERVICE_UNAVAILABLE);
        };
        match tokio::time::timeout(gate.read_timeout, read_capped(body, cap)).await {
            Err(_) => return answer(StatusCode::REQUEST_TIMEOUT),
            Ok(Err(ReadError::TooLarge)) => return answer(StatusCode::PAYLOAD_TOO_LARGE),
            Ok(Err(ReadError::Broken)) => return answer(StatusCode::BAD_REQUEST),
            Ok(Ok(bytes)) => bytes,
        }
    };
    if let Err(refused) = verify(&profile, &headers, &body, &secret, crate::now_secs()) {
        log_refused(
            match refused {
                super::verify::Refused::Secret => "secret",
                super::verify::Refused::Signature => "signature",
                super::verify::Refused::Timestamp => "timestamp",
                super::verify::Refused::Mismatch => "mismatch",
            },
            &hook.platform,
        );
        // Only an endpoint's failed verifications count against it, and
        // only after verifying: the per-endpoint limit never refuses a
        // delivery that verifies (the per-network queue above still can).
        if let Err(retry) = webhooks
            .limits
            .ingress_per_endpoint
            .take(&endpoint_id, std::time::Instant::now())
        {
            return super::limits::too_many(retry);
        }
        return answer(StatusCode::UNAUTHORIZED);
    }

    // Verified. Only now is anything in the request read.
    *verified = true;
    let Some(delivery_id) = single_header(&headers, &deliveries.delivery_id_header)
        .filter(|id| {
            !id.is_empty() && id.len() <= 255 && id.bytes().all(|b| (0x21..=0x7e).contains(&b))
        })
        .map(str::to_owned)
    else {
        return answer(StatusCode::BAD_REQUEST);
    };
    if super::metadata::json_depth(&body) > MAX_JSON_DEPTH {
        // Verified but uncapturable, with no source that can be trusted:
        // the consumers' periodic full reads are the fallback.
        return answer(StatusCode::ACCEPTED);
    }
    let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&body) else {
        return answer(StatusCode::ACCEPTED);
    };
    let event_type = match &deliveries.event_type {
        EventType::Header(name) => single_header(&headers, name).map(str::to_owned),
        EventType::Body(pointer) => pointer.key(&parsed),
    };
    let Some(event_type) = event_type else {
        return answer(StatusCode::NO_CONTENT);
    };
    let action = deliveries.action.as_ref().and_then(|p| p.key(&parsed));

    let Some(_slot) = slot(&gate.database, gate.wait).await else {
        return answer(StatusCode::SERVICE_UNAVAILABLE);
    };
    if let Err(status) = revoke(
        state,
        webhooks,
        &hook.platform,
        &deliveries,
        &event_type,
        action.as_deref(),
        &parsed,
    )
    .await
    {
        return answer(status);
    }

    // Nothing to keep: answered like any durable outcome.
    let Some(event) = deliveries.events.get(&event_type) else {
        return answer(StatusCode::NO_CONTENT);
    };
    let source = &deliveries.sources[&event.source];
    let Some(source_key) = source.key.key(&parsed) else {
        return answer(StatusCode::NO_CONTENT);
    };
    let context: BTreeMap<String, String> = source
        .context
        .iter()
        .filter_map(|(name, pointer)| Some((name.clone(), pointer.key(&parsed)?)))
        .collect();
    let delivery = Delivery {
        endpoint_id,
        delivery_id,
        event_type,
        action,
        source_kind: event.source.clone(),
        source_key,
        context,
        body: retained_body(webhooks.notifications_only, &body),
    };
    match webhooks.store.ingest(&delivery, super::store::now()).await {
        // Retained, recorded as a gap, a duplicate, or wanted by nobody:
        // durable either way.
        Ok(_) => answer(StatusCode::NO_CONTENT),
        Err(error) => {
            tracing::error!(%error, "webhook delivery not stored; the provider may retry");
            answer(StatusCode::SERVICE_UNAVAILABLE)
        }
    }
}

/// Suspends the bindings a revocation delivery names.
async fn revoke(
    _state: &AppState,
    webhooks: &super::Webhooks,
    platform: &str,
    deliveries: &Deliveries,
    event_type: &str,
    action: Option<&str>,
    parsed: &serde_json::Value,
) -> Result<(), StatusCode> {
    for revocation in &deliveries.revocations {
        if revocation.event != event_type {
            continue;
        }
        if let Some(actions) = &revocation.actions {
            if !action.is_some_and(|a| actions.iter().any(|x| x == a)) {
                continue;
            }
        }
        let keys = revocation.keys.keys(parsed);
        webhooks
            .store
            .suspend_bindings(
                platform,
                &revocation.source,
                revocation.context.as_deref(),
                &keys,
            )
            .await
            .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
    }
    Ok(())
}

/// Routing and signature verification happen before this boundary. Only routing
/// metadata and a fixed change hint cross it in notification-only deployments.
fn retained_body(notifications_only: bool, body: &[u8]) -> Vec<u8> {
    if notifications_only {
        br#"{"notification":true}"#.to_vec()
    } else {
        body.to_vec()
    }
}

#[cfg(test)]
mod notification_tests {
    #[test]
    fn provider_content_never_crosses_the_notification_storage_boundary() {
        let body = br#"{"title":"private note","content":"provider data"}"#;
        assert_eq!(
            super::retained_body(true, body),
            br#"{"notification":true}"#
        );
        assert_eq!(super::retained_body(false, body), body);
    }
}