Skip to main content

token_manager/
credentials.rs

1use crate::state::{Account, Credential, read_private};
2use anyhow::{Result, bail, ensure};
3use std::{
4    io::Write,
5    process::{Command, Stdio},
6    thread,
7    time::{Duration, Instant},
8};
9
10pub fn validate(secret: String) -> Result<String> {
11    let secret = secret.trim().to_owned();
12    ensure!(
13        !secret.is_empty() && secret.len() <= 8192 && !secret.chars().any(char::is_control),
14        "credential must be nonempty, bounded and contain no control characters"
15    );
16    Ok(secret)
17}
18fn keyring(action: &str, name: &str, input: Option<&str>) -> Result<String> {
19    let mut command = Command::new("secret-tool");
20    command.arg(action);
21    if action == "store" {
22        command.arg("--label=Token Manager account credential");
23    }
24    command
25        .args(["application", "token-manager", "account", name])
26        .stdin(Stdio::piped())
27        .stdout(Stdio::piped())
28        .stderr(Stdio::null());
29    let mut child = command.spawn().map_err(|_| {
30        anyhow::anyhow!("OS keyring unavailable; install secret-tool, or use --env or --key-file")
31    })?;
32    if let Some(input) = input {
33        child.stdin.take().unwrap().write_all(input.as_bytes())?;
34    } else {
35        drop(child.stdin.take());
36    }
37    let deadline = Instant::now() + Duration::from_secs(10);
38    loop {
39        if child.try_wait()?.is_some() {
40            break;
41        }
42        if Instant::now() >= deadline {
43            let _ = child.kill();
44            let _ = child.wait();
45            bail!("OS keyring did not respond; unlock it or use --env/--key-file");
46        }
47        thread::sleep(Duration::from_millis(20));
48    }
49    let output = child.wait_with_output()?;
50    ensure!(
51        output.status.success(),
52        "OS keyring operation failed; unlock your keyring or use --env/--key-file"
53    );
54    String::from_utf8(output.stdout).map_err(|_| anyhow::anyhow!("invalid credential encoding"))
55}
56pub fn store(name: &str, secret: &str) -> Result<()> {
57    keyring("store", name, Some(secret))?;
58    Ok(())
59}
60pub fn resolve(account: &Account) -> Result<String> {
61    let value = match &account.credential {
62        Credential::None => bail!("No credential method for this account capability"),
63        Credential::Keyring(id) => keyring("lookup", id, None)?,
64        Credential::Env(name) => std::env::var(name)
65            .map_err(|_| anyhow::anyhow!("credential environment variable is unset"))?,
66        Credential::File(path) => String::from_utf8(read_private(path)?)
67            .map_err(|_| anyhow::anyhow!("invalid credential encoding"))?,
68    };
69    validate(value)
70}