Skip to main content

teamcraft/
localserver.rs

1//! `teamcraft local`: a test installation on one computer, for trying
2//! TeamCraft out without Docker or a database administrator. It runs a
3//! private PostgreSQL cluster and the server, both only on `127.0.0.1`, with
4//! every file in one data directory:
5//!
6//! ```text
7//! <data dir>/postgres/        the cluster (initdb on the first start)
8//! <data dir>/postgres.log     PostgreSQL's log
9//! <data dir>/db-password      the generated database password (0600)
10//! <data dir>/vault/           the file vault
11//! ```
12//!
13//! The PostgreSQL programs come from the release bundle (`postgresql/bin`
14//! next to the executable, as the desktop app's *with local server*
15//! installers ship it), from `--pg-bin`, or from an installation on this
16//! computer. The cluster gets its own free port and no Unix socket; it uses
17//! scram-sha-256 with a random password, so other accounts on the computer
18//! cannot connect. The desktop app starts this command for *Try TeamCraft on
19//! this computer* (`desktop/src/localserver.rs`). Never for production:
20//! one user's laptop, no backups, no TLS.
21
22use std::{
23    collections::BTreeMap,
24    ffi::OsStr,
25    path::{Path, PathBuf},
26    process::Output,
27};
28
29use anyhow::{bail, Context, Result};
30use rand::{rngs::OsRng, RngCore};
31use sqlx::{
32    postgres::{PgConnectOptions, PgSslMode},
33    ConnectOptions, Connection,
34};
35
36/// Database role and database of the local installation.
37pub const DB_USER: &str = "teamcraft";
38pub const DB_NAME: &str = "teamcraft";
39
40/// The name of this binary in the desktop downloads *with local server*
41/// (`teamcraft-server[.exe]` next to the app; `desktop/src/localserver.rs`).
42pub const SIDECAR_NAME: &str = "teamcraft-server";
43
44/// HTTP port when none is given (the port of every other quick start).
45pub const DEFAULT_PORT: u16 = 8080;
46
47/// The directory the release bundles put the PostgreSQL programs in, next to
48/// the `teamcraft` executable (`postgresql/bin/initdb`, …).
49pub const BUNDLED_PG_DIR: &str = "postgresql";
50
51/// How long `pg_ctl` may take to start or stop the cluster, in seconds.
52const PG_CTL_TIMEOUT_SECS: u32 = 120;
53
54/// Line added to `postgresql.conf` after initdb: the settings of each start
55/// (port, listen address) are written to this file.
56const INCLUDE_LINE: &str = "include_if_exists = 'teamcraft-local.conf'";
57const LOCAL_CONF: &str = "teamcraft-local.conf";
58
59fn exe(name: &str) -> String {
60    if cfg!(windows) {
61        format!("{name}.exe")
62    } else {
63        name.to_string()
64    }
65}
66
67/// Where the data lives when no `--data-dir` is given: the per-user data
68/// directory of the operating system, so that the desktop app and the
69/// command line share one installation.
70///
71/// * Linux: `$XDG_DATA_HOME/teamcraft/local-server` (`~/.local/share/…`)
72/// * macOS: `~/Library/Application Support/TeamCraft/local-server`
73/// * Windows: `%LOCALAPPDATA%\TeamCraft\local-server`
74pub fn default_data_dir() -> Option<PathBuf> {
75    data_dir_from(|key| std::env::var_os(key).map(PathBuf::from))
76}
77
78fn data_dir_from(var: impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
79    let set = |key: &str| var(key).filter(|p| !p.as_os_str().is_empty());
80    if cfg!(windows) {
81        return set("LOCALAPPDATA").map(|d| d.join("TeamCraft").join("local-server"));
82    }
83    let home = set("HOME");
84    if cfg!(target_os = "macos") {
85        return home.map(|h| {
86            h.join("Library")
87                .join("Application Support")
88                .join("TeamCraft")
89                .join("local-server")
90        });
91    }
92    set("XDG_DATA_HOME")
93        .filter(|p| p.is_absolute())
94        .or_else(|| home.map(|h| h.join(".local").join("share")))
95        .map(|d| d.join("teamcraft").join("local-server"))
96}
97
98/// Whether `dir` holds the programs `teamcraft local` runs.
99pub fn is_pg_bin(dir: &Path) -> bool {
100    ["initdb", "pg_ctl", "postgres"]
101        .iter()
102        .all(|name| dir.join(exe(name)).is_file())
103}
104
105/// The directories searched for the PostgreSQL programs, in order:
106/// `--pg-bin`; the bundle next to the executable (and in the macOS app's
107/// `Resources`); `PATH`; the usual installation directories (Debian/Ubuntu
108/// `/usr/lib/postgresql/<n>/bin`, Homebrew, Postgres.app, the Windows
109/// installer), newest version first.
110pub fn pg_bin_candidates(explicit: Option<&Path>, exe_dir: Option<&Path>) -> Vec<PathBuf> {
111    let mut out = Vec::new();
112    if let Some(dir) = explicit {
113        out.push(dir.to_path_buf());
114        // only the given directory: a wrong --pg-bin must not fall back silently
115        return out;
116    }
117    if let Some(dir) = exe_dir {
118        out.push(dir.join(BUNDLED_PG_DIR).join("bin"));
119        // macOS app bundle: Contents/MacOS/teamcraft, Contents/Resources/postgresql
120        out.push(
121            dir.join("..")
122                .join("Resources")
123                .join(BUNDLED_PG_DIR)
124                .join("bin"),
125        );
126        // Linux packages and the AppImage: usr/bin/teamcraft, usr/lib/<app>/postgresql
127        for app in ["teamcraft", "TeamCraft", "TeamCraft Local"] {
128            out.push(
129                dir.join("..")
130                    .join("lib")
131                    .join(app)
132                    .join(BUNDLED_PG_DIR)
133                    .join("bin"),
134            );
135        }
136    }
137    if let Some(path) = std::env::var_os("PATH") {
138        out.extend(std::env::split_paths(&path));
139    }
140    let versioned = |parent: &Path, prefix: &str, suffix: &[&str]| -> Vec<PathBuf> {
141        let Ok(entries) = std::fs::read_dir(parent) else {
142            return Vec::new();
143        };
144        let mut found: Vec<(u32, PathBuf)> = entries
145            .flatten()
146            .filter_map(|e| {
147                let name = e.file_name().to_string_lossy().to_string();
148                let version = name.strip_prefix(prefix)?.parse::<u32>().ok()?;
149                let mut path = e.path();
150                for part in suffix {
151                    path.push(part);
152                }
153                Some((version, path))
154            })
155            .collect();
156        found.sort_by_key(|(version, _)| std::cmp::Reverse(*version));
157        found.into_iter().map(|(_, p)| p).collect()
158    };
159    if cfg!(windows) {
160        for root in ["ProgramFiles", "ProgramW6432"] {
161            if let Some(pf) = std::env::var_os(root) {
162                out.extend(versioned(
163                    &PathBuf::from(pf).join("PostgreSQL"),
164                    "",
165                    &["bin"],
166                ));
167            }
168        }
169    } else {
170        out.extend(versioned(Path::new("/usr/lib/postgresql"), "", &["bin"]));
171        for brew in ["/opt/homebrew/opt", "/usr/local/opt"] {
172            out.extend(versioned(Path::new(brew), "postgresql@", &["bin"]));
173        }
174        out.push(PathBuf::from(
175            "/Applications/Postgres.app/Contents/Versions/latest/bin",
176        ));
177    }
178    out
179}
180
181/// The first candidate that holds `initdb`, `pg_ctl` and `postgres`.
182pub fn find_pg_bin(explicit: Option<&Path>) -> Result<PathBuf> {
183    let explicit = explicit.map(without_verbatim_prefix);
184    let exe_dir = std::env::current_exe()
185        .ok()
186        .and_then(|p| p.parent().map(without_verbatim_prefix));
187    let candidates = pg_bin_candidates(explicit.as_deref(), exe_dir.as_deref());
188    if let Some(found) = candidates.iter().find(|d| is_pg_bin(d)) {
189        return Ok(found.clone());
190    }
191    match explicit {
192        Some(dir) => bail!(
193            "{} does not contain initdb, pg_ctl and postgres",
194            dir.display()
195        ),
196        None => bail!(
197            "PostgreSQL was not found: no {BUNDLED_PG_DIR}/bin next to teamcraft, none on PATH \
198             or in the usual installation directories. Install PostgreSQL (16 or newer), \
199             or give its bin directory with --pg-bin"
200        ),
201    }
202}
203
204/// `\\?\C:\dir` → `C:\dir` and `\\?\UNC\server\share` → `\\server\share`;
205/// every other path unchanged. Windows hands out such "verbatim" paths (the
206/// desktop app's resource folder from Tauri, canonicalised paths), and
207/// PostgreSQL cannot use them: `initdb` looks for `postgres.exe` under
208/// `//?/C:/…` and fails with "The system cannot find the path specified".
209/// Pure string handling, so it is tested on every platform.
210pub fn without_verbatim_prefix(path: &Path) -> PathBuf {
211    let Some(s) = path.to_str() else {
212        return path.to_path_buf();
213    };
214    if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
215        return PathBuf::from(format!(r"\\{rest}"));
216    }
217    match s.strip_prefix(r"\\?\") {
218        // only a drive path (`C:\…`); other verbatim forms stay as they are
219        Some(rest)
220            if rest.len() >= 3
221                && rest.as_bytes()[0].is_ascii_alphabetic()
222                && &rest[1..3] == r":\" =>
223        {
224            PathBuf::from(rest)
225        }
226        _ => path.to_path_buf(),
227    }
228}
229
230/// A free TCP port on 127.0.0.1 (asked from the operating system).
231pub fn free_port() -> Result<u16> {
232    let listener = std::net::TcpListener::bind(("127.0.0.1", 0))
233        .context("cannot find a free port on 127.0.0.1")?;
234    Ok(listener.local_addr()?.port())
235}
236
237/// 32 random alphanumeric characters (about 190 bits).
238fn random_password() -> String {
239    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
240    let mut bytes = [0u8; 32];
241    OsRng.fill_bytes(&mut bytes);
242    bytes
243        .iter()
244        .map(|b| ALPHABET[(*b as usize) % ALPHABET.len()] as char)
245        .collect()
246}
247
248/// Writes a file only the owner can read (0600 on Unix).
249fn write_private(path: &Path, content: &str) -> Result<()> {
250    let mut options = std::fs::OpenOptions::new();
251    options.write(true).create(true).truncate(true);
252    #[cfg(unix)]
253    {
254        use std::os::unix::fs::OpenOptionsExt;
255        options.mode(0o600);
256    }
257    let mut file = options
258        .open(path)
259        .with_context(|| format!("cannot write {}", path.display()))?;
260    std::io::Write::write_all(&mut file, content.as_bytes())
261        .with_context(|| format!("cannot write {}", path.display()))?;
262    Ok(())
263}
264
265/// The settings of one start, written to `teamcraft-local.conf` in the
266/// cluster: only 127.0.0.1, the given port, no Unix socket (nothing in /tmp,
267/// no socket directory that would need root).
268pub fn local_conf(port: u16) -> String {
269    format!(
270        "# written by `teamcraft local` at every start – changes are overwritten\n\
271         listen_addresses = '127.0.0.1'\n\
272         port = {port}\n\
273         unix_socket_directories = ''\n"
274    )
275}
276
277/// The configuration variables of the local installation. They replace the
278/// same variables (and their `_FILE` forms) from the environment; see
279/// [`overlay_lookup`].
280pub fn local_variables(
281    data_dir: &Path,
282    http_port: u16,
283    db_port: u16,
284    password: &str,
285) -> BTreeMap<&'static str, String> {
286    BTreeMap::from([
287        ("TEAMCRAFT_BIND_ADDR", format!("127.0.0.1:{http_port}")),
288        (
289            "TEAMCRAFT_PUBLIC_URL",
290            format!("http://127.0.0.1:{http_port}"),
291        ),
292        ("TEAMCRAFT_DB_HOST", "127.0.0.1".to_string()),
293        ("TEAMCRAFT_DB_PORT", db_port.to_string()),
294        ("TEAMCRAFT_DB_USER", DB_USER.to_string()),
295        ("TEAMCRAFT_DB_NAME", DB_NAME.to_string()),
296        ("TEAMCRAFT_DB_PASSWORD", password.to_string()),
297        ("TEAMCRAFT_DB_SSLMODE", "disable".to_string()),
298        (
299            "TEAMCRAFT_VAULT_DIR",
300            data_dir.join("vault").to_string_lossy().to_string(),
301        ),
302    ])
303}
304
305/// Variables that would point the server at another database; hidden from
306/// the configuration of the local installation.
307const MASKED: &[&str] = &["DATABASE_URL", "TEAMCRAFT_DATABASE_URL"];
308
309/// A lookup for [`crate::config::Config::from_lookup`]: the local variables
310/// win, their `_FILE` forms and the database URLs are hidden, everything
311/// else (an assistant key, OIDC, …) comes from `env`.
312pub fn overlay_lookup<F>(
313    local: BTreeMap<&'static str, String>,
314    env: F,
315) -> impl Fn(&str) -> Option<String>
316where
317    F: Fn(&str) -> Option<String>,
318{
319    move |key: &str| {
320        if let Some(value) = local.get(key) {
321            return Some(value.clone());
322        }
323        let base = key.strip_suffix("_FILE").unwrap_or(key);
324        if local.contains_key(base) || MASKED.contains(&base) {
325            return None;
326        }
327        env(key)
328    }
329}
330
331/// A command for a PostgreSQL program. On Windows without a console window:
332/// the desktop app starts `teamcraft local` without one, and every program
333/// started from there would otherwise open its own.
334fn pg_command(bin: &Path, name: &str) -> tokio::process::Command {
335    #[allow(unused_mut)]
336    let mut command = tokio::process::Command::new(bin.join(exe(name)));
337    command.stdin(std::process::Stdio::null());
338    #[cfg(windows)]
339    {
340        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
341        command.creation_flags(CREATE_NO_WINDOW);
342    }
343    command
344}
345
346fn output_text(output: &Output) -> String {
347    let mut text = String::from_utf8_lossy(&output.stderr).trim().to_string();
348    let stdout = String::from_utf8_lossy(&output.stdout);
349    if !stdout.trim().is_empty() {
350        if !text.is_empty() {
351            text.push('\n');
352        }
353        text.push_str(stdout.trim());
354    }
355    text
356}
357
358async fn run(mut command: tokio::process::Command, what: &str) -> Result<Output> {
359    let output = command
360        .output()
361        .await
362        .with_context(|| format!("cannot run {what}"))?;
363    if !output.status.success() {
364        let text = output_text(&output);
365        if text.contains("cannot be run as root") {
366            bail!(
367                "PostgreSQL refuses to run as root: start `teamcraft local` as a normal user\n{text}"
368            );
369        }
370        bail!("{what} failed ({}):\n{text}", output.status);
371    }
372    Ok(output)
373}
374
375/// The running PostgreSQL cluster of a local installation.
376pub struct Cluster {
377    bin: PathBuf,
378    pgdata: PathBuf,
379    /// The port of this start.
380    pub port: u16,
381    /// The database password (from `<data dir>/db-password`).
382    pub password: String,
383}
384
385impl Cluster {
386    /// Creates the cluster on the first start, then starts it on a free port
387    /// and creates the database if it is missing. A cluster left running by
388    /// a previous start that did not stop it (killed, power loss) is stopped
389    /// first.
390    pub async fn start(bin: &Path, data_dir: &Path) -> Result<Self> {
391        std::fs::create_dir_all(data_dir)
392            .with_context(|| format!("cannot create {}", data_dir.display()))?;
393        let pgdata = data_dir.join("postgres");
394        let password_file = data_dir.join("db-password");
395
396        if !pgdata.join("PG_VERSION").is_file() {
397            if pgdata.exists() && std::fs::read_dir(&pgdata)?.next().is_some() {
398                bail!(
399                    "{} exists but is not a PostgreSQL cluster; move it away or choose another --data-dir",
400                    pgdata.display()
401                );
402            }
403            tracing::info!(dir = %pgdata.display(), "creating the PostgreSQL cluster (first start)");
404            let password = random_password();
405            write_private(&password_file, &password)?;
406            // initdb reads the password from a file; it must not end up on
407            // the command line, where other users could see it
408            let pwfile = data_dir.join("initdb-password.tmp");
409            write_private(&pwfile, &format!("{password}\n"))?;
410            let mut initdb = pg_command(bin, "initdb");
411            initdb
412                .arg("--pgdata")
413                .arg(&pgdata)
414                .args(["--username", DB_USER])
415                .args(["--auth", "scram-sha-256"])
416                .arg(format!("--pwfile={}", pwfile.display()))
417                .args(["--encoding", "UTF8", "--no-locale"]);
418            let result = run(initdb, "initdb").await;
419            let _ = std::fs::remove_file(&pwfile);
420            if let Err(e) = result {
421                // a half-created cluster would block the next attempt
422                let _ = std::fs::remove_dir_all(&pgdata);
423                return Err(e);
424            }
425            let conf = pgdata.join("postgresql.conf");
426            let mut text = std::fs::read_to_string(&conf)
427                .with_context(|| format!("cannot read {}", conf.display()))?;
428            text.push_str(&format!("\n# added by `teamcraft local`\n{INCLUDE_LINE}\n"));
429            std::fs::write(&conf, text)
430                .with_context(|| format!("cannot write {}", conf.display()))?;
431        }
432        let password = std::fs::read_to_string(&password_file)
433            .with_context(|| format!("cannot read {}", password_file.display()))?
434            .trim()
435            .to_string();
436        if password.is_empty() {
437            bail!("{} is empty", password_file.display());
438        }
439
440        let mut cluster = Self {
441            bin: bin.to_path_buf(),
442            pgdata,
443            port: 0,
444            password,
445        };
446        if cluster.running().await {
447            tracing::info!("stopping the PostgreSQL cluster left running by an earlier start");
448            cluster.stop_async().await?;
449        }
450        cluster.port = free_port()?;
451        std::fs::write(cluster.pgdata.join(LOCAL_CONF), local_conf(cluster.port))
452            .context("cannot write the cluster settings")?;
453        // pg_ctl's own output goes to a file, never to a pipe: on Windows
454        // pg_ctl starts postgres through cmd.exe with handle inheritance, so
455        // the postmaster – which keeps running – would hold the write end of
456        // a pipe, and reading the pipe to its end would wait forever.
457        let pg_ctl_log = data_dir.join("pg_ctl.log");
458        let out = std::fs::File::create(&pg_ctl_log)
459            .with_context(|| format!("cannot write {}", pg_ctl_log.display()))?;
460        let err = out.try_clone()?;
461        let mut start = pg_command(bin, "pg_ctl");
462        start
463            .arg("start")
464            .arg("--pgdata")
465            .arg(&cluster.pgdata)
466            .arg("--log")
467            .arg(data_dir.join("postgres.log"))
468            .args(["--wait", "--silent"])
469            .arg(format!("--timeout={PG_CTL_TIMEOUT_SECS}"))
470            .stdout(out)
471            .stderr(err);
472        let status = start.status().await.context("cannot run pg_ctl start")?;
473        if !status.success() {
474            let said = std::fs::read_to_string(&pg_ctl_log).unwrap_or_default();
475            bail!(
476                "PostgreSQL did not start ({status}); see {}\n{}",
477                data_dir.join("postgres.log").display(),
478                said.trim()
479            );
480        }
481        tracing::info!(port = cluster.port, "PostgreSQL is running on 127.0.0.1");
482        if let Err(e) = cluster.ensure_database().await {
483            cluster.stop();
484            return Err(e);
485        }
486        Ok(cluster)
487    }
488
489    fn options(&self, database: &str) -> PgConnectOptions {
490        PgConnectOptions::new()
491            .host("127.0.0.1")
492            .port(self.port)
493            .username(DB_USER)
494            .password(&self.password)
495            .database(database)
496            .ssl_mode(PgSslMode::Disable)
497            .application_name("teamcraft local")
498    }
499
500    /// Creates the database on the first start.
501    async fn ensure_database(&self) -> Result<()> {
502        let mut conn = self
503            .options("postgres")
504            .connect()
505            .await
506            .context("cannot connect to the local PostgreSQL cluster")?;
507        let exists: bool =
508            sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = $1)")
509                .bind(DB_NAME)
510                .fetch_one(&mut conn)
511                .await?;
512        if !exists {
513            // the name is a constant: no quoting needed
514            sqlx::query(&format!("CREATE DATABASE {DB_NAME}"))
515                .execute(&mut conn)
516                .await
517                .context("cannot create the database")?;
518        }
519        conn.close().await.ok();
520        Ok(())
521    }
522
523    /// Whether a postmaster runs on this data directory (`pg_ctl status`).
524    async fn running(&self) -> bool {
525        let mut status = pg_command(&self.bin, "pg_ctl");
526        status.arg("status").arg("--pgdata").arg(&self.pgdata);
527        matches!(status.output().await, Ok(o) if o.status.success())
528    }
529
530    async fn stop_async(&self) -> Result<()> {
531        let mut stop = pg_command(&self.bin, "pg_ctl");
532        stop.args(stop_args(&self.pgdata));
533        run(stop, "pg_ctl stop").await.map(|_| ())
534    }
535
536    /// Stops the cluster (fast shutdown: open connections are closed). Used
537    /// after the server stopped; errors are logged, not returned.
538    pub fn stop(&self) {
539        let mut stop = std::process::Command::new(self.bin.join(exe("pg_ctl")));
540        stop.args(stop_args(&self.pgdata))
541            .stdin(std::process::Stdio::null());
542        #[cfg(windows)]
543        {
544            use std::os::windows::process::CommandExt;
545            stop.creation_flags(0x0800_0000);
546        }
547        match stop.output() {
548            Ok(o) if o.status.success() => tracing::info!("PostgreSQL stopped"),
549            Ok(o) => tracing::warn!(error = %output_text(&o), "pg_ctl stop failed"),
550            Err(e) => tracing::warn!(error = %e, "cannot run pg_ctl stop"),
551        }
552    }
553}
554
555fn stop_args(pgdata: &Path) -> Vec<&OsStr> {
556    vec![
557        OsStr::new("stop"),
558        OsStr::new("--pgdata"),
559        pgdata.as_os_str(),
560        OsStr::new("--mode=fast"),
561        OsStr::new("--wait"),
562        OsStr::new("--silent"),
563    ]
564}
565
566/// `<data dir>/local-server.port`: the HTTP port of the running instance,
567/// written once PostgreSQL runs and removed when it stopped.
568const PORT_FILE: &str = "local-server.port";
569
570/// Records the HTTP port of this instance in the data directory.
571pub fn write_port_file(data_dir: &Path, http_port: u16) -> Result<()> {
572    std::fs::write(data_dir.join(PORT_FILE), format!("{http_port}\n"))
573        .context("cannot write the port file")
574}
575
576/// Removes the port file again (after the cluster stopped).
577pub fn remove_port_file(data_dir: &Path) {
578    let _ = std::fs::remove_file(data_dir.join(PORT_FILE));
579}
580
581/// The port of another `teamcraft local` that still serves this data
582/// directory: its port file names a port whose `/readyz` answers like
583/// TeamCraft. Starting a second one would stop its PostgreSQL (it looks
584/// left running), so the caller refuses instead. A port file left behind by
585/// a killed instance does not count.
586pub async fn running_instance(data_dir: &Path) -> Option<u16> {
587    let port: u16 = std::fs::read_to_string(data_dir.join(PORT_FILE))
588        .ok()?
589        .trim()
590        .parse()
591        .ok()?;
592    let client = reqwest::Client::builder()
593        .no_proxy()
594        .timeout(std::time::Duration::from_secs(3))
595        .build()
596        .ok()?;
597    let body: serde_json::Value = client
598        .get(format!("http://127.0.0.1:{port}/readyz"))
599        .send()
600        .await
601        .ok()?
602        .json()
603        .await
604        .ok()?;
605    body.get("status").is_some().then_some(port)
606}
607
608/// Resolves when standard input reaches its end (or fails). The desktop app
609/// starts `teamcraft local --exit-with-stdin` with a pipe it never writes
610/// to: when the app ends – also when it crashes or is killed – the pipe
611/// closes and the server and PostgreSQL shut down cleanly. A plain thread,
612/// not a blocking tokio task: the runtime would wait for it at shutdown.
613pub async fn stdin_closed() {
614    let (tx, rx) = tokio::sync::oneshot::channel::<()>();
615    std::thread::spawn(move || {
616        let mut buf = [0u8; 256];
617        let mut stdin = std::io::stdin();
618        loop {
619            match std::io::Read::read(&mut stdin, &mut buf) {
620                Ok(0) | Err(_) => break,
621                Ok(_) => {}
622            }
623        }
624        let _ = tx.send(());
625    });
626    let _ = rx.await;
627}
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632
633    #[test]
634    fn data_dir_per_os() {
635        let vars = |pairs: &'static [(&'static str, &'static str)]| {
636            move |key: &str| {
637                pairs
638                    .iter()
639                    .find(|(k, _)| *k == key)
640                    .map(|(_, v)| PathBuf::from(v))
641            }
642        };
643        if cfg!(windows) {
644            assert_eq!(
645                data_dir_from(vars(&[("LOCALAPPDATA", r"C:\Users\a\AppData\Local")])),
646                Some(PathBuf::from(
647                    r"C:\Users\a\AppData\Local\TeamCraft\local-server"
648                ))
649            );
650            assert_eq!(data_dir_from(vars(&[])), None);
651        } else if cfg!(target_os = "macos") {
652            assert_eq!(
653                data_dir_from(vars(&[("HOME", "/Users/a")])),
654                Some(PathBuf::from(
655                    "/Users/a/Library/Application Support/TeamCraft/local-server"
656                ))
657            );
658        } else {
659            assert_eq!(
660                data_dir_from(vars(&[("HOME", "/home/a")])),
661                Some(PathBuf::from("/home/a/.local/share/teamcraft/local-server"))
662            );
663            assert_eq!(
664                data_dir_from(vars(&[("HOME", "/home/a"), ("XDG_DATA_HOME", "/data")])),
665                Some(PathBuf::from("/data/teamcraft/local-server"))
666            );
667            // a relative XDG_DATA_HOME is invalid by the specification
668            assert_eq!(
669                data_dir_from(vars(&[("HOME", "/home/a"), ("XDG_DATA_HOME", "rel")])),
670                Some(PathBuf::from("/home/a/.local/share/teamcraft/local-server"))
671            );
672            assert_eq!(data_dir_from(vars(&[("HOME", "")])), None);
673        }
674    }
675
676    /// Windows verbatim paths (the desktop app's resource folder) lose their
677    /// `\\?\` prefix, which PostgreSQL cannot handle; others stay.
678    #[test]
679    fn verbatim_prefixes_are_removed() {
680        let s = |p: &str| {
681            without_verbatim_prefix(Path::new(p))
682                .to_string_lossy()
683                .to_string()
684        };
685        assert_eq!(
686            s(r"\\?\C:\Users\a\AppData\Local\TeamCraft Local\postgresql\bin"),
687            r"C:\Users\a\AppData\Local\TeamCraft Local\postgresql\bin"
688        );
689        assert_eq!(s(r"\\?\UNC\server\share\pg"), r"\\server\share\pg");
690        assert_eq!(s(r"C:\pg\bin"), r"C:\pg\bin");
691        assert_eq!(
692            s("/usr/lib/postgresql/16/bin"),
693            "/usr/lib/postgresql/16/bin"
694        );
695        // other verbatim forms (device paths) are left alone
696        assert_eq!(s(r"\\?\Volume{1234}\pg"), r"\\?\Volume{1234}\pg");
697    }
698
699    #[test]
700    fn explicit_pg_bin_is_the_only_candidate() {
701        let dir = Path::new("/somewhere/pg/bin");
702        assert_eq!(
703            pg_bin_candidates(Some(dir), Some(Path::new("/opt/tc"))),
704            vec![dir.to_path_buf()]
705        );
706    }
707
708    #[test]
709    fn bundle_next_to_the_executable_comes_first() {
710        let exe_dir = Path::new("/opt/tc");
711        let candidates = pg_bin_candidates(None, Some(exe_dir));
712        assert_eq!(candidates[0], exe_dir.join("postgresql").join("bin"));
713        assert_eq!(
714            candidates[1],
715            exe_dir
716                .join("..")
717                .join("Resources")
718                .join("postgresql")
719                .join("bin")
720        );
721    }
722
723    /// A new empty directory below the system's temporary directory.
724    fn scratch(name: &str) -> PathBuf {
725        let dir =
726            std::env::temp_dir().join(format!("teamcraft-local-{name}-{}", uuid::Uuid::new_v4()));
727        std::fs::create_dir_all(&dir).unwrap();
728        dir
729    }
730
731    #[test]
732    fn pg_bin_needs_all_three_programs() {
733        let dir = scratch("bin");
734        assert!(!is_pg_bin(&dir));
735        for name in ["initdb", "pg_ctl"] {
736            std::fs::write(dir.join(exe(name)), "").unwrap();
737        }
738        assert!(!is_pg_bin(&dir));
739        std::fs::write(dir.join(exe("postgres")), "").unwrap();
740        assert!(is_pg_bin(&dir));
741        assert_eq!(find_pg_bin(Some(&dir)).unwrap(), dir);
742        let empty = scratch("empty");
743        let err = find_pg_bin(Some(&empty)).unwrap_err().to_string();
744        assert!(err.contains("does not contain initdb"), "{err}");
745        let _ = std::fs::remove_dir_all(&dir);
746        let _ = std::fs::remove_dir_all(&empty);
747    }
748
749    #[test]
750    fn cluster_settings_listen_on_loopback_only() {
751        let conf = local_conf(54321);
752        assert!(conf.contains("listen_addresses = '127.0.0.1'\n"));
753        assert!(conf.contains("port = 54321\n"));
754        assert!(conf.contains("unix_socket_directories = ''\n"));
755    }
756
757    #[test]
758    fn passwords_are_random_and_alphanumeric() {
759        let (a, b) = (random_password(), random_password());
760        assert_eq!(a.len(), 32);
761        assert_ne!(a, b);
762        assert!(a.chars().all(|c| c.is_ascii_alphanumeric()));
763    }
764
765    #[cfg(unix)]
766    #[test]
767    fn private_files_are_owner_only() {
768        use std::os::unix::fs::PermissionsExt;
769        let dir = scratch("private");
770        let path = dir.join("secret");
771        write_private(&path, "x").unwrap();
772        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
773        assert_eq!(mode & 0o777, 0o600);
774        let _ = std::fs::remove_dir_all(&dir);
775    }
776
777    #[test]
778    fn local_variables_win_over_the_environment() {
779        let password = random_password();
780        let local = local_variables(Path::new("/data"), 8099, 54000, &password);
781        let env = |key: &str| -> Option<String> {
782            match key {
783                "TEAMCRAFT_DATABASE_URL" => Some("postgres://elsewhere/db".into()),
784                "DATABASE_URL_FILE" => Some("/run/secrets/url".into()),
785                "TEAMCRAFT_DB_PASSWORD_FILE" => Some("/run/secrets/pw".into()),
786                "TEAMCRAFT_BIND_ADDR" => Some("0.0.0.0:80".into()),
787                "TEAMCRAFT_INSTANCE_NAME" => Some("Kept".into()),
788                _ => None,
789            }
790        };
791        let lookup = overlay_lookup(local, env);
792        assert_eq!(
793            lookup("TEAMCRAFT_BIND_ADDR").as_deref(),
794            Some("127.0.0.1:8099")
795        );
796        assert_eq!(
797            lookup("TEAMCRAFT_PUBLIC_URL").as_deref(),
798            Some("http://127.0.0.1:8099")
799        );
800        assert_eq!(lookup("TEAMCRAFT_DB_PORT").as_deref(), Some("54000"));
801        assert_eq!(
802            lookup("TEAMCRAFT_DB_PASSWORD").as_deref(),
803            Some(password.as_str())
804        );
805        assert_eq!(lookup("TEAMCRAFT_DB_PASSWORD_FILE"), None);
806        assert_eq!(lookup("TEAMCRAFT_DATABASE_URL"), None);
807        assert_eq!(lookup("DATABASE_URL_FILE"), None);
808        assert_eq!(lookup("TEAMCRAFT_INSTANCE_NAME").as_deref(), Some("Kept"));
809        let vault = PathBuf::from(lookup("TEAMCRAFT_VAULT_DIR").unwrap());
810        assert_eq!(vault, Path::new("/data").join("vault"));
811    }
812
813    /// The overlay gives a valid server configuration on loopback, which the
814    /// first-start setup page needs (`web::auth_pages::setup_open`).
815    #[test]
816    fn local_configuration_is_valid_and_loopback() {
817        let local = local_variables(Path::new("/data"), 8099, 54000, &random_password());
818        let config = crate::config::Config::from_lookup(overlay_lookup(local, |_| None)).unwrap();
819        assert!(config.bind_addr.ip().is_loopback());
820        assert_eq!(config.bind_addr.port(), 8099);
821        assert_eq!(config.public_url, "http://127.0.0.1:8099");
822        assert_eq!(config.vault_dir, Path::new("/data").join("vault"));
823    }
824}