Skip to main content

webserver_base/analytics/
config.rs

1//! What the proxies need to know about their upstreams.
2
3use crate::env::{self, EnvError};
4use crate::environment::Environment;
5
6/// The environment variable holding the Plausible script id.
7pub const ENV_ANALYTICS_ID: &str = "WSB_ANALYTICS_ID";
8
9/// The environment variable holding the browser Sentry DSN.
10pub const ENV_SENTRY_BROWSER_DSN: &str = "WSB_SENTRY_BROWSER_DSN";
11
12/// Plausible's script host.
13pub const PLAUSIBLE_HOST: &str = "https://plausible.io";
14
15/// Sentry's browser-bundle CDN.
16pub const SENTRY_BROWSER_CDN_HOST: &str = "https://browser.sentry-cdn.com";
17
18/// The Sentry browser SDK version every site serves.
19///
20/// Pinned, so a Sentry release never changes what visitors run until this
21/// library is upgraded. The one place to bump it: check that both bundles
22/// exist at the new version, and that `window.Sentry` still carries
23/// `browserTracingIntegration`, `getActiveSpan`, `getRootSpan`,
24/// `spanToJSON` and `startInactiveSpan`, which the layout's span helper uses.
25pub const SENTRY_BROWSER_SDK_VERSION: &str = "10.78.0";
26
27/// Which Plausible site events belong to, or that none do.
28///
29/// Modern Plausible identifies a site by the id embedded in its script URL
30/// rather than a `data-domain` attribute, so this is the whole configuration.
31/// Deriving it from the request's hostname instead would split `www.` and
32/// apex traffic into two sites Plausible does not both know about, and would
33/// let a staging deploy pour into production's numbers.
34///
35/// A config can also be *disabled*: no script tag, no proxy routes, no
36/// upstream fetch, no event forwarding. That is what a local run gets, and
37/// what a blank or missing id gets.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct AnalyticsConfig {
40    script_id: Option<String>,
41}
42
43impl AnalyticsConfig {
44    /// Events for the site this script id belongs to. A blank id disables
45    /// analytics, as [`AnalyticsConfig::disabled`] does.
46    #[must_use]
47    pub fn new(script_id: impl Into<String>) -> Self {
48        let script_id: String = script_id.into();
49        Self::from_optional_id(Some(&script_id))
50    }
51
52    /// Analytics off: nothing is rendered, mounted, fetched or forwarded.
53    #[must_use]
54    pub const fn disabled() -> Self {
55        Self { script_id: None }
56    }
57
58    /// Enabled only for a non-blank id.
59    #[must_use]
60    pub fn from_optional_id(script_id: Option<&str>) -> Self {
61        Self {
62            script_id: script_id
63                .map(str::trim)
64                .filter(|id| !id.is_empty())
65                .map(String::from),
66        }
67    }
68
69    /// Reads [`ENV_ANALYTICS_ID`] and `WSB_ENVIRONMENT`.
70    ///
71    /// Disabled when the environment is `local`, or when the id is unset or
72    /// blank. Only a production run with an id is enabled.
73    ///
74    /// # Errors
75    ///
76    /// [`EnvError`] if `WSB_ENVIRONMENT` is unset, blank or invalid.
77    pub fn from_env() -> Result<Self, EnvError> {
78        Self::from_values(
79            std::env::var("WSB_ENVIRONMENT").ok().as_deref(),
80            env::optional(ENV_ANALYTICS_ID).as_deref(),
81        )
82    }
83
84    /// [`AnalyticsConfig::from_env`]'s logic over already-read values.
85    ///
86    /// # Errors
87    ///
88    /// [`EnvError`] if the environment is `None`, blank or invalid.
89    pub fn from_values(
90        environment: Option<&str>,
91        script_id: Option<&str>,
92    ) -> Result<Self, EnvError> {
93        Ok(Self::resolve(
94            Environment::from_value(environment)?,
95            script_id,
96        ))
97    }
98
99    /// The config for `environment` and an optional id: disabled when local or
100    /// when the id is missing or blank.
101    #[must_use]
102    pub fn resolve(environment: Environment, script_id: Option<&str>) -> Self {
103        if environment.is_local() {
104            Self::disabled()
105        } else {
106            Self::from_optional_id(script_id)
107        }
108    }
109
110    /// This config as it applies in `environment`: always disabled when local,
111    /// whatever id was passed in.
112    #[must_use]
113    pub fn for_environment(self, environment: Environment) -> Self {
114        if environment.is_local() {
115            Self::disabled()
116        } else {
117            self
118        }
119    }
120
121    /// Whether analytics is on.
122    #[must_use]
123    pub const fn is_enabled(&self) -> bool {
124        self.script_id.is_some()
125    }
126
127    /// The configured script id, or `""` when analytics is disabled. Prefer
128    /// [`AnalyticsConfig::script_id_if_enabled`].
129    #[must_use]
130    pub fn script_id(&self) -> &str {
131        self.script_id.as_deref().unwrap_or_default()
132    }
133
134    /// The configured script id, if enabled.
135    #[must_use]
136    pub fn script_id_if_enabled(&self) -> Option<&str> {
137        self.script_id.as_deref()
138    }
139
140    /// The upstream script URL this proxy fetches, or `""` when analytics is
141    /// disabled. Prefer [`AnalyticsConfig::upstream_script_url_if_enabled`].
142    #[must_use]
143    pub fn upstream_script_url(&self) -> String {
144        self.upstream_script_url_if_enabled().unwrap_or_default()
145    }
146
147    /// The upstream script URL this proxy fetches, if enabled.
148    #[must_use]
149    pub fn upstream_script_url_if_enabled(&self) -> Option<String> {
150        self.script_id
151            .as_ref()
152            .map(|id| format!("{PLAUSIBLE_HOST}/js/{id}.js"))
153    }
154
155    /// The upstream event endpoint this proxy forwards to.
156    #[must_use]
157    pub fn upstream_event_url() -> String {
158        format!("{PLAUSIBLE_HOST}/api/event")
159    }
160}
161
162/// A parsed Sentry DSN.
163///
164/// Only the pieces the tunnel needs: which host to relay to, and which project.
165/// Because a frontend declares exactly one browser DSN, the tunnel never has to
166/// parse an envelope to discover where an event belongs — which keeps it a dumb
167/// byte relay and stops it being usable as an open relay to arbitrary projects.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct SentryDsn {
170    dsn: String,
171    host: String,
172    project_id: String,
173}
174
175/// Why a DSN could not be understood.
176#[derive(Debug, thiserror::Error)]
177#[error("`{dsn}` is not a Sentry DSN; expected `https://<key>@<host>/<project id>`")]
178pub struct SentryDsnParseError {
179    dsn: String,
180}
181
182impl SentryDsn {
183    /// Parses `https://<public key>@<host>/<project id>`.
184    ///
185    /// # Errors
186    ///
187    /// [`SentryDsnParseError`] if the DSN is not in that shape.
188    pub fn parse(dsn: &str) -> Result<Self, SentryDsnParseError> {
189        let malformed = || SentryDsnParseError {
190            dsn: dsn.to_string(),
191        };
192
193        let scheme_end: usize = dsn.find("://").ok_or_else(malformed)? + 3;
194        let rest: &str = &dsn[scheme_end..];
195        let (public_key, remainder) = rest.split_once('@').ok_or_else(malformed)?;
196        let (host, project_id) = remainder.rsplit_once('/').ok_or_else(malformed)?;
197
198        if public_key.is_empty() || host.is_empty() || project_id.is_empty() {
199            return Err(malformed());
200        }
201
202        Ok(Self {
203            dsn: dsn.to_string(),
204            host: host.to_string(),
205            project_id: project_id.to_string(),
206        })
207    }
208
209    /// The DSN as given. A browser DSN is public by design: it only lets a
210    /// client send events, and the browser needs it to build them.
211    #[must_use]
212    pub fn as_str(&self) -> &str {
213        &self.dsn
214    }
215
216    /// The pinned browser bundle, with tracing (page-load spans and web
217    /// vitals) or without. The tracing bundle is about 60% larger, so a site
218    /// that traces nothing is served the errors-only one.
219    ///
220    /// Not the per-project loader script: that one serves whichever bundle the
221    /// project's dashboard toggle names, so tracing would depend on a setting
222    /// outside the code, and it fetches the bundle from Sentry's origin, past
223    /// this site's proxy.
224    #[must_use]
225    pub fn upstream_bundle_url(tracing: bool) -> String {
226        let bundle: &str = if tracing { "bundle.tracing" } else { "bundle" };
227        format!("{SENTRY_BROWSER_CDN_HOST}/{SENTRY_BROWSER_SDK_VERSION}/{bundle}.min.js")
228    }
229
230    /// Where envelopes are relayed, verbatim.
231    #[must_use]
232    pub fn upstream_envelope_url(&self) -> String {
233        format!("https://{}/api/{}/envelope/", self.host, self.project_id)
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::{AnalyticsConfig, SENTRY_BROWSER_SDK_VERSION, SentryDsn};
240    use crate::environment::Environment;
241
242    #[test]
243    fn local_mode_disables_analytics_even_with_an_id() {
244        let config: AnalyticsConfig = AnalyticsConfig::resolve(Environment::Local, Some("pa-x"));
245        assert!(!config.is_enabled());
246        assert_eq!(None, config.upstream_script_url_if_enabled());
247
248        let config: AnalyticsConfig =
249            AnalyticsConfig::new("pa-x").for_environment(Environment::Local);
250        assert!(!config.is_enabled());
251    }
252
253    #[test]
254    fn an_unset_or_blank_id_disables_analytics_in_production() {
255        assert!(!AnalyticsConfig::resolve(Environment::Production, None).is_enabled());
256        assert!(!AnalyticsConfig::resolve(Environment::Production, Some("")).is_enabled());
257        assert!(!AnalyticsConfig::resolve(Environment::Production, Some("  ")).is_enabled());
258        assert!(!AnalyticsConfig::new("").is_enabled());
259    }
260
261    #[test]
262    fn from_values_covers_local_production_and_an_unset_environment() {
263        let local = AnalyticsConfig::from_values(Some("local"), Some("pa-x")).expect("valid");
264        assert!(!local.is_enabled());
265
266        let prod = AnalyticsConfig::from_values(Some("production"), Some("pa-x")).expect("valid");
267        assert!(prod.is_enabled());
268
269        let no_id = AnalyticsConfig::from_values(Some("production"), None).expect("valid");
270        assert!(!no_id.is_enabled());
271
272        assert!(AnalyticsConfig::from_values(None, Some("pa-x")).is_err());
273        assert!(AnalyticsConfig::from_values(Some(""), Some("pa-x")).is_err());
274        assert!(AnalyticsConfig::from_values(Some("staging"), Some("pa-x")).is_err());
275    }
276
277    #[test]
278    fn the_plain_accessors_keep_their_types_and_are_empty_when_disabled() {
279        let off: AnalyticsConfig = AnalyticsConfig::disabled();
280        assert_eq!("", off.script_id());
281        assert_eq!(String::new(), off.upstream_script_url());
282
283        let on: AnalyticsConfig = AnalyticsConfig::new("pa-x");
284        assert_eq!("pa-x", on.script_id());
285        assert_eq!("https://plausible.io/js/pa-x.js", on.upstream_script_url());
286    }
287
288    #[test]
289    fn production_with_an_id_is_unchanged() {
290        let config: AnalyticsConfig =
291            AnalyticsConfig::resolve(Environment::Production, Some("pa-x"));
292        assert!(config.is_enabled());
293        assert_eq!(Some("pa-x"), config.script_id_if_enabled());
294        assert_eq!(config, AnalyticsConfig::new("pa-x"));
295        assert_eq!(
296            config,
297            AnalyticsConfig::new("pa-x").for_environment(Environment::Production)
298        );
299    }
300
301    #[test]
302    fn the_plausible_script_url_embeds_the_site_id() {
303        let config: AnalyticsConfig = AnalyticsConfig::new("pa-1qi0TQEvpewNxVHboeeOC");
304
305        let expected: Option<String> = Some(String::from(
306            "https://plausible.io/js/pa-1qi0TQEvpewNxVHboeeOC.js",
307        ));
308        let actual: Option<String> = config.upstream_script_url_if_enabled();
309        assert_eq!(expected, actual);
310    }
311
312    #[test]
313    fn a_dsn_yields_its_envelope_endpoint_and_is_kept_verbatim() {
314        let dsn: SentryDsn =
315            SentryDsn::parse("https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968")
316                .expect("a well-formed DSN");
317
318        let expected: &str = "https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968";
319        assert_eq!(expected, dsn.as_str());
320
321        let expected: String = String::from(
322            "https://o4504844394627072.ingest.sentry.io/api/4504862450515968/envelope/",
323        );
324        let actual: String = dsn.upstream_envelope_url();
325        assert_eq!(expected, actual);
326    }
327
328    #[test]
329    fn the_bundle_is_pinned_and_the_tracing_one_is_only_named_when_asked_for() {
330        let expected: String =
331            format!("https://browser.sentry-cdn.com/{SENTRY_BROWSER_SDK_VERSION}/bundle.min.js");
332        assert_eq!(expected, SentryDsn::upstream_bundle_url(false));
333
334        let expected: String = format!(
335            "https://browser.sentry-cdn.com/{SENTRY_BROWSER_SDK_VERSION}/bundle.tracing.min.js"
336        );
337        assert_eq!(expected, SentryDsn::upstream_bundle_url(true));
338    }
339
340    #[test]
341    fn a_malformed_dsn_is_rejected_at_boot_rather_than_at_the_first_error() {
342        assert!(SentryDsn::parse("not-a-dsn").is_err());
343        assert!(SentryDsn::parse("https://o123.ingest.sentry.io/456").is_err());
344        assert!(SentryDsn::parse("https://key@host/").is_err());
345        assert!(SentryDsn::parse("https://@host/456").is_err());
346    }
347}