Skip to main content

weirdnet_vault/
audit.rs

1//! The hash-chained, append-only audit log.
2use crate::error::{Result, VaultError};
3use crate::policy::Action;
4use crate::scope::{Environment, Scope};
5use crate::secret::SecretId;
6use serde::{Deserialize, Serialize};
7
8/// The `prev_hash` of the first record: 64 zeros.
9pub const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000";
10const DOMAIN: &[u8] = b"weirdnet-vault/v1/audit\0";
11/// The longest detail text kept, in bytes.
12pub const MAX_DETAIL: usize = 512;
13/// The most records one query returns.
14pub const MAX_LIMIT: usize = 10_000;
15
16/// How a request ended.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum Outcome {
20    /// Done.
21    Allowed,
22    /// Refused (no grant, policy, environment).
23    Denied,
24    /// Allowed but failed (not found, conflict, storage).
25    Failed,
26}
27
28impl Outcome {
29    /// `allowed`, `denied` or `failed`.
30    pub fn as_str(self) -> &'static str {
31        match self {
32            Outcome::Allowed => "allowed",
33            Outcome::Denied => "denied",
34            Outcome::Failed => "failed",
35        }
36    }
37
38    /// Parses [`as_str`](Outcome::as_str) names.
39    pub fn parse(s: &str) -> Result<Self> {
40        match s {
41            "allowed" => Ok(Outcome::Allowed),
42            "denied" => Ok(Outcome::Denied),
43            "failed" => Ok(Outcome::Failed),
44            other => Err(VaultError::invalid("outcome", format!("{other:?}"))),
45        }
46    }
47}
48
49/// One audit record. It says who did what, where and when, and how it ended; it never holds a
50/// secret value.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct AuditRecord {
53    /// Position in the log, from 1, without gaps.
54    pub seq: u64,
55    /// When (ms since the Unix epoch).
56    pub at: i64,
57    /// The caller's identity.
58    pub actor: String,
59    /// The caller's environment.
60    pub environment: Environment,
61    /// What was asked.
62    pub action: Action,
63    /// Where.
64    pub scope: Scope,
65    /// The secret, if any.
66    pub secret_id: Option<SecretId>,
67    /// The version, if any.
68    pub version: Option<u32>,
69    /// How it ended.
70    pub outcome: Outcome,
71    /// A short note: a reason, a grantee, a count.
72    pub detail: String,
73    /// The previous record's hash ([`GENESIS`] for the first).
74    pub prev_hash: String,
75    /// This record's hash.
76    pub hash: String,
77}
78
79fn field(h: &mut blake3::Hasher, b: &[u8]) {
80    h.update(&(b.len() as u64).to_le_bytes());
81    h.update(b);
82}
83
84impl AuditRecord {
85    /// The hash this record should have: BLAKE3 over a domain label, `prev_hash` and every
86    /// field, each length-prefixed.
87    pub fn expected_hash(&self) -> String {
88        let mut h = blake3::Hasher::new();
89        h.update(DOMAIN);
90        field(&mut h, self.prev_hash.as_bytes());
91        h.update(&self.seq.to_le_bytes());
92        h.update(&self.at.to_le_bytes());
93        field(&mut h, self.actor.as_bytes());
94        field(&mut h, self.environment.as_str().as_bytes());
95        field(&mut h, self.action.as_str().as_bytes());
96        field(&mut h, self.scope.as_str().as_bytes());
97        field(&mut h, self.secret_id.as_ref().map(|s| s.as_str()).unwrap_or("").as_bytes());
98        match self.version {
99            Some(v) => {
100                h.update(&[1]);
101                h.update(&v.to_le_bytes());
102            }
103            None => {
104                h.update(&[0]);
105            }
106        }
107        field(&mut h, self.outcome.as_str().as_bytes());
108        field(&mut h, self.detail.as_bytes());
109        h.finalize().to_hex().to_string()
110    }
111
112    /// True if [`hash`](AuditRecord::hash) matches the fields.
113    pub fn is_intact(&self) -> bool {
114        self.hash == self.expected_hash()
115    }
116}
117
118/// Checks a contiguous run of records: each is intact, follows the one before (or
119/// `prev_hash`, when given) and has the next sequence number. Returns the failing `seq`.
120pub fn verify_chain(records: &[AuditRecord], prev_hash: Option<&str>) -> Result<()> {
121    let mut prev: Option<(&str, u64)> = prev_hash.map(|h| (h, 0));
122    for (i, r) in records.iter().enumerate() {
123        let linked = match prev {
124            Some((h, s)) => r.prev_hash == h && (i == 0 || r.seq == s + 1),
125            None => true,
126        };
127        if !linked || !r.is_intact() {
128            return Err(VaultError::AuditBroken(r.seq));
129        }
130        prev = Some((&r.hash, r.seq));
131    }
132    Ok(())
133}
134
135/// The newest record's position and hash. Publish it somewhere else (another node, a signed
136/// note) to make a rewritten log detectable.
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138pub struct AuditHead {
139    /// The newest `seq` (0 when the log is empty).
140    pub seq: u64,
141    /// Its hash ([`GENESIS`] when empty).
142    pub hash: String,
143}
144
145/// Filters for [`Vault::audit`](crate::Vault::audit). Everything is optional; records come
146/// back oldest first.
147///
148/// ```
149/// use weirdnet_vault::{Action, AuditQuery};
150/// let q = AuditQuery::new().between(1_000, 2_000).actor("alice").action(Action::Reveal).limit(50);
151/// assert_eq!(q.limit, 50);
152/// ```
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154#[non_exhaustive]
155pub struct AuditQuery {
156    /// From this time (inclusive, ms).
157    pub from: Option<i64>,
158    /// Until this time (exclusive, ms).
159    pub to: Option<i64>,
160    /// Only records in this scope or below it.
161    pub scope: Option<Scope>,
162    /// Only this actor.
163    pub actor: Option<String>,
164    /// Only this action.
165    pub action: Option<Action>,
166    /// Only this outcome.
167    pub outcome: Option<Outcome>,
168    /// Only records after this `seq` (paging).
169    pub after_seq: Option<u64>,
170    /// At most this many (1 to 10 000; 500 by default).
171    pub limit: usize,
172}
173
174impl Default for AuditQuery {
175    fn default() -> Self {
176        AuditQuery { from: None, to: None, scope: None, actor: None, action: None, outcome: None, after_seq: None, limit: 500 }
177    }
178}
179
180impl AuditQuery {
181    /// Everything, 500 at a time.
182    pub fn new() -> Self {
183        Self::default()
184    }
185    /// `from <= at < to`.
186    pub fn between(mut self, from: i64, to: i64) -> Self {
187        self.from = Some(from);
188        self.to = Some(to);
189        self
190    }
191    /// From this time on.
192    pub fn since(mut self, from: i64) -> Self {
193        self.from = Some(from);
194        self
195    }
196    /// Before this time.
197    pub fn until(mut self, to: i64) -> Self {
198        self.to = Some(to);
199        self
200    }
201    /// In this scope or below it.
202    pub fn scope(mut self, scope: Scope) -> Self {
203        self.scope = Some(scope);
204        self
205    }
206    /// By this actor.
207    pub fn actor(mut self, actor: impl Into<String>) -> Self {
208        self.actor = Some(actor.into());
209        self
210    }
211    /// For this action.
212    pub fn action(mut self, action: Action) -> Self {
213        self.action = Some(action);
214        self
215    }
216    /// With this outcome.
217    pub fn outcome(mut self, outcome: Outcome) -> Self {
218        self.outcome = Some(outcome);
219        self
220    }
221    /// After this `seq`.
222    pub fn after(mut self, seq: u64) -> Self {
223        self.after_seq = Some(seq);
224        self
225    }
226    /// At most `n`.
227    pub fn limit(mut self, n: usize) -> Self {
228        self.limit = n;
229        self
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    fn rec(seq: u64, prev: &str) -> AuditRecord {
238        let mut r = AuditRecord {
239            seq,
240            at: seq as i64 * 10,
241            actor: "alice".into(),
242            environment: Environment::Live,
243            action: Action::Use,
244            scope: Scope::new(["t"]).unwrap(),
245            secret_id: None,
246            version: Some(1),
247            outcome: Outcome::Allowed,
248            detail: "active".into(),
249            prev_hash: prev.into(),
250            hash: String::new(),
251        };
252        r.hash = r.expected_hash();
253        r
254    }
255
256    #[test]
257    fn chain_verifies_and_detects_changes() {
258        let a = rec(1, GENESIS);
259        let b = rec(2, &a.hash);
260        let c = rec(3, &b.hash);
261        let chain = vec![a, b, c];
262        verify_chain(&chain, Some(GENESIS)).unwrap();
263        verify_chain(&chain[1..], None).unwrap();
264        let mut bad = chain.clone();
265        bad[1].actor = "mallory".into();
266        assert!(matches!(verify_chain(&bad, Some(GENESIS)), Err(VaultError::AuditBroken(2))));
267        let mut gap = chain.clone();
268        gap.remove(1);
269        assert!(matches!(verify_chain(&gap, Some(GENESIS)), Err(VaultError::AuditBroken(3))));
270        let mut v = chain[0].clone();
271        v.version = None;
272        assert!(!v.is_intact());
273    }
274}