Skip to main content

rws_proxy/traffic/
config.rs

1//! `[traffic]` settings (`RWS_CONFIG_TRAFFIC_*`).
2
3use std::path::PathBuf;
4
5pub const RWS_CONFIG_TRAFFIC_ENABLED: &str = "RWS_CONFIG_TRAFFIC_ENABLED";
6pub const RWS_CONFIG_TRAFFIC_RETENTION_DAYS: &str = "RWS_CONFIG_TRAFFIC_RETENTION_DAYS";
7pub const RWS_CONFIG_TRAFFIC_PERSIST: &str = "RWS_CONFIG_TRAFFIC_PERSIST";
8pub const RWS_CONFIG_TRAFFIC_EXCLUDE: &str = "RWS_CONFIG_TRAFFIC_EXCLUDE";
9pub const RWS_CONFIG_TRAFFIC_GEO_DB: &str = "RWS_CONFIG_TRAFFIC_GEO_DB";
10pub const RWS_CONFIG_TRAFFIC_SCRIPT: &str = "RWS_CONFIG_TRAFFIC_SCRIPT";
11pub const RWS_CONFIG_TRAFFIC_GOALS: &str = "RWS_CONFIG_TRAFFIC_GOALS";
12pub const RWS_CONFIG_TRAFFIC_DATABASE_URL_ENV: &str = "RWS_CONFIG_TRAFFIC_DATABASE_URL_ENV";
13pub const RWS_CONFIG_TRAFFIC_HOSTING_NETWORKS: &str = "RWS_CONFIG_TRAFFIC_HOSTING_NETWORKS";
14pub const RWS_CONFIG_TRAFFIC_APPS: &str = "RWS_CONFIG_TRAFFIC_APPS";
15pub const RWS_CONFIG_TRAFFIC_OWNER_NETWORKS: &str = "RWS_CONFIG_TRAFFIC_OWNER_NETWORKS";
16pub const RWS_CONFIG_TRAFFIC_PROBE_ADDRESSES: &str = "RWS_CONFIG_TRAFFIC_PROBE_ADDRESSES";
17pub const RWS_CONFIG_TRAFFIC_HIDE_HOSTS: &str = "RWS_CONFIG_TRAFFIC_HIDE_HOSTS";
18
19fn read(key: &str) -> String {
20    std::env::var(key).unwrap_or_default().trim().to_string()
21}
22
23/// `enabled`: `Some(false)` turns counting off even with the admin API on;
24/// `None` when unset.
25pub fn enabled_setting() -> Option<bool> {
26    match read(RWS_CONFIG_TRAFFIC_ENABLED).to_ascii_lowercase().as_str() {
27        "" => None,
28        "false" | "0" | "no" | "off" => Some(false),
29        _ => Some(true),
30    }
31}
32
33/// `retention_days`: 1–90, default 30.
34pub fn retention_days() -> u64 {
35    read(RWS_CONFIG_TRAFFIC_RETENTION_DAYS).parse::<u64>().ok().filter(|d| *d >= 1).map_or(30, |d| d.min(90))
36}
37
38/// `exclude`: exact paths not counted (comma-separated); default the
39/// health, readiness and metrics endpoints.
40pub fn exclude() -> Vec<String> {
41    let value = std::env::var(RWS_CONFIG_TRAFFIC_EXCLUDE);
42    match value {
43        Ok(v) => v.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect(),
44        Err(_) => ["/healthz", "/readyz", "/metrics"].iter().map(|p| p.to_string()).collect(),
45    }
46}
47
48/// `persist`: the file the counts are saved to. Unset: `traffic.json` next
49/// to the certificate (the ACME certificate's directory, else the TLS
50/// certificate's) — the state directory; without either, nothing is
51/// saved. `"off"`: not saved.
52pub fn persist_path() -> Option<PathBuf> {
53    let value = read(RWS_CONFIG_TRAFFIC_PERSIST);
54    if value.eq_ignore_ascii_case("off") {
55        return None;
56    }
57    if !value.is_empty() {
58        return Some(PathBuf::from(value));
59    }
60    [crate::entry_point::Config::RWS_CONFIG_ACME_CERT_PATH, crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE]
61        .iter()
62        .map(|key| read(key))
63        .find(|path| !path.is_empty())
64        .and_then(|cert| PathBuf::from(cert).parent().map(|dir| dir.join("traffic.json")))
65}
66
67/// `geo_db`: a country table (`ci/gen_geo.py`'s format) to use instead of
68/// the built-in one; unset: the built-in one.
69pub fn geo_db() -> Option<PathBuf> {
70    let value = read(RWS_CONFIG_TRAFFIC_GEO_DB);
71    (!value.is_empty()).then(|| PathBuf::from(value))
72}
73
74/// `script`: serve the first-party script at `/_rws/t.js` and take its
75/// reports at `/_rws/t`. Default off.
76pub fn script() -> bool {
77    matches!(read(RWS_CONFIG_TRAFFIC_SCRIPT).to_ascii_lowercase().as_str(), "true" | "1" | "yes" | "on")
78}
79
80/// `hosting_networks`: count browsers from cloud and server hosting
81/// networks as bots (`traffic::hosting`). Default on; `false` counts them
82/// as people when they load assets, as before 18.35.
83pub fn hosting_networks() -> bool {
84    !matches!(read(RWS_CONFIG_TRAFFIC_HOSTING_NETWORKS).to_ascii_lowercase().as_str(), "false" | "0" | "no" | "off")
85}
86
87/// The most goals counted.
88pub const MAX_GOALS: usize = 32;
89
90/// `goals`: what counts as a conversion — a page path (`/thanks/`, or a
91/// prefix ending in `*`: `/docs/*`) or a script event (`event:signup`),
92/// comma-separated; at most [`MAX_GOALS`].
93pub fn goals() -> Vec<String> {
94    read(RWS_CONFIG_TRAFFIC_GOALS).split(',').map(str::trim).filter(|g| !g.is_empty()).take(MAX_GOALS).map(str::to_string).collect()
95}
96
97/// `database_url_env`: the environment variable holding a `postgres://` URL
98/// to write page views and script reports to (the URL itself stays out of
99/// the config file and the admin API). `None` when unset or the variable is
100/// empty.
101pub fn database_url() -> Option<String> {
102    let name = read(RWS_CONFIG_TRAFFIC_DATABASE_URL_ENV);
103    if name.is_empty() {
104        return None;
105    }
106    std::env::var(&name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
107}
108
109fn list(key: &str) -> Vec<String> {
110    read(key).split(',').map(str::trim).filter(|v| !v.is_empty()).map(str::to_string).collect()
111}
112
113/// `apps`: the site's native apps and browser extensions, as
114/// `name=pattern` (`traffic::apps`): a `User-Agent` token (`HITOP/`) or an
115/// extension origin (`chrome-extension://<id>`).
116pub fn apps() -> Vec<String> {
117    list(RWS_CONFIG_TRAFFIC_APPS)
118}
119
120/// `owner_networks`: addresses or CIDR ranges whose requests are the
121/// owner's (`traffic::owner`), counted apart from everyone else's.
122pub fn owner_networks() -> Vec<String> {
123    list(RWS_CONFIG_TRAFFIC_OWNER_NETWORKS)
124}
125
126/// `probe_addresses`: keep the addresses of scanners (requests for
127/// `/.env`, `/.git/config`…) in the probes list, to block them. Default
128/// off: no address is kept, only country and network.
129pub fn probe_addresses() -> bool {
130    matches!(read(RWS_CONFIG_TRAFFIC_PROBE_ADDRESSES).to_ascii_lowercase().as_str(), "true" | "1" | "yes" | "on")
131}
132
133/// `hide_hosts`: names routes serve that aren't sites to report (a mail
134/// server's name, an MTA-STS policy host): counted under `other`.
135pub fn hide_hosts() -> Vec<String> {
136    list(RWS_CONFIG_TRAFFIC_HIDE_HOSTS)
137}