1use crate::error::{NetError, Result};
13use crate::profile::Profile;
14use crate::user::{Card, decode_public, user_id};
15use libp2p::PeerId;
16use libp2p::identity::{Keypair, PublicKey};
17use serde::{Deserialize, Serialize, de::DeserializeOwned};
18
19const MEMBERSHIP_DOMAIN: &str = "weirdnet/member/membership/1";
20const REVOCATION_DOMAIN: &str = "weirdnet/member/revocation/1";
21pub const CLOCK_SKEW_MS: i64 = 5 * 60 * 1000;
23pub const MAX_FRAME: usize = 256 * 1024;
25
26pub(crate) fn signed_bytes<T: Serialize>(domain: &str, body: &T) -> Vec<u8> {
28 let mut v = domain.as_bytes().to_vec();
29 v.push(b'\n');
30 v.extend(serde_json::to_vec(body).unwrap_or_default());
31 v
32}
33
34pub(crate) fn sign_with(kp: &Keypair, domain: &str, body: &impl Serialize) -> Result<Vec<u8>> {
35 kp.sign(&signed_bytes(domain, body)).map_err(|e| NetError::Crypto(format!("{domain}: {e}")))
36}
37
38pub(crate) fn issuer(key: &[u8], id: &str) -> Result<PublicKey> {
40 let k = decode_public(key)?;
41 if user_id(&k) != id {
42 return Err(NetError::Crypto("the issuer id does not match its key".into()));
43 }
44 Ok(k)
45}
46
47fn check_text(what: &'static str, s: &str, max: usize) -> Result<()> {
48 if s.is_empty() || s.len() > max || s.chars().any(char::is_control) {
49 return Err(NetError::invalid(what, format!("1 to {max} bytes, no control characters")));
50 }
51 Ok(())
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Membership {
56 pub v: u8,
57 pub resource: String,
59 pub user_id: String,
61 pub role: String,
63 pub issued_at: i64,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub expires_at: Option<i64>,
66 pub issuer_id: String,
68 pub issuer_key: Vec<u8>,
69 pub sig: Vec<u8>,
70}
71
72impl Membership {
73 pub fn issue(owner: &Keypair, resource: &str, member: &str, role: &str, now: i64, expires_at: Option<i64>) -> Result<Membership> {
75 check_text("resource", resource, 256)?;
76 check_text("role", role, 64)?;
77 check_text("user id", member, 64)?;
78 let mut m = Membership {
79 v: 1,
80 resource: resource.into(),
81 user_id: member.into(),
82 role: role.into(),
83 issued_at: now,
84 expires_at,
85 issuer_id: user_id(&owner.public()),
86 issuer_key: owner.public().encode_protobuf(),
87 sig: vec![],
88 };
89 m.sig = sign_with(owner, MEMBERSHIP_DOMAIN, &m)?;
90 Ok(m)
91 }
92
93 pub fn verify(&self, now: i64) -> Result<()> {
95 if self.v != 1 {
96 return Err(NetError::invalid("membership", "unknown version"));
97 }
98 let k = issuer(&self.issuer_key, &self.issuer_id)?;
99 let mut body = self.clone();
100 body.sig = vec![];
101 if !k.verify(&signed_bytes(MEMBERSHIP_DOMAIN, &body), &self.sig) {
102 return Err(NetError::Crypto("membership: bad signature".into()));
103 }
104 if self.issued_at > now + CLOCK_SKEW_MS {
105 return Err(NetError::invalid("membership", "issued in the future"));
106 }
107 if self.expires_at.is_some_and(|e| e <= now) {
108 return Err(NetError::invalid("membership", "expired"));
109 }
110 Ok(())
111 }
112
113 pub fn verify_for(&self, owner: &str, resource: &str, now: i64) -> Result<()> {
115 if self.issuer_id != owner || self.resource != resource {
116 return Err(NetError::invalid("membership", "not for this resource"));
117 }
118 self.verify(now)
119 }
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct MemberRevocation {
124 pub v: u8,
125 pub resource: String,
126 pub user_id: String,
127 pub before: i64,
129 pub at: i64,
130 pub issuer_id: String,
131 pub issuer_key: Vec<u8>,
132 pub sig: Vec<u8>,
133}
134
135impl MemberRevocation {
136 pub fn revoke(owner: &Keypair, resource: &str, member: &str, before: i64, now: i64) -> Result<MemberRevocation> {
138 check_text("resource", resource, 256)?;
139 check_text("user id", member, 64)?;
140 let mut r = MemberRevocation {
141 v: 1,
142 resource: resource.into(),
143 user_id: member.into(),
144 before,
145 at: now,
146 issuer_id: user_id(&owner.public()),
147 issuer_key: owner.public().encode_protobuf(),
148 sig: vec![],
149 };
150 r.sig = sign_with(owner, REVOCATION_DOMAIN, &r)?;
151 Ok(r)
152 }
153
154 pub fn verify(&self) -> Result<()> {
155 if self.v != 1 {
156 return Err(NetError::invalid("revocation", "unknown version"));
157 }
158 let k = issuer(&self.issuer_key, &self.issuer_id)?;
159 let mut body = self.clone();
160 body.sig = vec![];
161 if !k.verify(&signed_bytes(REVOCATION_DOMAIN, &body), &self.sig) {
162 return Err(NetError::Crypto("revocation: bad signature".into()));
163 }
164 Ok(())
165 }
166
167 pub fn voids(&self, m: &Membership) -> bool {
169 self.issuer_id == m.issuer_id && self.resource == m.resource && self.user_id == m.user_id && m.issued_at <= self.before
170 }
171}
172
173#[derive(Debug, Clone, Default)]
175pub struct Revocations {
176 owner: String,
177 list: Vec<MemberRevocation>,
178}
179
180impl Revocations {
181 pub fn new(owner: &str) -> Self {
182 Revocations { owner: owner.into(), list: vec![] }
183 }
184
185 pub fn add(&mut self, r: MemberRevocation) -> Result<()> {
187 if r.issuer_id != self.owner {
188 return Err(NetError::invalid("revocation", "not the owner's"));
189 }
190 r.verify()?;
191 if let Some(old) = self.list.iter_mut().find(|o| o.resource == r.resource && o.user_id == r.user_id) {
192 if r.before > old.before {
193 *old = r;
194 }
195 } else {
196 self.list.push(r);
197 }
198 Ok(())
199 }
200
201 pub fn extend(&mut self, rs: impl IntoIterator<Item = MemberRevocation>) -> Result<()> {
203 rs.into_iter().try_for_each(|r| self.add(r))
204 }
205
206 pub fn revokes(&self, m: &Membership) -> bool {
207 self.list.iter().any(|r| r.voids(m))
208 }
209
210 pub fn list(&self) -> &[MemberRevocation] {
211 &self.list
212 }
213}
214
215#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218pub struct Presented {
219 pub membership: Membership,
220 pub card: Card,
221}
222
223pub fn check_presented(
226 profile: &Profile,
227 p: &Presented,
228 peer: &PeerId,
229 owner: &str,
230 resource: &str,
231 revoked: &Revocations,
232 now: i64,
233) -> Result<Membership> {
234 p.membership.verify_for(owner, resource, now)?;
235 if p.card.id != p.membership.user_id {
236 return Err(NetError::invalid("membership", "the card is someone else's"));
237 }
238 profile.check_card(&peer.to_string(), &p.card)?;
239 if revoked.revokes(&p.membership) {
240 return Err(NetError::invalid("membership", "revoked"));
241 }
242 Ok(p.membership.clone())
243}
244
245pub fn write_frame<W: std::io::Write>(w: &mut W, v: &impl Serialize) -> Result<()> {
247 let b = serde_json::to_vec(v).map_err(NetError::net)?;
248 w.write_all(&(b.len() as u32).to_be_bytes()).and_then(|_| w.write_all(&b)).and_then(|_| w.flush()).map_err(NetError::net)
249}
250
251pub fn read_frame<T: DeserializeOwned, R: std::io::Read>(r: &mut R) -> Result<T> {
253 let mut l = [0u8; 4];
254 r.read_exact(&mut l).map_err(NetError::net)?;
255 let l = u32::from_be_bytes(l) as usize;
256 if l > MAX_FRAME {
257 return Err(NetError::invalid("frame", "too large"));
258 }
259 let mut b = vec![0u8; l];
260 r.read_exact(&mut b).map_err(NetError::net)?;
261 serde_json::from_slice(&b).map_err(|e| NetError::invalid("frame", e.to_string()))
262}
263
264pub async fn write_frame_async<W: futures::AsyncWrite + Unpin>(w: &mut W, v: &impl Serialize) -> Result<()> {
265 use futures::AsyncWriteExt;
266 let b = serde_json::to_vec(v).map_err(NetError::net)?;
267 let mut f = (b.len() as u32).to_be_bytes().to_vec();
268 f.extend(b);
269 w.write_all(&f).await.map_err(NetError::net)?;
270 w.flush().await.map_err(NetError::net)
271}
272
273pub async fn read_frame_async<T: DeserializeOwned, R: futures::AsyncRead + Unpin>(r: &mut R) -> Result<T> {
274 use futures::AsyncReadExt;
275 let mut l = [0u8; 4];
276 r.read_exact(&mut l).await.map_err(NetError::net)?;
277 let l = u32::from_be_bytes(l) as usize;
278 if l > MAX_FRAME {
279 return Err(NetError::invalid("frame", "too large"));
280 }
281 let mut b = vec![0u8; l];
282 r.read_exact(&mut b).await.map_err(NetError::net)?;
283 serde_json::from_slice(&b).map_err(|e| NetError::invalid("frame", e.to_string()))
284}
285
286pub fn present<S: std::io::Write>(s: &mut S, p: &Presented) -> Result<()> {
288 write_frame(s, p)
289}
290
291pub fn read_presented<S: std::io::Read>(
293 s: &mut S,
294 profile: &Profile,
295 peer: &PeerId,
296 owner: &str,
297 resource: &str,
298 revoked: &Revocations,
299 now: i64,
300) -> Result<Membership> {
301 let p: Presented = read_frame(s)?;
302 check_presented(profile, &p, peer, owner, resource, revoked, now)
303}