webserver-base 0.3.7

A Rust library which contains shared logic for all of my webserver projects.
Documentation
//! What the proxies need to know about their upstreams.

use crate::env::{self, EnvError};
use crate::environment::Environment;

/// The environment variable holding the Plausible script id.
pub const ENV_ANALYTICS_ID: &str = "WSB_ANALYTICS_ID";

/// The environment variable holding the browser Sentry DSN.
pub const ENV_SENTRY_BROWSER_DSN: &str = "WSB_SENTRY_BROWSER_DSN";

/// Plausible's script host.
pub const PLAUSIBLE_HOST: &str = "https://plausible.io";

/// Sentry's browser-bundle CDN.
pub const SENTRY_BROWSER_CDN_HOST: &str = "https://browser.sentry-cdn.com";

/// The Sentry browser SDK version every site serves.
///
/// Pinned, so a Sentry release never changes what visitors run until this
/// library is upgraded. The one place to bump it: check that both bundles
/// exist at the new version, and that `window.Sentry` still carries
/// `browserTracingIntegration`, `getActiveSpan`, `getRootSpan`,
/// `spanToJSON` and `startInactiveSpan`, which the layout's span helper uses.
pub const SENTRY_BROWSER_SDK_VERSION: &str = "10.78.0";

/// Which Plausible site events belong to, or that none do.
///
/// Modern Plausible identifies a site by the id embedded in its script URL
/// rather than a `data-domain` attribute, so this is the whole configuration.
/// Deriving it from the request's hostname instead would split `www.` and
/// apex traffic into two sites Plausible does not both know about, and would
/// let a staging deploy pour into production's numbers.
///
/// A config can also be *disabled*: no script tag, no proxy routes, no
/// upstream fetch, no event forwarding. That is what a local run gets, and
/// what a blank or missing id gets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalyticsConfig {
    script_id: Option<String>,
}

impl AnalyticsConfig {
    /// Events for the site this script id belongs to. A blank id disables
    /// analytics, as [`AnalyticsConfig::disabled`] does.
    #[must_use]
    pub fn new(script_id: impl Into<String>) -> Self {
        let script_id: String = script_id.into();
        Self::from_optional_id(Some(&script_id))
    }

    /// Analytics off: nothing is rendered, mounted, fetched or forwarded.
    #[must_use]
    pub const fn disabled() -> Self {
        Self { script_id: None }
    }

    /// Enabled only for a non-blank id.
    #[must_use]
    pub fn from_optional_id(script_id: Option<&str>) -> Self {
        Self {
            script_id: script_id
                .map(str::trim)
                .filter(|id| !id.is_empty())
                .map(String::from),
        }
    }

    /// Reads [`ENV_ANALYTICS_ID`] and `WSB_ENVIRONMENT`.
    ///
    /// Disabled when the environment is `local`, or when the id is unset or
    /// blank. Only a production run with an id is enabled.
    ///
    /// # Errors
    ///
    /// [`EnvError`] if `WSB_ENVIRONMENT` is unset, blank or invalid.
    pub fn from_env() -> Result<Self, EnvError> {
        Self::from_values(
            std::env::var("WSB_ENVIRONMENT").ok().as_deref(),
            env::optional(ENV_ANALYTICS_ID).as_deref(),
        )
    }

    /// [`AnalyticsConfig::from_env`]'s logic over already-read values.
    ///
    /// # Errors
    ///
    /// [`EnvError`] if the environment is `None`, blank or invalid.
    pub fn from_values(
        environment: Option<&str>,
        script_id: Option<&str>,
    ) -> Result<Self, EnvError> {
        Ok(Self::resolve(
            Environment::from_value(environment)?,
            script_id,
        ))
    }

    /// The config for `environment` and an optional id: disabled when local or
    /// when the id is missing or blank.
    #[must_use]
    pub fn resolve(environment: Environment, script_id: Option<&str>) -> Self {
        if environment.is_local() {
            Self::disabled()
        } else {
            Self::from_optional_id(script_id)
        }
    }

    /// This config as it applies in `environment`: always disabled when local,
    /// whatever id was passed in.
    #[must_use]
    pub fn for_environment(self, environment: Environment) -> Self {
        if environment.is_local() {
            Self::disabled()
        } else {
            self
        }
    }

    /// Whether analytics is on.
    #[must_use]
    pub const fn is_enabled(&self) -> bool {
        self.script_id.is_some()
    }

