use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use chrono::{DateTime, Utc};
use rusty_agent_runtime::journal::{Clock, EventDraft, Journal};
use rusty_agent_runtime::receipt::{RunReceipt, SigningKey, SigningKeyRotation};
use rusty_agent_runtime::record::{Effect, RunEventKind};
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use crate::server_store::{ServerStore, StoreResult};
pub(crate) const RECEIPTS_JOURNAL_RUN_ID: &str = "receipt-keys";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct ReceiptKeyRecord {
pub key_id: String,
pub public_key: String,
pub registered_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retired_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone)]
pub(crate) struct RotationOutcome {
pub previous_key_id: Option<String>,
pub new_key_id: String,
pub public_key: String,
pub event_id: String,
}
pub(crate) fn keys_dir(root: &Path) -> PathBuf {
root.join("keys")
}
pub(crate) fn receipts_dir(root: &Path) -> PathBuf {
root.join("receipts")
}
fn secret_path(root: &Path, key_id: &str) -> PathBuf {
keys_dir(root).join(format!("{key_id}.secret"))
}
fn record_path(root: &Path, key_id: &str) -> PathBuf {
keys_dir(root).join(format!("{key_id}.json"))
}
fn receipt_path(root: &Path, run_id: &str) -> PathBuf {
receipts_dir(root).join(format!("{run_id}.json"))
}
pub(crate) async fn persist_key_record(root: &Path, record: &ReceiptKeyRecord) -> io::Result<()> {
let dir = keys_dir(root);
tokio::fs::create_dir_all(&dir).await?;
let bytes = serde_json::to_vec_pretty(record)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let path = record_path(root, &record.key_id);
let tmp = dir.join(format!(".{}.tmp", record.key_id));
tokio::fs::write(&tmp, bytes).await?;
tokio::fs::rename(&tmp, path).await
}
pub(crate) async fn load_key_record(
root: &Path,
key_id: &str,
) -> io::Result<Option<ReceiptKeyRecord>> {
match tokio::fs::read(record_path(root, key_id)).await {
Ok(bytes) => serde_json::from_slice(&bytes)
.map(Some)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
pub(crate) fn load_key_records(root: &Path) -> Vec<ReceiptKeyRecord> {
let mut out = Vec::new();
let Ok(entries) = std::fs::read_dir(keys_dir(root)) else {
return out;
};
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
match std::fs::read(&path)
.ok()
.and_then(|bytes| serde_json::from_slice::<ReceiptKeyRecord>(&bytes).ok())
{
Some(record) => out.push(record),
None => tracing::warn!(path = %path.display(), "skipping unreadable key record file"),
}
}
out
}
pub(crate) async fn persist_run_receipt(
root: &Path,
run_id: &str,
receipt: &RunReceipt,
) -> io::Result<()> {
let dir = receipts_dir(root);
tokio::fs::create_dir_all(&dir).await?;
let bytes = serde_json::to_vec_pretty(receipt)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let path = receipt_path(root, run_id);
let tmp = dir.join(format!(".{run_id}.{}.tmp", uuid::Uuid::new_v4()));
tokio::fs::write(&tmp, bytes).await?;
tokio::fs::rename(&tmp, path).await
}
pub(crate) async fn load_run_receipt(root: &Path, run_id: &str) -> io::Result<Option<RunReceipt>> {
match tokio::fs::read(receipt_path(root, run_id)).await {
Ok(bytes) => serde_json::from_slice(&bytes)
.map(Some)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
pub(crate) fn load_all_run_receipts(root: &Path) -> io::Result<Vec<(String, RunReceipt)>> {
let mut out = Vec::new();
let entries = match std::fs::read_dir(receipts_dir(root)) {
Ok(entries) => entries,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(out),
Err(e) => return Err(e),
};
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let Some(run_id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else {
continue;
};
let bytes = std::fs::read(&path)?;
let receipt = serde_json::from_slice::<RunReceipt>(&bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
out.push((run_id, receipt));
}
Ok(out)
}
async fn write_secret(root: &Path, key_id: &str, signing_key: &SigningKey) -> io::Result<()> {
let dir = keys_dir(root);
tokio::fs::create_dir_all(&dir).await?;
let path = secret_path(root, key_id);
#[cfg(unix)]
{
let mut options = tokio::fs::OpenOptions::new();
options.write(true).create_new(true).mode(0o600);
use tokio::io::AsyncWriteExt as _;
let mut file = options.open(&path).await?;
file.write_all(signing_key.to_hex().as_bytes()).await?;
}
#[cfg(not(unix))]
{
tokio::fs::write(&path, signing_key.to_hex()).await?;
}
Ok(())
}
fn read_secret(root: &Path, key_id: &str) -> Option<SigningKey> {
let hex = std::fs::read_to_string(secret_path(root, key_id)).ok()?;
SigningKey::from_hex(hex.trim())
}
pub(crate) async fn journal_key_rotation(
store: &Arc<dyn ServerStore>,
rotation: &SigningKeyRotation,
) -> StoreResult<String> {
let journal = match store.get_journal(RECEIPTS_JOURNAL_RUN_ID).await? {
Some(snapshot) => Journal::from_snapshot(snapshot, Clock::System)
.map_err(|e| format!("the receipts journal failed its integrity check: {e}"))?,
None => Journal::new(
RECEIPTS_JOURNAL_RUN_ID,
RECEIPTS_JOURNAL_RUN_ID,
Clock::System,
),
};
let event_id = journal.record(
EventDraft::new(RunEventKind::SigningKeyRotated, Effect::Pure)
.output(serde_json::to_value(rotation).map_err(|e| e.to_string())?),
);
store.put_journal(&journal.snapshot()).await?;
Ok(event_id)
}
pub(crate) struct SigningKeyring {
store: Arc<dyn ServerStore>,
store_path: PathBuf,
active: Mutex<Option<SigningKey>>,
}
impl SigningKeyring {
pub(crate) fn new(store: Arc<dyn ServerStore>, store_path: PathBuf) -> Self {
Self {
store,
store_path,
active: Mutex::new(None),
}
}
pub(crate) async fn active_key(&self) -> StoreResult<SigningKey> {
let mut guard = self.active.lock().await;
self.ensure_locked(&mut guard).await
}
async fn ensure_locked(&self, guard: &mut Option<SigningKey>) -> StoreResult<SigningKey> {
if let Some(key) = guard {
return Ok(key.clone());
}
let mut records = self.store.list_receipt_keys().await?;
records.sort_by_key(|record| record.registered_at);
let active_records: Vec<&ReceiptKeyRecord> = records
.iter()
.filter(|record| record.retired_at.is_none())
.collect();
for record in active_records.iter().rev() {
if let Some(key) = read_secret(&self.store_path, &record.key_id) {
*guard = Some(key.clone());
return Ok(key);
}
}
let key = SigningKey::generate();
let key_id = key.key_id();
write_secret(&self.store_path, &key_id, &key)
.await
.map_err(|e| format!("write signing key secret: {e}"))?;
let record = ReceiptKeyRecord {
key_id: key_id.clone(),
public_key: key.public_key().to_hex(),
registered_at: Utc::now(),
retired_at: None,
};
self.store.put_receipt_key(&record).await?;
let previous_key_id = active_records.last().map(|record| record.key_id.clone());
journal_key_rotation(
&self.store,
&SigningKeyRotation {
previous_key_id,
new_key_id: key_id,
public_key: record.public_key,
rotated_at: record.registered_at,
},
)
.await?;
*guard = Some(key.clone());
Ok(key)
}
pub(crate) async fn rotate(&self) -> StoreResult<RotationOutcome> {
let mut guard = self.active.lock().await;
let current = self.ensure_locked(&mut guard).await?;
let previous_key_id = current.key_id();
let now = Utc::now();
if let Some(mut record) = self.store.get_receipt_key(&previous_key_id).await? {
record.retired_at = Some(now);
self.store.put_receipt_key(&record).await?;
}
let successor = SigningKey::generate();
let new_key_id = successor.key_id();
write_secret(&self.store_path, &new_key_id, &successor)
.await
.map_err(|e| format!("write signing key secret: {e}"))?;
let record = ReceiptKeyRecord {
key_id: new_key_id.clone(),
public_key: successor.public_key().to_hex(),
registered_at: now,
retired_at: None,
};
self.store.put_receipt_key(&record).await?;
let event_id = journal_key_rotation(
&self.store,
&SigningKeyRotation {
previous_key_id: Some(previous_key_id.clone()),
new_key_id: new_key_id.clone(),
public_key: record.public_key.clone(),
rotated_at: now,
},
)
.await?;
*guard = Some(successor);
Ok(RotationOutcome {
previous_key_id: Some(previous_key_id),
new_key_id,
public_key: record.public_key,
event_id,
})
}
}