fhttp_core/profiles/
profile_variable.rs

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
use std::cell::RefCell;

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::Config;

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ProfileVariable {
    StringValue(String),
    PassSecret {
        pass: String,
        #[serde(skip)]
        cache: RefCell<Option<String>>,
    },
    Request {
        request: String,
    },
}

impl ProfileVariable {
    pub fn get(&self, config: &Config, for_dependency: bool) -> Result<String> {
        match self {
            ProfileVariable::StringValue(ref value) => Ok(value.to_owned()),
            ProfileVariable::PassSecret { pass: path, cache } => {
                if config.curl() && !for_dependency {
                    Ok(format!("$(pass {})", path))
                } else {
                    if cache.borrow().is_none() {
                        config.log(2, format!("resolving pass secret '{}'... ", &path));
                        let value = resolve_pass(path)?.trim().to_owned();
                        config.logln(2, "done");
                        cache.borrow_mut().replace(value);
                    }

                    Ok(cache.borrow().as_ref().unwrap().clone())
                }
            }
            ProfileVariable::Request { request: _ } => {
                panic!("ProfileVariable::Request cannot resolve by itself")
            }
        }
    }
}

#[cfg(test)]
thread_local!(
    static PASS_INVOCATIONS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) }
);

#[cfg(test)]
fn resolve_pass(path: &str) -> Result<String> {
    PASS_INVOCATIONS.with(|it| it.borrow_mut().push(path.to_string()));
    Ok("pass_secret".to_string())
}

#[cfg(not(test))]
fn resolve_pass(path: &str) -> Result<String> {
    use anyhow::anyhow;
    use std::process::Command;

    let output = Command::new("pass").args([path]).output().unwrap();

    if output.status.success() {
        let output = output.stdout;
        Ok(String::from_utf8(output).unwrap())
    } else {
        let stderr = String::from_utf8(output.stderr).unwrap();
        Err(anyhow!("pass returned an error: '{}'", stderr))
    }
}

#[cfg(test)]
mod test {
    use indoc::indoc;

    use super::*;

    #[test]
    fn deserialize_string_value() {
        let input = "\"foo\"";
        let result = serde_json::from_str::<ProfileVariable>(input).unwrap();
        assert_eq!(result, ProfileVariable::StringValue("foo".into()));
    }

    #[test]
    fn deserialize_pass_secret() {
        let input = indoc!(
            r##"
            {
                "pass": "foo/bar"
            }
        "##
        );
        let result = serde_json::from_str::<ProfileVariable>(input).unwrap();
        assert_eq!(
            result,
            ProfileVariable::PassSecret {
                pass: "foo/bar".into(),
                cache: RefCell::new(None)
            }
        );
    }
}

#[cfg(test)]
mod curl {
    use super::*;
    use rstest::{fixture, rstest};

    #[fixture]
    fn program() -> Config {
        Config::new(false, 0, false, false, None, true)
    }

    #[rstest]
    fn string_value_should_return_normally(program: Config) {
        let var = ProfileVariable::StringValue(String::from("value"));
        let result = var.get(&program, false);

        assert_ok!(result, String::from("value"));
    }

    #[rstest]
    fn pass_should_return_pass_invocation_string_for_non_dependencies(program: Config) {
        PASS_INVOCATIONS.with(|it| it.borrow_mut().clear());

        let var = ProfileVariable::PassSecret {
            pass: "path/to/secret".to_string(),
            cache: RefCell::new(None),
        };
        let result = var.get(&program, false);

        assert_ok!(result, String::from("$(pass path/to/secret)"));

        PASS_INVOCATIONS.with(|it| assert_eq!(it.borrow().len(), 0));
    }

    #[rstest]
    fn pass_should_invoke_pass_for_dependencies(program: Config) {
        PASS_INVOCATIONS.with(|it| it.borrow_mut().clear());

        let var = ProfileVariable::PassSecret {
            pass: "path/to/secret".to_string(),
            cache: RefCell::new(None),
        };
        let result = var.get(&program, true);

        assert_ok!(result, String::from("pass_secret"));

        PASS_INVOCATIONS.with(|it| {
            let invocations = it.borrow().iter().map(String::clone).collect::<Vec<_>>();
            assert_eq!(&invocations, &["path/to/secret".to_string()]);
        });
    }
}