Skip to main content

hyprstream_core/auth/
age_seal.rs

1//! Shared `age` seal/open boundary for deployment secrets.
2//!
3//! Deployment trust minting and relational UserStore DEK wrapping deliberately
4//! use this one subprocess boundary. Keeping recipient/identity validation and
5//! partial-plaintext zeroization here prevents the two production paths from
6//! drifting into subtly different `age` invocations.
7
8use anyhow::{anyhow, ensure, Context, Result};
9use std::{
10    collections::BTreeSet,
11    fs::File,
12    io::{Seek as _, SeekFrom, Write as _},
13    os::fd::{AsRawFd as _, FromRawFd as _},
14    path::{Path, PathBuf},
15    process::{Command, Stdio},
16};
17use zeroize::Zeroizing;
18
19/// A validated, non-empty set of deployment `age` recipients.
20#[derive(Clone, Debug, Eq, PartialEq)]
21pub(crate) struct AgeRecipients(Vec<String>);
22
23impl AgeRecipients {
24    pub(crate) fn new(recipients: Vec<String>) -> Result<Self> {
25        let mut distinct = BTreeSet::new();
26        for recipient in recipients {
27            let recipient = recipient.trim();
28            ensure!(!recipient.is_empty(), "age recipient is empty");
29            ensure!(
30                recipient.is_ascii() && !recipient.contains(['\n', '\r', '\0']),
31                "age recipient contains invalid characters"
32            );
33            distinct.insert(recipient.to_owned());
34        }
35        ensure!(!distinct.is_empty(), "no age recipients supplied");
36        Ok(Self(distinct.into_iter().collect()))
37    }
38
39    /// Encrypt bytes through the deployment trust-mint `age` seam.
40    pub(crate) fn seal(&self, plaintext: &[u8], max_ciphertext_bytes: usize) -> Result<Vec<u8>> {
41        let mut command = age_command(false);
42        for recipient in &self.0 {
43            command.arg("--recipient").arg(recipient);
44        }
45        command.arg("-");
46        let output = run_with_stdin(command, plaintext, "encryption")?;
47        ensure!(output.status.success(), "age encryption failed");
48        ensure!(
49            !output.stdout.is_empty() && output.stdout.len() <= max_ciphertext_bytes,
50            "age encryption returned invalid ciphertext size"
51        );
52        Ok(output.stdout.to_vec())
53    }
54}
55
56/// Where an `age` identity comes from: an on-disk file, or in-memory bytes
57/// staged into an anonymous memfd for the `age` child so the inherited-FD
58/// credential interface (`mint-registry-jwt --identity-fd`) never writes
59/// plaintext identity material to a filesystem path.
60#[derive(Clone, Debug, Eq, PartialEq)]
61pub(crate) enum AgeIdentitySource {
62    Path(PathBuf),
63    InMemory(Zeroizing<Vec<u8>>),
64}
65
66/// A validated, non-empty set of deployment `age` identities.
67#[derive(Clone, Debug, Eq, PartialEq)]
68pub(crate) struct AgeIdentities(Vec<AgeIdentitySource>);
69
70impl AgeIdentities {
71    pub(crate) fn new(identities: Vec<PathBuf>) -> Result<Self> {
72        Self::from_sources(
73            identities
74                .into_iter()
75                .map(AgeIdentitySource::Path)
76                .collect(),
77        )
78    }
79
80    /// In-memory identities read from inherited file descriptors. The bytes
81    /// are handed to the `age` child through an anonymous memfd, never a
82    /// filesystem path.
83    pub(crate) fn new_in_memory(identities: Vec<Zeroizing<Vec<u8>>>) -> Result<Self> {
84        Self::from_sources(
85            identities
86                .into_iter()
87                .map(AgeIdentitySource::InMemory)
88                .collect(),
89        )
90    }
91
92    pub(crate) fn from_sources(identities: Vec<AgeIdentitySource>) -> Result<Self> {
93        ensure!(!identities.is_empty(), "no age identities supplied");
94        for identity in &identities {
95            match identity {
96                AgeIdentitySource::Path(path) => ensure!(
97                    path.is_file(),
98                    "age identity file does not exist: {}",
99                    path.display()
100                ),
101                AgeIdentitySource::InMemory(bytes) => {
102                    ensure!(!bytes.is_empty(), "in-memory age identity is empty");
103                }
104            }
105        }
106        Ok(Self(identities))
107    }
108
109    /// Decrypt an in-memory ciphertext, zeroizing partial output on every
110    /// status and size error path.
111    pub(crate) fn open(
112        &self,
113        ciphertext: &[u8],
114        max_plaintext_bytes: usize,
115    ) -> Result<Zeroizing<Vec<u8>>> {
116        ensure!(!ciphertext.is_empty(), "age ciphertext is empty");
117        let (mut command, _guards) = self.decrypt_command()?;
118        command.arg("-");
119        let output = run_with_stdin(command, ciphertext, "decryption")?;
120        checked_plaintext(output, max_plaintext_bytes)
121    }
122
123    /// Decrypt a file without copying its ciphertext into process memory.
124    pub(crate) fn open_file(
125        &self,
126        path: &Path,
127        max_plaintext_bytes: usize,
128    ) -> Result<Zeroizing<Vec<u8>>> {
129        ensure!(
130            path.is_file(),
131            "age ciphertext file does not exist: {}",
132            path.display()
133        );
134        let (mut command, _guards) = self.decrypt_command()?;
135        command.stdin(Stdio::inherit()).arg(path);
136        let output = command.output().context("launch age decryption")?;
137        checked_plaintext(
138            GuardedOutput {
139                status: output.status,
140                stdout: Zeroizing::new(output.stdout),
141            },
142            max_plaintext_bytes,
143        )
144    }
145
146    /// Build the `age --decrypt` command. Returned `File` guards keep the
147    /// memfd descriptors backing in-memory identities alive (and inheritable
148    /// by the child) until the command has been awaited.
149    fn decrypt_command(&self) -> Result<(Command, Vec<File>)> {
150        let mut command = age_command(true);
151        let mut guards = Vec::new();
152        for identity in &self.0 {
153            command.arg("--identity");
154            match identity {
155                AgeIdentitySource::Path(path) => {
156                    command.arg(path);
157                }
158                AgeIdentitySource::InMemory(bytes) => {
159                    let memfd = memfd_identity(bytes)?;
160                    command.arg(format!("/proc/self/fd/{}", memfd.as_raw_fd()));
161                    guards.push(memfd);
162                }
163            }
164        }
165        Ok((command, guards))
166    }
167}
168
169/// Stage identity bytes in an anonymous memfd the `age` child inherits.
170///
171/// The memfd is created without `MFD_CLOEXEC` so the child spawned by
172/// [`Command`] inherits it; `Command` only closes descriptors flagged
173/// close-on-exec. The caller keeps the returned `File` alive until the child
174/// has exited.
175fn memfd_identity(bytes: &[u8]) -> Result<File> {
176    let name = c"hyprstream-age-identity";
177    let fd = unsafe { libc::memfd_create(name.as_ptr(), 0) };
178    if fd < 0 {
179        return Err(std::io::Error::last_os_error()).context("create memfd for age identity");
180    }
181    let mut file = unsafe { File::from_raw_fd(fd) };
182    file.write_all(bytes)
183        .context("write age identity to memfd")?;
184    file.seek(SeekFrom::Start(0))
185        .context("rewind age identity memfd")?;
186    Ok(file)
187}
188
189fn age_command(decrypt: bool) -> Command {
190    let mut command = Command::new("age");
191    command
192        .arg(if decrypt { "--decrypt" } else { "--encrypt" })
193        .arg("--output")
194        .arg("-")
195        .stdin(Stdio::piped())
196        .stdout(Stdio::piped())
197        .stderr(Stdio::inherit());
198    command
199}
200
201fn run_with_stdin(
202    mut command: Command,
203    input: &[u8],
204    operation: &'static str,
205) -> Result<GuardedOutput> {
206    let mut child = command
207        .spawn()
208        .with_context(|| format!("launch age {operation}"))?;
209    let write_result = child
210        .stdin
211        .take()
212        .ok_or_else(|| anyhow!("age stdin unavailable"))?
213        .write_all(input)
214        .with_context(|| format!("write age {operation} input"));
215    let output = child
216        .wait_with_output()
217        .with_context(|| format!("wait for age {operation}"))?;
218    let output = GuardedOutput {
219        status: output.status,
220        // Encryption produces ciphertext, while decryption can produce partial
221        // plaintext before failure. Guard both so a stdin-write error is also
222        // unable to bypass zeroization.
223        stdout: Zeroizing::new(output.stdout),
224    };
225    write_result?;
226    Ok(output)
227}
228
229struct GuardedOutput {
230    status: std::process::ExitStatus,
231    stdout: Zeroizing<Vec<u8>>,
232}
233
234fn checked_plaintext(
235    output: GuardedOutput,
236    max_plaintext_bytes: usize,
237) -> Result<Zeroizing<Vec<u8>>> {
238    ensure!(output.status.success(), "age decryption failed");
239    ensure!(
240        !output.stdout.is_empty() && output.stdout.len() <= max_plaintext_bytes,
241        "age decryption returned invalid plaintext size"
242    );
243    Ok(output.stdout)
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn recipient_validation_is_nonempty_distinct_and_control_free() {
252        assert!(AgeRecipients::new(Vec::new()).is_err());
253        assert!(AgeRecipients::new(vec!["age1ok\nage1injected".to_owned()]).is_err());
254        assert_eq!(
255            AgeRecipients::new(vec![" age1same ".to_owned(), "age1same".to_owned()])
256                .unwrap_or_else(|error| panic!("{error}"))
257                .0,
258            vec!["age1same"]
259        );
260    }
261
262    #[test]
263    fn identity_validation_is_fail_closed() {
264        assert!(AgeIdentities::new(Vec::new()).is_err());
265        assert!(AgeIdentities::new(vec![PathBuf::from("/definitely/not/an/identity")]).is_err());
266    }
267
268    #[test]
269    fn in_memory_identity_validation_is_fail_closed() {
270        assert!(AgeIdentities::new_in_memory(Vec::new()).is_err());
271        assert!(AgeIdentities::new_in_memory(vec![Zeroizing::new(Vec::new())]).is_err());
272        assert!(AgeIdentities::new_in_memory(vec![Zeroizing::new(
273            b"AGE-SECRET-KEY-1TEST".to_vec()
274        )])
275        .is_ok());
276    }
277}