use crate::enc::{Enc, signed_by};
use crate::ids::{Permission, ProjectId, RecordId, RoleId, StreamId};
use serde::{Deserialize, Serialize};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;
#[derive(Debug, thiserror::Error)]
#[error("cannot sign: {0}")]
pub struct SignError(pub String);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Subject {
Member(UserId),
Role(RoleId),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Effect {
Allow,
Deny,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rule {
pub id: RecordId,
pub subject: Subject,
pub project: ProjectId,
pub permission: Permission,
pub effect: Effect,
pub expires_ms: Option<i64>,
pub set_by: UserId,
pub set_ms: i64,
pub key: Vec<u8>,
pub sig: Vec<u8>,
}
impl Rule {
pub fn signing_bytes(&self) -> Vec<u8> {
let e = Enc::new("rule").s(self.id.as_str());
let e = match &self.subject {
Subject::Member(u) => e.u8(0).s(u.as_str()),
Subject::Role(r) => e.u8(1).s(r.as_str()),
};
e.s(self.project.as_str())
.s(self.permission.as_str())
.u8(matches!(self.effect, Effect::Allow) as u8)
.opt_i64(self.expires_ms)
.s(self.set_by.as_str())
.i64(self.set_ms)
.b(&self.key)
.done()
}
#[allow(clippy::too_many_arguments)]
pub fn sign(
kp: &Keypair,
id: &str,
subject: Subject,
project: &ProjectId,
permission: &str,
effect: Effect,
expires_ms: Option<i64>,
now: i64,
) -> Result<Rule, SignError> {
let mut r = Rule {
id: RecordId::new(id),
subject,
project: project.clone(),
permission: Permission::new(permission),
effect,
expires_ms,
set_by: UserId::of_keypair(kp),
set_ms: now,
key: kp.public().encode_protobuf(),
sig: Vec::new(),
};
r.sig = kp.sign(&r.signing_bytes()).map_err(|e| SignError(e.to_string()))?;
Ok(r)
}
pub fn verify(&self) -> bool {
signed_by(&self.set_by, &self.key, &self.signing_bytes(), &self.sig)
}
pub fn live(&self, now: i64) -> bool {
self.expires_ms.is_none_or(|t| t > now)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Duration {
Once,
Always,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum GrantStreams {
All,
Only(Vec<StreamId>),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConsentGrant {
pub id: RecordId,
pub owner: UserId,
pub grantee: UserId,
pub project: ProjectId,
pub permission: Permission,
pub streams: GrantStreams,
pub duration: Duration,
pub granted_ms: i64,
pub key: Vec<u8>,
pub sig: Vec<u8>,
}
impl ConsentGrant {
pub fn signing_bytes(&self) -> Vec<u8> {
let e = Enc::new("consent")
.s(self.id.as_str())
.s(self.owner.as_str())
.s(self.grantee.as_str())
.s(self.project.as_str())
.s(self.permission.as_str());
let e = match &self.streams {
GrantStreams::All => e.u8(0),
GrantStreams::Only(v) => v.iter().fold(e.u8(1).u32(v.len() as u32), |e, s| e.s(s.as_str())),
};
e.u8(matches!(self.duration, Duration::Always) as u8).i64(self.granted_ms).b(&self.key).done()
}
#[allow(clippy::too_many_arguments)]
pub fn sign(
owner: &Keypair,
id: &str,
grantee: &UserId,
project: &ProjectId,
permission: &str,
streams: GrantStreams,
duration: Duration,
now: i64,
) -> Result<ConsentGrant, SignError> {
let mut g = ConsentGrant {
id: RecordId::new(id),
owner: UserId::of_keypair(owner),
grantee: grantee.clone(),
project: project.clone(),
permission: Permission::new(permission),
streams,
duration,
granted_ms: now,
key: owner.public().encode_protobuf(),
sig: Vec::new(),
};
g.sig = owner.sign(&g.signing_bytes()).map_err(|e| SignError(e.to_string()))?;
Ok(g)
}
pub fn verify(&self) -> bool {
signed_by(&self.owner, &self.key, &self.signing_bytes(), &self.sig)
}
pub fn covers(&self, stream: Option<&StreamId>) -> bool {
match (&self.streams, stream) {
(GrantStreams::All, _) => true,
(GrantStreams::Only(v), Some(s)) => v.contains(s),
(GrantStreams::Only(_), None) => false,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Revocation {
pub grant: RecordId,
pub owner: UserId,
pub at_ms: i64,
pub key: Vec<u8>,
pub sig: Vec<u8>,
}
impl Revocation {
fn bytes(&self) -> Vec<u8> {
Enc::new("revocation").s(self.grant.as_str()).s(self.owner.as_str()).i64(self.at_ms).b(&self.key).done()
}
pub fn sign(owner: &Keypair, grant: &RecordId, now: i64) -> Result<Revocation, SignError> {
let mut r =
Revocation { grant: grant.clone(), owner: UserId::of_keypair(owner), at_ms: now, key: owner.public().encode_protobuf(), sig: Vec::new() };
r.sig = owner.sign(&r.bytes()).map_err(|e| SignError(e.to_string()))?;
Ok(r)
}
pub fn verify(&self) -> bool {
signed_by(&self.owner, &self.key, &self.bytes(), &self.sig)
}
}