Skip to main content

weirdnet_collab/
records.rs

1//! Signed records: rules, consent grants and revocations.
2use crate::enc::{Enc, signed_by};
3use crate::ids::{Permission, ProjectId, RecordId, RoleId, StreamId};
4use serde::{Deserialize, Serialize};
5use weirdnet_contacts::UserId;
6use weirdnet_net::Keypair;
7
8/// Why a record could not be made.
9#[derive(Debug, thiserror::Error)]
10#[error("cannot sign: {0}")]
11pub struct SignError(pub String);
12
13/// Who a rule is about.
14#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
15pub enum Subject {
16    /// One person.
17    Member(UserId),
18    /// Everyone in a role.
19    Role(RoleId),
20}
21
22/// Allow or deny.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
24pub enum Effect {
25    /// Grants the permission.
26    Allow,
27    /// Refuses it.
28    Deny,
29}
30
31/// A project-level rule. Permissions stop at the project: there is no narrower level.
32#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Rule {
34    /// Unique id.
35    pub id: RecordId,
36    /// About whom.
37    pub subject: Subject,
38    /// The project.
39    pub project: ProjectId,
40    /// What it decides.
41    pub permission: Permission,
42    /// Allow or deny.
43    pub effect: Effect,
44    /// When it stops applying, milliseconds since the epoch.
45    pub expires_ms: Option<i64>,
46    /// Who set it.
47    pub set_by: UserId,
48    /// When.
49    pub set_ms: i64,
50    /// The setter's public key, protobuf-encoded.
51    pub key: Vec<u8>,
52    /// The setter's signature over [`Rule::signing_bytes`].
53    pub sig: Vec<u8>,
54}
55
56impl Rule {
57    /// The signed bytes.
58    pub fn signing_bytes(&self) -> Vec<u8> {
59        let e = Enc::new("rule").s(self.id.as_str());
60        let e = match &self.subject {
61            Subject::Member(u) => e.u8(0).s(u.as_str()),
62            Subject::Role(r) => e.u8(1).s(r.as_str()),
63        };
64        e.s(self.project.as_str())
65            .s(self.permission.as_str())
66            .u8(matches!(self.effect, Effect::Allow) as u8)
67            .opt_i64(self.expires_ms)
68            .s(self.set_by.as_str())
69            .i64(self.set_ms)
70            .b(&self.key)
71            .done()
72    }
73
74    /// Make and sign a rule.
75    #[allow(clippy::too_many_arguments)]
76    pub fn sign(
77        kp: &Keypair,
78        id: &str,
79        subject: Subject,
80        project: &ProjectId,
81        permission: &str,
82        effect: Effect,
83        expires_ms: Option<i64>,
84        now: i64,
85    ) -> Result<Rule, SignError> {
86        let mut r = Rule {
87            id: RecordId::new(id),
88            subject,
89            project: project.clone(),
90            permission: Permission::new(permission),
91            effect,
92            expires_ms,
93            set_by: UserId::of_keypair(kp),
94            set_ms: now,
95            key: kp.public().encode_protobuf(),
96            sig: Vec::new(),
97        };
98        r.sig = kp.sign(&r.signing_bytes()).map_err(|e| SignError(e.to_string()))?;
99        Ok(r)
100    }
101
102    /// Whether the signature is the setter's.
103    pub fn verify(&self) -> bool {
104        signed_by(&self.set_by, &self.key, &self.signing_bytes(), &self.sig)
105    }
106
107    /// Whether the rule applies at `now`.
108    pub fn live(&self, now: i64) -> bool {
109        self.expires_ms.is_none_or(|t| t > now)
110    }
111}
112
113/// How long a grant lasts.
114#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
115pub enum Duration {
116    /// For one take: spent by [`crate::Project::spend_consent`].
117    Once,
118    /// Until the owner revokes it.
119    Always,
120}
121
122/// Which of the owner's streams a grant covers.
123#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124pub enum GrantStreams {
125    /// Every stream of theirs in the project.
126    All,
127    /// Only these.
128    Only(Vec<StreamId>),
129}
130
131/// An owner's consent for one person to do a gated thing with the owner's audio. Only the owner
132/// can sign one; a host cannot grant it or waive it.
133#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
134pub struct ConsentGrant {
135    /// Unique id.
136    pub id: RecordId,
137    /// Whose audio.
138    pub owner: UserId,
139    /// Who may.
140    pub grantee: UserId,
141    /// The project.
142    pub project: ProjectId,
143    /// The gated permission (`stream.record`, `mic.record`, `route.connect`).
144    pub permission: Permission,
145    /// Which streams.
146    pub streams: GrantStreams,
147    /// Once or always.
148    pub duration: Duration,
149    /// When it was given.
150    pub granted_ms: i64,
151    /// The owner's public key, protobuf-encoded.
152    pub key: Vec<u8>,
153    /// The owner's signature.
154    pub sig: Vec<u8>,
155}
156
157impl ConsentGrant {
158    /// The signed bytes.
159    pub fn signing_bytes(&self) -> Vec<u8> {
160        let e = Enc::new("consent")
161            .s(self.id.as_str())
162            .s(self.owner.as_str())
163            .s(self.grantee.as_str())
164            .s(self.project.as_str())
165            .s(self.permission.as_str());
166        let e = match &self.streams {
167            GrantStreams::All => e.u8(0),
168            GrantStreams::Only(v) => v.iter().fold(e.u8(1).u32(v.len() as u32), |e, s| e.s(s.as_str())),
169        };
170        e.u8(matches!(self.duration, Duration::Always) as u8).i64(self.granted_ms).b(&self.key).done()
171    }
172
173    /// Make and sign a grant as `owner`.
174    #[allow(clippy::too_many_arguments)]
175    pub fn sign(
176        owner: &Keypair,
177        id: &str,
178        grantee: &UserId,
179        project: &ProjectId,
180        permission: &str,
181        streams: GrantStreams,
182        duration: Duration,
183        now: i64,
184    ) -> Result<ConsentGrant, SignError> {
185        let mut g = ConsentGrant {
186            id: RecordId::new(id),
187            owner: UserId::of_keypair(owner),
188            grantee: grantee.clone(),
189            project: project.clone(),
190            permission: Permission::new(permission),
191            streams,
192            duration,
193            granted_ms: now,
194            key: owner.public().encode_protobuf(),
195            sig: Vec::new(),
196        };
197        g.sig = owner.sign(&g.signing_bytes()).map_err(|e| SignError(e.to_string()))?;
198        Ok(g)
199    }
200
201    /// Whether the signature is the owner's.
202    pub fn verify(&self) -> bool {
203        signed_by(&self.owner, &self.key, &self.signing_bytes(), &self.sig)
204    }
205
206    /// Whether the grant covers `stream`.
207    pub fn covers(&self, stream: Option<&StreamId>) -> bool {
208        match (&self.streams, stream) {
209            (GrantStreams::All, _) => true,
210            (GrantStreams::Only(v), Some(s)) => v.contains(s),
211            (GrantStreams::Only(_), None) => false,
212        }
213    }
214}
215
216/// The owner's signed revocation of a grant.
217#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
218pub struct Revocation {
219    /// The grant revoked.
220    pub grant: RecordId,
221    /// The owner who revokes it.
222    pub owner: UserId,
223    /// When.
224    pub at_ms: i64,
225    /// The owner's public key.
226    pub key: Vec<u8>,
227    /// The owner's signature.
228    pub sig: Vec<u8>,
229}
230
231impl Revocation {
232    fn bytes(&self) -> Vec<u8> {
233        Enc::new("revocation").s(self.grant.as_str()).s(self.owner.as_str()).i64(self.at_ms).b(&self.key).done()
234    }
235
236    /// Revoke `grant` as its owner.
237    pub fn sign(owner: &Keypair, grant: &RecordId, now: i64) -> Result<Revocation, SignError> {
238        let mut r =
239            Revocation { grant: grant.clone(), owner: UserId::of_keypair(owner), at_ms: now, key: owner.public().encode_protobuf(), sig: Vec::new() };
240        r.sig = owner.sign(&r.bytes()).map_err(|e| SignError(e.to_string()))?;
241        Ok(r)
242    }
243
244    /// Whether the signature is the owner's.
245    pub fn verify(&self) -> bool {
246        signed_by(&self.owner, &self.key, &self.bytes(), &self.sig)
247    }
248}