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