Skip to main content

perspt_agent/
grant.rs

1//! Persistent grant signing-key resolution.
2
3use std::fs::OpenOptions;
4use std::io::{Read, Write};
5use std::path::PathBuf;
6
7use anyhow::{Context, Result};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum GrantKeySource {
11    OperatorEnvironment,
12    OsCredentialStore,
13    InstallationFile,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct GrantSigningKey {
18    pub bytes: [u8; 32],
19    pub source: GrantKeySource,
20}
21
22impl GrantSigningKey {
23    /// The Ed25519 public key persisted grants must verify against.
24    pub fn public_key(&self) -> [u8; 32] {
25        perspt_sdk::grant_public_key(&self.bytes)
26    }
27
28    pub fn resolve() -> Result<Self> {
29        if let Ok(value) = std::env::var("PERSPT_GRANT_SIGNING_KEY") {
30            return Ok(Self {
31                bytes: decode_key(value.trim())?,
32                source: GrantKeySource::OperatorEnvironment,
33            });
34        }
35        if let Some(bytes) = credential_store_key() {
36            return Ok(Self {
37                bytes,
38                source: GrantKeySource::OsCredentialStore,
39            });
40        }
41        let path = key_file_path()?;
42        if path.is_file() {
43            let mut value = String::new();
44            std::fs::File::open(&path)?.read_to_string(&mut value)?;
45            return Ok(Self {
46                bytes: decode_key(value.trim())?,
47                source: GrantKeySource::InstallationFile,
48            });
49        }
50        let parent = path.parent().context("grant key path has no parent")?;
51        std::fs::create_dir_all(parent)?;
52        let mut bytes = [0u8; 32];
53        rand::fill(&mut bytes);
54        write_private_key(&path, &encode_key(&bytes))?;
55        log::warn!(
56            "OS credential store unavailable; persistent grant key stored in mode-0600 file {}",
57            path.display()
58        );
59        Ok(Self {
60            bytes,
61            source: GrantKeySource::InstallationFile,
62        })
63    }
64}
65
66fn key_file_path() -> Result<PathBuf> {
67    perspt_core::paths::config_dir()
68        .map(|directory| directory.join("grant-signing.key"))
69        .context("platform configuration directory is unavailable")
70}
71
72#[cfg(unix)]
73fn write_private_key(path: &std::path::Path, value: &str) -> Result<()> {
74    use std::os::unix::fs::OpenOptionsExt;
75    let mut file = OpenOptions::new()
76        .create_new(true)
77        .write(true)
78        .mode(0o600)
79        .open(path)?;
80    file.write_all(value.as_bytes())?;
81    Ok(())
82}
83
84#[cfg(not(unix))]
85fn write_private_key(path: &std::path::Path, value: &str) -> Result<()> {
86    let mut file = OpenOptions::new().create_new(true).write(true).open(path)?;
87    file.write_all(value.as_bytes())?;
88    Ok(())
89}
90
91#[cfg(target_os = "macos")]
92fn credential_store_key() -> Option<[u8; 32]> {
93    let output = std::process::Command::new("/usr/bin/security")
94        .args([
95            "find-generic-password",
96            "-s",
97            "perspt-grant-signing-key",
98            "-w",
99        ])
100        .output()
101        .ok()?;
102    if output.status.success() {
103        decode_key(String::from_utf8_lossy(&output.stdout).trim()).ok()
104    } else {
105        None
106    }
107}
108
109#[cfg(target_os = "linux")]
110fn credential_store_key() -> Option<[u8; 32]> {
111    let output = std::process::Command::new("secret-tool")
112        .args([
113            "lookup",
114            "application",
115            "perspt",
116            "purpose",
117            "grant-signing",
118        ])
119        .output()
120        .ok()?;
121    if output.status.success() {
122        decode_key(String::from_utf8_lossy(&output.stdout).trim()).ok()
123    } else {
124        None
125    }
126}
127
128#[cfg(not(any(target_os = "macos", target_os = "linux")))]
129fn credential_store_key() -> Option<[u8; 32]> {
130    None
131}
132
133fn decode_key(value: &str) -> Result<[u8; 32]> {
134    anyhow::ensure!(
135        value.len() == 64,
136        "grant signing key must be 64 hex characters"
137    );
138    perspt_sdk::hex_decode(value)
139        .map_err(|error| anyhow::anyhow!("grant signing key contains invalid hex: {error}"))?
140        .try_into()
141        .map_err(|_| anyhow::anyhow!("grant signing key must decode to 32 bytes"))
142}
143
144fn encode_key(bytes: &[u8; 32]) -> String {
145    perspt_sdk::hex_encode(bytes)
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn key_encoding_round_trips() {
154        let bytes = [19u8; 32];
155        assert_eq!(decode_key(&encode_key(&bytes)).unwrap(), bytes);
156    }
157}