Files
hearth/package/routine-tui/src/crypto.rs
T
yukkop 21cc43a1c3
runner nix smoke / nix label and flake smoke (push) Canceled after 0s
overude
2026-10-15 23:53:23 +00:00

380 lines
13 KiB
Rust

use std::env;
use std::fs::OpenOptions;
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
#[cfg(test)]
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::model::{EncryptedFields, PrivatePayload, Routine, Task};
const ENCRYPTION_VERSION: i16 = 1;
static CONTENT_COUNTER: AtomicU64 = AtomicU64::new(0);
pub struct Crypto {
identity_file: Option<PathBuf>,
temporary_identity_file: Option<PathBuf>,
}
impl Crypto {
pub fn from_env() -> Result<Self, String> {
Self::from_configuration(
env::var_os("ROUTINE_AGE_IDENTITY_FILE").map(PathBuf::from),
env::var("ROUTINE_AGE_IDENTITY_COMMAND").ok(),
)
}
fn from_configuration(
identity_file: Option<PathBuf>,
identity_command: Option<String>,
) -> Result<Self, String> {
match (identity_file, identity_command) {
(Some(_), Some(_)) => Err(
"set only one of ROUTINE_AGE_IDENTITY_FILE or ROUTINE_AGE_IDENTITY_COMMAND"
.to_owned(),
),
(Some(identity_file), None) => Ok(Self {
identity_file: Some(identity_file),
temporary_identity_file: None,
}),
(None, Some(command)) => {
let identity_file = run_identity_command(&command)?;
Ok(Self {
identity_file: Some(identity_file.clone()),
temporary_identity_file: Some(identity_file),
})
}
(None, None) => Ok(Self {
identity_file: None,
temporary_identity_file: None,
}),
}
}
#[cfg(test)]
pub fn disabled() -> Self {
Self {
identity_file: None,
temporary_identity_file: None,
}
}
pub fn encrypt_optional(
&self,
private_title: Option<String>,
notes: Option<String>,
recipients: &[String],
) -> Result<EncryptedFields, String> {
if private_title.is_none() && notes.is_none() {
return Ok(EncryptedFields::default());
}
if recipients.is_empty() {
return Err(
"register at least one active encryption device for private fields".to_owned(),
);
}
let content_id = new_content_id()?;
let plaintext = serde_json::to_vec(&PrivatePayload {
version: ENCRYPTION_VERSION as u8,
content_id: content_id.clone(),
private_title,
notes,
})
.map_err(|error| format!("cannot encode private fields: {error}"))?;
let mut arguments = vec!["--encrypt".to_owned(), "--armor".to_owned()];
for recipient in recipients {
arguments.push("--recipient".to_owned());
arguments.push(recipient.clone());
}
let encrypted_payload = run_age(&arguments, &plaintext)?;
let encrypted_payload = String::from_utf8(encrypted_payload)
.map_err(|_| "age returned non-UTF-8 armored output".to_owned())?;
Ok(EncryptedFields {
encrypted_payload: Some(encrypted_payload),
encryption_version: Some(ENCRYPTION_VERSION),
content_id: Some(content_id),
})
}
pub fn decrypt_task(&self, task: &mut Task) {
match self.decrypt_fields(
task.encrypted_payload.as_deref(),
task.encryption_version,
task.content_id.as_deref(),
) {
Ok(Some(private)) => {
task.private_title = private
.private_title
.filter(|title| !title.trim().is_empty());
task.private_notes = private.notes.filter(|notes| !notes.trim().is_empty());
}
Ok(None) => {}
Err(()) => task.decryption_failed = true,
}
}
pub fn decrypt_routine(&self, routine: &mut Routine) {
match self.decrypt_fields(
routine.encrypted_payload.as_deref(),
routine.encryption_version,
routine.content_id.as_deref(),
) {
Ok(Some(private)) => {
routine.private_title = private
.private_title
.filter(|title| !title.trim().is_empty());
routine.private_notes = private.notes.filter(|notes| !notes.trim().is_empty());
}
Ok(None) => {}
Err(()) => routine.decryption_failed = true,
}
}
fn decrypt_fields(
&self,
encrypted_payload: Option<&str>,
encryption_version: Option<i16>,
content_id: Option<&str>,
) -> Result<Option<PrivatePayload>, ()> {
let Some(encrypted_payload) = encrypted_payload else {
return Ok(None);
};
if encryption_version != Some(ENCRYPTION_VERSION) {
return Err(());
}
let identity_file = self.identity_file.as_ref().ok_or(())?;
let identity = identity_file.to_str().ok_or(())?;
let plaintext = run_age(
&[
"--decrypt".to_owned(),
"--identity".to_owned(),
identity.to_owned(),
],
encrypted_payload.as_bytes(),
)
.map_err(|_| ())?;
let private: PrivatePayload = serde_json::from_slice(&plaintext).map_err(|_| ())?;
if private.version != ENCRYPTION_VERSION as u8
|| Some(private.content_id.as_str()) != content_id
{
return Err(());
}
Ok(Some(private))
}
}
impl Drop for Crypto {
fn drop(&mut self) {
if let Some(path) = &self.temporary_identity_file {
let _ = std::fs::remove_file(path);
}
}
}
fn run_identity_command(command: &str) -> Result<PathBuf, String> {
if command.trim().is_empty() {
return Err("ROUTINE_AGE_IDENTITY_COMMAND must not be empty".to_owned());
}
let output = Command::new("sh")
.args(["-c", command])
.stdin(Stdio::inherit())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.output()
.map_err(|error| format!("cannot start ROUTINE_AGE_IDENTITY_COMMAND: {error}"))?;
if !output.status.success() {
return Err(format!(
"ROUTINE_AGE_IDENTITY_COMMAND exited with {}",
output.status
));
}
if output.stdout.iter().all(u8::is_ascii_whitespace) {
return Err("ROUTINE_AGE_IDENTITY_COMMAND returned an empty identity".to_owned());
}
let path = env::temp_dir().join(format!("routine-age-identity-{}", new_content_id()?));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&path)
.map_err(|error| format!("cannot create temporary age identity: {error}"))?;
if let Err(error) = file.write_all(&output.stdout) {
let _ = std::fs::remove_file(&path);
return Err(format!("cannot write temporary age identity: {error}"));
}
Ok(path)
}
fn run_age(arguments: &[String], input: &[u8]) -> Result<Vec<u8>, String> {
let mut child = Command::new("age")
.args(arguments)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|error| format!("cannot start age: {error}"))?;
child
.stdin
.take()
.ok_or_else(|| "cannot open age input".to_owned())?
.write_all(input)
.map_err(|error| format!("cannot write age input: {error}"))?;
let output = child
.wait_with_output()
.map_err(|error| format!("cannot wait for age: {error}"))?;
if output.status.success() {
Ok(output.stdout)
} else {
let detail = String::from_utf8_lossy(&output.stderr);
Err(format!("age failed: {}", detail.trim()))
}
}
fn new_content_id() -> Result<String, String> {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| "system clock is before Unix epoch".to_owned())?
.as_nanos();
let counter = CONTENT_COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
let process = std::process::id() as u128;
Ok(format!("{:032x}", nanos ^ (process << 64) ^ counter))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn age_round_trip_preserves_private_json_and_content_id() {
let test_dir =
env::temp_dir().join(format!("routine-age-test-{}", new_content_id().unwrap()));
std::fs::create_dir(&test_dir).unwrap();
let identity_file = test_dir.join("identity.txt");
let generated = Command::new("age-keygen")
.args(["-o", identity_file.to_str().unwrap()])
.output()
.unwrap();
assert!(generated.status.success());
let recipient = Command::new("age-keygen")
.args(["-y", identity_file.to_str().unwrap()])
.output()
.unwrap();
assert!(recipient.status.success());
let crypto =
Crypto::from_configuration(None, Some(format!("cat {}", identity_file.display())))
.unwrap();
let recipient = String::from_utf8(recipient.stdout)
.unwrap()
.trim()
.to_owned();
let encrypted = crypto
.encrypt_optional(
Some("Private appointment".to_owned()),
Some("Private notes".to_owned()),
&[recipient],
)
.unwrap();
let decrypted = crypto
.decrypt_fields(
encrypted.encrypted_payload.as_deref(),
encrypted.encryption_version,
encrypted.content_id.as_deref(),
)
.unwrap()
.unwrap();
assert_eq!(decrypted.content_id, encrypted.content_id.unwrap());
assert_eq!(
decrypted.private_title.as_deref(),
Some("Private appointment")
);
assert_eq!(decrypted.notes.as_deref(), Some("Private notes"));
std::fs::remove_dir_all(test_dir).unwrap();
}
#[test]
fn one_payload_decrypts_with_each_registered_identity() {
let test_dir = env::temp_dir().join(format!(
"routine-age-multi-test-{}",
new_content_id().unwrap()
));
std::fs::create_dir(&test_dir).unwrap();
let mut identities = Vec::new();
let mut recipients = Vec::new();
for index in 0..2 {
let identity = test_dir.join(format!("identity-{index}.txt"));
assert!(Command::new("age-keygen")
.args(["-o", identity.to_str().unwrap()])
.status()
.unwrap()
.success());
let recipient = Command::new("age-keygen")
.args(["-y", identity.to_str().unwrap()])
.output()
.unwrap();
recipients.push(
String::from_utf8(recipient.stdout)
.unwrap()
.trim()
.to_owned(),
);
identities.push(identity);
}
let encryptor = Crypto {
identity_file: None,
temporary_identity_file: None,
};
let encrypted = encryptor
.encrypt_optional(Some("shared".to_owned()), None, &recipients)
.unwrap();
for identity_file in identities {
let decryptor = Crypto {
identity_file: Some(identity_file),
temporary_identity_file: None,
};
let decrypted = decryptor
.decrypt_fields(
encrypted.encrypted_payload.as_deref(),
encrypted.encryption_version,
encrypted.content_id.as_deref(),
)
.unwrap()
.unwrap();
assert_eq!(decrypted.private_title.as_deref(), Some("shared"));
}
std::fs::remove_dir_all(test_dir).unwrap();
}
#[test]
fn identity_command_is_loaded_before_use_and_removed_on_drop() {
let crypto =
Crypto::from_configuration(None, Some("printf 'AGE-SECRET-KEY-TEST\\n'".to_owned()))
.unwrap();
let path = crypto.identity_file.clone().unwrap();
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"AGE-SECRET-KEY-TEST\n"
);
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
drop(crypto);
assert!(!path.exists());
}
#[test]
fn identity_sources_are_mutually_exclusive() {
let error = Crypto::from_configuration(
Some(PathBuf::from("identity.txt")),
Some("password-manager read identity".to_owned()),
)
.err()
.unwrap();
assert!(error.contains("set only one"));
}
}