//! A member's approval of one request (docs/TEAM.md, "Approval statements"). use serde::{Deserialize, Serialize}; use crate::member::MemberKey; use crate::policy::RosterMember; use crate::request::SignRequest; use crate::{TeamError, b64, unb64, unhex}; pub const APPROVAL_DOMAIN: &[u8] = b"custos team approval v1\0"; /// `{"member", "code", "at", "sig"}`: who approved which request (by its hash, outside), with which code, when. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Statement { pub member: String, pub code: String, pub at: u64, /// Base64 of the 64-byte Ed25519 signature. pub sig: String, } /// What a statement signs. pub fn message(request_hash: &[u8; 32], code: &str, member: &[u8; 16], at: u64) -> Vec { let mut m = Vec::with_capacity(APPROVAL_DOMAIN.len() + 32 + 6 + 16 + 8); m.extend_from_slice(APPROVAL_DOMAIN); m.extend_from_slice(request_hash); m.extend_from_slice(code.as_bytes()); m.extend_from_slice(member); m.extend_from_slice(&at.to_be_bytes()); m } fn code_ok(code: &str) -> bool { code.len() == 6 && code.bytes().all(|c| c.is_ascii_digit()) } /// A member approves `req`. `shown_code` is the code the card showed: when it is not the request's own match code, /// the request changed after the card was drawn, or it is someone else's, and nothing is signed (`WrongMatch`). pub fn approve(key: &MemberKey, req: &SignRequest, shown_code: &str, now: u64) -> Result { if shown_code != req.match_code() { return Err(TeamError::WrongMatch); } let id = key.public().id_bytes(); let sig = key.sign(&message(&req.hash(), shown_code, &id, now)); Ok(Statement { member: key.id(), code: shown_code.into(), at: now, sig: b64(&sig) }) } impl Statement { /// Checks this statement for `req` against the roster: the member is on it, the code is the request's own, /// the signature is the member's. pub fn verify(&self, req: &SignRequest, roster: &[RosterMember]) -> Result<(), TeamError> { if !code_ok(&self.code) || self.code != req.match_code() { return Err(TeamError::WrongMatch); } let m = roster.iter().find(|m| m.id == self.member).ok_or(TeamError::NotAMember)?; let id: [u8; 16] = unhex(&self.member).ok_or(TeamError::NotAMember)?; let sig: [u8; 64] = unb64(&self.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?; if !crate::member::verify(&m.ed25519, &message(&req.hash(), &self.code, &id, self.at), &sig) { return Err(TeamError::BadSignature); } Ok(()) } } /// The member ids of the statements that verify for `req`, each once, in order; the others are dropped. pub fn verified_members(statements: &[Statement], req: &SignRequest, roster: &[RosterMember]) -> Vec { let mut out: Vec = Vec::new(); for s in statements { if s.verify(req, roster).is_ok() && !out.contains(&s.member) { out.push(s.member.clone()); } } out }