    /// The configured script id, or `""` when analytics is disabled. Prefer
    /// [`AnalyticsConfig::script_id_if_enabled`].
    #[must_use]
    pub fn script_id(&self) -> &str {
        self.script_id.as_deref().unwrap_or_default()
    }

    /// The configured script id, if enabled.
    #[must_use]
    pub fn script_id_if_enabled(&self) -> Option<&str> {
        self.script_id.as_deref()
    }

    /// The upstream script URL this proxy fetches, or `""` when analytics is
    /// disabled. Prefer [`AnalyticsConfig::upstream_script_url_if_enabled`].
    #[must_use]
    pub fn upstream_script_url(&self) -> String {
        self.upstream_script_url_if_enabled().unwrap_or_default()
    }

    /// The upstream script URL this proxy fetches, if enabled.
    #[must_use]
    pub fn upstream_script_url_if_enabled(&self) -> Option<String> {
        self.script_id
            .as_ref()
            .map(|id| format!("{PLAUSIBLE_HOST}/js/{id}.js"))
    }

    /// The upstream event endpoint this proxy forwards to.
    #[must_use]
    pub fn upstream_event_url() -> String {
        format!("{PLAUSIBLE_HOST}/api/event")
    }
}

/// A parsed Sentry DSN.
///
/// Only the pieces the tunnel needs: which host to relay to, and which project.
/// Because a frontend declares exactly one browser DSN, the tunnel never has to
/// parse an envelope to discover where an event belongs — which keeps it a dumb
/// byte relay and stops it being usable as an open relay to arbitrary projects.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SentryDsn {
    dsn: String,
    host: String,
    project_id: String,
}

/// Why a DSN could not be understood.
#[derive(Debug, thiserror::Error)]
#[error("`{dsn}` is not a Sentry DSN; expected `https://<key>@<host>/<project id>`")]
pub struct SentryDsnParseError {
    dsn: String,
}

impl SentryDsn {
    /// Parses `https://<public key>@<host>/<project id>`.
    ///
    /// # Errors
    ///
    /// [`SentryDsnParseError`] if the DSN is not in that shape.
    pub fn parse(dsn: &str) -> Result<Self, SentryDsnParseError> {
        let malformed = || SentryDsnParseError {
            dsn: dsn.to_string(),
        };

        let scheme_end: usize = dsn.find("://").ok_or_else(malformed)? + 3;
        let rest: &str = &dsn[scheme_end..];
        let (public_key, remainder) = rest.split_once('@').ok_or_else(malformed)?;
        let (host, project_id) = remainder.rsplit_once('/').ok_or_else(malformed)?;

        if public_key.is_empty() || host.is_empty() || project_id.is_empty() {
            return Err(malformed());
        }

        Ok(Self {
            dsn: dsn.to_string(),
            host: host.to_string(),
            project_id: project_id.to_string(),
        })
    }

    /// The DSN as given. A browser DSN is public by design: it only lets a
    /// client send events, and the browser needs it to build them.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.dsn
    }

    /// The pinned browser bundle, with tracing (page-load spans and web
    /// vitals) or without. The tracing bundle is about 60% larger, so a site
    /// that traces nothing is served the errors-only one.
    ///
    /// Not the per-project loader script: that one serves whichever bundle the
    /// project's dashboard toggle names, so tracing would depend on a setting
    /// outside the code, and it fetches the bundle from Sentry's origin, past
    /// this site's proxy.
    #[must_use]
    pub fn upstream_bundle_url(tracing: bool) -> String {
        let bundle: &str = if tracing { "bundle.tracing" } else { "bundle" };
        format!("{SENTRY_BROWSER_CDN_HOST}/{SENTRY_BROWSER_SDK_VERSION}/{bundle}.min.js")
    }

    /// Where envelopes are relayed, verbatim.
    #[must_use]
    pub fn upstream_envelope_url(&self) -> String {
        format!("https://{}/api/{}/envelope/", self.host, self.project_id)
    }
}

#[cfg(test)]
mod tests {
    use super::{AnalyticsConfig, SENTRY_BROWSER_SDK_VERSION, SentryDsn};
    use crate::environment::Environment;

    #[test]
    fn local_mode_disables_analytics_even_with_an_id() {
        let config: AnalyticsConfig = AnalyticsConfig::resolve(Environment::Local, Some("pa-x"));
        assert!(!config.is_enabled());
        assert_eq!(None, config.upstream_script_url_if_enabled());

        let config: AnalyticsConfig =
            AnalyticsConfig::new("pa-x").for_environment(Environment::Local);
        assert!(!config.is_enabled());
    }

