mod files;
#[cfg(test)]
mod tests;
use age::{
armor::{ArmoredReader, ArmoredWriter, Format},
secrecy::ExposeSecret,
x25519,
};
use anyhow::{Context, Result, ensure};
use bech32::FromBase32;
use gent_protocol::secret_handoff::{MAX_ARMOR_BYTES as MAX_ARMOR, MAX_SECRET_BYTES as MAX_SECRET};
use ring::{agreement, rand::SystemRandom};
use serde_json::{Value, json};
use std::{
io::{Read, Write},
path::PathBuf,
};
use zeroize::Zeroizing;
#[derive(clap::Subcommand)]
pub enum Command {
Keygen {
#[arg(long)]
identity: PathBuf,
},
Seal {
#[arg(long)]
recipient: String,
#[arg(long)]
input: PathBuf,
#[arg(long)]
out: PathBuf,
},
Open {
#[arg(long)]
identity: PathBuf,
#[arg(long)]
input: PathBuf,
#[arg(long)]
out: PathBuf,
},
}
pub fn execute(command: Command) -> Result<Value> {
match command {
Command::Keygen { identity } => {
let key = x25519::Identity::generate();
let recipient = key.to_public().to_string();
let secret = key.to_string();
files::publish(&identity, |file| {
writeln!(file, "{}", secret.expose_secret())
})?;
let url = format!("https://gent.link/assets/secret-handoff.html#{recipient}");
Ok(json!({"recipient": recipient, "url": url}))
}
Command::Seal {
recipient,
input,
out,
} => {
let recipient = parse_recipient(&recipient)?;
let plaintext = files::read(&input, MAX_SECRET, false)?;
let encryptor = age::Encryptor::with_recipients(std::iter::once(
&recipient as &dyn age::Recipient,
))?;
let armor = ArmoredWriter::wrap_output(Vec::new(), Format::AsciiArmor)?;
let mut encrypted = encryptor.wrap_output(armor)?;
encrypted.write_all(&plaintext)?;
let envelope = encrypted.finish()?.finish()?;
ensure!(
envelope.len() <= MAX_ARMOR,
"encrypted handoff exceeds message limit"
);
files::publish(&out, |file| file.write_all(&envelope))?;
Ok(json!({"state": "sealed"}))
}
Command::Open {
identity,
input,
out,
} => {
let key = files::read(&identity, 1024, true)?;
let key = std::str::from_utf8(&key)
.ok()
.and_then(|s| s.trim().parse::<x25519::Identity>().ok())
.context("expected one private age X25519 identity")?;
let envelope = files::read(&input, MAX_ARMOR, false)?;
let plaintext = open(&key, &envelope).map_err(|_| {
anyhow::anyhow!("invalid handoff, wrong identity, or secret outside the size limit")
})?;
files::publish(&out, |file| file.write_all(&plaintext))?;
Ok(json!({"state": "opened"}))
}
}
}
fn parse_recipient(encoded: &str) -> Result<x25519::Recipient> {
const INVALID: &str = "invalid public age X25519 recipient";
let recipient = encoded.parse().ok().context(INVALID)?;
let (_, words, _) = bech32::decode(encoded).ok().context(INVALID)?;
let public = Vec::<u8>::from_base32(&words).ok().context(INVALID)?;
let public = agreement::UnparsedPublicKey::new(&agreement::X25519, public);
let probe = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &SystemRandom::new())
.map_err(|_| anyhow::anyhow!("cannot validate recipient"))?;
agreement::agree_ephemeral(probe, &public, |_| ()).map_err(|_| anyhow::anyhow!(INVALID))?;
Ok(recipient)
}
fn open(key: &x25519::Identity, envelope: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
ensure!(
envelope.starts_with(b"-----BEGIN AGE ENCRYPTED FILE-----"),
"expected age armor"
);
let mut ciphertext = Vec::new();
ArmoredReader::new(envelope).read_to_end(&mut ciphertext)?;
let decryptor = age::Decryptor::new_buffered(ciphertext.as_slice())?;
let reader = decryptor.decrypt(std::iter::once(key as &dyn age::Identity))?;
let mut bytes = Zeroizing::new(Vec::with_capacity(MAX_SECRET + 1));
reader
.take((MAX_SECRET + 1) as u64)
.read_to_end(&mut bytes)?;
ensure!(
(1..=MAX_SECRET).contains(&bytes.len()),
"invalid plaintext length"
);
Ok(bytes)
}