use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::ops::Range;
use std::str::FromStr;
use std::sync::Arc;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::principal::{ActingContext, AgentId, SubjectRef};
use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
pub const AUDIT_RECORD_VERSION: u32 = 1;
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct AuditHash(pub [u8; 32]);
impl AuditHash {
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
impl fmt::Display for AuditHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in self.0 {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
impl fmt::Debug for AuditHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AuditHash({self})")
}
}
impl FromStr for AuditHash {
type Err = InvalidAuditHash;
fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
let bytes = text.as_bytes();
if bytes.len() != 64 {
return Err(InvalidAuditHash(format!(
"expected 64 hex characters, got {}",
bytes.len()
)));
}
let mut out = [0u8; 32];
for (index, pair) in bytes.chunks_exact(2).enumerate() {
let digit = |c: u8| match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
_ => None,
};
match (digit(pair[0]), digit(pair[1])) {
(Some(high), Some(low)) => out[index] = (high << 4) | low,
_ => {
return Err(InvalidAuditHash(
"expected lowercase hex characters (0-9, a-f)".to_string(),
));
}
}
}
Ok(Self(out))
}
}
impl TryFrom<String> for AuditHash {
type Error = InvalidAuditHash;
fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
value.parse()
}
}
impl From<AuditHash> for String {
fn from(value: AuditHash) -> Self {
value.to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("invalid audit hash: {0}")]
pub struct InvalidAuditHash(String);
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
#[non_exhaustive]
pub enum AuditRecordKind {
ToolCall,
Approval,
Governance,
Payment,
Access,
Authentication,
Configuration,
KeyRotated,
Erasure,
SessionHistory,
Other(String),
}
impl AuditRecordKind {
pub fn as_str(&self) -> &str {
match self {
Self::ToolCall => "tool_call",
Self::Approval => "approval",
Self::Governance => "governance",
Self::Payment => "payment",
Self::Access => "access",
Self::Authentication => "authentication",
Self::Configuration => "configuration",
Self::KeyRotated => "key_rotated",
Self::Erasure => "erasure",
Self::SessionHistory => "session_history",
Self::Other(name) => name,
}
}
}
impl From<String> for AuditRecordKind {
fn from(value: String) -> Self {
match value.as_str() {
"tool_call" => Self::ToolCall,
"approval" => Self::Approval,
"governance" => Self::Governance,
"payment" => Self::Payment,
"access" => Self::Access,
"authentication" => Self::Authentication,
"configuration" => Self::Configuration,
"key_rotated" => Self::KeyRotated,
"erasure" => Self::Erasure,
"session_history" => Self::SessionHistory,
_ => Self::Other(value),
}
}
}
impl From<AuditRecordKind> for String {
fn from(value: AuditRecordKind) -> Self {
match value {
AuditRecordKind::Other(name) => name,
known => known.as_str().to_string(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuditDecision {
Allowed,
Denied,
ApprovalRequired,
Approved,
Rejected,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuditRecordOutcome {
Succeeded,
Failed,
OutcomeUnknown,
NotRun,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditActor {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent: Option<AgentId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tenant: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instance: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_behalf_of: Option<SubjectRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub delegation_chain: Vec<SubjectRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub invocation_id: Option<String>,
}
impl AuditActor {
pub fn subject(subject: SubjectRef) -> Self {
Self { on_behalf_of: Some(subject), ..Self::default() }
}
}
impl AuditActor {
pub fn new(context: &ActingContext, invocation_id: impl Into<String>) -> Self {
let invocation_id = invocation_id.into();
Self {
agent: Some(context.agent.id.clone()),
tenant: context.agent.tenant.clone(),
instance: context.agent.instance.clone(),
on_behalf_of: context.on_behalf_of.clone(),
delegation_chain: context.delegation_chain.clone(),
invocation_id: (!invocation_id.is_empty()).then_some(invocation_id),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditRecord {
pub v: u32,
pub log_id: String,
pub seq: u64,
pub ts: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prev_hash: Option<AuditHash>,
pub actor: AuditActor,
pub kind: AuditRecordKind,
pub action: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub args_digest: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub decision: Option<AuditDecision>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outcome: Option<AuditRecordOutcome>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payload_ref: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub ext: BTreeMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AuditRecordDraft {
pub actor: AuditActor,
pub kind: AuditRecordKind,
pub action: String,
pub args_digest: Option<String>,
pub decision: Option<AuditDecision>,
pub outcome: Option<AuditRecordOutcome>,
pub policy_ref: Option<String>,
pub payload_ref: Option<String>,
pub ext: BTreeMap<String, serde_json::Value>,
}
impl AuditRecordDraft {
pub fn new(kind: AuditRecordKind, action: impl Into<String>) -> Self {
Self {
actor: AuditActor::default(),
kind,
action: action.into(),
args_digest: None,
decision: None,
outcome: None,
policy_ref: None,
payload_ref: None,
ext: BTreeMap::new(),
}
}
pub fn actor(mut self, actor: AuditActor) -> Self {
self.actor = actor;
self
}
pub fn args_digest(mut self, digest: impl Into<String>) -> Self {
self.args_digest = Some(digest.into());
self
}
pub fn decision(mut self, decision: AuditDecision) -> Self {
self.decision = Some(decision);
self
}
pub fn outcome(mut self, outcome: AuditRecordOutcome) -> Self {
self.outcome = Some(outcome);
self
}
pub fn policy_ref(mut self, policy_ref: impl Into<String>) -> Self {
self.policy_ref = Some(policy_ref.into());
self
}
pub fn payload_ref(mut self, digest: impl Into<String>) -> Self {
self.payload_ref = Some(digest.into());
self
}
pub fn ext(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
self.ext.insert(key.into(), value);
self
}
pub fn into_record(
self,
log_id: impl Into<String>,
seq: u64,
ts: DateTime<Utc>,
prev_hash: Option<AuditHash>,
) -> AuditRecord {
AuditRecord {
v: AUDIT_RECORD_VERSION,
log_id: log_id.into(),
seq,
ts,
prev_hash,
actor: self.actor,
kind: self.kind,
action: self.action,
args_digest: self.args_digest,
decision: self.decision,
outcome: self.outcome,
policy_ref: self.policy_ref,
payload_ref: self.payload_ref,
ext: self.ext,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditLogEntry {
pub seq: u64,
pub leaf_hash: AuditHash,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub record: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditTreeNode {
pub level: u8,
pub index: u64,
pub hash: AuditHash,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuditAppend {
pub log_id: String,
pub entries: Vec<AuditLogEntry>,
pub nodes: Vec<AuditTreeNode>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditCheckpoint {
pub log_id: String,
pub size: u64,
pub root_hash: AuditHash,
pub note: String,
pub created_at: DateTime<Utc>,
}
#[async_trait]
pub trait AuditLogStore: Send + Sync {
async fn append(&self, batch: AuditAppend) -> Result<Range<u64>>;
async fn size(&self, log_id: &str) -> Result<u64>;
async fn read(&self, log_id: &str, range: Range<u64>) -> Result<Vec<AuditLogEntry>>;
async fn hash_at(&self, log_id: &str, level: u8, index: u64) -> Result<Option<AuditHash>>;
async fn put_checkpoint(&self, checkpoint: AuditCheckpoint) -> Result<()>;
async fn latest_checkpoint(&self, log_id: &str) -> Result<Option<AuditCheckpoint>>;
async fn checkpoints(&self, log_id: &str) -> Result<Vec<AuditCheckpoint>>;
async fn prune(&self, log_id: &str, before_seq: u64) -> Result<u64>;
async fn logs(&self) -> Result<Vec<String>>;
async fn redact(&self, log_id: &str, seqs: &[u64]) -> Result<u64> {
let _ = seqs;
Err(audit_error(
ErrorCategory::Unsupported,
"audit_log.redact_unsupported",
format!("the audit log store holding '{log_id}' cannot redact single records"),
))
}
}
pub fn check_redaction(log_id: &str, seqs: &[u64], size: u64) -> Result<()> {
match seqs.iter().find(|seq| **seq >= size) {
Some(seq) => Err(out_of_range_error(log_id, size, *seq)),
None => Ok(()),
}
}
fn audit_error(category: ErrorCategory, code: &'static str, message: String) -> AdkError {
AdkError::new(ErrorComponent::Auth, category, code, message)
}
pub fn seq_conflict_error(log_id: &str, expected: u64, got: u64) -> AdkError {
audit_error(
ErrorCategory::Conflict,
"audit_log.seq_conflict",
format!(
"audit log '{log_id}' has {expected} records but the append starts at {got}. \
Another writer is using this log_id; give each replica its own log_id"
),
)
}
pub fn out_of_range_error(log_id: &str, size: u64, requested: u64) -> AdkError {
audit_error(
ErrorCategory::NotFound,
"audit_log.out_of_range",
format!("audit log '{log_id}' has {size} records; position {requested} is past its end"),
)
}
pub fn checkpoint_conflict_error(log_id: &str, size: u64) -> AdkError {
audit_error(
ErrorCategory::Conflict,
"audit_log.checkpoint_conflict",
format!(
"audit log '{log_id}' already has a checkpoint at size {size} with a different root; \
the log has forked and must be investigated before it is checkpointed again"
),
)
}
fn invalid_batch(log_id: &str, reason: &str) -> AdkError {
audit_error(
ErrorCategory::InvalidInput,
"audit_log.invalid_batch",
format!("audit log '{log_id}': {reason}"),
)
}
pub fn validate_append(batch: &AuditAppend, size: u64) -> Result<Range<u64>> {
let log_id = batch.log_id.as_str();
let Some(first) = batch.entries.first() else {
return Err(invalid_batch(log_id, "the batch has no entries"));
};
if first.seq != size {
return Err(seq_conflict_error(log_id, size, first.seq));
}
for (offset, entry) in batch.entries.iter().enumerate() {
if entry.seq != size + offset as u64 {
return Err(invalid_batch(log_id, "entry sequence numbers are not contiguous"));
}
if entry.record.is_none() {
return Err(invalid_batch(log_id, "an appended entry has no record"));
}
}
let end = size + batch.entries.len() as u64;
for node in &batch.nodes {
let covers = node
.index
.checked_add(1)
.and_then(|next| next.checked_shl(u32::from(node.level)))
.filter(|_| node.level >= 1 && node.level < 64);
match covers {
Some(node_end) if node_end <= end && node_end > size => {}
_ => {
return Err(invalid_batch(
log_id,
"a tree node is not completed by the appended entries",
));
}
}
}
Ok(size..end)
}
pub fn validate_checkpoint(
checkpoint: &AuditCheckpoint,
size: u64,
existing_root: Option<AuditHash>,
) -> Result<bool> {
if checkpoint.size > size {
return Err(out_of_range_error(&checkpoint.log_id, size, checkpoint.size));
}
match existing_root {
Some(root) if root != checkpoint.root_hash => {
Err(checkpoint_conflict_error(&checkpoint.log_id, checkpoint.size))
}
Some(_) => Ok(true),
None => Ok(false),
}
}
#[derive(Debug, Default)]
struct MemoryLog {
entries: Vec<AuditLogEntry>,
nodes: HashMap<(u8, u64), AuditHash>,
checkpoints: BTreeMap<u64, AuditCheckpoint>,
}
#[derive(Debug, Clone, Default)]
pub struct InMemoryAuditLogStore {
logs: Arc<tokio::sync::RwLock<HashMap<String, MemoryLog>>>,
}
impl InMemoryAuditLogStore {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl AuditLogStore for InMemoryAuditLogStore {
async fn append(&self, batch: AuditAppend) -> Result<Range<u64>> {
let mut logs = self.logs.write().await;
let size = logs.get(&batch.log_id).map_or(0, |log| log.entries.len() as u64);
let range = validate_append(&batch, size)?;
let log = logs.entry(batch.log_id).or_default();
log.entries.extend(batch.entries);
for node in batch.nodes {
log.nodes.insert((node.level, node.index), node.hash);
}
Ok(range)
}
async fn size(&self, log_id: &str) -> Result<u64> {
Ok(self.logs.read().await.get(log_id).map_or(0, |log| log.entries.len() as u64))
}
async fn read(&self, log_id: &str, range: Range<u64>) -> Result<Vec<AuditLogEntry>> {
let logs = self.logs.read().await;
let entries = logs.get(log_id).map_or(&[][..], |log| log.entries.as_slice());
let size = entries.len() as u64;
if range.end > size {
return Err(out_of_range_error(log_id, size, range.end));
}
if range.start >= range.end {
return Ok(Vec::new());
}
Ok(entries[range.start as usize..range.end as usize].to_vec())
}
async fn hash_at(&self, log_id: &str, level: u8, index: u64) -> Result<Option<AuditHash>> {
let logs = self.logs.read().await;
let Some(log) = logs.get(log_id) else {
return Ok(None);
};
if level == 0 {
return Ok(usize::try_from(index)
.ok()
.and_then(|at| log.entries.get(at))
.map(|entry| entry.leaf_hash));
}
Ok(log.nodes.get(&(level, index)).copied())
}
async fn put_checkpoint(&self, checkpoint: AuditCheckpoint) -> Result<()> {
let mut logs = self.logs.write().await;
let log = logs.get(&checkpoint.log_id);
let size = log.map_or(0, |log| log.entries.len() as u64);
let existing =
log.and_then(|log| log.checkpoints.get(&checkpoint.size)).map(|c| c.root_hash);
validate_checkpoint(&checkpoint, size, existing)?;
logs.entry(checkpoint.log_id.clone())
.or_default()
.checkpoints
.insert(checkpoint.size, checkpoint);
Ok(())
}
async fn latest_checkpoint(&self, log_id: &str) -> Result<Option<AuditCheckpoint>> {
let logs = self.logs.read().await;
Ok(logs.get(log_id).and_then(|log| log.checkpoints.values().next_back().cloned()))
}
async fn checkpoints(&self, log_id: &str) -> Result<Vec<AuditCheckpoint>> {
let logs = self.logs.read().await;
Ok(logs
.get(log_id)
.map(|log| log.checkpoints.values().cloned().collect())
.unwrap_or_default())
}
async fn prune(&self, log_id: &str, before_seq: u64) -> Result<u64> {
let mut logs = self.logs.write().await;
let size = logs.get(log_id).map_or(0, |log| log.entries.len() as u64);
if before_seq > size {
return Err(out_of_range_error(log_id, size, before_seq));
}
let Some(log) = logs.get_mut(log_id) else {
return Ok(0);
};
let mut pruned = 0;
for entry in &mut log.entries[..before_seq as usize] {
if entry.record.take().is_some() {
pruned += 1;
}
}
Ok(pruned)
}
async fn logs(&self) -> Result<Vec<String>> {
let mut ids: Vec<String> = self.logs.read().await.keys().cloned().collect();
ids.sort();
Ok(ids)
}
async fn redact(&self, log_id: &str, seqs: &[u64]) -> Result<u64> {
let mut logs = self.logs.write().await;
let size = logs.get(log_id).map_or(0, |log| log.entries.len() as u64);
check_redaction(log_id, seqs, size)?;
let Some(log) = logs.get_mut(log_id) else { return Ok(0) };
let mut redacted = 0;
for seq in seqs {
if log.entries[*seq as usize].record.take().is_some() {
redacted += 1;
}
}
Ok(redacted)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum AuditFailureMode {
#[default]
Block,
Warn,
}
#[async_trait]
pub trait AuditRecorder: Send + Sync {
fn digest(&self, value: &serde_json::Value) -> String;
async fn record(&self, draft: AuditRecordDraft) -> Result<()>;
async fn seal(&self) -> Result<()> {
Ok(())
}
}
#[derive(Clone)]
pub struct AuditTrail {
recorder: Arc<dyn AuditRecorder>,
failure_mode: AuditFailureMode,
}
impl fmt::Debug for AuditTrail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AuditTrail").field("failure_mode", &self.failure_mode).finish()
}
}
impl AuditTrail {
pub fn new(recorder: Arc<dyn AuditRecorder>) -> Self {
Self { recorder, failure_mode: AuditFailureMode::Block }
}
#[must_use]
pub fn with_failure_mode(mut self, mode: AuditFailureMode) -> Self {
self.failure_mode = mode;
self
}
pub fn failure_mode(&self) -> AuditFailureMode {
self.failure_mode
}
pub fn recorder(&self) -> &Arc<dyn AuditRecorder> {
&self.recorder
}
pub fn digest(&self, value: &serde_json::Value) -> String {
self.recorder.digest(value)
}
pub async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
let action = draft.action.clone();
let Err(error) = self.recorder.record(draft).await else {
return Ok(());
};
match self.failure_mode {
AuditFailureMode::Block => {
tracing::error!(audit.action = %action, error = %error, "audit record failed; refusing the action");
Err(AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Unavailable,
"audit.record_failed",
format!(
"'{action}' refused: its audit record could not be written ({error}). \
Restore the audit log, or set AuditFailureMode::Warn to continue \
without a record"
),
))
}
AuditFailureMode::Warn => {
tracing::warn!(audit.action = %action, error = %error, "audit record failed; continuing without a record");
Ok(())
}
}
}
}
impl AuditActor {
pub fn for_invocation(
app_name: &str,
agent_name: &str,
user_id: &str,
invocation_id: &str,
) -> Self {
Self::new(
&ActingContext::derived(app_name, agent_name, user_id, crate::SubjectKind::Human),
invocation_id,
)
}
pub fn for_context(ctx: &dyn crate::ReadonlyContext) -> Self {
Self::new(&ctx.acting_context(), ctx.invocation_id())
}
}
#[derive(Debug, Clone, Default)]
pub struct InMemoryAuditRecorder {
records: Arc<std::sync::Mutex<Vec<AuditRecordDraft>>>,
}
impl InMemoryAuditRecorder {
pub fn new() -> Self {
Self::default()
}
pub fn records(&self) -> Vec<AuditRecordDraft> {
self.records.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
}
#[async_trait]
impl AuditRecorder for InMemoryAuditRecorder {
fn digest(&self, value: &serde_json::Value) -> String {
crate::json_digest(value)
}
async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
self.records.lock().unwrap_or_else(|e| e.into_inner()).push(draft);
Ok(())
}
}
#[derive(Clone)]
pub struct FileAuditRecorder {
path: std::path::PathBuf,
log_id: String,
state: Arc<std::sync::Mutex<FileAuditState>>,
}
#[derive(Debug, Default)]
struct FileAuditState {
len: u64,
records: u64,
}
impl fmt::Debug for FileAuditRecorder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FileAuditRecorder")
.field("path", &self.path)
.field("log_id", &self.log_id)
.finish_non_exhaustive()
}
}
fn file_audit_error(path: &std::path::Path, action: &str, error: impl fmt::Display) -> AdkError {
AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Unavailable,
"audit.file_failed",
format!(
"could not {action} the audit file {}: {error}. Check that the directory exists \
and is writable, and that the disk has space",
path.display()
),
)
}
fn complete_lines(bytes: &[u8]) -> (u64, u64) {
let lines = bytes.iter().filter(|byte| **byte == b'\n').count() as u64;
let end = bytes.iter().rposition(|byte| *byte == b'\n').map_or(0, |at| at as u64 + 1);
(lines, end)
}
impl FileAuditRecorder {
pub fn open(path: impl Into<std::path::PathBuf>) -> Result<Self> {
let path = path.into();
if let Some(parent) = path.parent().filter(|parent| !parent.as_os_str().is_empty()) {
std::fs::create_dir_all(parent)
.map_err(|error| file_audit_error(&path, "create the directory of", error))?;
}
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.map_err(|error| file_audit_error(&path, "open", error))?;
Ok(Self {
log_id: format!("file:{}", path.display()),
path,
state: Arc::new(std::sync::Mutex::new(FileAuditState::default())),
})
}
#[must_use]
pub fn with_log_id(mut self, log_id: impl Into<String>) -> Self {
self.log_id = log_id.into();
self
}
pub fn path(&self) -> &std::path::Path {
&self.path
}
pub fn read(path: impl AsRef<std::path::Path>) -> Result<Vec<AuditRecord>> {
let path = path.as_ref();
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(file_audit_error(path, "read", error)),
};
let (_, end) = complete_lines(&bytes);
bytes[..end as usize]
.split(|byte| *byte == b'\n')
.filter(|line| !line.is_empty())
.enumerate()
.map(|(index, line)| {
serde_json::from_slice(line).map_err(|error| {
file_audit_error(path, &format!("read record {index} of"), error)
})
})
.collect()
}
pub async fn records(&self) -> Result<Vec<AuditRecord>> {
let path = self.path.clone();
tokio::task::spawn_blocking(move || Self::read(path))
.await
.map_err(|error| file_audit_error(&self.path, "read", error))?
}
fn append(&self, draft: AuditRecordDraft) -> Result<()> {
use std::io::{Read as _, Seek as _, SeekFrom, Write as _};
let path = &self.path;
let mut file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(path)
.map_err(|error| file_audit_error(path, "open", error))?;
file.lock().map_err(|error| file_audit_error(path, "lock", error))?;
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let len = file.metadata().map_err(|error| file_audit_error(path, "inspect", error))?.len();
if len != state.len {
let from = if len > state.len { state.len } else { 0 };
if from == 0 {
state.records = 0;
}
let mut tail = Vec::new();
file.seek(SeekFrom::Start(from))
.and_then(|_| file.read_to_end(&mut tail))
.map_err(|error| file_audit_error(path, "read", error))?;
let (lines, end) = complete_lines(&tail);
state.records += lines;
state.len = from + end;
if state.len < len {
file.set_len(state.len).map_err(|error| file_audit_error(path, "repair", error))?;
}
}
let record = AuditRecord {
v: AUDIT_RECORD_VERSION,
log_id: self.log_id.clone(),
seq: state.records,
ts: Utc::now(),
prev_hash: None,
actor: draft.actor,
kind: draft.kind,
action: draft.action,
args_digest: draft.args_digest,
decision: draft.decision,
outcome: draft.outcome,
policy_ref: draft.policy_ref,
payload_ref: draft.payload_ref,
ext: draft.ext,
};
let mut line = serde_json::to_vec(&record)
.map_err(|error| file_audit_error(path, "encode a record for", error))?;
line.push(b'\n');
file.seek(SeekFrom::Start(state.len))
.and_then(|_| file.write_all(&line))
.and_then(|()| file.sync_data())
.map_err(|error| file_audit_error(path, "append to", error))?;
state.len += line.len() as u64;
state.records += 1;
Ok(())
}
}
#[async_trait]
impl AuditRecorder for FileAuditRecorder {
fn digest(&self, value: &serde_json::Value) -> String {
use sha2::{Digest as _, Sha256};
use std::fmt::Write as _;
let mut canonical = String::new();
crate::context::write_canonical(value, &mut canonical);
let mut digest = String::with_capacity(7 + 64);
digest.push_str("sha256:");
for byte in Sha256::digest(canonical.as_bytes()) {
let _ = write!(digest, "{byte:02x}");
}
digest
}
async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
let recorder = self.clone();
tokio::task::spawn_blocking(move || recorder.append(draft))
.await
.map_err(|error| file_audit_error(&self.path, "append to", error))?
}
}
#[cfg(test)]
mod tests {
use super::*;
fn draft(action: &str) -> AuditRecordDraft {
AuditRecordDraft::new(AuditRecordKind::Other("site".into()), action)
.ext("releaseSeq", serde_json::json!(7))
}
#[tokio::test]
async fn a_file_recorder_keeps_its_records_across_a_reopen() {
let dir = std::env::temp_dir().join(format!("adk-audit-{}", uuid::Uuid::new_v4()));
let path = dir.join("nested").join("audit.jsonl");
let recorder = FileAuditRecorder::open(&path).unwrap().with_log_id("example.com");
recorder.record(draft("site.release.built")).await.unwrap();
recorder.record(draft("site.release.signed")).await.unwrap();
drop(recorder);
let first = FileAuditRecorder::open(&path).unwrap().with_log_id("example.com");
let second = FileAuditRecorder::open(&path).unwrap().with_log_id("example.com");
first.record(draft("awp.keys.rotated")).await.unwrap();
second.record(draft("awp.keys.delegated")).await.unwrap();
first.record(draft("site.content.published")).await.unwrap();
let records = first.records().await.unwrap();
let read: Vec<(u64, &str)> = records.iter().map(|r| (r.seq, r.action.as_str())).collect();
assert_eq!(
read,
vec![
(0, "site.release.built"),
(1, "site.release.signed"),
(2, "awp.keys.rotated"),
(3, "awp.keys.delegated"),
(4, "site.content.published"),
]
);
assert!(records.iter().all(|r| r.log_id == "example.com" && r.v == AUDIT_RECORD_VERSION));
assert_eq!(records[0].ext["releaseSeq"], 7);
std::fs::remove_dir_all(dir).ok();
}
#[tokio::test]
async fn an_unfinished_line_is_cut_and_never_read() {
use std::io::Write as _;
let dir = std::env::temp_dir().join(format!("adk-audit-{}", uuid::Uuid::new_v4()));
let path = dir.join("audit.jsonl");
let recorder = FileAuditRecorder::open(&path).unwrap();
recorder.record(draft("site.content.approved")).await.unwrap();
std::fs::OpenOptions::new()
.append(true)
.open(&path)
.unwrap()
.write_all(b"{\"v\":1,\"logId\":\"torn")
.unwrap();
assert_eq!(FileAuditRecorder::read(&path).unwrap().len(), 1, "the torn line is left out");
let reopened = FileAuditRecorder::open(&path).unwrap();
reopened.record(draft("site.content.withdrawn")).await.unwrap();
let records = FileAuditRecorder::read(&path).unwrap();
assert_eq!(
records.iter().map(|r| (r.seq, r.action.as_str())).collect::<Vec<_>>(),
vec![(0, "site.content.approved"), (1, "site.content.withdrawn")]
);
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn the_file_digest_is_sha256_of_the_canonical_json() {
let dir = std::env::temp_dir().join(format!("adk-audit-{}", uuid::Uuid::new_v4()));
let recorder = FileAuditRecorder::open(dir.join("audit.jsonl")).unwrap();
let a = recorder.digest(&serde_json::json!({ "b": 1, "a": [1, 2] }));
let b = recorder.digest(&serde_json::json!({ "a": [1, 2], "b": 1 }));
assert_eq!(a, b);
assert!(a.starts_with("sha256:") && a.len() == 7 + 64, "{a}");
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn hash_rejects_bad_text() {
assert!("ab".parse::<AuditHash>().is_err());
assert!("G".repeat(64).parse::<AuditHash>().is_err());
assert!("AB".repeat(32).parse::<AuditHash>().is_err());
}
#[test]
fn kind_round_trips_unknown_names() {
let kind: AuditRecordKind = serde_json::from_str("\"deploy\"").unwrap();
assert_eq!(kind, AuditRecordKind::Other("deploy".into()));
assert_eq!(serde_json::to_string(&AuditRecordKind::KeyRotated).unwrap(), "\"key_rotated\"");
assert_eq!(serde_json::to_string(&kind).unwrap(), "\"deploy\"");
}
}