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