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
200
201
202
use std::{fmt::Display, str::FromStr};

/// Represents configuration as stored in /etc/nix/nix.conf.
/// This list is not exhaustive, feel free to add more.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct NixConfig<'a> {
    pub allowed_users: Option<Vec<&'a str>>,
    pub auto_optimise_store: Option<bool>,
    pub cores: Option<u64>,
    pub max_jobs: Option<u64>,
    pub require_sigs: Option<bool>,
    pub sandbox: Option<SandboxSetting>,
    pub sandbox_fallback: Option<bool>,
    pub substituters: Option<Vec<&'a str>>,
    pub system_features: Option<Vec<&'a str>>,
    pub trusted_public_keys: Option<Vec<crate::narinfo::VerifyingKey>>,
    pub trusted_substituters: Option<Vec<&'a str>>,
    pub trusted_users: Option<Vec<&'a str>>,
    pub extra_platforms: Option<Vec<&'a str>>,
    pub extra_sandbox_paths: Option<Vec<&'a str>>,
    pub experimental_features: Option<Vec<&'a str>>,
    pub builders_use_substitutes: Option<bool>,
}

impl<'a> NixConfig<'a> {
    /// Parses configuration from a file like `/etc/nix/nix.conf`, returning
    /// a [NixConfig] with all values contained in there.
    /// It does not support parsing multiple config files, merging semantics,
    /// and also does not understand `include` and `!include` statements.
    pub fn parse(input: &'a str) -> Result<Self, Error> {
        let mut out = Self::default();

        for line in input.lines() {
            // strip comments at the end of the line
            let line = if let Some((line, _comment)) = line.split_once('#') {
                line
            } else {
                line
            };

            // skip comments and empty lines
            if line.trim().is_empty() {
                continue;
            }

            let (tag, val) = line
                .split_once('=')
                .ok_or_else(|| Error::InvalidLine(line.to_string()))?;

            // trim whitespace
            let tag = tag.trim();
            let val = val.trim();

            #[inline]
            fn parse_val<'a>(this: &mut NixConfig<'a>, tag: &str, val: &'a str) -> Option<()> {
                match tag {
                    "allowed-users" => {
                        this.allowed_users = Some(val.split_whitespace().collect());
                    }
                    "auto-optimise-store" => {
                        this.auto_optimise_store = Some(val.parse::<bool>().ok()?);
                    }
                    "cores" => {
                        this.cores = Some(val.parse().ok()?);
                    }
                    "max-jobs" => {
                        this.max_jobs = Some(val.parse().ok()?);
                    }
                    "require-sigs" => {
                        this.require_sigs = Some(val.parse().ok()?);
                    }
                    "sandbox" => this.sandbox = Some(val.parse().ok()?),
                    "sandbox-fallback" => this.sandbox_fallback = Some(val.parse().ok()?),
                    "substituters" => this.substituters = Some(val.split_whitespace().collect()),
                    "system-features" => {
                        this.system_features = Some(val.split_whitespace().collect())
                    }
                    "trusted-public-keys" => {
                        this.trusted_public_keys = Some(
                            val.split_whitespace()
                                .map(crate::narinfo::VerifyingKey::parse)
                                .collect::<Result<Vec<crate::narinfo::VerifyingKey>, _>>()
                                .ok()?,
                        )
                    }
                    "trusted-substituters" => {
                        this.trusted_substituters = Some(val.split_whitespace().collect())
                    }
                    "trusted-users" => this.trusted_users = Some(val.split_whitespace().collect()),
                    "extra-platforms" => {
                        this.extra_platforms = Some(val.split_whitespace().collect())
                    }
                    "extra-sandbox-paths" => {
                        this.extra_sandbox_paths = Some(val.split_whitespace().collect())
                    }
                    "experimental-features" => {
                        this.experimental_features = Some(val.split_whitespace().collect())
                    }
                    "builders-use-substitutes" => {
                        this.builders_use_substitutes = Some(val.parse().ok()?)
                    }
                    _ => return None,
                }
                Some(())
            }

            parse_val(&mut out, tag, val)
                .ok_or_else(|| Error::InvalidValue(tag.to_string(), val.to_string()))?
        }

        Ok(out)
    }
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Invalid line: {0}")]
    InvalidLine(String),
    #[error("Unrecognized key: {0}")]
    UnrecognizedKey(String),
    #[error("Invalid value '{1}' for key '{0}'")]
    InvalidValue(String, String),
}

/// Valid values for the Nix 'sandbox' setting
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SandboxSetting {
    True,
    False,
    Relaxed,
}

impl Display for SandboxSetting {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SandboxSetting::True => write!(f, "true"),
            SandboxSetting::False => write!(f, "false"),
            SandboxSetting::Relaxed => write!(f, "relaxed"),
        }
    }
}

impl FromStr for SandboxSetting {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "true" => Self::True,
            "false" => Self::False,
            "relaxed" => Self::Relaxed,
            _ => return Err("invalid value"),
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::{narinfo::VerifyingKey, nixcpp::conf::SandboxSetting};

    use super::NixConfig;

    #[test]
    pub fn test_parse() {
        let config = NixConfig::parse(include_str!("../../testdata/nix.conf")).expect("must parse");

        assert_eq!(
            NixConfig {
                allowed_users: Some(vec!["*"]),
                auto_optimise_store: Some(false),
                cores: Some(0),
                max_jobs: Some(8),
                require_sigs: Some(true),
                sandbox: Some(SandboxSetting::True),
                sandbox_fallback: Some(false),
                substituters: Some(vec!["https://nix-community.cachix.org", "https://cache.nixos.org/"]),
                system_features: Some(vec!["nixos-test", "benchmark", "big-parallel", "kvm"]),
                trusted_public_keys: Some(vec![
                    VerifyingKey::parse("cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=")
                        .expect("failed to parse pubkey"),
                    VerifyingKey::parse("nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=")
                        .expect("failed to parse pubkey")
                ]),
                trusted_substituters: Some(vec![]),
                trusted_users: Some(vec!["flokli"]),
                extra_platforms: Some(vec!["aarch64-linux", "i686-linux"]),
                extra_sandbox_paths: Some(vec![
                    "/run/binfmt", "/nix/store/swwyxyqpazzvbwx8bv40z7ih144q841f-qemu-aarch64-binfmt-P-x86_64-unknown-linux-musl"
                ]),
                experimental_features: Some(vec!["nix-command"]),
                builders_use_substitutes: Some(true)
            },
            config
        );

        // parse a config file using some non-space whitespaces, as well as comments right after the lines.
        // ensure it contains the same data as initially parsed.
        let other_config = NixConfig::parse(include_str!("../../testdata/other_nix.conf"))
            .expect("other config must parse");

        assert_eq!(config, other_config);
    }
}