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