RustForge

rustforge

RustForge: the read-only, cgit-style git web host serving this site

rustforge / src / config.rs
6434 bytes ยท raw
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//! Loading and validating the TOML config file.
//!
//! The config is the *only* thing that decides which repositories are served.
//! A request for a repo name that is not listed here gets a 404, so nobody can
//! ask the server to read an arbitrary directory on disk.

use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// The whole config file, as written by the user.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default)]
    pub server: ServerConfig,
    /// Each `[[repo]]` table in the TOML file becomes one entry here.
    #[serde(default, rename = "repo")]
    pub repos: Vec<RepoConfig>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServerConfig {
    /// Address to listen on, e.g. "127.0.0.1:8090".
    #[serde(default = "default_listen")]
    pub listen: String,
    /// Title shown at the top of every page.
    #[serde(default = "default_title")]
    pub site_title: String,
    /// Base URL shown in "git clone ..." hints, e.g. "https://git.example.com".
    /// When unset, the `Host` header of the request is used.
    #[serde(default)]
    pub clone_base_url: Option<String>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        ServerConfig { listen: default_listen(), site_title: default_title(), clone_base_url: None }
    }
}

fn default_listen() -> String {
    "127.0.0.1:8090".to_string()
}

fn default_title() -> String {
    "git".to_string()
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RepoConfig {
    /// URL name, e.g. "rust-kernel" -> http://host/rust-kernel/
    pub name: String,
    /// Path on disk: a bare repo (`foo.git`) or a normal checkout (`foo/`).
    pub path: PathBuf,
    #[serde(default)]
    pub description: String,
}

/// The validated, ready-to-use set of repos, looked up by name.
#[derive(Debug, Clone)]
pub struct Repos {
    by_name: BTreeMap<String, RepoConfig>,
}

impl Repos {
    pub fn get(&self, name: &str) -> Option<&RepoConfig> {
        // Allow `/name.git/...` as an alias for `/name/...` (people expect it in clone URLs).
        let name = name.strip_suffix(".git").unwrap_or(name);
        self.by_name.get(name)
    }

    /// All repos, sorted by name.
    pub fn iter(&self) -> impl Iterator<Item = &RepoConfig> {
        self.by_name.values()
    }

    pub fn len(&self) -> usize {
        self.by_name.len()
    }

    pub fn is_empty(&self) -> bool {
        self.by_name.is_empty()
    }
}

impl Config {
    /// Parse a config from TOML text.
    pub fn from_toml(text: &str) -> Result<Config, String> {
        toml::from_str(text).map_err(|e| format!("invalid config: {e}"))
    }

    /// Read and parse a config file from disk.
    pub fn load(path: &Path) -> Result<Config, String> {
        let text =
            std::fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
        Config::from_toml(&text)
    }

    /// Check names and paths, and build the lookup table.
    ///
    /// Paths are canonicalized (symlinks and `..` resolved) once, here, so the
    /// rest of the program only ever deals with fixed absolute paths.
    pub fn validate(&self) -> Result<Repos, String> {
        let mut by_name = BTreeMap::new();
        for repo in &self.repos {
            let name = repo.name.strip_suffix(".git").unwrap_or(&repo.name);
            if !is_valid_repo_name(name) {
                return Err(format!(
                    "repo name {:?} is not allowed (use letters, digits, '-', '_' and '.', not starting with '.')",
                    repo.name
                ));
            }
            let path = std::fs::canonicalize(&repo.path)
                .map_err(|e| format!("repo {name:?}: path {}: {e}", repo.path.display()))?;
            let fixed = RepoConfig { name: name.to_string(), path, description: repo.description.clone() };
            if by_name.insert(name.to_string(), fixed).is_some() {
                return Err(format!("repo name {name:?} is listed twice"));
            }
        }
        Ok(Repos { by_name })
    }
}

/// Repo names end up in URLs, so keep them boring.
pub fn is_valid_repo_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 100
        && !name.starts_with('.')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
}

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

    #[test]
    fn parses_full_config() {
        let cfg = Config::from_toml(
            r#"
            [server]
            listen = "0.0.0.0:9000"
            site_title = "my git"

            [[repo]]
            name = "one"
            path = "/tmp"
            description = "first"
            "#,
        )
        .unwrap();
        assert_eq!(cfg.server.listen, "0.0.0.0:9000");
        assert_eq!(cfg.server.site_title, "my git");
        assert_eq!(cfg.repos.len(), 1);
        assert_eq!(cfg.repos[0].description, "first");
    }

    #[test]
    fn defaults_apply() {
        let cfg = Config::from_toml("").unwrap();
        assert_eq!(cfg.server.listen, "127.0.0.1:8090");
        assert!(cfg.repos.is_empty());
    }

    #[test]
    fn rejects_unknown_keys() {
        assert!(Config::from_toml("bogus = 1").is_err());
    }

    #[test]
    fn repo_names() {
        assert!(is_valid_repo_name("rust-kernel"));
        assert!(is_valid_repo_name("a_b.c"));
        assert!(!is_valid_repo_name(""));
        assert!(!is_valid_repo_name(".."));
        assert!(!is_valid_repo_name(".hidden"));
        assert!(!is_valid_repo_name("a/b"));
        assert!(!is_valid_repo_name("a b"));
        assert!(!is_valid_repo_name("<script>"));
    }

    #[test]
    fn validate_rejects_bad_and_duplicate_names() {
        let bad = Config::from_toml("[[repo]]\nname = \"../x\"\npath = \"/tmp\"").unwrap();
        assert!(bad.validate().is_err());
        let dup = Config::from_toml(
            "[[repo]]\nname = \"x\"\npath = \"/tmp\"\n[[repo]]\nname = \"x.git\"\npath = \"/tmp\"",
        )
        .unwrap();
        assert!(dup.validate().is_err());
        let ok = Config::from_toml("[[repo]]\nname = \"x.git\"\npath = \"/tmp\"").unwrap();
        let repos = ok.validate().unwrap();
        assert!(repos.get("x").is_some());
        assert!(repos.get("x.git").is_some());
        assert!(repos.get("y").is_none());
    }
}