weirdnet-collab 0.3.0

Collaboration control for Weirdnet apps: project members and roles, signed allow and deny rules, owner consent grants, a decision with a reason chain, invites and a signed, mergeable audit log. App-agnostic: the app defines what a project, role and permission are.
Documentation
//! Signed records: rules, consent grants and revocations.
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;

/// Why a record could not be made.
#[derive(Debug, thiserror::Error)]
#[error("cannot sign: {0}")]
pub struct SignError(pub String);

/// Who a rule is about.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Subject {
    /// One person.
    Member(UserId),
    /// Everyone in a role.
    Role(RoleId),
}

/// Allow or deny.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Effect {
    /// Grants the permission.
    Allow,
    /// Refuses it.
    Deny,
}

/// A project-level rule. Permissions stop at the project: there is no narrower level.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rule {
    /// Unique id.
    pub id: RecordId,
    /// About whom.
    pub subject: Subject,
    /// The project.
    pub project: ProjectId,
    /// What it decides.
    pub permission: Permission,
    /// Allow or deny.
    pub effect: Effect,
    /// When it stops applying, milliseconds since the epoch.
    pub expires_ms: Option<i64>,
    /// Who set it.
    pub set_by: UserId,
    /// When.
    pub set_ms: i64,
    /// The setter's public key, protobuf-encoded.
    pub key: Vec<u8>,
    /// The setter's signature over [`Rule::signing_bytes`].
    pub sig: Vec<u8>,
}

impl Rule {
    /// The signed bytes.
    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()
    }

    /// Make and sign a rule.
    #[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)
    }

    /// Whether the signature is the setter's.
    pub fn verify(&self) -> bool {
        signed_by(&self.set_by, &self.key, &self.signing_bytes(), &self.sig)
    }

    /// Whether the rule applies at `now`.
    pub fn live(&self, now: i64) -> bool {
        self.expires_ms.is_none_or(|t| t > now)
    }
}

/// How long a grant lasts.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Duration {
    /// For one take: spent by [`crate::Project::spend_consent`].
    Once,
    /// Until the owner revokes it.
    Always,
}

/// Which of the owner's streams a grant covers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum GrantStreams {
    /// Every stream of theirs in the project.
    All,
    /// Only these.
    Only(Vec<StreamId>),
}

/// An owner's consent for one person to do a gated thing with the owner's audio. Only the owner
/// can sign one; a host cannot grant it or waive it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConsentGrant {
    /// Unique id.
    pub id: RecordId,
    /// Whose audio.
    pub owner: UserId,
    /// Who may.
    pub grantee: UserId,
    /// The project.
    pub project: ProjectId,
    /// The gated permission (`stream.record`, `mic.record`, `route.connect`).
    pub permission: Permission,
    /// Which streams.
    pub streams: GrantStreams,
    /// Once or always.
    pub duration: Duration,
    /// When it was given.
    pub granted_ms: i64,
    /// The owner's public key, protobuf-encoded.
    pub key: Vec<u8>,
    /// The owner's signature.
    pub sig: Vec<u8>,
}

impl ConsentGrant {
    /// The signed bytes.
    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()
    }

    /// Make and sign a grant as `owner`.
    #[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)
    }

    /// Whether the signature is the owner's.
    pub fn verify(&self) -> bool {
        signed_by(&self.owner, &self.key, &self.signing_bytes(), &self.sig)
    }

    /// Whether the grant covers `stream`.
    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,
        }
    }
}

/// The owner's signed revocation of a grant.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Revocation {
    /// The grant revoked.
    pub grant: RecordId,
    /// The owner who revokes it.
    pub owner: UserId,
    /// When.
    pub at_ms: i64,
    /// The owner's public key.
    pub key: Vec<u8>,
    /// The owner's signature.
    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()
    }

    /// Revoke `grant` as its owner.
    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)
    }

    /// Whether the signature is the owner's.
    pub fn verify(&self) -> bool {
        signed_by(&self.owner, &self.key, &self.bytes(), &self.sig)
    }
}