    #[test]
    fn an_unset_or_blank_id_disables_analytics_in_production() {
        assert!(!AnalyticsConfig::resolve(Environment::Production, None).is_enabled());
        assert!(!AnalyticsConfig::resolve(Environment::Production, Some("")).is_enabled());
        assert!(!AnalyticsConfig::resolve(Environment::Production, Some("  ")).is_enabled());
        assert!(!AnalyticsConfig::new("").is_enabled());
    }

    #[test]
    fn from_values_covers_local_production_and_an_unset_environment() {
        let local = AnalyticsConfig::from_values(Some("local"), Some("pa-x")).expect("valid");
        assert!(!local.is_enabled());

        let prod = AnalyticsConfig::from_values(Some("production"), Some("pa-x")).expect("valid");
        assert!(prod.is_enabled());

        let no_id = AnalyticsConfig::from_values(Some("production"), None).expect("valid");
        assert!(!no_id.is_enabled());

        assert!(AnalyticsConfig::from_values(None, Some("pa-x")).is_err());
        assert!(AnalyticsConfig::from_values(Some(""), Some("pa-x")).is_err());
        assert!(AnalyticsConfig::from_values(Some("staging"), Some("pa-x")).is_err());
    }

    #[test]
    fn the_plain_accessors_keep_their_types_and_are_empty_when_disabled() {
        let off: AnalyticsConfig = AnalyticsConfig::disabled();
        assert_eq!("", off.script_id());
        assert_eq!(String::new(), off.upstream_script_url());

        let on: AnalyticsConfig = AnalyticsConfig::new("pa-x");
        assert_eq!("pa-x", on.script_id());
        assert_eq!("https://plausible.io/js/pa-x.js", on.upstream_script_url());
    }

    #[test]
    fn production_with_an_id_is_unchanged() {
        let config: AnalyticsConfig =
            AnalyticsConfig::resolve(Environment::Production, Some("pa-x"));
        assert!(config.is_enabled());
        assert_eq!(Some("pa-x"), config.script_id_if_enabled());
        assert_eq!(config, AnalyticsConfig::new("pa-x"));
        assert_eq!(
            config,
            AnalyticsConfig::new("pa-x").for_environment(Environment::Production)
        );
    }

    #[test]
    fn the_plausible_script_url_embeds_the_site_id() {
        let config: AnalyticsConfig = AnalyticsConfig::new("pa-1qi0TQEvpewNxVHboeeOC");

        let expected: Option<String> = Some(String::from(
            "https://plausible.io/js/pa-1qi0TQEvpewNxVHboeeOC.js",
        ));
        let actual: Option<String> = config.upstream_script_url_if_enabled();
        assert_eq!(expected, actual);
    }

    #[test]
    fn a_dsn_yields_its_envelope_endpoint_and_is_kept_verbatim() {
        let dsn: SentryDsn =
            SentryDsn::parse("https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968")
                .expect("a well-formed DSN");

        let expected: &str = "https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968";
        assert_eq!(expected, dsn.as_str());

        let expected: String = String::from(
            "https://o4504844394627072.ingest.sentry.io/api/4504862450515968/envelope/",
        );
        let actual: String = dsn.upstream_envelope_url();
        assert_eq!(expected, actual);
    }

    #[test]
    fn the_bundle_is_pinned_and_the_tracing_one_is_only_named_when_asked_for() {
        let expected: String =
            format!("https://browser.sentry-cdn.com/{SENTRY_BROWSER_SDK_VERSION}/bundle.min.js");
        assert_eq!(expected, SentryDsn::upstream_bundle_url(false));

        let expected: String = format!(
            "https://browser.sentry-cdn.com/{SENTRY_BROWSER_SDK_VERSION}/bundle.tracing.min.js"
        );
        assert_eq!(expected, SentryDsn::upstream_bundle_url(true));
    }

    #[test]
    fn a_malformed_dsn_is_rejected_at_boot_rather_than_at_the_first_error() {
        assert!(SentryDsn::parse("not-a-dsn").is_err());
        assert!(SentryDsn::parse("https://o123.ingest.sentry.io/456").is_err());
        assert!(SentryDsn::parse("https://key@host/").is_err());
        assert!(SentryDsn::parse("https://@host/456").is_err());
    }
}