GITv
master
config.rs158 lines, 6.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//! Settings that differ between installations, read once from `/etc/gitv/gitv.conf`
//! (`$GITV_CONFIG` to use another file):
//!
//! ```text
//! # The name people reach this server by, in clone addresses and help.
//! host = git.example.com
//! # Where gitv is installed: what each key's forced command runs.
//! command = /usr/local/bin/gitv
//! ```
//!
//! Both are optional. `host` defaults to `$GITV_HOST`, then the machine's hostname; `command`
//! defaults to `/usr/local/bin/gitv`. A missing file means all defaults; an unknown key or a bad
//! value is an error, so a typo can't silently change nothing. Each binary calls [`load`] at
//! startup, so a problem stops it with a clear message before it serves anything.

use std::path::{Path, PathBuf};
use std::sync::LazyLock;

pub struct Config {
    /// The server's public hostname, lowercase.
    pub host: String,
    /// The absolute path of the `gitv` binary, for forced commands.
    pub command: String,
    /// Where `host` came from, for startup messages.
    pub host_source: &'static str,
}

static CONFIG: LazyLock<Result<Config, String>> =
    LazyLock::new(|| read(&config_path(), std::env::var("GITV_HOST").ok()));

/// Where the configuration file is: `$GITV_CONFIG`, or `/etc/gitv/gitv.conf`.
pub fn config_path() -> PathBuf {
    std::env::var_os("GITV_CONFIG").map_or_else(|| PathBuf::from("/etc/gitv/gitv.conf"), PathBuf::from)
}

/// Read and check the configuration.
///
/// # Errors
/// A message naming the file and the problem.
pub fn load() -> Result<&'static Config, String> {
    CONFIG.as_ref().map_err(Clone::clone)
}

/// The server's public hostname. Binaries [`load`] the configuration first; should it be
/// broken anyway, `localhost` stands in rather than a wrong real name.
pub fn host() -> &'static str {
    CONFIG.as_ref().map_or("localhost", |c| c.host.as_str())
}

/// The command each key's forced command runs.
pub fn command() -> &'static str {
    CONFIG.as_ref().map_or("/usr/local/bin/gitv", |c| c.command.as_str())
}

fn read(path: &Path, host_override: Option<String>) -> Result<Config, String> {
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(format!("couldn't read {}: {e}", path.display())),
    };
    parse(&text, host_override).map_err(|e| format!("{}: {e}", path.display()))
}

fn parse(text: &str, host_override: Option<String>) -> Result<Config, String> {
    let (mut host, mut command) = (None, None);
    for (number, line) in text.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let (key, value) =
            line.split_once('=').ok_or_else(|| format!("line {}: expected `key = value`", number + 1))?;
        let value = value.trim().to_string();
        match key.trim() {
            "host" => host = Some(value),
            "command" => command = Some(value),
            other => return Err(format!("line {}: unknown setting `{other}` (known: host, command)", number + 1)),
        }
    }
    // Every value given is checked, even one GITV_HOST overrides: a broken file is still broken.
    let checked = |host: String, source: &'static str| {
        let host = host.to_ascii_lowercase();
        if valid_host(&host) { Ok((host, source)) } else { Err(format!("`{host}` (from {source}) isn't a hostname")) }
    };
    let from_file = host.map(|host| checked(host, "the configuration file")).transpose()?;
    let (host, host_source) = match (host_override, from_file) {
        (Some(host), _) => checked(host, "GITV_HOST")?,
        (None, Some(found)) => found,
        (None, None) => {
            let name = nix::unistd::gethostname().map_err(|e| format!("no host set and no hostname: {e}"))?;
            checked(name.to_string_lossy().into_owned(), "the machine's hostname")?
        }
    };
    let command = command.unwrap_or_else(|| "/usr/local/bin/gitv".into());
    // It goes inside command="..." in authorized_keys, so nothing that could end or escape that.
    if !command.starts_with('/') || command.bytes().any(|b| b.is_ascii_whitespace() || b"\"\\'".contains(&b)) {
        return Err(format!("command `{command}` must be an absolute path without spaces or quotes"));
    }
    Ok(Config { host, command, host_source })
}

/// A DNS name: dot-separated labels of letters, digits and inner hyphens, 253 characters at most.
fn valid_host(host: &str) -> bool {
    host.len() <= 253
        && host.split('.').all(|label| {
            (1..=63).contains(&label.len())
                && label.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
                && !label.starts_with('-')
                && !label.ends_with('-')
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn settings_come_from_the_file_with_the_environment_first() {
        let file = "# comment\nhost = Git.Example.COM\n\ncommand = /opt/gitv/bin/gitv\n";
        let config = parse(file, None).unwrap();
        assert_eq!((config.host.as_str(), config.command.as_str()), ("git.example.com", "/opt/gitv/bin/gitv"));
        assert_eq!(config.host_source, "the configuration file");
        let config = parse(file, Some("other.example".into())).unwrap();
        assert_eq!((config.host.as_str(), config.host_source), ("other.example", "GITV_HOST"));
    }

    #[test]
    fn defaults_fill_in_what_is_missing() {
        let config = parse("", None).unwrap();
        assert_eq!(config.command, "/usr/local/bin/gitv");
        assert_eq!(config.host_source, "the machine's hostname");
        assert!(valid_host(&config.host));
    }

    #[test]
    fn mistakes_are_refused_with_the_line() {
        for (text, expected) in [
            ("hots = x.example", "line 1: unknown setting `hots`"),
            ("\nhost", "line 2: expected `key = value`"),
            ("host = git.example.com/repos", "isn't a hostname"),
            ("host = -bad.example", "isn't a hostname"),
            ("host = a..b", "isn't a hostname"),
            ("command = gitv", "must be an absolute path"),
            ("command = /usr/bin/gitv\" evil", "must be an absolute path"),
        ] {
            let error = parse(text, Some("ok.example".into())).err().unwrap_or_default();
            assert!(error.contains(expected), "{text:?}: {error}");
        }
    }

    #[test]
    fn a_missing_file_means_defaults_and_an_unreadable_one_is_an_error() {
        let missing = std::env::temp_dir().join(format!("gitv-no-config-{}", std::process::id()));
        assert!(read(&missing, Some("x.example".into())).is_ok());
        let error = read(&std::env::temp_dir(), None).err().unwrap_or_default();
        assert!(error.contains("couldn't read"), "{error}");
    }
}