//! The signed change to the IP allowlist (plan ยง6). //! //! ```text //! list = canonical JSON array of {"cidr", "label"}, sorted by cidr //! statement = "cotton-allowlist-v1\n" database_id "\n" hex(sha256(list)) "\n" nonce "\n" issued_at //! sig = b64url Ed25519(person key, statement) //! ``` //! //! `issued_at` is ISO-8601 text as the phone wrote it; the Worker accepts a //! statement issued within [`FRESH_MS`] of its own clock, either side. A cidr //! appears once. An empty list is a valid statement: it means no lock. use serde_json::{json, Value}; use super::{b64, canonical_json, plain_field, sha256_hex, unb64, SealError}; use crate::keys::person::{self, PersonKey}; pub const ALLOWLIST_CONTEXT: &str = "cotton-allowlist-v1"; /// How far `issued_at` may sit from the Worker's clock: five minutes. pub const FRESH_MS: i64 = 5 * 60 * 1000; #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Entry { pub cidr: String, pub label: String, } /// The list's canonical text. A cidr named twice is refused. pub fn canonical_list(entries: &[Entry]) -> Result { let mut sorted: Vec<&Entry> = entries.iter().collect(); sorted.sort_by(|a, b| a.cidr.cmp(&b.cidr)); if sorted.windows(2).any(|w| w[0].cidr == w[1].cidr) { return Err(SealError::BadInput("a cidr is listed twice".into())); } if sorted.iter().any(|e| e.cidr.trim().is_empty() || e.cidr.trim() != e.cidr) { return Err(SealError::BadInput("a cidr is blank or padded".into())); } Ok(canonical_json(&Value::Array(sorted.iter().map(|e| json!({ "cidr": e.cidr, "label": e.label })).collect()))) } /// The bytes the person key signs. pub fn allowlist_statement(database_id: &str, entries: &[Entry], nonce: &str, issued_at: &str) -> Result, SealError> { plain_field("database", database_id)?; plain_field("nonce", nonce)?; plain_field("issued_at", issued_at)?; Ok(format!("{ALLOWLIST_CONTEXT}\n{database_id}\n{}\n{nonce}\n{issued_at}", sha256_hex(canonical_list(entries)?.as_bytes())).into_bytes()) } /// Sign a change on the phone. pub fn sign_allowlist(person: &PersonKey, database_id: &str, entries: &[Entry], nonce: &str, issued_at: &str) -> Result { Ok(b64(&person.sign(&allowlist_statement(database_id, entries, nonce, issued_at)?))) } /// Does `sig` verify as `person_public_key`'s over this change? pub fn verify_allowlist(person_public_key: &str, database_id: &str, entries: &[Entry], nonce: &str, issued_at: &str, sig: &str) -> bool { let (Ok(statement), Some(sig)) = (allowlist_statement(database_id, entries, nonce, issued_at), unb64(sig)) else { return false; }; person::verify(person_public_key, &statement, &sig) } /// Is a statement issued at `issued_at_ms` fresh at `now_ms`? pub fn is_fresh(issued_at_ms: i64, now_ms: i64) -> bool { (now_ms - issued_at_ms).abs() <= FRESH_MS } #[cfg(test)] #[path = "allowlist_tests.rs"] mod tests;