This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
use std::env;
|
||||
use std::io::Write;
|
||||
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 {
|
||||
recipient: Option<String>,
|
||||
identity_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Crypto {
|
||||
pub fn from_env() -> Self {
|
||||
Self {
|
||||
recipient: env::var("ROUTINE_AGE_RECIPIENT").ok(),
|
||||
identity_file: env::var_os("ROUTINE_AGE_IDENTITY_FILE").map(PathBuf::from),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn disabled() -> Self {
|
||||
Self {
|
||||
recipient: None,
|
||||
identity_file: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encrypt_optional(
|
||||
&self,
|
||||
private_title: Option<String>,
|
||||
notes: Option<String>,
|
||||
) -> Result<EncryptedFields, String> {
|
||||
if private_title.is_none() && notes.is_none() {
|
||||
return Ok(EncryptedFields::default());
|
||||
}
|
||||
let recipient = self
|
||||
.recipient
|
||||
.as_deref()
|
||||
.ok_or_else(|| "ROUTINE_AGE_RECIPIENT is required 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 encrypted_payload = run_age(
|
||||
&["--encrypt", "--armor", "--recipient", recipient],
|
||||
&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", "--identity", identity],
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
fn run_age(arguments: &[&str], 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 {
|
||||
recipient: Some(
|
||||
String::from_utf8(recipient.stdout)
|
||||
.unwrap()
|
||||
.trim()
|
||||
.to_owned(),
|
||||
),
|
||||
identity_file: Some(identity_file),
|
||||
};
|
||||
let encrypted = crypto
|
||||
.encrypt_optional(
|
||||
Some("Private appointment".to_owned()),
|
||||
Some("Private notes".to_owned()),
|
||||
)
|
||||
.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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user