use crate::error::{Result, VaultError};
use crate::policy::Action;
use crate::scope::{Environment, Scope};
use crate::secret::SecretId;
use serde::{Deserialize, Serialize};
pub const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000";
const DOMAIN: &[u8] = b"weirdnet-vault/v1/audit\0";
pub const MAX_DETAIL: usize = 512;
pub const MAX_LIMIT: usize = 10_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Allowed,
Denied,
Failed,
}
impl Outcome {
pub fn as_str(self) -> &'static str {
match self {
Outcome::Allowed => "allowed",
Outcome::Denied => "denied",
Outcome::Failed => "failed",
}
}
pub fn parse(s: &str) -> Result<Self> {
match s {
"allowed" => Ok(Outcome::Allowed),
"denied" => Ok(Outcome::Denied),
"failed" => Ok(Outcome::Failed),
other => Err(VaultError::invalid("outcome", format!("{other:?}"))),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuditRecord {
pub seq: u64,
pub at: i64,
pub actor: String,
pub environment: Environment,
pub action: Action,
pub scope: Scope,
pub secret_id: Option<SecretId>,
pub version: Option<u32>,
pub outcome: Outcome,
pub detail: String,
pub prev_hash: String,
pub hash: String,
}
fn field(h: &mut blake3::Hasher, b: &[u8]) {
h.update(&(b.len() as u64).to_le_bytes());
h.update(b);
}
impl AuditRecord {
pub fn expected_hash(&self) -> String {
let mut h = blake3::Hasher::new();
h.update(DOMAIN);
field(&mut h, self.prev_hash.as_bytes());
h.update(&self.seq.to_le_bytes());
h.update(&self.at.to_le_bytes());
field(&mut h, self.actor.as_bytes());
field(&mut h, self.environment.as_str().as_bytes());
field(&mut h, self.action.as_str().as_bytes());
field(&mut h, self.scope.as_str().as_bytes());
field(&mut h, self.secret_id.as_ref().map(|s| s.as_str()).unwrap_or("").as_bytes());
match self.version {
Some(v) => {
h.update(&[1]);
h.update(&v.to_le_bytes());
}
None => {
h.update(&[0]);
}
}
field(&mut h, self.outcome.as_str().as_bytes());
field(&mut h, self.detail.as_bytes());
h.finalize().to_hex().to_string()
}
pub fn is_intact(&self) -> bool {
self.hash == self.expected_hash()
}
}
pub fn verify_chain(records: &[AuditRecord], prev_hash: Option<&str>) -> Result<()> {
let mut prev: Option<(&str, u64)> = prev_hash.map(|h| (h, 0));
for (i, r) in records.iter().enumerate() {
let linked = match prev {
Some((h, s)) => r.prev_hash == h && (i == 0 || r.seq == s + 1),
None => true,
};
if !linked || !r.is_intact() {
return Err(VaultError::AuditBroken(r.seq));
}
prev = Some((&r.hash, r.seq));
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuditHead {
pub seq: u64,
pub hash: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AuditQuery {
pub from: Option<i64>,
pub to: Option<i64>,
pub scope: Option<Scope>,
pub actor: Option<String>,
pub action: Option<Action>,
pub outcome: Option<Outcome>,
pub after_seq: Option<u64>,
pub limit: usize,
}
impl Default for AuditQuery {
fn default() -> Self {
AuditQuery { from: None, to: None, scope: None, actor: None, action: None, outcome: None, after_seq: None, limit: 500 }
}
}
impl AuditQuery {
pub fn new() -> Self {
Self::default()
}
pub fn between(mut self, from: i64, to: i64) -> Self {
self.from = Some(from);
self.to = Some(to);
self
}
pub fn since(mut self, from: i64) -> Self {
self.from = Some(from);
self
}
pub fn until(mut self, to: i64) -> Self {
self.to = Some(to);
self
}
pub fn scope(mut self, scope: Scope) -> Self {
self.scope = Some(scope);
self
}
pub fn actor(mut self, actor: impl Into<String>) -> Self {
self.actor = Some(actor.into());
self
}
pub fn action(mut self, action: Action) -> Self {
self.action = Some(action);
self
}
pub fn outcome(mut self, outcome: Outcome) -> Self {
self.outcome = Some(outcome);
self
}
pub fn after(mut self, seq: u64) -> Self {
self.after_seq = Some(seq);
self
}
pub fn limit(mut self, n: usize) -> Self {
self.limit = n;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rec(seq: u64, prev: &str) -> AuditRecord {
let mut r = AuditRecord {
seq,
at: seq as i64 * 10,
actor: "alice".into(),
environment: Environment::Live,
action: Action::Use,
scope: Scope::new(["t"]).unwrap(),
secret_id: None,
version: Some(1),
outcome: Outcome::Allowed,
detail: "active".into(),
prev_hash: prev.into(),
hash: String::new(),
};
r.hash = r.expected_hash();
r
}
#[test]
fn chain_verifies_and_detects_changes() {
let a = rec(1, GENESIS);
let b = rec(2, &a.hash);
let c = rec(3, &b.hash);
let chain = vec![a, b, c];
verify_chain(&chain, Some(GENESIS)).unwrap();
verify_chain(&chain[1..], None).unwrap();
let mut bad = chain.clone();
bad[1].actor = "mallory".into();
assert!(matches!(verify_chain(&bad, Some(GENESIS)), Err(VaultError::AuditBroken(2))));
let mut gap = chain.clone();
gap.remove(1);
assert!(matches!(verify_chain(&gap, Some(GENESIS)), Err(VaultError::AuditBroken(3))));
let mut v = chain[0].clone();
v.version = None;
assert!(!v.is_intact());
}
}