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