Skip to main content

webserver_base/analytics/
proxy.rs

1//! First-party proxies for Plausible and the Sentry browser SDK.
2//!
3//! Both are **byte relays**. Nothing is parsed, rewritten, or re-reported: the
4//! upstream receives exactly what the browser sent, and the browser receives
5//! exactly what the upstream returned, headers included. That matters most for
6//! Sentry — a server that *interpreted* a client error and re-raised it through
7//! its own SDK would file a browser problem as a server one, with the wrong
8//! stack and the wrong context. Relaying the envelope keeps it a genuine
9//! browser event.
10//!
11//! The point of proxying at all is that a same-origin request is
12//! indistinguishable from the site's own assets. Plausible puts the cost of not
13//! doing it at "typically between 5% and 25%" of visitors, depending on
14//! audience.
15
16use std::net::SocketAddr;
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::{Arc, Mutex, PoisonError};
19use std::time::Duration;
20
21use axum::body::Bytes;
22use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
23use axum::response::{IntoResponse, Response};
24use tokio::time::Instant;
25use tracing::{error, instrument, warn};
26
27use super::ip::resolve_true_client_ip_address;
28use super::retry::{self, RetryPolicy};
29use crate::traces::UpstreamFailure;
30
31/// `status` as a response, marked [`UpstreamFailure`] when it is a 5xx, with a
32/// `warn` naming the `what` that failed.
33fn relayed(status: StatusCode, what: &str) -> Response {
34    let mut response: Response = status.into_response();
35    if status.is_server_error() {
36        warn!("upstream answered {status} to {what}");
37        response.extensions_mut().insert(UpstreamFailure);
38    }
39    response
40}
41
42/// Fetches an upstream script and returns it with the upstream's own headers.
43///
44/// Content type, cache policy and `ETag` are echoed rather than invented, so
45/// the proxied script behaves exactly as the vendor intends it to.
46/// Intermittent upstream failures are retried for a few seconds. Uncached: a
47/// site serves its scripts through [`ScriptRelay`], which keeps a copy.
48#[instrument(skip_all)]
49pub async fn relay_script(client: &reqwest::Client, upstream: &str) -> Response {
50    match fetch_script(client, upstream, &RetryPolicy::READ).await {
51        Ok(script) => script.respond(&HeaderMap::new()),
52        Err(status) => {
53            error!("failed to fetch `{upstream}`");
54            status.into_response()
55        }
56    }
57}
58
59/// How long a cached script is served before it is refreshed. Refreshing
60/// happens in the background, so no visitor waits on it.
61const SCRIPT_TTL: Duration = Duration::from_secs(300);
62
63/// A copy this old that still cannot be refreshed is reported: visitors are
64/// fine, but the upstream URL has probably stopped working for good.
65const STALE_ALARM: Duration = Duration::from_hours(24);
66
67/// A proxied third-party script, held in memory.
68///
69/// Keeps the vendor's CDN off the page's critical path: after the first fetch
70/// every request is answered from memory, a copy older than five minutes is
71/// refreshed in the background, and a failed refresh keeps serving the last
72/// good copy. Only a cold cache waits on the upstream, and then for a few
73/// seconds of retries at most. `If-None-Match` is answered with `304` from the
74/// cached `ETag`.
75///
76/// Cheap to clone: clones share one cache.
77#[derive(Clone)]
78pub struct ScriptRelay {
79    inner: Arc<Inner>,
80}
81
82struct Inner {
83    client: reqwest::Client,
84    upstream: String,
85    policy: RetryPolicy,
86    ttl: Duration,
87    cached: Mutex<Option<Script>>,
88    refreshing: AtomicBool,
89}
90
91#[derive(Clone)]
92struct Script {
93    headers: HeaderMap,
94    body: Bytes,
95    fetched_at: Instant,
96}
97
98impl ScriptRelay {
99    /// A relay for `upstream`, empty until its first request.
100    #[must_use]
101    pub fn new(client: reqwest::Client, upstream: impl Into<String>) -> Self {
102        Self::with(client, upstream.into(), RetryPolicy::READ, SCRIPT_TTL)
103    }
104
105    fn with(client: reqwest::Client, upstream: String, policy: RetryPolicy, ttl: Duration) -> Self {
106        Self {
107            inner: Arc::new(Inner {
108                client,
109                upstream,
110                policy,
111                ttl,
112                cached: Mutex::new(None),
113                refreshing: AtomicBool::new(false),
114            }),
115        }
116    }
117
118    /// The script, answering `request_headers`' `If-None-Match` when it can.
119    #[instrument(skip_all)]
120    pub async fn respond(&self, request_headers: &HeaderMap) -> Response {
121        if let Some(script) = self.inner.cached() {
122            if script.fetched_at.elapsed() > self.inner.ttl {
123                self.refresh_in_background();
124            }
125            return script.respond(request_headers);
126        }
127        match self.inner.fetch().await {
128            Ok(script) => script.respond(request_headers),
129            Err(status) => {
130                error!(
131                    "failed to fetch `{}` with no copy cached",
132                    self.inner.upstream
133                );
134                status.into_response()
135            }
136        }
137    }
138
139    fn refresh_in_background(&self) {
140        // One refresh at a time: a busy page would otherwise start one per
141        // request until the first finished.
142        if self.inner.refreshing.swap(true, Ordering::AcqRel) {
143            return;
144        }
145        let inner: Arc<Inner> = Arc::clone(&self.inner);
146        tokio::spawn(async move {
147            if inner.fetch().await.is_err() {
148                let age: Duration = inner
149                    .cached()
150                    .map_or(Duration::ZERO, |script| script.fetched_at.elapsed());
151                if age > STALE_ALARM {
152                    error!(
153                        "`{}` has failed to refresh for {}h; still serving the last good copy",
154                        inner.upstream,
155                        age.as_secs() / 3600
156                    );
157                } else {
158                    warn!(
159                        "failed to refresh `{}`; serving the last good copy",
160                        inner.upstream
161                    );
162                }
163            }
164            inner.refreshing.store(false, Ordering::Release);
165        });
166    }
167}
168
169impl Inner {
170    fn cached(&self) -> Option<Script> {
171        self.cached
172            .lock()
173            .unwrap_or_else(PoisonError::into_inner)
174            .clone()
175    }
176
177    /// Fetches and caches the script. Only a success is cached, so a failure
178    /// never replaces a good copy.
179    async fn fetch(&self) -> Result<Script, StatusCode> {
180        let script: Script = fetch_script(&self.client, &self.upstream, &self.policy).await?;
181        *self.cached.lock().unwrap_or_else(PoisonError::into_inner) = Some(script.clone());
182        Ok(script)
183    }
184}
185
186impl Script {
187    fn respond(&self, request_headers: &HeaderMap) -> Response {
188        let not_modified: bool = match (
189            self.headers.get(header::ETAG),
190            request_headers.get(header::IF_NONE_MATCH),
191        ) {
192            (Some(etag), Some(wanted)) => wanted.to_str().is_ok_and(|wanted: &str| {
193                wanted
194                    .split(',')
195                    .any(|tag: &str| tag.trim().as_bytes() == etag.as_bytes())
196            }),
197            _ => false,
198        };
199        if not_modified {
200            return (StatusCode::NOT_MODIFIED, self.headers.clone()).into_response();
201        }
202        (StatusCode::OK, self.headers.clone(), self.body.clone()).into_response()
203    }
204}
205
206/// A successful fetch, or the status to answer when there is nothing better:
207/// the upstream's own, or `502` when it never answered.
208async fn fetch_script(
209    client: &reqwest::Client,
210    upstream: &str,
211    policy: &RetryPolicy,
212) -> Result<Script, StatusCode> {
213    let response: reqwest::Response = match retry::get(client, upstream, policy).await {
214        Ok(response) => response,
215        Err(error) => {
216            warn!("failed to fetch `{upstream}`: {error}");
217            return Err(StatusCode::BAD_GATEWAY);
218        }
219    };
220
221    let status: StatusCode =
222        StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
223    if !status.is_success() {
224        warn!("`{upstream}` answered {status}");
225        return Err(status);
226    }
227    let mut headers: HeaderMap = HeaderMap::new();
228    // ETag too, so a revalidation still costs nothing when the script has not
229    // changed.
230    for name in [header::CONTENT_TYPE, header::CACHE_CONTROL, header::ETAG] {
231        if let Some(value) = response.headers().get(&name)
232            && let Ok(value) = HeaderValue::from_bytes(value.as_bytes())
233        {
234            headers.insert(name, value);
235        }
236    }
237
238    match response.bytes().await {
239        Ok(body) => Ok(Script {
240            headers,
241            body,
242            fetched_at: Instant::now(),
243        }),
244        Err(error) => {
245            warn!("failed to read `{upstream}`: {error}");
246            Err(StatusCode::BAD_GATEWAY)
247        }
248    }
249}
250
251/// Forwards a Plausible event, carrying the real visitor IP.
252///
253/// `X-Forwarded-For` is not optional: without it Plausible's bot filter rejects
254/// proxied events outright, because every one of them would appear to originate
255/// from this server.
256///
257/// Sent once, never retried: a retry of an event that had in fact landed is a
258/// duplicate pageview.
259#[instrument(skip_all)]
260pub async fn relay_event(
261    client: &reqwest::Client,
262    upstream: &str,
263    headers: &HeaderMap,
264    peer: SocketAddr,
265    body: Bytes,
266) -> Response {
267    let mut request: reqwest::RequestBuilder = client.post(upstream).body(body).header(
268        "X-Forwarded-For",
269        resolve_true_client_ip_address(peer, headers),
270    );
271    if let Some(user_agent) = headers.get(header::USER_AGENT) {
272        request = request.header(header::USER_AGENT, user_agent.clone());
273    }
274    if let Some(content_type) = headers.get(header::CONTENT_TYPE) {
275        request = request.header(header::CONTENT_TYPE, content_type.clone());
276    }
277
278    match request.send().await {
279        Ok(response) => relayed(
280            StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::ACCEPTED),
281            "an analytics event",
282        ),
283        Err(error) => {
284            error!("failed to forward an analytics event: {error}");
285            // A dropped pageview must never surface to the visitor.
286            StatusCode::ACCEPTED.into_response()
287        }
288    }
289}
290
291/// Relays a Sentry envelope verbatim.
292///
293/// The body is passed through untouched — it is a complete envelope the browser
294/// SDK built, carrying its own stack trace, breadcrumbs and release. The
295/// destination comes from the configured DSN rather than from the envelope
296/// header, so this cannot be pointed at an arbitrary Sentry project.
297///
298/// Sent once, never retried: a retry of an envelope that had in fact landed is
299/// a duplicate error report.
300#[instrument(skip_all)]
301pub async fn relay_envelope(client: &reqwest::Client, upstream: &str, body: Bytes) -> Response {
302    match client
303        .post(upstream)
304        .header(header::CONTENT_TYPE, "application/x-sentry-envelope")
305        .body(body)
306        .send()
307        .await
308    {
309        Ok(response) => relayed(
310            StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::OK),
311            "a Sentry envelope",
312        ),
313        Err(error) => {
314            error!("failed to relay a Sentry envelope: {error}");
315            StatusCode::OK.into_response()
316        }
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use std::time::Duration;
323
324    use axum::body::to_bytes;
325    use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
326    use axum::response::Response;
327
328    use super::ScriptRelay;
329    use crate::analytics::fake_upstream::{FakeUpstream, Reply};
330    use crate::analytics::retry::RetryPolicy;
331
332    const FAST: RetryPolicy = RetryPolicy {
333        attempts: 3,
334        attempt_timeout: Duration::from_millis(500),
335        base_delay: Duration::from_millis(10),
336        max_delay: Duration::from_millis(20),
337        max_retry_after: Duration::from_secs(2),
338        budget: Duration::from_secs(2),
339    };
340
341    fn relay(upstream: &FakeUpstream, ttl: Duration) -> ScriptRelay {
342        ScriptRelay::with(reqwest::Client::new(), upstream.url.clone(), FAST, ttl)
343    }
344
345    async fn body(response: Response) -> String {
346        let bytes: axum::body::Bytes = to_bytes(response.into_body(), usize::MAX)
347            .await
348            .expect("a body");
349        String::from_utf8(bytes.to_vec()).expect("utf-8")
350    }
351
352    /// Lets a background refresh run to completion.
353    async fn settle() {
354        tokio::time::sleep(Duration::from_millis(300)).await;
355    }
356
357    #[tokio::test]
358    async fn a_cached_script_is_served_without_asking_the_upstream_again() {
359        let upstream: FakeUpstream = FakeUpstream::start(vec![Reply::script("v1")]).await;
360        let relay: ScriptRelay = relay(&upstream, Duration::from_secs(300));
361
362        assert_eq!("v1", body(relay.respond(&HeaderMap::new()).await).await);
363        assert_eq!("v1", body(relay.respond(&HeaderMap::new()).await).await);
364        assert_eq!(1, upstream.hits());
365    }
366
367    #[tokio::test]
368    async fn the_vendors_headers_are_echoed() {
369        let upstream: FakeUpstream = FakeUpstream::start(vec![
370            Reply::script("v1")
371                .header("content-type", "application/javascript")
372                .header("cache-control", "public, max-age=60"),
373        ])
374        .await;
375        let relay: ScriptRelay = relay(&upstream, Duration::from_secs(300));
376
377        let response: Response = relay.respond(&HeaderMap::new()).await;
378        assert_eq!(StatusCode::OK, response.status());
379        assert_eq!(
380            Some("application/javascript"),
381            response
382                .headers()
383                .get(header::CONTENT_TYPE)
384                .and_then(|value: &HeaderValue| value.to_str().ok())
385        );
386        assert_eq!(
387            Some("public, max-age=60"),
388            response
389                .headers()
390                .get(header::CACHE_CONTROL)
391                .and_then(|value: &HeaderValue| value.to_str().ok())
392        );
393    }
394
395    #[tokio::test]
396    async fn a_matching_if_none_match_gets_a_304_from_the_cache() {
397        let upstream: FakeUpstream =
398            FakeUpstream::start(vec![Reply::script("v1").header("etag", "\"abc\"")]).await;
399        let relay: ScriptRelay = relay(&upstream, Duration::from_secs(300));
400        let mut headers: HeaderMap = HeaderMap::new();
401        headers.insert(
402            header::IF_NONE_MATCH,
403            HeaderValue::from_static("\"zzz\", \"abc\""),
404        );
405
406        assert_eq!(
407            StatusCode::NOT_MODIFIED,
408            relay.respond(&headers).await.status()
409        );
410        headers.insert(header::IF_NONE_MATCH, HeaderValue::from_static("\"zzz\""));
411        assert_eq!(StatusCode::OK, relay.respond(&headers).await.status());
412        assert_eq!(1, upstream.hits());
413    }
414
415    #[tokio::test]
416    async fn an_expired_copy_is_served_at_once_and_refreshed_in_the_background() {
417        let upstream: FakeUpstream = FakeUpstream::start(vec![Reply::script("v1")]).await;
418        let relay: ScriptRelay = relay(&upstream, Duration::ZERO);
419        assert_eq!("v1", body(relay.respond(&HeaderMap::new()).await).await);
420        upstream.reply_from_now_on(Reply::script("v2").after(Duration::from_millis(100)));
421
422        // The slow refresh does not hold up the visitor.
423        let started: std::time::Instant = std::time::Instant::now();
424        assert_eq!("v1", body(relay.respond(&HeaderMap::new()).await).await);
425        assert!(started.elapsed() < Duration::from_millis(100));
426        settle().await;
427        assert_eq!("v2", body(relay.respond(&HeaderMap::new()).await).await);
428    }
429
430    #[tokio::test]
431    async fn a_failed_refresh_keeps_serving_the_last_good_copy() {
432        let upstream: FakeUpstream = FakeUpstream::start(vec![Reply::script("v1")]).await;
433        let relay: ScriptRelay = relay(&upstream, Duration::ZERO);
434        assert_eq!("v1", body(relay.respond(&HeaderMap::new()).await).await);
435        upstream.reply_from_now_on(Reply::status(503));
436
437        assert_eq!("v1", body(relay.respond(&HeaderMap::new()).await).await);
438        settle().await;
439        let response: Response = relay.respond(&HeaderMap::new()).await;
440        assert_eq!(StatusCode::OK, response.status());
441        assert_eq!("v1", body(response).await);
442    }
443
444    #[tokio::test]
445    async fn a_cold_cache_retries_an_intermittent_failure() {
446        let upstream: FakeUpstream =
447            FakeUpstream::start(vec![Reply::status(503), Reply::script("v1")]).await;
448        let relay: ScriptRelay = relay(&upstream, Duration::from_secs(300));
449
450        assert_eq!("v1", body(relay.respond(&HeaderMap::new()).await).await);
451        assert_eq!(2, upstream.hits());
452    }
453
454    #[tokio::test]
455    async fn a_failure_is_answered_with_the_upstreams_status_and_never_cached() {
456        let upstream: FakeUpstream = FakeUpstream::start(vec![Reply::status(404)]).await;
457        let relay: ScriptRelay = relay(&upstream, Duration::from_secs(300));
458
459        assert_eq!(
460            StatusCode::NOT_FOUND,
461            relay.respond(&HeaderMap::new()).await.status()
462        );
463        assert_eq!(
464            StatusCode::NOT_FOUND,
465            relay.respond(&HeaderMap::new()).await.status()
466        );
467        assert_eq!(2, upstream.hits());
468    }
469
470    #[tokio::test]
471    async fn an_upstream_that_never_answers_is_a_bad_gateway() {
472        let relay: ScriptRelay = ScriptRelay::with(
473            reqwest::Client::new(),
474            "http://127.0.0.1:9/script.js".to_owned(),
475            FAST,
476            Duration::from_secs(300),
477        );
478
479        assert_eq!(
480            StatusCode::BAD_GATEWAY,
481            relay.respond(&HeaderMap::new()).await.status()
482        );
483    }
484}