Skip to main content

weirdnet_collab/
audit.rs

1//! The audit log: who changed which role, rule, link or consent, and when. Entries are signed by
2//! the person who acted. Each person sees the entries they are part of; the host sees all and is
3//! the only one who can delete, by a signed deletion that merges to the other nodes.
4use crate::enc::{Enc, signed_by};
5use crate::ids::{Permission, RecordId, RoleId};
6use crate::records::{Effect, SignError};
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeSet;
9use weirdnet_contacts::UserId;
10use weirdnet_net::Keypair;
11
12/// What happened.
13#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
14pub enum AuditKind {
15    /// A rule was set.
16    RuleSet {
17        /// The rule.
18        rule: RecordId,
19        /// The permission.
20        permission: Permission,
21        /// Allow or deny.
22        effect: Effect,
23        /// Who it is about (a member), if a member rule.
24        member: Option<UserId>,
25        /// The role, if a role rule.
26        role: Option<RoleId>,
27    },
28    /// A rule was removed.
29    RuleRemoved {
30        /// The rule.
31        rule: RecordId,
32    },
33    /// A member's role changed.
34    RoleChanged {
35        /// The member.
36        user: UserId,
37        /// The role before.
38        from: RoleId,
39        /// The role after.
40        to: RoleId,
41    },
42    /// Someone joined.
43    MemberJoined {
44        /// The member.
45        user: UserId,
46        /// Their role.
47        role: RoleId,
48        /// The invite they used, if any.
49        invite: Option<RecordId>,
50    },
51    /// Someone was removed.
52    MemberKicked {
53        /// The member.
54        user: UserId,
55    },
56    /// Someone was banned from the project.
57    MemberBanned {
58        /// The identity.
59        user: UserId,
60    },
61    /// A ban was lifted.
62    MemberUnbanned {
63        /// The identity.
64        user: UserId,
65    },
66    /// An invite or link was made.
67    InviteCreated {
68        /// The invite.
69        invite: RecordId,
70        /// The role it grants.
71        role: RoleId,
72        /// The addressee of a direct invite.
73        to: Option<UserId>,
74    },
75    /// An invite or link was revoked.
76    InviteRevoked {
77        /// The invite.
78        invite: RecordId,
79    },
80    /// A person asked to join and waits for approval.
81    JoinRequested {
82        /// The identity.
83        user: UserId,
84        /// The invite.
85        invite: RecordId,
86    },
87    /// A join request was denied.
88    JoinDenied {
89        /// The identity.
90        user: UserId,
91    },
92    /// An owner gave consent.
93    ConsentGranted {
94        /// The grant.
95        grant: RecordId,
96        /// The audio's owner.
97        owner: UserId,
98        /// Who may.
99        grantee: UserId,
100        /// The gated permission.
101        permission: Permission,
102    },
103    /// An owner revoked consent.
104    ConsentRevoked {
105        /// The grant.
106        grant: RecordId,
107    },
108    /// The session was closed or reopened.
109    SessionOpen {
110        /// Whether it is open now.
111        open: bool,
112    },
113    /// The host role moved. Logged by the new host; the old host's signed handover is kept in
114    /// the project.
115    HostHandedOver {
116        /// The old host.
117        from: UserId,
118        /// The new host.
119        to: UserId,
120        /// Whether the old host left on purpose (false: a standby handover was used).
121        left: bool,
122    },
123}
124
125impl AuditKind {
126    fn encode(&self, e: Enc) -> Enc {
127        match self {
128            AuditKind::RuleSet { rule, permission, effect, member, role } => e
129                .u8(0)
130                .s(rule.as_str())
131                .s(permission.as_str())
132                .u8(matches!(effect, Effect::Allow) as u8)
133                .opt_s(member.as_ref().map(|u| u.as_str()))
134                .opt_s(role.as_ref().map(|r| r.as_str())),
135            AuditKind::RuleRemoved { rule } => e.u8(1).s(rule.as_str()),
136            AuditKind::RoleChanged { user, from, to } => e.u8(2).s(user.as_str()).s(from.as_str()).s(to.as_str()),
137            AuditKind::MemberJoined { user, role, invite } => e.u8(3).s(user.as_str()).s(role.as_str()).opt_s(invite.as_ref().map(|i| i.as_str())),
138            AuditKind::MemberKicked { user } => e.u8(4).s(user.as_str()),
139            AuditKind::MemberBanned { user } => e.u8(5).s(user.as_str()),
140            AuditKind::MemberUnbanned { user } => e.u8(6).s(user.as_str()),
141            AuditKind::InviteCreated { invite, role, to } => e.u8(7).s(invite.as_str()).s(role.as_str()).opt_s(to.as_ref().map(|u| u.as_str())),
142            AuditKind::InviteRevoked { invite } => e.u8(8).s(invite.as_str()),
143            AuditKind::JoinRequested { user, invite } => e.u8(9).s(user.as_str()).s(invite.as_str()),
144            AuditKind::JoinDenied { user } => e.u8(10).s(user.as_str()),
145            AuditKind::ConsentGranted { grant, owner, grantee, permission } => {
146                e.u8(11).s(grant.as_str()).s(owner.as_str()).s(grantee.as_str()).s(permission.as_str())
147            }
148            AuditKind::ConsentRevoked { grant } => e.u8(12).s(grant.as_str()),
149            AuditKind::SessionOpen { open } => e.u8(13).u8(*open as u8),
150            AuditKind::HostHandedOver { from, to, left } => e.u8(14).s(from.as_str()).s(to.as_str()).u8(*left as u8),
151        }
152    }
153
154    /// Whether `user` is a party to this event (so they see the entry).
155    pub fn involves(&self, user: &UserId) -> bool {
156        match self {
157            AuditKind::RuleSet { member, .. } => member.as_ref() == Some(user),
158            AuditKind::RoleChanged { user: u, .. }
159            | AuditKind::MemberJoined { user: u, .. }
160            | AuditKind::MemberKicked { user: u }
161            | AuditKind::MemberBanned { user: u }
162            | AuditKind::MemberUnbanned { user: u }
163            | AuditKind::JoinRequested { user: u, .. }
164            | AuditKind::JoinDenied { user: u } => u == user,
165            AuditKind::InviteCreated { to, .. } => to.as_ref() == Some(user),
166            AuditKind::HostHandedOver { from, to, .. } => from == user || to == user,
167            AuditKind::ConsentGranted { owner, grantee, .. } => owner == user || grantee == user,
168            AuditKind::RuleRemoved { .. } | AuditKind::InviteRevoked { .. } | AuditKind::ConsentRevoked { .. } | AuditKind::SessionOpen { .. } => {
169                false
170            }
171        }
172    }
173}
174
175/// One signed entry.
176#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
177pub struct AuditEntry {
178    /// Unique id.
179    pub id: RecordId,
180    /// When, milliseconds since the epoch.
181    pub at_ms: i64,
182    /// Who acted.
183    pub by: UserId,
184    /// What happened.
185    pub kind: AuditKind,
186    /// The actor's public key.
187    pub key: Vec<u8>,
188    /// The actor's signature.
189    pub sig: Vec<u8>,
190}
191
192impl AuditEntry {
193    fn bytes(&self) -> Vec<u8> {
194        self.kind.encode(Enc::new("audit").s(self.id.as_str()).i64(self.at_ms).s(self.by.as_str()).b(&self.key)).done()
195    }
196
197    /// Make and sign an entry as `actor`.
198    pub fn sign(actor: &Keypair, id: &str, kind: AuditKind, now: i64) -> Result<AuditEntry, SignError> {
199        let mut e = AuditEntry {
200            id: RecordId::new(id),
201            at_ms: now,
202            by: UserId::of_keypair(actor),
203            kind,
204            key: actor.public().encode_protobuf(),
205            sig: Vec::new(),
206        };
207        e.sig = actor.sign(&e.bytes()).map_err(|x| SignError(x.to_string()))?;
208        Ok(e)
209    }
210
211    /// The entry an owner signs on their own node to record a grant they gave, for the host to
212    /// take in with [`crate::Project::accept_consent_logged`].
213    pub fn for_grant(owner: &Keypair, g: &crate::records::ConsentGrant) -> Result<AuditEntry, SignError> {
214        let kind =
215            AuditKind::ConsentGranted { grant: g.id.clone(), owner: g.owner.clone(), grantee: g.grantee.clone(), permission: g.permission.clone() };
216        AuditEntry::sign(owner, &format!("{}-granted", g.id), kind, g.granted_ms)
217    }
218
219    /// The entry an owner signs to record a revocation, for
220    /// [`crate::Project::accept_revocation_logged`].
221    pub fn for_revocation(owner: &Keypair, r: &crate::records::Revocation) -> Result<AuditEntry, SignError> {
222        AuditEntry::sign(owner, &format!("{}-revoked", r.grant), AuditKind::ConsentRevoked { grant: r.grant.clone() }, r.at_ms)
223    }
224
225    /// Whether the signature is the actor's.
226    pub fn verify(&self) -> bool {
227        signed_by(&self.by, &self.key, &self.bytes(), &self.sig)
228    }
229}
230
231/// A host's signed deletion of entries.
232#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
233pub struct AuditDeletion {
234    /// The entries deleted.
235    pub ids: Vec<RecordId>,
236    /// Who deleted them.
237    pub by: UserId,
238    /// When.
239    pub at_ms: i64,
240    /// The deleter's public key.
241    pub key: Vec<u8>,
242    /// The deleter's signature.
243    pub sig: Vec<u8>,
244}
245
246impl AuditDeletion {
247    fn bytes(&self) -> Vec<u8> {
248        self.ids
249            .iter()
250            .fold(Enc::new("audit-delete").u32(self.ids.len() as u32), |e, i| e.s(i.as_str()))
251            .s(self.by.as_str())
252            .i64(self.at_ms)
253            .b(&self.key)
254            .done()
255    }
256
257    /// Delete `ids` as `actor`.
258    pub fn sign(actor: &Keypair, ids: Vec<RecordId>, now: i64) -> Result<AuditDeletion, SignError> {
259        let mut d = AuditDeletion { ids, by: UserId::of_keypair(actor), at_ms: now, key: actor.public().encode_protobuf(), sig: Vec::new() };
260        d.sig = actor.sign(&d.bytes()).map_err(|x| SignError(x.to_string()))?;
261        Ok(d)
262    }
263
264    /// Whether the signature is the deleter's.
265    pub fn verify(&self) -> bool {
266        signed_by(&self.by, &self.key, &self.bytes(), &self.sig)
267    }
268}
269
270/// The log.
271#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
272pub struct AuditLog {
273    entries: Vec<AuditEntry>,
274    deletions: Vec<AuditDeletion>,
275    /// Entries older than this are dropped by [`AuditLog::prune`]; set by the host.
276    pub retention_ms: Option<i64>,
277}
278
279impl AuditLog {
280    fn deleted(&self) -> BTreeSet<&RecordId> {
281        self.deletions.iter().flat_map(|d| d.ids.iter()).collect()
282    }
283
284    pub(crate) fn push(&mut self, e: AuditEntry) {
285        if !self.entries.iter().any(|x| x.id == e.id) {
286            let at = self.entries.partition_point(|x| (x.at_ms, &x.id) < (e.at_ms, &e.id));
287            self.entries.insert(at, e);
288        }
289    }
290
291    pub(crate) fn delete(&mut self, d: AuditDeletion) {
292        self.deletions.push(d);
293    }
294
295    /// Entries that are not deleted, oldest first.
296    pub fn entries(&self) -> Vec<&AuditEntry> {
297        let gone = self.deleted();
298        self.entries.iter().filter(|e| !gone.contains(&e.id)).collect()
299    }
300
301    /// What `user` sees: everything for a host, otherwise the entries they made or are a party to.
302    pub fn visible_to(&self, user: &UserId, host: bool) -> Vec<&AuditEntry> {
303        self.entries().into_iter().filter(|e| host || &e.by == user || e.kind.involves(user)).collect()
304    }
305
306    /// Drop entries older than the retention setting.
307    pub fn prune(&mut self, now: i64) -> usize {
308        let Some(keep) = self.retention_ms else { return 0 };
309        let before = self.entries.len();
310        self.entries.retain(|e| now - e.at_ms <= keep);
311        before - self.entries.len()
312    }
313
314    /// Fold in another node's copy. Entries and deletions are checked for signature; a deletion
315    /// counts only if `is_host(deleter)` says the deleter is a host. Returns how many entries
316    /// were new.
317    pub fn merge(&mut self, other: &AuditLog, is_host: impl Fn(&UserId) -> bool) -> usize {
318        let mut added = 0;
319        for e in &other.entries {
320            if e.verify() && !self.entries.iter().any(|x| x.id == e.id) {
321                self.push(e.clone());
322                added += 1;
323            }
324        }
325        for d in &other.deletions {
326            if d.verify() && is_host(&d.by) && !self.deletions.contains(d) {
327                self.deletions.push(d.clone());
328            }
329        }
330        added
331    }
332}