Skip to main content

renox_core/
config.rs

1use std::env;
2use std::net::{IpAddr, Ipv4Addr, SocketAddr};
3use std::path::PathBuf;
4use std::time::Duration;
5
6use anyhow::{Context, bail};
7
8use crate::mail::MailConfig;
9use crate::storage::StorageConfig;
10
11/// The environment the application runs in, from `APP_ENV`.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum Environment {
15    /// `local` (also `dev`, `development`), the default.
16    Local,
17    /// `testing` (also `test`).
18    Testing,
19    /// `production` (also `prod`); requires `APP_KEY`.
20    Production,
21}
22
23impl Environment {
24    fn parse(value: &str) -> anyhow::Result<Self> {
25        match value.to_ascii_lowercase().as_str() {
26            "local" | "dev" | "development" => Ok(Self::Local),
27            "testing" | "test" => Ok(Self::Testing),
28            "production" | "prod" => Ok(Self::Production),
29            other => bail!("APP_ENV must be local, testing or production, got `{other}`"),
30        }
31    }
32}
33
34/// How strict the Content-Security-Policy header is, from `CSP`.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36#[non_exhaustive]
37pub enum CspMode {
38    /// Scripts from this site, inline scripts and `eval` (which Alpine.js's
39    /// standard build needs) are allowed; other sites' scripts, framing by
40    /// other sites and plugins are not.
41    #[default]
42    Relaxed,
43    /// Scripts only from this site or with `nonce="{{ csp_nonce() }}"`, no
44    /// `eval`: Renox switches to Alpine's CSP build (expressions are limited
45    /// to properties and methods; put logic in `Alpine.data(...)`) and turns
46    /// off htmx's `eval`.
47    Strict,
48    /// No Content-Security-Policy header.
49    Off,
50}
51
52impl CspMode {
53    fn parse(value: &str) -> anyhow::Result<Self> {
54        match value.to_ascii_lowercase().as_str() {
55            "relaxed" | "" => Ok(Self::Relaxed),
56            "strict" => Ok(Self::Strict),
57            "off" | "false" | "none" => Ok(Self::Off),
58            other => bail!("CSP must be relaxed, strict or off, got `{other}`"),
59        }
60    }
61}
62
63/// The `Permissions-Policy` header, from `PERMISSIONS_POLICY`.
64#[derive(Debug, Clone, PartialEq, Eq, Default)]
65#[non_exhaustive]
66pub enum PermissionsMode {
67    /// Switches off the features a typical app never uses (camera,
68    /// microphone, geolocation, payment, USB…); `App::permissions_policy`
69    /// allows some back.
70    #[default]
71    Default,
72    /// No `Permissions-Policy` header.
73    Off,
74    /// This header value as the base, e.g. `geolocation=(self), camera=()`.
75    Custom(String),
76}
77
78impl PermissionsMode {
79    fn parse(value: &str) -> anyhow::Result<Self> {
80        let value = value.trim();
81        match value.to_ascii_lowercase().as_str() {
82            "default" | "" => Ok(Self::Default),
83            "off" | "false" | "none" => Ok(Self::Off),
84            _ => {
85                crate::security::parse_permissions_policy(value)
86                    .with_context(|| format!("PERMISSIONS_POLICY is not usable: `{value}`"))?;
87                Ok(Self::Custom(value.to_owned()))
88            }
89        }
90    }
91}
92
93setting_enum! {
94    /// Where sessions live, from `SESSION_DRIVER`.
95    pub enum SessionDriver ("SESSION_DRIVER") {
96        /// The whole session in an encrypted cookie (the default).
97        Cookie = "cookie",
98        /// An id in the cookie, the session in the `sessions` table.
99        Database = "database",
100    }
101}
102
103setting_enum! {
104    /// How log lines are written, from `LOG_FORMAT`.
105    pub enum LogFormat ("LOG_FORMAT") {
106        /// Readable lines (the default).
107        Text = "text",
108        /// One JSON object per line, for a log service.
109        Json = "json",
110    }
111}
112
113setting_enum! {
114    /// Where the cache keeps its values, from `CACHE_STORE`.
115    pub enum CacheStore ("CACHE_STORE") {
116        /// In this process's memory (the default).
117        Memory = "memory",
118        /// In the `cache` table, shared by every server (throttles and the login lock too).
119        Database = "database",
120    }
121}
122
123/// Application configuration, read from the process environment and `.env`.
124#[derive(Clone)]
125#[non_exhaustive]
126pub struct Config {
127    /// The application's name, from `APP_NAME` (Renox).
128    pub name: String,
129    /// The environment, from `APP_ENV` (local).
130    pub env: Environment,
131    /// Show error details and backtraces in responses. Never enable in production.
132    pub debug: bool,
133    /// The public base URL, from `APP_URL` (`http://{host}:{port}`).
134    pub url: String,
135    /// Secret used for signing and encryption. Required in production.
136    pub key: Option<String>,
137    /// The IP address to listen on, from `APP_HOST` (127.0.0.1).
138    pub host: IpAddr,
139    /// The port to listen on, from `APP_PORT` (3000).
140    pub port: u16,
141    /// Where templates live, from `VIEWS_PATH`.
142    pub views_path: PathBuf,
143    /// Files served as-is at the site root, from `PUBLIC_PATH`.
144    pub public_path: PathBuf,
145    /// Inactivity before a session expires, from `SESSION_LIFETIME` in
146    /// minutes (default 120).
147    pub session_lifetime: Duration,
148    /// Name of the session cookie, from `SESSION_COOKIE`.
149    pub session_cookie: String,
150    /// Where sessions live, from `SESSION_DRIVER`: `cookie` (default: the
151    /// whole session in an encrypted cookie) or `database` (the cookie holds
152    /// an id; the `sessions` table holds the rest).
153    pub session_driver: SessionDriver,
154    /// How long a "remember me" login lasts, from `REMEMBER_LIFETIME` in
155    /// minutes (default 43200: 30 days).
156    pub remember_lifetime: Duration,
157    /// SQLite database, from `DATABASE_URL`, e.g. `sqlite://storage/app.db`.
158    pub database_url: String,
159    /// Maximum open connections, from `DATABASE_POOL_SIZE`.
160    pub database_pool_size: u32,
161    /// How long a query waits for a free connection before failing, from
162    /// `DATABASE_ACQUIRE_TIMEOUT` in seconds (default 5).
163    pub database_acquire_timeout: Duration,
164    /// Longest a PostgreSQL statement may run, from `DATABASE_STATEMENT_TIMEOUT`
165    /// in seconds (default 30; 0 for none).
166    pub database_statement_timeout: Option<Duration>,
167    /// Longest a request may take to answer, from `REQUEST_TIMEOUT` in
168    /// seconds (default 60; 0 for none). Streaming a response isn't counted.
169    pub request_timeout: Option<Duration>,
170    /// Default language of the app, from `APP_LOCALE`. Renox's own texts are
171    /// English; other locales need a lang file (`resources/lang/es.json`).
172    pub locale: String,
173    /// Language used for keys missing in the request's locale, from `APP_FALLBACK_LOCALE`.
174    pub fallback_locale: String,
175    /// The currency of the `money` template filter, an ISO 4217 code, from
176    /// `APP_CURRENCY` (default `USD`): `USD` shows `$75.00`, `EUR`
177    /// `€75.00`, `IDR` `Rp 75,000`, with the page's separators.
178    pub currency: String,
179    /// Where translation files live, from `LANG_PATH`.
180    pub lang_path: PathBuf,
181    /// Mail settings, from `MAIL_*`.
182    pub mail: MailConfig,
183    /// Queue workers `serve` runs in-process, from `QUEUE_WORKERS` (0 turns them off).
184    pub queue_workers: usize,
185    /// Consecutive failed deliveries after which an outbound webhook endpoint is
186    /// disabled, from `WEBHOOK_DISABLE_AFTER` (default 20, at least 1).
187    pub webhook_disable_after: u32,
188    /// How far a signed request's timestamp may be from now, in seconds, from
189    /// `WEBHOOK_TOLERANCE_SECS` (default 300, at least 1). See `SignedRequest`.
190    pub webhook_tolerance_secs: u64,
191    /// Days the keys of `.offline()` routes are kept before `idempotency:prune`
192    /// (and its scheduled task) removes them, from `IDEMPOTENCY_RETENTION_DAYS`
193    /// (default 7, at least 1).
194    pub idempotency_retention_days: u32,
195    /// Whether `serve` runs scheduled tasks, from `SCHEDULER`.
196    pub scheduler: bool,
197    /// `text` (default) or `json` (one object per line), from `LOG_FORMAT`.
198    pub log_format: LogFormat,
199    /// Where logs go instead of stdout, from `LOG_FILE` (appended to).
200    pub log_file: Option<PathBuf>,
201    /// The zone of scheduled times and the `date` filter, from
202    /// `APP_TIMEZONE`: an IANA name (`Asia/Jakarta`), an offset (`+07:00`) or
203    /// `UTC`. See [`crate::timezone::Zone`].
204    pub timezone: crate::timezone::Zone,
205    /// `memory` or `database`, from `CACHE_STORE`.
206    pub cache_store: CacheStore,
207    /// Where the app keeps runtime files (maintenance flag, uploads), from `STORAGE_PATH`.
208    pub storage_path: PathBuf,
209    /// File storage, from `STORAGE_DISK`, `S3_*` and `STORAGE_URL`.
210    pub storage: StorageConfig,
211    /// Largest request body in bytes, from `UPLOAD_MAX_SIZE` in megabytes (default 10).
212    pub upload_max_size: usize,
213    /// Largest live component snapshot in bytes, from `LIVE_SNAPSHOT_MAX_SIZE` in kilobytes (default 64).
214    pub live_snapshot_max: usize,
215    /// The Content-Security-Policy, from `CSP` (`relaxed`, `strict` or `off`).
216    pub csp: CspMode,
217    /// The Permissions-Policy, from `PERMISSIONS_POLICY` (`default`, `off` or a
218    /// full header value such as `geolocation=(self), camera=()`).
219    pub permissions_policy: PermissionsMode,
220    /// Values `var()` returns before looking at the environment, e.g. a
221    /// webhook secret set in a test with `TestApp::with_config`.
222    pub vars: std::collections::HashMap<String, String>,
223    /// Search engines and analytics; used only in production.
224    pub analytics: AnalyticsConfig,
225    /// Reverse proxies whose `X-Forwarded-For` is believed, from `TRUSTED_PROXIES`.
226    pub trusted_proxies: crate::TrustedProxies,
227    /// Host names the app answers, from `TRUSTED_HOSTS` (comma-separated;
228    /// `*.example.com` for subdomains). Empty: any host. When set, `APP_URL`'s
229    /// host is allowed too, and other hosts get a 400.
230    pub trusted_hosts: Vec<String>,
231}
232
233impl std::fmt::Debug for Config {
234    // Secrets show as `[hidden]`, so a logged config doesn't leak them.
235    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236        f.debug_struct("Config")
237            .field("name", &self.name)
238            .field("env", &self.env)
239            .field("debug", &self.debug)
240            .field("url", &self.url)
241            .field("key", &self.key.as_ref().map(|_| "[hidden]"))
242            .field("host", &self.host)
243            .field("port", &self.port)
244            .field("views_path", &self.views_path)
245            .field("public_path", &self.public_path)
246            .field("permissions_policy", &self.permissions_policy)
247            .field("session_lifetime", &self.session_lifetime)
248            .field("session_cookie", &self.session_cookie)
249            .field("session_driver", &self.session_driver)
250            .field("remember_lifetime", &self.remember_lifetime)
251            .field("database_url", &self.database_url)
252            .field("database_pool_size", &self.database_pool_size)
253            .field("database_acquire_timeout", &self.database_acquire_timeout)
254            .field(
255                "database_statement_timeout",
256                &self.database_statement_timeout,
257            )
258            .field("request_timeout", &self.request_timeout)
259            .field("locale", &self.locale)
260            .field("fallback_locale", &self.fallback_locale)
261            .field("currency", &self.currency)
262            .field("lang_path", &self.lang_path)
263            .field("mail", &self.mail)
264            .field("queue_workers", &self.queue_workers)
265            .field("webhook_disable_after", &self.webhook_disable_after)
266            .field("webhook_tolerance_secs", &self.webhook_tolerance_secs)
267            .field(
268                "idempotency_retention_days",
269                &self.idempotency_retention_days,
270            )
271            .field("scheduler", &self.scheduler)
272            .field("log_format", &self.log_format)
273            .field("log_file", &self.log_file)
274            .field("timezone", &self.timezone)
275            .field("cache_store", &self.cache_store)
276            .field("storage_path", &self.storage_path)
277            .field("storage", &self.storage)
278            .field("upload_max_size", &self.upload_max_size)
279            .field("live_snapshot_max", &self.live_snapshot_max)
280            .field("csp", &self.csp)
281            .field(
282                "vars",
283                &self.vars.keys().collect::<std::collections::BTreeSet<_>>(),
284            )
285            .field("analytics", &self.analytics)
286            .field("trusted_proxies", &self.trusted_proxies)
287            .field("trusted_hosts", &self.trusted_hosts)
288            .finish()
289    }
290}
291
292/// Google Search Console, Google Analytics 4 and Google Tag Manager, from
293/// `GOOGLE_SITE_VERIFICATION`, `GA4_MEASUREMENT_ID`, `GA4_API_SECRET` and
294/// `GTM_CONTAINER_ID`. Tags are added to pages only in production.
295#[derive(Clone, Default)]
296#[non_exhaustive]
297pub struct AnalyticsConfig {
298    /// The `content` of Search Console's `google-site-verification` meta tag.
299    pub google_site_verification: Option<String>,
300    /// e.g. `G-XXXXXXXXXX`: adds the GA4 tag to every page.
301    pub ga4_measurement_id: Option<String>,
302    /// For events sent from the server (Measurement Protocol).
303    pub ga4_api_secret: Option<String>,
304    /// e.g. `GTM-XXXXXXX`: adds the Tag Manager container to every page.
305    pub gtm_container_id: Option<String>,
306}
307
308impl std::fmt::Debug for AnalyticsConfig {
309    // Secrets show as `[hidden]`, so a logged config doesn't leak them.
310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        f.debug_struct("AnalyticsConfig")
312            .field("google_site_verification", &self.google_site_verification)
313            .field("ga4_measurement_id", &self.ga4_measurement_id)
314            .field(
315                "ga4_api_secret",
316                &self.ga4_api_secret.as_ref().map(|_| "[hidden]"),
317            )
318            .field("gtm_container_id", &self.gtm_container_id)
319            .finish()
320    }
321}
322
323impl Config {
324    /// Loads `.env` (if present) and reads the configuration from the environment.
325    pub fn load() -> crate::Result<Self> {
326        let _ = dotenvy::dotenv();
327        Self::from_env()
328    }
329
330    /// Reads the configuration from the environment only, without loading `.env`.
331    pub fn from_env() -> crate::Result<Self> {
332        Self::from_vars(|name| env::var(name).ok())
333    }
334
335    /// Reads the configuration from `get` (a variable's value by name), e.g.
336    /// a map in a test: `Config::from_vars(|name| vars.get(name).cloned())`.
337    /// A value that doesn't fit is an error naming its variable.
338    pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> crate::Result<Self> {
339        Ok(Self::read(get)?)
340    }
341
342    fn read(get: impl Fn(&str) -> Option<String>) -> anyhow::Result<Self> {
343        let v = Vars(get);
344        let env = Environment::parse(&v.or("APP_ENV", "local"))?;
345        let debug = v.bool("APP_DEBUG", env == Environment::Local)?;
346        let host = v
347            .or("APP_HOST", "127.0.0.1")
348            .parse()
349            .context("APP_HOST must be an IP address")?;
350        let port = v
351            .or("APP_PORT", "3000")
352            .parse()
353            .context("APP_PORT must be a port number")?;
354        let key = v.get("APP_KEY").filter(|k| !k.is_empty());
355
356        if env == Environment::Production && key.is_none() {
357            bail!("APP_KEY must be set in production");
358        }
359
360        Ok(Self {
361            name: v.or("APP_NAME", "Renox"),
362            env,
363            debug,
364            url: v.or("APP_URL", &format!("http://{host}:{port}")),
365            key,
366            host,
367            port,
368            views_path: v.or("VIEWS_PATH", "resources/views").into(),
369            public_path: v.or("PUBLIC_PATH", "public").into(),
370            session_lifetime: Duration::from_secs(
371                v.or("SESSION_LIFETIME", "120")
372                    .parse::<u64>()
373                    .context("SESSION_LIFETIME must be a number of minutes")?
374                    .saturating_mul(60),
375            ),
376            session_cookie: v.or("SESSION_COOKIE", "renox_session"),
377            session_driver: SessionDriver::parse(&v.or("SESSION_DRIVER", "cookie"))?,
378            remember_lifetime: Duration::from_secs(
379                v.or("REMEMBER_LIFETIME", "43200")
380                    .parse::<u64>()
381                    .context("REMEMBER_LIFETIME must be a number of minutes")?
382                    .saturating_mul(60),
383            ),
384            database_url: v.or("DATABASE_URL", "sqlite://storage/app.db"),
385            database_pool_size: v
386                .or("DATABASE_POOL_SIZE", "8")
387                .parse()
388                .ok()
389                .filter(|n| *n > 0)
390                .context("DATABASE_POOL_SIZE must be a number above 0")?,
391            database_acquire_timeout: v
392                .seconds("DATABASE_ACQUIRE_TIMEOUT", 5)?
393                .unwrap_or(Duration::from_secs(5)),
394            database_statement_timeout: v.seconds("DATABASE_STATEMENT_TIMEOUT", 30)?,
395            request_timeout: v.seconds("REQUEST_TIMEOUT", 60)?,
396            locale: v.or("APP_LOCALE", "en"),
397            fallback_locale: v.or("APP_FALLBACK_LOCALE", "en"),
398            currency: match v.or("APP_CURRENCY", "USD").trim().to_ascii_uppercase() {
399                code if code.len() == 3 && code.bytes().all(|b| b.is_ascii_uppercase()) => code,
400                other => {
401                    bail!("APP_CURRENCY must be an ISO 4217 code like USD or EUR, got `{other}`")
402                }
403            },
404            lang_path: v.or("LANG_PATH", "resources/lang").into(),
405            mail: MailConfig {
406                mailer: crate::mail::MailDriver::parse(&v.or("MAIL_MAILER", "log"))?,
407                host: v.or("MAIL_HOST", "localhost"),
408                port: v
409                    .get("MAIL_PORT")
410                    .filter(|p| !p.is_empty())
411                    .map(|p| p.parse())
412                    .transpose()
413                    .context("MAIL_PORT must be a port number")?,
414                username: v.get("MAIL_USERNAME").filter(|v| !v.is_empty()),
415                password: v.get("MAIL_PASSWORD").filter(|v| !v.is_empty()),
416                encryption: crate::mail::MailEncryption::parse(
417                    &v.or("MAIL_ENCRYPTION", "starttls"),
418                )?,
419                from_address: v.or("MAIL_FROM_ADDRESS", "hello@example.com"),
420                from_name: v.get("MAIL_FROM_NAME").filter(|v| !v.is_empty()),
421                timeout: v
422                    .seconds("MAIL_TIMEOUT", 10)?
423                    .unwrap_or(Duration::from_secs(10)),
424                failover: v
425                    .or("MAIL_FAILOVER", "")
426                    .split(',')
427                    .map(|name| name.trim().to_owned())
428                    .filter(|name| !name.is_empty())
429                    .collect(),
430            },
431            queue_workers: v
432                .or("QUEUE_WORKERS", "2")
433                .parse()
434                .context("QUEUE_WORKERS must be a number")?,
435            webhook_disable_after: v
436                .or("WEBHOOK_DISABLE_AFTER", "20")
437                .parse()
438                .ok()
439                .filter(|n| *n > 0)
440                .context("WEBHOOK_DISABLE_AFTER must be a number of at least 1")?,
441            webhook_tolerance_secs: v
442                .or("WEBHOOK_TOLERANCE_SECS", "300")
443                .parse()
444                .ok()
445                .filter(|n| *n > 0)
446                .context("WEBHOOK_TOLERANCE_SECS must be a number of at least 1")?,
447            idempotency_retention_days: v
448                .or("IDEMPOTENCY_RETENTION_DAYS", "7")
449                .parse()
450                .ok()
451                .filter(|n| *n > 0)
452                .context("IDEMPOTENCY_RETENTION_DAYS must be a number of at least 1")?,
453            scheduler: v.bool("SCHEDULER", true)?,
454            log_format: LogFormat::parse(&v.or("LOG_FORMAT", "text"))?,
455            log_file: v
456                .get("LOG_FILE")
457                .filter(|p| !p.is_empty())
458                .map(PathBuf::from),
459            timezone: v
460                .or("APP_TIMEZONE", "UTC")
461                .parse()
462                .map_err(|err| anyhow::anyhow!("APP_TIMEZONE: {err}"))?,
463            cache_store: CacheStore::parse(&v.or("CACHE_STORE", "memory"))?,
464            storage_path: v.or("STORAGE_PATH", "storage").into(),
465            storage: StorageConfig {
466                disk: crate::storage::DiskDriver::parse(&v.or("STORAGE_DISK", "local"))?,
467                bucket: v.optional("S3_BUCKET"),
468                region: v.optional("S3_REGION"),
469                endpoint: v.optional("S3_ENDPOINT"),
470                access_key_id: v.optional("S3_ACCESS_KEY_ID"),
471                secret_access_key: v.optional("S3_SECRET_ACCESS_KEY"),
472                url: v.optional("STORAGE_URL"),
473                root: None,
474            },
475            upload_max_size: v
476                .or("UPLOAD_MAX_SIZE", "10")
477                .parse::<usize>()
478                .ok()
479                .and_then(|mb| mb.checked_mul(1024 * 1024))
480                .context("UPLOAD_MAX_SIZE must be a number of megabytes")?,
481            live_snapshot_max: v
482                .or("LIVE_SNAPSHOT_MAX_SIZE", "64")
483                .parse::<usize>()
484                .ok()
485                .and_then(|kb| kb.checked_mul(1024))
486                .context("LIVE_SNAPSHOT_MAX_SIZE must be a number of kilobytes")?,
487            csp: CspMode::parse(&v.or("CSP", "relaxed"))?,
488            permissions_policy: PermissionsMode::parse(&v.or("PERMISSIONS_POLICY", "default"))?,
489            trusted_proxies: crate::TrustedProxies::read(&v.or("TRUSTED_PROXIES", ""))?,
490            trusted_hosts: v
491                .or("TRUSTED_HOSTS", "")
492                .split(',')
493                .map(|host| host.trim().to_ascii_lowercase())
494                .filter(|host| !host.is_empty())
495                .collect(),
496            vars: Default::default(),
497            analytics: AnalyticsConfig {
498                google_site_verification: v.optional("GOOGLE_SITE_VERIFICATION"),
499                ga4_measurement_id: v.optional("GA4_MEASUREMENT_ID"),
500                ga4_api_secret: v.optional("GA4_API_SECRET"),
501                gtm_container_id: v.optional("GTM_CONTAINER_ID"),
502            },
503        })
504    }
505
506    /// Any other setting, e.g. an API key: `config.vars`, else the
507    /// environment (which includes `.env`). Empty values count as missing.
508    pub fn var(&self, name: &str) -> Option<String> {
509        self.vars
510            .get(name)
511            .cloned()
512            .or_else(|| env::var(name).ok())
513            .filter(|v| !v.is_empty())
514    }
515
516    /// The address to listen on: `host` and `port`.
517    pub fn addr(&self) -> SocketAddr {
518        SocketAddr::new(self.host, self.port)
519    }
520}
521
522impl Default for Config {
523    fn default() -> Self {
524        Self {
525            name: "Renox".into(),
526            env: Environment::Local,
527            debug: true,
528            url: "http://127.0.0.1:3000".into(),
529            key: None,
530            host: IpAddr::V4(Ipv4Addr::LOCALHOST),
531            port: 3000,
532            views_path: "resources/views".into(),
533            public_path: "public".into(),
534            session_lifetime: Duration::from_secs(120 * 60),
535            session_cookie: "renox_session".into(),
536            session_driver: SessionDriver::Cookie,
537            remember_lifetime: Duration::from_secs(43_200 * 60),
538            database_url: "sqlite::memory:".into(),
539            database_pool_size: 8,
540            // Generous: parallel test suites open many SQLite files at once.
541            // (An in-memory database still fails fast; see `db::connect`.)
542            database_acquire_timeout: Duration::from_secs(30),
543            database_statement_timeout: Some(Duration::from_secs(30)),
544            request_timeout: Some(Duration::from_secs(60)),
545            locale: "en".into(),
546            fallback_locale: "en".into(),
547            currency: "USD".into(),
548            lang_path: "resources/lang".into(),
549            mail: MailConfig {
550                mailer: crate::mail::MailDriver::Memory,
551                ..MailConfig::default()
552            },
553            queue_workers: 0,
554            webhook_disable_after: 20,
555            webhook_tolerance_secs: 300,
556            idempotency_retention_days: 7,
557            scheduler: false,
558            log_format: LogFormat::Text,
559            log_file: None,
560            timezone: crate::timezone::Zone::default(),
561            cache_store: CacheStore::Memory,
562            storage_path: "storage".into(),
563            storage: StorageConfig::default(),
564            upload_max_size: 10 * 1024 * 1024,
565            live_snapshot_max: 64 * 1024,
566            csp: CspMode::Relaxed,
567            permissions_policy: PermissionsMode::Default,
568            vars: Default::default(),
569            analytics: AnalyticsConfig::default(),
570            trusted_proxies: Default::default(),
571            trusted_hosts: Vec::new(),
572        }
573    }
574}
575
576/// Variables by name, for `Config::from_vars`.
577struct Vars<F>(F);
578
579impl<F: Fn(&str) -> Option<String>> Vars<F> {
580    fn get(&self, name: &str) -> Option<String> {
581        (self.0)(name)
582    }
583
584    fn optional(&self, name: &str) -> Option<String> {
585        self.get(name).filter(|v| !v.is_empty())
586    }
587
588    fn or(&self, name: &str, default: &str) -> String {
589        self.get(name).unwrap_or_else(|| default.to_owned())
590    }
591
592    /// A number of seconds from `name`; `None` when it is 0 (no limit).
593    fn seconds(&self, name: &str, default: u64) -> anyhow::Result<Option<Duration>> {
594        let value: u64 = self
595            .or(name, &default.to_string())
596            .parse()
597            .with_context(|| format!("{name} must be a number of seconds"))?;
598        Ok((value > 0).then(|| Duration::from_secs(value)))
599    }
600
601    fn bool(&self, name: &str, default: bool) -> anyhow::Result<bool> {
602        match self.get(name) {
603            None => Ok(default),
604            Some(v) => match v.to_ascii_lowercase().as_str() {
605                "1" | "true" | "yes" | "on" => Ok(true),
606                "0" | "false" | "no" | "off" | "" => Ok(false),
607                other => bail!("{name} must be true or false, got `{other}`"),
608            },
609        }
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    #[test]
618    fn parses_environment_aliases() {
619        assert_eq!(Environment::parse("local").unwrap(), Environment::Local);
620        assert_eq!(Environment::parse("DEV").unwrap(), Environment::Local);
621        assert_eq!(Environment::parse("test").unwrap(), Environment::Testing);
622        assert_eq!(Environment::parse("prod").unwrap(), Environment::Production);
623        assert!(Environment::parse("staging").is_err());
624    }
625
626    fn load(pairs: &[(&str, &str)]) -> anyhow::Result<Config> {
627        let vars: std::collections::HashMap<String, String> = pairs
628            .iter()
629            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
630            .collect();
631        Config::read(|name| vars.get(name).cloned())
632    }
633
634    #[test]
635    fn defaults_without_any_variable() {
636        let c = load(&[]).unwrap();
637        assert_eq!(c.env, Environment::Local);
638        assert!(c.debug, "local defaults to debug");
639        assert_eq!(
640            (c.port, c.database_pool_size, c.upload_max_size),
641            (3000, 8, 10 * 1024 * 1024)
642        );
643        assert_eq!(c.database_acquire_timeout, Duration::from_secs(5));
644        assert_eq!(c.request_timeout, Some(Duration::from_secs(60)));
645        assert_eq!(c.cache_store, CacheStore::Memory);
646        assert_eq!(c.csp, CspMode::Relaxed);
647        assert_eq!(c.permissions_policy, PermissionsMode::Default);
648        assert!(c.key.is_none() && c.mail.port.is_none());
649    }
650
651    #[test]
652    fn debug_hides_secrets() {
653        let mut c = load(&[("APP_KEY", "base64:c2VjcmV0"), ("MAIL_PASSWORD", "hunter2")]).unwrap();
654        c.vars
655            .insert("XENDIT_SECRET_KEY".into(), "xnd_live_123".into());
656        let shown = format!("{c:?}");
657        for secret in ["c2VjcmV0", "hunter2", "xnd_live_123"] {
658            assert!(!shown.contains(secret), "{secret} in {shown}");
659        }
660        assert!(
661            shown.contains("XENDIT_SECRET_KEY"),
662            "variable names stay: {shown}"
663        );
664        assert!(shown.contains("[hidden]"));
665    }
666
667    #[test]
668    fn session_driver() {
669        assert_eq!(load(&[]).unwrap().session_driver, SessionDriver::Cookie);
670        assert_eq!(
671            load(&[("SESSION_DRIVER", "database")])
672                .unwrap()
673                .session_driver,
674            SessionDriver::Database
675        );
676        assert!(load(&[("SESSION_DRIVER", "redis")]).is_err());
677    }
678
679    #[test]
680    fn log_format_and_file() {
681        let c = load(&[]).unwrap();
682        assert_eq!((c.log_format.as_str(), c.log_file), ("text", None));
683        let c = load(&[("LOG_FORMAT", "json"), ("LOG_FILE", "storage/logs/app.log")]).unwrap();
684        assert_eq!(c.log_format, LogFormat::Json);
685        assert_eq!(c.log_file, Some(PathBuf::from("storage/logs/app.log")));
686        let err = load(&[("LOG_FORMAT", "xml")]).unwrap_err();
687        assert!(err.to_string().contains("LOG_FORMAT"), "{err}");
688    }
689
690    #[test]
691    fn currency() {
692        assert_eq!(load(&[]).unwrap().currency, "USD");
693        assert_eq!(load(&[("APP_CURRENCY", " idr ")]).unwrap().currency, "IDR");
694        for bad in ["US", "rupiah", "U$D"] {
695            let err = load(&[("APP_CURRENCY", bad)]).unwrap_err();
696            assert!(err.to_string().contains("APP_CURRENCY"), "{err}");
697        }
698    }
699
700    #[test]
701    fn reads_every_kind_of_value() {
702        let c = load(&[
703            ("APP_ENV", "production"),
704            ("APP_KEY", "base64:abc"),
705            ("APP_DEBUG", "off"),
706            ("APP_PORT", "8080"),
707            ("DATABASE_POOL_SIZE", "3"),
708            ("REQUEST_TIMEOUT", "0"),
709            ("DATABASE_STATEMENT_TIMEOUT", "5"),
710            ("UPLOAD_MAX_SIZE", "2"),
711            ("LIVE_SNAPSHOT_MAX_SIZE", "2"),
712            ("MAIL_PORT", "2525"),
713            ("MAIL_USERNAME", ""),
714            ("MAIL_FAILOVER", "backup, log"),
715            ("CSP", "strict"),
716            ("PERMISSIONS_POLICY", "geolocation=(self), camera=()"),
717            ("TRUSTED_PROXIES", "10.0.0.0/8"),
718            ("TRUSTED_HOSTS", "shop.example.com, *.Example.org"),
719            ("S3_BUCKET", "files"),
720        ])
721        .unwrap();
722        assert_eq!(c.env, Environment::Production);
723        assert!(!c.debug);
724        assert_eq!((c.port, c.database_pool_size), (8080, 3));
725        assert_eq!(c.request_timeout, None, "0 means no limit");
726        assert_eq!(c.database_statement_timeout, Some(Duration::from_secs(5)));
727        assert_eq!(c.upload_max_size, 2 * 1024 * 1024);
728        assert_eq!(c.live_snapshot_max, 2048);
729        assert_eq!(c.mail.port, Some(2525));
730        assert_eq!(c.mail.username, None, "empty means unset");
731        assert_eq!(c.mail.failover, ["backup", "log"]);
732        assert_eq!(c.csp, CspMode::Strict);
733        assert_eq!(
734            c.permissions_policy,
735            PermissionsMode::Custom("geolocation=(self), camera=()".into())
736        );
737        assert!(c.trusted_proxies.contains("10.1.2.3".parse().unwrap()));
738        assert_eq!(c.trusted_hosts, ["shop.example.com", "*.example.org"]);
739        assert_eq!(c.storage.bucket.as_deref(), Some("files"));
740    }
741
742    #[test]
743    fn permissions_policy_takes_default_off_or_a_header_value() {
744        for (value, want) in [
745            ("", PermissionsMode::Default),
746            ("DEFAULT", PermissionsMode::Default),
747            ("off", PermissionsMode::Off),
748            ("false", PermissionsMode::Off),
749            (
750                "camera=(self \"https://a.example\"), payment=*",
751                PermissionsMode::Custom("camera=(self \"https://a.example\"), payment=*".into()),
752            ),
753        ] {
754            let c = load(&[("PERMISSIONS_POLICY", value)]).unwrap();
755            assert_eq!(c.permissions_policy, want, "{value}");
756        }
757        // `CSP=off` leaves it alone.
758        let c = load(&[("CSP", "off")]).unwrap();
759        assert_eq!(c.permissions_policy, PermissionsMode::Default);
760    }
761
762    #[test]
763    fn refuses_bad_values_with_the_variable_name() {
764        for (name, value) in [
765            ("APP_ENV", "staging"),
766            ("APP_DEBUG", "maybe"),
767            ("APP_PORT", "http"),
768            ("APP_HOST", "localhost"),
769            ("DATABASE_POOL_SIZE", "0"),
770            ("REQUEST_TIMEOUT", "-1"),
771            ("UPLOAD_MAX_SIZE", "99999999999999999"),
772            ("MAIL_PORT", "99999"),
773            ("CSP", "loose"),
774            ("PERMISSIONS_POLICY", "camera"),
775            ("PERMISSIONS_POLICY", "Camera=(self)"),
776            ("PERMISSIONS_POLICY", "camera=(http://x.example)"),
777            ("TRUSTED_PROXIES", "proxy.local"),
778            ("SESSION_DRIVER", "redis"),
779            ("CACHE_STORE", "redis"),
780            ("LOG_FORMAT", "xml"),
781            ("MAIL_MAILER", "sendgrid"),
782            ("MAIL_ENCRYPTION", "ssl3"),
783            ("STORAGE_DISK", "ftp"),
784            ("APP_TIMEZONE", "Mars/Olympus"),
785        ] {
786            let err = load(&[(name, value)])
787                .err()
788                .map(|e| format!("{e:#}"))
789                .unwrap_or_default();
790            assert!(
791                err.contains(name) || err.contains(value),
792                "{name}={value}: {err}"
793            );
794        }
795        let err = load(&[("APP_ENV", "production")]).unwrap_err();
796        assert!(
797            format!("{err}").contains("APP_KEY"),
798            "production needs a key"
799        );
800    }
801
802    /// Settings print and serialize as the word `.env` takes.
803    #[test]
804    fn settings_print_and_serialize_as_their_word() {
805        assert_eq!(SessionDriver::Database.to_string(), "database");
806        assert_eq!(
807            serde_json::to_string(&CacheStore::Database).unwrap(),
808            r#""database""#
809        );
810        assert_eq!(format!("{}", LogFormat::Json), "json");
811    }
812}