Skip to main content

rungbot_exec/
keys.rs

1//! Loading venue credentials, and refusing to load them carelessly.
2//!
3//! Two sources, in order: the environment, then a file you own and nobody else can read.
4//! **Never the watchlist config** — that file is meant to be shareable, and a credential
5//! in it is a credential in a screenshot.
6//!
7//! On Unix a key file that is group- or world-readable is refused outright rather than
8//! warned about. A warning gets scrolled past. The same goes for a Revolut X private
9//! key file.
10//!
11//! | venue | environment | file `~/.config/rungbot/<venue>.env` |
12//! |---|---|---|
13//! | Gate | `RUNGBOT_GATE_KEY`, `RUNGBOT_GATE_SECRET` | `KEY`, `SECRET` |
14//! | Binance | `RUNGBOT_BINANCE_KEY`, `RUNGBOT_BINANCE_SECRET` | `KEY`, `SECRET` |
15//! | Revolut X | `RUNGBOT_REVX_KEY`, `RUNGBOT_REVX_PRIVATE_KEY_PEM` (a path) | `KEY`, `PRIVATE_KEY_PEM` |
16//!
17//! Nothing here prints a secret: `Debug` redacts it.
18
19use std::path::{Path, PathBuf};
20
21use crate::revx::RevxCredentials;
22
23#[derive(Clone, PartialEq, Eq)]
24pub struct Credentials {
25    pub key: String,
26    pub secret: String,
27}
28
29impl core::fmt::Debug for Credentials {
30    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
31        f.debug_struct("Credentials")
32            .field("key", &self.key)
33            .field("secret", &"<redacted>")
34            .finish()
35    }
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum KeyError {
40    Missing(String),
41    Unreadable(String),
42    BadPermissions { path: String, mode: u32 },
43    Malformed(String),
44}
45
46impl core::fmt::Display for KeyError {
47    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
48        match self {
49            KeyError::Missing(m) => write!(f, "{m}"),
50            KeyError::Unreadable(m) => write!(f, "{m}"),
51            KeyError::BadPermissions { path, mode } => write!(
52                f,
53                "{path} is mode {mode:04o}; others can read your credentials. \
54                 Run: chmod 600 {path}"
55            ),
56            KeyError::Malformed(m) => write!(f, "{m}"),
57        }
58    }
59}
60
61impl std::error::Error for KeyError {}
62
63pub fn default_key_path(venue: &str) -> PathBuf {
64    let base = match std::env::var("XDG_CONFIG_HOME") {
65        Ok(v) if !v.trim().is_empty() => PathBuf::from(v),
66        _ => PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".into())).join(".config"),
67    };
68    base.join("rungbot").join(format!("{venue}.env"))
69}
70
71#[cfg(unix)]
72fn check_permissions(path: &Path) -> Result<(), KeyError> {
73    use std::os::unix::fs::PermissionsExt;
74    let meta = std::fs::metadata(path)
75        .map_err(|e| KeyError::Unreadable(format!("cannot stat {}: {e}", path.display())))?;
76    let mode = meta.permissions().mode() & 0o777;
77    if mode & 0o077 != 0 {
78        return Err(KeyError::BadPermissions {
79            path: path.display().to_string(),
80            mode,
81        });
82    }
83    Ok(())
84}
85
86#[cfg(not(unix))]
87fn check_permissions(_path: &Path) -> Result<(), KeyError> {
88    Ok(())
89}
90
91/// Parse `KEY=value` lines, ignoring blanks and `#` comments.
92fn parse_env(text: &str) -> std::collections::BTreeMap<String, String> {
93    let mut out = std::collections::BTreeMap::new();
94    for line in text.lines() {
95        let line = line.trim();
96        if line.is_empty() || line.starts_with('#') {
97            continue;
98        }
99        if let Some((k, v)) = line.split_once('=') {
100            let v = v.trim();
101            // Tolerate quoting, because a value pasted from a UI often arrives quoted.
102            let v = v
103                .strip_prefix('"')
104                .and_then(|x| x.strip_suffix('"'))
105                .unwrap_or(v);
106            let v = v
107                .strip_prefix('\'')
108                .and_then(|x| x.strip_suffix('\''))
109                .unwrap_or(v);
110            out.insert(k.trim().to_uppercase(), v.to_string());
111        }
112    }
113    out
114}
115
116/// Revolut X: an API key and the path of the Ed25519 private key registered to it.
117/// Environment first, then `revx.env`. The key file itself must be private too.
118pub fn load_revx(path: Option<&Path>) -> Result<RevxCredentials, KeyError> {
119    let (k_env, p_env) = ("RUNGBOT_REVX_KEY", "RUNGBOT_REVX_PRIVATE_KEY_PEM");
120    let from_env = (std::env::var(k_env), std::env::var(p_env));
121    let (key, pem) = match from_env {
122        (Ok(k), Ok(p)) if !k.trim().is_empty() && !p.trim().is_empty() => {
123            (k.trim().to_string(), p.trim().to_string())
124        }
125        _ => {
126            let owned;
127            let path = match path {
128                Some(p) => p,
129                None => {
130                    owned = default_key_path("revx");
131                    &owned
132                }
133            };
134            if !path.exists() {
135                return Err(KeyError::Missing(format!(
136                    "no credentials for revx: set {k_env} and {p_env}, or create {} (mode 600)",
137                    path.display()
138                )));
139            }
140            check_permissions(path)?;
141            let text = std::fs::read_to_string(path).map_err(|e| {
142                KeyError::Unreadable(format!("cannot read {}: {e}", path.display()))
143            })?;
144            let vars = parse_env(&text);
145            let key = vars.get(k_env).or_else(|| vars.get("KEY"));
146            let pem = vars.get(p_env).or_else(|| vars.get("PRIVATE_KEY_PEM"));
147            match (key, pem) {
148                (Some(k), Some(p)) if !k.is_empty() && !p.is_empty() => (k.clone(), p.clone()),
149                _ => {
150                    return Err(KeyError::Malformed(format!(
151                        "{} has no {k_env}/{p_env} (or KEY/PRIVATE_KEY_PEM) pair",
152                        path.display()
153                    )))
154                }
155            }
156        }
157    };
158    let pem_path = PathBuf::from(pem);
159    if !pem_path.exists() {
160        return Err(KeyError::Missing(format!(
161            "the Revolut X private key {} does not exist",
162            pem_path.display()
163        )));
164    }
165    check_permissions(&pem_path)?;
166    Ok(RevxCredentials { key, pem_path })
167}
168
169/// Environment first, then the key file.
170pub fn load(venue: &str, path: Option<&Path>) -> Result<Credentials, KeyError> {
171    let v = venue.to_uppercase();
172    let (k_env, s_env) = (format!("RUNGBOT_{v}_KEY"), format!("RUNGBOT_{v}_SECRET"));
173
174    if let (Ok(key), Ok(secret)) = (std::env::var(&k_env), std::env::var(&s_env)) {
175        if !key.trim().is_empty() && !secret.trim().is_empty() {
176            return Ok(Credentials {
177                key: key.trim().to_string(),
178                secret: secret.trim().to_string(),
179            });
180        }
181    }
182
183    let owned;
184    let path = match path {
185        Some(p) => p,
186        None => {
187            owned = default_key_path(venue);
188            &owned
189        }
190    };
191    if !path.exists() {
192        return Err(KeyError::Missing(format!(
193            "no credentials for {venue}: set {k_env} and {s_env}, or create {} (mode 600)",
194            path.display()
195        )));
196    }
197    check_permissions(path)?;
198    let text = std::fs::read_to_string(path)
199        .map_err(|e| KeyError::Unreadable(format!("cannot read {}: {e}", path.display())))?;
200    let vars = parse_env(&text);
201    let key = vars.get(&k_env).or_else(|| vars.get("KEY"));
202    let secret = vars.get(&s_env).or_else(|| vars.get("SECRET"));
203    match (key, secret) {
204        (Some(k), Some(s)) if !k.is_empty() && !s.is_empty() => Ok(Credentials {
205            key: k.clone(),
206            secret: s.clone(),
207        }),
208        _ => Err(KeyError::Malformed(format!(
209            "{} has no {k_env}/{s_env} (or KEY/SECRET) pair",
210            path.display()
211        ))),
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use std::io::Write;
219
220    /// A fixture path unique per test: two tests sharing one path race under the
221    /// default parallel runner, and the failure looks like a logic bug.
222    fn tmpfile(name: &str, body: &str, mode: u32) -> PathBuf {
223        let dir = std::env::temp_dir().join(format!("rungbot-keys-{}", std::process::id()));
224        std::fs::create_dir_all(&dir).unwrap();
225        let p = dir.join(format!("{name}.env"));
226        let mut f = std::fs::File::create(&p).unwrap();
227        f.write_all(body.as_bytes()).unwrap();
228        #[cfg(unix)]
229        {
230            use std::os::unix::fs::PermissionsExt;
231            std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode)).unwrap();
232        }
233        p
234    }
235
236    #[test]
237    fn the_environment_wins_over_a_file() {
238        let _env = crate::testenv::EnvGuard::set(&[
239            ("RUNGBOT_TESTV_KEY", Some("envkey")),
240            ("RUNGBOT_TESTV_SECRET", Some("envsecret")),
241        ]);
242        let c = load("testv", None).expect("env is enough");
243        assert_eq!(c.key, "envkey");
244    }
245
246    #[test]
247    fn a_missing_credential_says_exactly_what_to_set() {
248        let _env = crate::testenv::EnvGuard::set(&[
249            ("RUNGBOT_NOPEV_KEY", None),
250            ("RUNGBOT_NOPEV_SECRET", None),
251        ]);
252        let e = load("nopev", Some(Path::new("/definitely/not/here.env"))).unwrap_err();
253        let m = e.to_string();
254        assert!(m.contains("RUNGBOT_NOPEV_KEY"), "{m}");
255        assert!(m.contains("mode 600"), "{m}");
256    }
257
258    #[cfg(unix)]
259    #[test]
260    fn a_world_readable_key_file_is_refused_not_warned_about() {
261        let _env = crate::testenv::EnvGuard::set(&[
262            ("RUNGBOT_GATE_KEY", None),
263            ("RUNGBOT_GATE_SECRET", None),
264        ]);
265        let p = tmpfile("world-readable", "KEY=a\nSECRET=b\n", 0o644);
266        let e = load("gate", Some(&p)).unwrap_err();
267        assert!(matches!(e, KeyError::BadPermissions { .. }), "{e}");
268        assert!(e.to_string().contains("chmod 600"), "{e}");
269    }
270
271    #[cfg(unix)]
272    #[test]
273    fn a_private_key_file_loads_and_tolerates_quoting() {
274        let _env = crate::testenv::EnvGuard::set(&[
275            ("RUNGBOT_GATE_KEY", None),
276            ("RUNGBOT_GATE_SECRET", None),
277        ]);
278        let p = tmpfile("private", "# gate\nKEY=\"abc\"\nSECRET='def'\n", 0o600);
279        let c = load("gate", Some(&p)).expect("0600 is fine");
280        assert_eq!(c.key, "abc");
281        assert_eq!(c.secret, "def", "quotes a UI added are stripped");
282    }
283
284    #[cfg(unix)]
285    #[test]
286    fn a_file_without_a_pair_is_malformed_rather_than_half_loaded() {
287        let _env = crate::testenv::EnvGuard::set(&[
288            ("RUNGBOT_GATE_KEY", None),
289            ("RUNGBOT_GATE_SECRET", None),
290        ]);
291        let p = tmpfile("half", "KEY=only\n", 0o600);
292        assert!(matches!(
293            load("gate", Some(&p)),
294            Err(KeyError::Malformed(_))
295        ));
296    }
297
298    #[test]
299    fn debug_never_prints_a_secret() {
300        let c = Credentials {
301            key: "k".into(),
302            secret: "very-secret".into(),
303        };
304        assert!(!format!("{c:?}").contains("very-secret"));
305    }
306
307    #[cfg(unix)]
308    #[test]
309    fn a_revx_key_loads_from_its_file_and_its_pem_must_be_private() {
310        let _env = crate::testenv::EnvGuard::set(&[
311            ("RUNGBOT_REVX_KEY", None),
312            ("RUNGBOT_REVX_PRIVATE_KEY_PEM", None),
313        ]);
314        let pem = tmpfile("revx-pem", "-----BEGIN PRIVATE KEY-----\n", 0o600);
315        let env = tmpfile(
316            "revx",
317            &format!("KEY=rk\nPRIVATE_KEY_PEM={}\n", pem.display()),
318            0o600,
319        );
320        let c = load_revx(Some(&env)).expect("private files load");
321        assert_eq!(c.key, "rk");
322        assert_eq!(c.pem_path, pem);
323
324        let open = tmpfile("revx-pem-open", "x", 0o644);
325        let env2 = tmpfile(
326            "revx2",
327            &format!("KEY=rk\nPRIVATE_KEY_PEM={}\n", open.display()),
328            0o600,
329        );
330        assert!(matches!(
331            load_revx(Some(&env2)),
332            Err(KeyError::BadPermissions { .. })
333        ));
334    }
335
336    #[test]
337    fn the_default_path_is_under_the_config_dir_not_next_to_the_watchlist() {
338        let _env = crate::testenv::EnvGuard::set(&[("XDG_CONFIG_HOME", Some("/tmp/cfg"))]);
339        let p = default_key_path("gate");
340        assert_eq!(p, PathBuf::from("/tmp/cfg/rungbot/gate.env"));
341    }
342}