aboutsummaryrefslogtreecommitdiff
path: root/src/app/api/env.rs
blob: db421f63f9c607a8d650493cef53561c20e24ef2 (plain)
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
use std::collections::HashMap;

pub(super) fn normalize_launch_env(
    env: HashMap<String, String>,
) -> Result<Vec<(String, String)>, (String, String)> {
    let mut normalized = Vec::with_capacity(env.len());
    for (key, value) in env {
        if key.is_empty() {
            return Err(("invalid_env".into(), "env key must not be empty".into()));
        }
        if key.contains('=') {
            return Err((
                "invalid_env".into(),
                format!("env key {key} must not contain '='"),
            ));
        }
        if key.contains('\0') {
            return Err((
                "invalid_env".into(),
                "env key must not contain NUL bytes".into(),
            ));
        }
        if value.contains('\0') {
            return Err((
                "invalid_env".into(),
                format!("env value for {key} must not contain NUL bytes"),
            ));
        }
        normalized.push((key, value));
    }
    normalized.sort_by(|left, right| left.0.cmp(&right.0));
    Ok(normalized)
}

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

    #[test]
    fn normalize_launch_env_sorts_entries() {
        let env = HashMap::from([
            ("ZED".to_string(), "last".to_string()),
            ("ALPHA".to_string(), "first".to_string()),
        ]);

        assert_eq!(
            normalize_launch_env(env).unwrap(),
            vec![
                ("ALPHA".to_string(), "first".to_string()),
                ("ZED".to_string(), "last".to_string()),
            ]
        );
    }

    #[test]
    fn normalize_launch_env_rejects_invalid_keys() {
        let env = HashMap::from([("BAD=KEY".to_string(), "value".to_string())]);

        assert_eq!(normalize_launch_env(env).unwrap_err().0, "invalid_env");
    }
}