1use 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#[derive(Debug, thiserror::Error)]
10#[error("cannot sign: {0}")]
11pub struct SignError(pub String);
12
13#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
15pub enum Subject {
16 Member(UserId),
18 Role(RoleId),
20}
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
24pub enum Effect {
25 Allow,
27 Deny,
29}
30
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Rule {
34 pub id: RecordId,
36 pub subject: Subject,
38 pub project: ProjectId,
40 pub permission: Permission,
42 pub effect: Effect,
44 pub expires_ms: Option<i64>,
46 pub set_by: UserId,
48 pub set_ms: i64,
50 pub key: Vec<u8>,
52 pub sig: Vec<u8>,
54}
55
56impl Rule {
57 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 #[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 pub fn verify(&self) -> bool {
104 signed_by(&self.set_by, &self.key, &self.signing_bytes(), &self.sig)
105 }
106
107 pub fn live(&self, now: i64) -> bool {
109 self.expires_ms.is_none_or(|t| t > now)
110 }
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
115pub enum Duration {
116 Once,
118 Always,
120}
121
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124pub enum GrantStreams {
125 All,
127 Only(Vec<StreamId>),
129}
130
131#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
134pub struct ConsentGrant {
135 pub id: RecordId,
137 pub owner: UserId,
139 pub grantee: UserId,
141 pub project: ProjectId,
143 pub permission: Permission,
145 pub streams: GrantStreams,
147 pub duration: Duration,
149 pub granted_ms: i64,
151 pub key: Vec<u8>,
153 pub sig: Vec<u8>,
155}
156
157impl ConsentGrant {
158 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 #[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 pub fn verify(&self) -> bool {
203 signed_by(&self.owner, &self.key, &self.signing_bytes(), &self.sig)
204 }
205
206 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
218pub struct Revocation {
219 pub grant: RecordId,
221 pub owner: UserId,
223 pub at_ms: i64,
225 pub key: Vec<u8>,
227 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 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 pub fn verify(&self) -> bool {
246 signed_by(&self.owner, &self.key, &self.bytes(), &self.sig)
247 }
248}