Skip to main content

recall_server/
config.rs

1//! Server settings.
2//!
3//! Environment variable names are deliberately unchanged from the
4//! shell/Node implementation this replaces, so no machine and no cloud
5//! environment needs re-provisioning to switch over.
6
7use std::env;
8use std::time::Duration;
9
10/// Why the server cannot start.
11#[derive(Debug, Clone, thiserror::Error)]
12pub enum ConfigError {
13    /// Mirrors the Node server's refusal to start without auth — a server
14    /// reachable from the internet with no token is not a degraded mode
15    /// worth supporting.
16    #[error("RECALL_TOKEN is not set; refusing to start with no auth")]
17    MissingToken,
18    /// `RECALL_TLS_CERT` and `RECALL_TLS_KEY` name one file each; half a
19    /// pair is almost always a typo in one of the two variable names.
20    #[error("RECALL_TLS_CERT and RECALL_TLS_KEY must both be set, or neither")]
21    PartialTlsFiles,
22    /// `RECALL_TLS_ACME_DOMAINS` and `RECALL_TLS_ACME_EMAIL` are the same
23    /// kind of pair, for the same reason.
24    #[error("RECALL_TLS_ACME_DOMAINS and RECALL_TLS_ACME_EMAIL must both be set, or neither")]
25    PartialTlsAcme,
26    /// The two TLS modes are mutually exclusive: each picks its own
27    /// certificate source, and a config with both is ambiguous about which
28    /// one wins rather than a config this server can just run.
29    #[error(
30        "RECALL_TLS_CERT/RECALL_TLS_KEY and RECALL_TLS_ACME_DOMAINS/RECALL_TLS_ACME_EMAIL \
31         are two different TLS modes; set one, not both"
32    )]
33    BothTlsModes,
34    /// With direct TLS there is no ingress, so the socket's own peer
35    /// address is the only client IP that is not the client's own choice.
36    /// Setting this variable anyway is either a no-op or, if it is ever
37    /// read, a way for a client to buy itself an unlimited number of token
38    /// guesses by rotating whatever header it names, so refusing to start
39    /// beats silently ignoring the setting.
40    ///
41    /// An explicitly *empty* value is the one exception: it means "trust no
42    /// header", which is exactly what TLS forces anyway, so
43    /// `deploy/docker-compose.direct.yml` sets it that way as a second
44    /// guard, in case its TLS variables ever go missing and the server
45    /// comes up as plain HTTP instead.
46    #[error(
47        "RECALL_TRUSTED_IP_HEADER must be unset or empty while TLS is on; with direct TLS there \
48         is no ingress, so the client IP always comes from the socket's peer address"
49    )]
50    TrustedIpHeaderWithTls,
51    /// `RECALL_TLS_REQUIRED` is set, but neither TLS mode is configured.
52    /// A deployment that publishes its port straight to the internet
53    /// (`deploy/docker-compose.direct.yml`) must never come up as plain
54    /// HTTP just because its certificate variables went missing or empty:
55    /// that would put the bearer token on the wire in clear text.
56    #[error(
57        "RECALL_TLS_REQUIRED is set, but no TLS mode is configured; set RECALL_TLS_CERT and \
58         RECALL_TLS_KEY, or RECALL_TLS_ACME_DOMAINS and RECALL_TLS_ACME_EMAIL"
59    )]
60    TlsRequired,
61    /// `RECALL_TLS_ACME_DOMAINS` was set but named no domain at all (only
62    /// commas or whitespace). There is nothing to ask a certificate for,
63    /// and a server with no certificate fails every handshake.
64    #[error("RECALL_TLS_ACME_DOMAINS names no domain")]
65    NoAcmeDomains,
66    /// TLS-ALPN-01, the only challenge this server answers, cannot prove
67    /// control of a wildcard name (Let's Encrypt requires DNS-01 for
68    /// those), so an order for one could only ever fail, over and over, on
69    /// the ACME directory's rate limit.
70    #[error("RECALL_TLS_ACME_DOMAINS: {0:?} is a wildcard, which TLS-ALPN-01 cannot validate")]
71    WildcardAcmeDomain(String),
72    /// A yes/no setting whose value is neither. Unlike the numeric
73    /// tunables, which fall back to a default on a typo, these two decide
74    /// whether the server may run without TLS and which certificate
75    /// authority it trusts, so guessing either way would be wrong
76    /// somewhere.
77    #[error("{var}={value:?} is not a yes/no value; use true/false, 1/0 or yes/no")]
78    InvalidFlag {
79        /// The variable's name.
80        var: &'static str,
81        /// What it was set to.
82        value: String,
83    },
84}
85
86/// What `recall-server` needs.
87///
88/// Every field has a default that is safe to run with, except [`token`],
89/// which has none — see [`ConfigError::MissingToken`].
90///
91/// | Field | Variable | Default |
92/// |---|---|---|
93/// | [`addr`] | `RECALL_HOST`, `RECALL_PORT` | `0.0.0.0:8787` |
94/// | [`token`] | `RECALL_TOKEN` | *required* |
95/// | [`db_path`] | `RECALL_DB_PATH` | `data/recall.db` |
96/// | [`git_commit`] | `RECALL_GIT_COMMIT` | the commit the binary was built from, else `unknown` |
97/// | [`backup_dir`] | `RECALL_BACKUP_DIR` | off |
98/// | [`backup_interval`] | `RECALL_BACKUP_INTERVAL_MS` | 24h |
99/// | [`backup_keep`] | `RECALL_BACKUP_KEEP` | 7 |
100/// | [`rate_limit_window`] | `RECALL_RATE_LIMIT_WINDOW_MS` | 60s |
101/// | [`rate_limit_max`] | `RECALL_RATE_LIMIT_MAX` | 60 |
102/// | [`trusted_ip_header`] | `RECALL_TRUSTED_IP_HEADER` | `cf-connecting-ip`, forced empty when [`tls`] is on |
103/// | [`merge_enabled`] | `RECALL_MERGE_ENABLED` | on |
104/// | [`merge_timeout`] | `RECALL_MERGE_TIMEOUT_MS` | 45s |
105/// | [`claude_bin`] | `RECALL_CLAUDE_BIN` | `claude` |
106/// | [`claude_status_interval`] | `RECALL_CLAUDE_STATUS_INTERVAL_MS` | 30m |
107/// | [`ephemeral_device_ttl`] | `RECALL_EPHEMERAL_DEVICE_TTL_HOURS` | 24h |
108/// | [`public_url`] | `RECALL_PUBLIC_URL` | unset: passkey sign-in off |
109/// | [`tls`] | `RECALL_TLS_CERT`/`RECALL_TLS_KEY`, or `RECALL_TLS_ACME_DOMAINS`/`RECALL_TLS_ACME_EMAIL`/`RECALL_TLS_ACME_DIR`/`RECALL_TLS_ACME_STAGING` | off |
110/// | [`tls_max_connections`] | `RECALL_TLS_MAX_CONNECTIONS` | 512 |
111///
112/// `RECALL_TLS_REQUIRED` is read but not stored: when it is true, a
113/// config with [`tls`] off refuses to start ([`ConfigError::TlsRequired`]).
114///
115/// [`addr`]: Config::addr
116/// [`token`]: Config::token
117/// [`db_path`]: Config::db_path
118/// [`git_commit`]: Config::git_commit
119/// [`backup_dir`]: Config::backup_dir
120/// [`backup_interval`]: Config::backup_interval
121/// [`backup_keep`]: Config::backup_keep
122/// [`rate_limit_window`]: Config::rate_limit_window
123/// [`rate_limit_max`]: Config::rate_limit_max
124/// [`trusted_ip_header`]: Config::trusted_ip_header
125/// [`merge_enabled`]: Config::merge_enabled
126/// [`merge_timeout`]: Config::merge_timeout
127/// [`claude_bin`]: Config::claude_bin
128/// [`claude_status_interval`]: Config::claude_status_interval
129/// [`ephemeral_device_ttl`]: Config::ephemeral_device_ttl
130/// [`public_url`]: Config::public_url
131/// [`tls`]: Config::tls
132/// [`tls_max_connections`]: Config::tls_max_connections
133#[derive(Debug, Clone)]
134pub struct Config {
135    /// The socket to bind, assembled from host and port.
136    pub addr: String,
137    /// The single bearer token. There is no second one, by design.
138    pub token: String,
139    /// The SQLite file. Opened, never created from a schema migration — it
140    /// is the same file the Node server wrote.
141    pub db_path: String,
142    /// Reported by `GET /health` so a deploy can be confirmed from outside.
143    /// A release binary knows its own commit, stamped at build time; the
144    /// variable overrides it, for an image built from a checkout.
145    pub git_commit: String,
146
147    /// Where periodic database snapshots go. Empty disables backups.
148    pub backup_dir: String,
149    /// How often to take one.
150    pub backup_interval: Duration,
151    /// How many to keep before deleting the oldest.
152    pub backup_keep: usize,
153
154    /// The window rate limiting counts requests over.
155    pub rate_limit_window: Duration,
156    /// How many requests one client may make in that window.
157    pub rate_limit_max: u32,
158    /// The one request header whose value is taken as the client's address,
159    /// or empty to trust none and use the socket's peer address.
160    ///
161    /// Rate limiting keys off this, and rate limiting runs *before* auth
162    /// precisely so a flood of invalid tokens is limited too — so a client
163    /// that can choose its own value here can rotate it and get unlimited
164    /// attempts at guessing the token.
165    ///
166    /// That makes this a statement about the deployment, not a preference:
167    /// it names the header the *ingress* sets, and it is only safe when
168    /// nothing can reach this server except through that ingress. Exactly
169    /// one header is read, so a value the client supplies under any other
170    /// name is ignored.
171    ///
172    /// | Ingress | Set this to |
173    /// |---|---|
174    /// | Cloudflare Tunnel | `cf-connecting-ip` (the default) |
175    /// | Traefik, nginx, Caddy | `x-real-ip` |
176    /// | None — reached directly | empty |
177    ///
178    /// Deliberately *not* `x-forwarded-for`: a proxy appends to it, so the
179    /// first entry is whatever the client sent. Reading it as one value is
180    /// the classic way to make this setting useless.
181    pub trusted_ip_header: String,
182
183    /// Whether to attempt semantic merge at all. Off means last-write-wins.
184    pub merge_enabled: bool,
185    /// How long a merge may take before it is abandoned — and, like every
186    /// other merge failure, degraded to last-write-wins.
187    pub merge_timeout: Duration,
188    /// The `claude` binary to shell out to. Never the Anthropic API.
189    pub claude_bin: String,
190    /// How often to re-check that the binary is present and logged in.
191    pub claude_status_interval: Duration,
192
193    /// How long an ephemeral device, one a cloud session enrolled with an
194    /// ephemeral authkey, may go without a signed request before it
195    /// is removed.
196    ///
197    /// A day by default. A cloud session left open over lunch, a meeting or
198    /// a night keeps its device; a day's worth of finished sessions does
199    /// not pile up in the device list; and the key a finished session left
200    /// in its container stops working within a day of its last use.
201    pub ephemeral_device_ttl: Duration,
202
203    /// The address people reach this server at, such as
204    /// `https://recall.example.com`: an origin, with no path.
205    ///
206    /// Passkeys are bound to a site, and the server cannot learn which one
207    /// from a request: behind Traefik it sees plain HTTP, and a `Host`
208    /// header is whatever the client sent. So the site is configured. The
209    /// WebAuthn relying party id is its host and the origin a passkey must
210    /// be used from is the whole of it. Empty leaves passkey sign-in on
211    /// `/admin` off, and the page says so; nothing else depends on it.
212    pub public_url: String,
213    /// Whether this server terminates TLS itself. Off by default: the two
214    /// existing deployments (`deploy/docker-compose.yml`,
215    /// `docker-compose.traefik.yml`) put an ingress in front instead, and
216    /// that stays the default. See [`TlsMode`].
217    pub tls: TlsMode,
218    /// How many connections the direct-TLS listener holds open at once,
219    /// counting ones still in their TLS handshake. Ignored with TLS off,
220    /// where the ingress in front owns this problem.
221    ///
222    /// With no ingress, every idle or half-open socket an attacker opens
223    /// costs this process a file descriptor and a task; this bound turns
224    /// "exhaust the process's descriptors" into "fill these slots until
225    /// the timeouts in `server/tls.rs` close them". A single owner's
226    /// machines need a handful; the default leaves generous room below the
227    /// `nofile` limit `docker-compose.direct.yml` sets.
228    pub tls_max_connections: usize,
229}
230
231/// Whether, and how, `recall-server` terminates TLS itself rather than
232/// leaving it to an ingress.
233///
234/// The two modes are mutually exclusive and each requires its own pair of
235/// variables in full; see [`ConfigError::PartialTlsFiles`],
236/// [`ConfigError::PartialTlsAcme`] and [`ConfigError::BothTlsModes`].
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub enum TlsMode {
239    /// Plain HTTP on [`Config::addr`]. An ingress is expected to terminate
240    /// TLS in front of this, per `deploy/README.md`.
241    Off,
242    /// `RECALL_TLS_CERT` + `RECALL_TLS_KEY`: serve HTTPS on
243    /// [`Config::addr`] from a certificate and key already on disk, such as
244    /// one a separate ACME client keeps renewed.
245    Files {
246        /// PEM certificate chain path (`RECALL_TLS_CERT`).
247        cert_path: String,
248        /// PEM private key path (`RECALL_TLS_KEY`).
249        key_path: String,
250    },
251    /// `RECALL_TLS_ACME_DOMAINS` + `RECALL_TLS_ACME_EMAIL`: the server gets
252    /// and renews its own certificate from an ACME directory (Let's
253    /// Encrypt, by default) over TLS-ALPN-01, which needs only the one port
254    /// it is already serving on, port 80 is never touched.
255    Acme {
256        /// The domain names to request a certificate for.
257        domains: Vec<String>,
258        /// The contact address the ACME directory may use for expiry
259        /// notices.
260        email: String,
261        /// Where the issued certificate and account key are cached, so a
262        /// restart does not re-issue one (`RECALL_TLS_ACME_DIR`).
263        cache_dir: String,
264        /// Let's Encrypt's staging directory instead of production
265        /// (`RECALL_TLS_ACME_STAGING`): much higher rate limits while
266        /// testing, at the cost of a certificate no client will trust.
267        staging: bool,
268    },
269}
270
271impl TlsMode {
272    /// Whether the server terminates TLS at all, in either mode.
273    pub fn is_enabled(&self) -> bool {
274        !matches!(self, TlsMode::Off)
275    }
276}
277
278impl Default for Config {
279    fn default() -> Self {
280        Self {
281            addr: "0.0.0.0:8787".to_string(),
282            token: String::new(),
283            db_path: "data/recall.db".to_string(),
284            git_commit: "unknown".to_string(),
285            backup_dir: String::new(),
286            backup_interval: Duration::from_secs(24 * 60 * 60),
287            backup_keep: 7,
288            rate_limit_window: Duration::from_secs(60),
289            rate_limit_max: 60,
290            trusted_ip_header: "cf-connecting-ip".to_string(),
291            merge_enabled: true,
292            merge_timeout: Duration::from_secs(45),
293            claude_bin: "claude".to_string(),
294            claude_status_interval: Duration::from_secs(30 * 60),
295            ephemeral_device_ttl: DEFAULT_EPHEMERAL_DEVICE_TTL,
296            public_url: String::new(),
297            tls: TlsMode::Off,
298            tls_max_connections: DEFAULT_TLS_MAX_CONNECTIONS,
299        }
300    }
301}
302
303const DEFAULT_EPHEMERAL_DEVICE_TTL: Duration = Duration::from_secs(24 * 60 * 60);
304
305/// See [`Config::tls_max_connections`].
306const DEFAULT_TLS_MAX_CONNECTIONS: usize = 512;
307
308/// Reads a yes/no variable: unset or empty is `false`; `true`/`1`/`yes`
309/// and `false`/`0`/`no` in any case are what they say; anything else is
310/// refused rather than guessed (see [`ConfigError::InvalidFlag`]).
311fn flag<F>(lookup: &F, var: &'static str) -> Result<bool, ConfigError>
312where
313    F: Fn(&str) -> Option<String>,
314{
315    let Some(raw) = lookup(var) else {
316        return Ok(false);
317    };
318    match raw.trim().to_ascii_lowercase().as_str() {
319        "" | "false" | "0" | "no" => Ok(false),
320        "true" | "1" | "yes" => Ok(true),
321        _ => Err(ConfigError::InvalidFlag { var, value: raw }),
322    }
323}
324
325impl Config {
326    /// Reads configuration from the real process environment.
327    pub fn from_env() -> Result<Self, ConfigError> {
328        Self::from_lookup(|key| env::var(key).ok())
329    }
330
331    /// Reads configuration through a caller-supplied lookup, applying the
332    /// same defaults the Node implementation used.
333    ///
334    /// The lookup is injected rather than read from `std::env` inside so the
335    /// clamping below is testable: `set_var` is process-global, and Rust runs
336    /// tests in parallel threads, so an env-reading test races every other
337    /// test in the binary.
338    ///
339    /// An unparseable value falls back rather than failing the boot, matching
340    /// the Node and Go implementations — a typo in one tunable should not be
341    /// the reason a server won't start.
342    pub fn from_lookup<F>(lookup: F) -> Result<Self, ConfigError>
343    where
344        F: Fn(&str) -> Option<String>,
345    {
346        let get = |key: &str| lookup(key).filter(|v| !v.is_empty());
347        let or = |key: &str, fallback: &str| get(key).unwrap_or_else(|| fallback.to_string());
348        let num =
349            |key: &str, fallback: u64| get(key).and_then(|v| v.parse().ok()).unwrap_or(fallback);
350
351        let files_tls = match (get("RECALL_TLS_CERT"), get("RECALL_TLS_KEY")) {
352            (Some(cert_path), Some(key_path)) => Some(TlsMode::Files {
353                cert_path,
354                key_path,
355            }),
356            (None, None) => None,
357            _ => return Err(ConfigError::PartialTlsFiles),
358        };
359        let acme_tls = match (get("RECALL_TLS_ACME_DOMAINS"), get("RECALL_TLS_ACME_EMAIL")) {
360            (Some(domains), Some(email)) => {
361                let domains: Vec<String> = domains
362                    .split(',')
363                    .map(str::trim)
364                    .filter(|d| !d.is_empty())
365                    .map(str::to_string)
366                    .collect();
367                if domains.is_empty() {
368                    return Err(ConfigError::NoAcmeDomains);
369                }
370                if let Some(wildcard) = domains.iter().find(|d| d.contains('*')) {
371                    return Err(ConfigError::WildcardAcmeDomain(wildcard.clone()));
372                }
373                Some(TlsMode::Acme {
374                    domains,
375                    email,
376                    cache_dir: or("RECALL_TLS_ACME_DIR", "/data/acme"),
377                    // A typo here used to mean production, silently; now
378                    // it refuses to start instead, since "I asked for
379                    // staging and burned the production rate limit" and
380                    // "I asked for production and got an untrusted
381                    // certificate" are both worse than a clear error.
382                    staging: flag(&lookup, "RECALL_TLS_ACME_STAGING")?,
383                })
384            }
385            (None, None) => None,
386            _ => return Err(ConfigError::PartialTlsAcme),
387        };
388        let tls = match (files_tls, acme_tls) {
389            (Some(_), Some(_)) => return Err(ConfigError::BothTlsModes),
390            (Some(mode), None) | (None, Some(mode)) => mode,
391            (None, None) => TlsMode::Off,
392        };
393        // With direct TLS there is no ingress, so the setting that protects
394        // the rate limiter behind one is not just unnecessary but actively
395        // dangerous here: reading it at all would let a direct client pick
396        // its own rate-limit bucket by supplying whatever header it names.
397        // Refusing to start beats silently ignoring a value left over from
398        // moving a deployment from behind an ingress to direct TLS.
399        // An explicitly empty value is allowed: it says "trust no header",
400        // which is what TLS forces anyway, and it is what lets the direct
401        // compose file pin the header off even if it ever came up without
402        // TLS.
403        if tls.is_enabled()
404            && lookup("RECALL_TRUSTED_IP_HEADER").is_some_and(|v| !v.trim().is_empty())
405        {
406            return Err(ConfigError::TrustedIpHeaderWithTls);
407        }
408        if !tls.is_enabled() && flag(&lookup, "RECALL_TLS_REQUIRED")? {
409            return Err(ConfigError::TlsRequired);
410        }
411
412        let mut cfg = Config {
413            addr: format!("0.0.0.0:{}", or("RECALL_PORT", "8787")),
414            token: get("RECALL_TOKEN").unwrap_or_default(),
415            db_path: or("RECALL_DB_PATH", "data/recall.db"),
416            git_commit: or(
417                "RECALL_GIT_COMMIT",
418                option_env!("RECALL_GIT_COMMIT").unwrap_or("unknown"),
419            ),
420            backup_dir: get("RECALL_BACKUP_DIR").unwrap_or_default(),
421            backup_interval: Duration::from_secs(
422                num("RECALL_BACKUP_INTERVAL_HOURS", 24).saturating_mul(3600),
423            ),
424            backup_keep: num("RECALL_BACKUP_KEEP", 7) as usize,
425            rate_limit_window: Duration::from_millis(num("RECALL_RATE_LIMIT_WINDOW_MS", 60_000)),
426            rate_limit_max: num("RECALL_RATE_LIMIT_MAX", 60) as u32,
427            // Lowercased because HeaderMap lookups are case-insensitive but
428            // this is compared as a plain string. Forced empty under TLS
429            // regardless of this default: the check above already refused
430            // to start if the variable named a header, and with no ingress
431            // in front, no header is safe to trust at all.
432            trusted_ip_header: if tls.is_enabled() {
433                String::new()
434            } else {
435                lookup("RECALL_TRUSTED_IP_HEADER")
436                    .map(|v| v.trim().to_ascii_lowercase())
437                    .unwrap_or_else(|| "cf-connecting-ip".to_string())
438            },
439            // Opt-out, not opt-in: only the literal "false" disables it, so a
440            // typo leaves merge on rather than silently off.
441            merge_enabled: lookup("RECALL_MERGE_ENABLED").as_deref() != Some("false"),
442            merge_timeout: Duration::from_millis(num("RECALL_MERGE_TIMEOUT_MS", 45_000)),
443            claude_bin: or("RECALL_CLAUDE_BIN", "claude"),
444            claude_status_interval: Duration::from_millis(num(
445                "RECALL_CLAUDE_STATUS_INTERVAL_MS",
446                30 * 60_000,
447            )),
448            ephemeral_device_ttl: Duration::from_secs(
449                num("RECALL_EPHEMERAL_DEVICE_TTL_HOURS", 24).saturating_mul(3600),
450            ),
451            // Checked when the server starts, not here: a bad value turns
452            // passkey sign-in off with the reason on the page, rather than
453            // keeping a server that syncs fine from starting.
454            public_url: get("RECALL_PUBLIC_URL")
455                .map(|v| v.trim().to_string())
456                .unwrap_or_default(),
457            tls,
458            tls_max_connections: num(
459                "RECALL_TLS_MAX_CONNECTIONS",
460                DEFAULT_TLS_MAX_CONNECTIONS as u64,
461            ) as usize,
462        };
463        if cfg.token.is_empty() {
464            return Err(ConfigError::MissingToken);
465        }
466        // A zero interval would spin a background loop as fast as the
467        // scheduler allows.
468        if cfg.backup_interval.is_zero() {
469            cfg.backup_interval = Duration::from_secs(24 * 60 * 60);
470        }
471        if cfg.rate_limit_window.is_zero() {
472            cfg.rate_limit_window = Duration::from_secs(60);
473        }
474        if cfg.claude_status_interval.is_zero() {
475            cfg.claude_status_interval = Duration::from_secs(30 * 60);
476        }
477        // Zero would remove every ephemeral device at the next sweep,
478        // including the one whose session is running now.
479        if cfg.ephemeral_device_ttl.is_zero() {
480            cfg.ephemeral_device_ttl = DEFAULT_EPHEMERAL_DEVICE_TTL;
481        }
482        // A zero timeout is worse than a spinning loop: every merge would
483        // hit an already-expired deadline and fail instantly, silently
484        // degrading to last-write-wins with nothing in the logs that points
485        // at the typo responsible.
486        if cfg.merge_timeout.is_zero() {
487            cfg.merge_timeout = Duration::from_millis(45_000);
488        }
489        // Zero connections would refuse every client, the TLS-mode
490        // equivalent of an expired merge timeout.
491        if cfg.tls_max_connections == 0 {
492            cfg.tls_max_connections = DEFAULT_TLS_MAX_CONNECTIONS;
493        }
494        Ok(cfg)
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501
502    fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
503        move |key| {
504            pairs
505                .iter()
506                .find(|(k, _)| *k == key)
507                .map(|(_, v)| (*v).to_string())
508        }
509    }
510
511    #[test]
512    fn defaults_match_the_node_implementation() {
513        let cfg = Config::default();
514        assert_eq!(cfg.rate_limit_max, 60);
515        assert_eq!(cfg.rate_limit_window, Duration::from_secs(60));
516        assert_eq!(cfg.merge_timeout, Duration::from_secs(45));
517        assert_eq!(cfg.backup_keep, 7);
518        assert!(cfg.merge_enabled);
519        assert_eq!(cfg.claude_bin, "claude");
520    }
521
522    #[test]
523    fn refuses_to_start_without_a_token() {
524        assert!(
525            matches!(
526                Config::from_lookup(env(&[])),
527                Err(ConfigError::MissingToken)
528            ),
529            "a server reachable from the internet with no auth is not a degraded mode worth supporting"
530        );
531        // Set-but-empty is not set. Go's os.Getenv couldn't tell the two
532        // apart; here it would otherwise boot with a token of "".
533        assert!(matches!(
534            Config::from_lookup(env(&[("RECALL_TOKEN", "")])),
535            Err(ConfigError::MissingToken)
536        ));
537    }
538
539    #[test]
540    fn reads_every_override() {
541        let cfg = Config::from_lookup(env(&[
542            ("RECALL_TOKEN", "t"),
543            ("RECALL_PORT", "9000"),
544            ("RECALL_DB_PATH", "/data/x.db"),
545            ("RECALL_GIT_COMMIT", "abc1234"),
546            ("RECALL_BACKUP_DIR", "/backups"),
547            ("RECALL_BACKUP_INTERVAL_HOURS", "6"),
548            ("RECALL_BACKUP_KEEP", "3"),
549            ("RECALL_RATE_LIMIT_WINDOW_MS", "1000"),
550            ("RECALL_RATE_LIMIT_MAX", "5"),
551            ("RECALL_MERGE_TIMEOUT_MS", "1234"),
552            ("RECALL_CLAUDE_BIN", "/usr/bin/claude"),
553            ("RECALL_CLAUDE_STATUS_INTERVAL_MS", "60000"),
554            ("RECALL_EPHEMERAL_DEVICE_TTL_HOURS", "2"),
555            ("RECALL_PUBLIC_URL", " https://recall.example.com "),
556        ]))
557        .unwrap();
558
559        assert_eq!(cfg.addr, "0.0.0.0:9000");
560        assert_eq!(cfg.db_path, "/data/x.db");
561        assert_eq!(cfg.git_commit, "abc1234");
562        assert_eq!(cfg.backup_dir, "/backups");
563        assert_eq!(cfg.backup_interval, Duration::from_secs(6 * 3600));
564        assert_eq!(cfg.backup_keep, 3);
565        assert_eq!(cfg.rate_limit_window, Duration::from_millis(1000));
566        assert_eq!(cfg.rate_limit_max, 5);
567        assert_eq!(cfg.merge_timeout, Duration::from_millis(1234));
568        assert_eq!(cfg.claude_bin, "/usr/bin/claude");
569        assert_eq!(cfg.claude_status_interval, Duration::from_millis(60_000));
570        assert_eq!(cfg.ephemeral_device_ttl, Duration::from_secs(2 * 3600));
571        assert_eq!(cfg.public_url, "https://recall.example.com");
572    }
573
574    #[test]
575    fn merge_is_disabled_only_by_the_literal_false() {
576        for (value, want) in [("false", false), ("true", true), ("0", true), ("", true)] {
577            let cfg = Config::from_lookup(env(&[
578                ("RECALL_TOKEN", "t"),
579                ("RECALL_MERGE_ENABLED", value),
580            ]))
581            .unwrap();
582            assert_eq!(cfg.merge_enabled, want, "RECALL_MERGE_ENABLED={value:?}");
583        }
584    }
585
586    /// Every duration is clamped, not just the ones whose failure is loud.
587    ///
588    /// The Go implementation clamped only two of the four. A zero
589    /// `CLAUDE_STATUS_INTERVAL` reached `time.NewTicker`, which panics on a
590    /// non-positive duration — one config typo crashing the server at
591    /// startup. A zero `MERGE_TIMEOUT` is quieter and worse: every merge
592    /// hits an already-expired deadline and fails instantly, silently
593    /// degrading to last-write-wins with nothing pointing at the cause.
594    #[test]
595    fn zero_and_unparseable_durations_fall_back_to_their_defaults() {
596        for value in ["0", "not-a-number", "-5", " 6"] {
597            let cfg = Config::from_lookup(env(&[
598                ("RECALL_TOKEN", "t"),
599                ("RECALL_BACKUP_INTERVAL_HOURS", value),
600                ("RECALL_RATE_LIMIT_WINDOW_MS", value),
601                ("RECALL_CLAUDE_STATUS_INTERVAL_MS", value),
602                ("RECALL_MERGE_TIMEOUT_MS", value),
603                ("RECALL_EPHEMERAL_DEVICE_TTL_HOURS", value),
604            ]))
605            .unwrap();
606
607            assert_eq!(
608                cfg.ephemeral_device_ttl,
609                Duration::from_secs(24 * 3600),
610                "{value:?}"
611            );
612
613            assert_eq!(
614                cfg.backup_interval,
615                Duration::from_secs(24 * 3600),
616                "{value:?}"
617            );
618            assert_eq!(cfg.rate_limit_window, Duration::from_secs(60), "{value:?}");
619            assert_eq!(
620                cfg.claude_status_interval,
621                Duration::from_secs(30 * 60),
622                "{value:?}"
623            );
624            assert_eq!(
625                cfg.merge_timeout,
626                Duration::from_millis(45_000),
627                "{value:?}"
628            );
629            assert!(
630                !cfg.merge_timeout.is_zero(),
631                "a zero merge timeout fails every merge instantly and silently"
632            );
633        }
634    }
635
636    #[test]
637    fn tls_is_off_by_default() {
638        assert_eq!(Config::default().tls, TlsMode::Off);
639        let cfg = Config::from_lookup(env(&[("RECALL_TOKEN", "t")])).unwrap();
640        assert_eq!(cfg.tls, TlsMode::Off);
641        assert_eq!(cfg.trusted_ip_header, "cf-connecting-ip");
642    }
643
644    #[test]
645    fn tls_files_mode_needs_both_variables() {
646        for pairs in [
647            &[("RECALL_TOKEN", "t"), ("RECALL_TLS_CERT", "/c.pem")][..],
648            &[("RECALL_TOKEN", "t"), ("RECALL_TLS_KEY", "/k.pem")][..],
649        ] {
650            assert!(
651                matches!(
652                    Config::from_lookup(env(pairs)),
653                    Err(ConfigError::PartialTlsFiles)
654                ),
655                "{pairs:?}"
656            );
657        }
658
659        let cfg = Config::from_lookup(env(&[
660            ("RECALL_TOKEN", "t"),
661            ("RECALL_TLS_CERT", "/c.pem"),
662            ("RECALL_TLS_KEY", "/k.pem"),
663        ]))
664        .unwrap();
665        assert_eq!(
666            cfg.tls,
667            TlsMode::Files {
668                cert_path: "/c.pem".to_string(),
669                key_path: "/k.pem".to_string(),
670            }
671        );
672    }
673
674    #[test]
675    fn tls_acme_mode_needs_both_variables_and_splits_domains() {
676        for pairs in [
677            &[
678                ("RECALL_TOKEN", "t"),
679                ("RECALL_TLS_ACME_DOMAINS", "example.com"),
680            ][..],
681            &[
682                ("RECALL_TOKEN", "t"),
683                ("RECALL_TLS_ACME_EMAIL", "me@example.com"),
684            ][..],
685        ] {
686            assert!(
687                matches!(
688                    Config::from_lookup(env(pairs)),
689                    Err(ConfigError::PartialTlsAcme)
690                ),
691                "{pairs:?}"
692            );
693        }
694
695        let cfg = Config::from_lookup(env(&[
696            ("RECALL_TOKEN", "t"),
697            ("RECALL_TLS_ACME_DOMAINS", " a.example.com, b.example.com ,"),
698            ("RECALL_TLS_ACME_EMAIL", "me@example.com"),
699        ]))
700        .unwrap();
701        assert_eq!(
702            cfg.tls,
703            TlsMode::Acme {
704                domains: vec!["a.example.com".to_string(), "b.example.com".to_string()],
705                email: "me@example.com".to_string(),
706                cache_dir: "/data/acme".to_string(),
707                staging: false,
708            }
709        );
710    }
711
712    #[test]
713    fn tls_acme_staging_and_cache_dir_are_overridable() {
714        let cfg = Config::from_lookup(env(&[
715            ("RECALL_TOKEN", "t"),
716            ("RECALL_TLS_ACME_DOMAINS", "example.com"),
717            ("RECALL_TLS_ACME_EMAIL", "me@example.com"),
718            ("RECALL_TLS_ACME_DIR", "/tmp/acme-cache"),
719            ("RECALL_TLS_ACME_STAGING", "true"),
720        ]))
721        .unwrap();
722        let TlsMode::Acme {
723            cache_dir, staging, ..
724        } = cfg.tls
725        else {
726            panic!("expected TlsMode::Acme, got {:?}", cfg.tls);
727        };
728        assert_eq!(cache_dir, "/tmp/acme-cache");
729        assert!(staging);
730    }
731
732    #[test]
733    fn configuring_both_tls_modes_is_refused() {
734        assert!(matches!(
735            Config::from_lookup(env(&[
736                ("RECALL_TOKEN", "t"),
737                ("RECALL_TLS_CERT", "/c.pem"),
738                ("RECALL_TLS_KEY", "/k.pem"),
739                ("RECALL_TLS_ACME_DOMAINS", "example.com"),
740                ("RECALL_TLS_ACME_EMAIL", "me@example.com"),
741            ])),
742            Err(ConfigError::BothTlsModes)
743        ));
744    }
745
746    /// The mandatory security rule: behind an ingress the trusted header is
747    /// how the rate limiter learns the real client address, but direct TLS
748    /// has no ingress to set it, so a client that could still choose the
749    /// value would buy itself unlimited token guesses. Naming a header
750    /// alongside TLS is refused outright, matching
751    /// `scripts/tls-trusted-ip-check.sh`'s socket-level proof of the same
752    /// rule.
753    #[test]
754    fn trusted_ip_header_with_tls_refuses_to_start() {
755        for tls_pairs in [
756            &[("RECALL_TLS_CERT", "/c.pem"), ("RECALL_TLS_KEY", "/k.pem")][..],
757            &[
758                ("RECALL_TLS_ACME_DOMAINS", "example.com"),
759                ("RECALL_TLS_ACME_EMAIL", "me@example.com"),
760            ][..],
761        ] {
762            let mut pairs = vec![("RECALL_TOKEN", "t")];
763            pairs.extend_from_slice(tls_pairs);
764
765            for header_value in ["x-real-ip", "cf-connecting-ip", " X-Real-IP "] {
766                let mut pairs = pairs.clone();
767                pairs.push(("RECALL_TRUSTED_IP_HEADER", header_value));
768                assert!(
769                    matches!(
770                        Config::from_lookup(env(&pairs)),
771                        Err(ConfigError::TrustedIpHeaderWithTls)
772                    ),
773                    "{pairs:?}"
774                );
775            }
776
777            // Unset, or explicitly empty (what docker-compose.direct.yml
778            // sets, as a second guard should TLS ever be missing), are the
779            // only values allowed, and both force the empty string, not the
780            // plain-HTTP default of cf-connecting-ip.
781            for header in [None, Some(""), Some("  ")] {
782                let mut pairs = pairs.clone();
783                if let Some(value) = header {
784                    pairs.push(("RECALL_TRUSTED_IP_HEADER", value));
785                }
786                let cfg = Config::from_lookup(env(&pairs)).unwrap();
787                assert_eq!(cfg.trusted_ip_header, "", "{pairs:?}");
788            }
789        }
790    }
791
792    /// The direct compose file's fail-closed switch: with
793    /// `RECALL_TLS_REQUIRED` on, a config whose TLS variables are missing
794    /// or empty refuses to start instead of coming up as plain HTTP with
795    /// the port published to the internet.
796    #[test]
797    fn tls_required_without_tls_refuses_to_start() {
798        for required in ["true", "TRUE", "1", "yes", "Yes"] {
799            for tls_pairs in [
800                &[][..],
801                // Empty is unset, so this is still no TLS at all.
802                &[("RECALL_TLS_CERT", ""), ("RECALL_TLS_KEY", "")][..],
803                &[
804                    ("RECALL_TLS_ACME_DOMAINS", ""),
805                    ("RECALL_TLS_ACME_EMAIL", ""),
806                ][..],
807            ] {
808                let mut pairs = vec![("RECALL_TOKEN", "t"), ("RECALL_TLS_REQUIRED", required)];
809                pairs.extend_from_slice(tls_pairs);
810                assert!(
811                    matches!(
812                        Config::from_lookup(env(&pairs)),
813                        Err(ConfigError::TlsRequired)
814                    ),
815                    "{pairs:?}"
816                );
817            }
818        }
819
820        // With TLS configured it starts, and off or unset it changes
821        // nothing about plain HTTP.
822        let cfg = Config::from_lookup(env(&[
823            ("RECALL_TOKEN", "t"),
824            ("RECALL_TLS_REQUIRED", "true"),
825            ("RECALL_TLS_CERT", "/c.pem"),
826            ("RECALL_TLS_KEY", "/k.pem"),
827        ]))
828        .unwrap();
829        assert!(cfg.tls.is_enabled());
830        for off in ["", "false", "0", "no", "NO"] {
831            let cfg =
832                Config::from_lookup(env(&[("RECALL_TOKEN", "t"), ("RECALL_TLS_REQUIRED", off)]))
833                    .unwrap();
834            assert_eq!(cfg.tls, TlsMode::Off, "{off:?}");
835        }
836
837        // A typo is refused rather than read as "not required".
838        assert!(matches!(
839            Config::from_lookup(env(&[
840                ("RECALL_TOKEN", "t"),
841                ("RECALL_TLS_REQUIRED", "ture"),
842            ])),
843            Err(ConfigError::InvalidFlag {
844                var: "RECALL_TLS_REQUIRED",
845                ..
846            })
847        ));
848    }
849
850    #[test]
851    fn tls_acme_refuses_an_empty_domain_list_and_wildcards() {
852        for domains in [",", " , ,", " "] {
853            let result = Config::from_lookup(env(&[
854                ("RECALL_TOKEN", "t"),
855                ("RECALL_TLS_ACME_DOMAINS", domains),
856                ("RECALL_TLS_ACME_EMAIL", "me@example.com"),
857            ]));
858            assert!(
859                matches!(result, Err(ConfigError::NoAcmeDomains)),
860                "{domains:?}: {result:?}"
861            );
862        }
863        for domains in ["*.example.com", "example.com, *.example.com"] {
864            let result = Config::from_lookup(env(&[
865                ("RECALL_TOKEN", "t"),
866                ("RECALL_TLS_ACME_DOMAINS", domains),
867                ("RECALL_TLS_ACME_EMAIL", "me@example.com"),
868            ]));
869            assert!(
870                matches!(&result, Err(ConfigError::WildcardAcmeDomain(d)) if d == "*.example.com"),
871                "{domains:?}: {result:?}"
872            );
873        }
874    }
875
876    /// Staging used to be on only for the literal `true`, so `TRUE` or
877    /// `1` silently meant production. Now every common spelling of yes
878    /// works, and anything unrecognised refuses to start.
879    #[test]
880    fn tls_acme_staging_accepts_common_spellings_and_refuses_the_rest() {
881        let acme = |staging: &'static str| {
882            Config::from_lookup(env(&[
883                ("RECALL_TOKEN", "t"),
884                ("RECALL_TLS_ACME_DOMAINS", "example.com"),
885                ("RECALL_TLS_ACME_EMAIL", "me@example.com"),
886                ("RECALL_TLS_ACME_STAGING", staging),
887            ]))
888        };
889        for (value, want) in [
890            ("true", true),
891            ("TRUE", true),
892            ("1", true),
893            ("yes", true),
894            ("false", false),
895            ("0", false),
896            ("No", false),
897            ("", false),
898        ] {
899            let TlsMode::Acme { staging, .. } = acme(value).unwrap().tls else {
900                panic!("expected TlsMode::Acme");
901            };
902            assert_eq!(staging, want, "RECALL_TLS_ACME_STAGING={value:?}");
903        }
904        for value in ["staging", "ture", "on?"] {
905            assert!(
906                matches!(
907                    acme(value),
908                    Err(ConfigError::InvalidFlag {
909                        var: "RECALL_TLS_ACME_STAGING",
910                        ..
911                    })
912                ),
913                "{value:?}"
914            );
915        }
916    }
917
918    #[test]
919    fn tls_max_connections_falls_back_to_its_default() {
920        let read = |value: &'static str| {
921            Config::from_lookup(env(&[
922                ("RECALL_TOKEN", "t"),
923                ("RECALL_TLS_MAX_CONNECTIONS", value),
924            ]))
925            .unwrap()
926            .tls_max_connections
927        };
928        assert_eq!(Config::default().tls_max_connections, 512);
929        assert_eq!(read("64"), 64);
930        for fallback in ["0", "", "lots", "-1"] {
931            assert_eq!(read(fallback), 512, "{fallback:?}");
932        }
933    }
934}