1use crate::error::{Result, VaultError};
3use crate::policy::Action;
4use crate::scope::{Environment, Scope};
5use crate::secret::SecretId;
6use serde::{Deserialize, Serialize};
7
8pub const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000";
10const DOMAIN: &[u8] = b"weirdnet-vault/v1/audit\0";
11pub const MAX_DETAIL: usize = 512;
13pub const MAX_LIMIT: usize = 10_000;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum Outcome {
20 Allowed,
22 Denied,
24 Failed,
26}
27
28impl Outcome {
29 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct AuditRecord {
53 pub seq: u64,
55 pub at: i64,
57 pub actor: String,
59 pub environment: Environment,
61 pub action: Action,
63 pub scope: Scope,
65 pub secret_id: Option<SecretId>,
67 pub version: Option<u32>,
69 pub outcome: Outcome,
71 pub detail: String,
73 pub prev_hash: String,
75 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 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 pub fn is_intact(&self) -> bool {
114 self.hash == self.expected_hash()
115 }
116}
117
118pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138pub struct AuditHead {
139 pub seq: u64,
141 pub hash: String,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154#[non_exhaustive]
155pub struct AuditQuery {
156 pub from: Option<i64>,
158 pub to: Option<i64>,
160 pub scope: Option<Scope>,
162 pub actor: Option<String>,
164 pub action: Option<Action>,
166 pub outcome: Option<Outcome>,
168 pub after_seq: Option<u64>,
170 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 pub fn new() -> Self {
183 Self::default()
184 }
185 pub fn between(mut self, from: i64, to: i64) -> Self {
187 self.from = Some(from);
188 self.to = Some(to);
189 self
190 }
191 pub fn since(mut self, from: i64) -> Self {
193 self.from = Some(from);
194 self
195 }
196 pub fn until(mut self, to: i64) -> Self {
198 self.to = Some(to);
199 self
200 }
201 pub fn scope(mut self, scope: Scope) -> Self {
203 self.scope = Some(scope);
204 self
205 }
206 pub fn actor(mut self, actor: impl Into<String>) -> Self {
208 self.actor = Some(actor.into());
209 self
210 }
211 pub fn action(mut self, action: Action) -> Self {
213 self.action = Some(action);
214 self
215 }
216 pub fn outcome(mut self, outcome: Outcome) -> Self {
218 self.outcome = Some(outcome);
219 self
220 }
221 pub fn after(mut self, seq: u64) -> Self {
223 self.after_seq = Some(seq);
224 self
225 }
226 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}