moreinlaw-kernel 0.3.3

The MoreInLaw federation protocol: what every instance must agree on to stay on the network.
Documentation
//! The kind-30777 lawyer badge: a Host's signed statement that one lawyer is verified on it.
//! Other instances and the phone app read these to show who is a lawyer, so a badge built
//! differently here is one nobody else recognises.
//!
//! The Host builds one whenever a lawyer is approved, renewed or revoked; readers check one with
//! `parse_badge`. Look here first for a badge that publishes but never shows as verified.

use nostr::prelude::*;

pub use crate::params::BADGE_KIND;

pub const STATUS_ACTIVE: &str = "active";
pub const STATUS_REVOKED: &str = "revoked";

/// A badge that passed every check, with the facts the Host's signature proves.
#[derive(Debug, Clone, PartialEq)]
pub struct Badge {
    pub lawyer: PublicKey,
    /// `STATUS_ACTIVE` or `STATUS_REVOKED`.
    pub status: String,
    /// Hash of the evidence the Host approved, when the badge names one.
    pub reviewed: Option<String>,
    /// NIP-40 expiration, unix seconds.
    pub expires_at: Option<u64>,
    pub created_at: u64,
}

/// The badge for `lawyer`, stamped now.
pub fn build_badge(
    host: &Keys,
    lawyer: &PublicKey,
    status: &str,
    reviewed: Option<&str>,
    expires_at: Option<u64>,
) -> Result<Event, String> {
    build_badge_at(host, lawyer, status, reviewed, expires_at, Timestamp::now())
}

/// Same as `build_badge` with an explicit time, for callers with their own clock and the
/// frozen test vectors.
pub fn build_badge_at(
    host: &Keys,
    lawyer: &PublicKey,
    status: &str,
    reviewed: Option<&str>,
    expires_at: Option<u64>,
    created_at: Timestamp,
) -> Result<Event, String> {
    if status != STATUS_ACTIVE && status != STATUS_REVOKED {
        return Err(format!(
            "badge status must be active or revoked, not {status:?}"
        ));
    }
    let tag = |parts: &[&str]| Tag::parse(parts).map_err(|e| format!("could not build tag: {e}"));
    // `d` is the lawyer's hex key: one slot per (Host, lawyer), so a revocation replaces the
    // active badge on every relay.
    let mut tags = vec![
        Tag::identifier(lawyer.to_hex()),
        Tag::public_key(*lawyer),
        tag(&["attr", "role", "lawyer"])?,
        tag(&["status", status])?,
    ];
    if let Some(hash) = reviewed {
        tags.push(tag(&["x", hash])?);
    }
    if let Some(at) = expires_at {
        tags.push(tag(&["expiration", &at.to_string()])?);
    }
    EventBuilder::new(Kind::Custom(BADGE_KIND), "", tags)
        .custom_created_at(created_at)
        .to_event(host)
        .map_err(|e| format!("could not sign the badge: {e}"))
}

/// Checks a badge claimed to come from `host` at unix time `now`. A revoked badge parses, so
/// the caller sees the revocation; an expired one does not.
pub fn parse_badge(event: &Event, host: &PublicKey, now: u64) -> Result<Badge, String> {
    if event.kind != Kind::Custom(BADGE_KIND) {
        return Err("not a badge event".to_string());
    }
    event
        .verify()
        .map_err(|_| "the badge's signature does not verify".to_string())?;
    if &event.pubkey != host {
        return Err("the badge was signed by a different key".to_string());
    }
    let (mut d, mut p, mut role, mut status, mut reviewed, mut expires_at) =
        (None, None, false, None, None, None);
    for t in event.tags() {
        let parts = t.as_vec();
        let get = |i: usize| parts.get(i).map(String::as_str);
        // The first of each tag wins, so a second copy cannot change what the badge says.
        match (get(0), get(1)) {
            (Some("d"), Some(v)) if d.is_none() => d = Some(v.to_string()),
            (Some("p"), Some(v)) if p.is_none() => p = Some(v.to_string()),
            (Some("attr"), Some("role")) if get(2) == Some("lawyer") => role = true,
            (Some("status"), Some(v)) if status.is_none() => status = Some(v.to_string()),
            (Some("x"), Some(v)) if reviewed.is_none() => reviewed = Some(v.to_string()),
            (Some("expiration"), Some(v)) if expires_at.is_none() => {
                expires_at = Some(
                    v.parse::<u64>()
                        .map_err(|_| "the badge's expiration is not a number".to_string())?,
                )
            }
            _ => {}
        }
    }
    let lawyer = match (d, p) {
        (Some(d), Some(p)) if d == p => PublicKey::from_hex(&p)
            .map_err(|_| "the badge names no valid lawyer key".to_string())?,
        _ => return Err("the badge's d and p tags must name the same lawyer".to_string()),
    };
    if !role {
        return Err("the badge does not give the lawyer role".to_string());
    }
    let status = match status {
        Some(s) if s == STATUS_ACTIVE || s == STATUS_REVOKED => s,
        _ => return Err("the badge's status must be active or revoked".to_string()),
    };
    if expires_at.is_some_and(|at| now >= at) {
        return Err("the badge has expired".to_string());
    }
    Ok(Badge {
        lawyer,
        status,
        reviewed,
        expires_at,
        created_at: event.created_at.as_u64(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    const NOW: u64 = 1_800_000_000;

    fn s(v: &[&str]) -> Vec<String> {
        v.iter().map(|x| x.to_string()).collect()
    }

    fn values(ev: &Event) -> Vec<Vec<String>> {
        ev.tags().iter().map(|t| t.as_vec().to_vec()).collect()
    }

    fn signed(host: &Keys, kind: u16, tags: Vec<Vec<String>>) -> Event {
        let tags: Vec<Tag> = tags.into_iter().map(|t| Tag::parse(&t).unwrap()).collect();
        EventBuilder::new(Kind::Custom(kind), "", tags)
            .to_event(host)
            .unwrap()
    }

    #[test]
    fn active_badge_has_the_wire_shape_and_roundtrips() {
        let (host, lawyer) = (Keys::generate(), Keys::generate().public_key());
        let x = "c".repeat(64);
        let ev = build_badge(&host, &lawyer, STATUS_ACTIVE, Some(&x), Some(NOW + 10)).unwrap();
        let hex = lawyer.to_hex();
        assert_eq!(ev.kind, Kind::Custom(30777));
        assert_eq!(ev.content, "");
        assert_eq!(
            values(&ev),
            vec![
                s(&["d", &hex]),
                s(&["p", &hex]),
                s(&["attr", "role", "lawyer"]),
                s(&["status", "active"]),
                s(&["x", &x]),
                s(&["expiration", &(NOW + 10).to_string()]),
            ]
        );
        let b = parse_badge(&ev, &host.public_key(), NOW).unwrap();
        assert_eq!(
            (b.lawyer, b.status.as_str(), b.reviewed, b.expires_at),
            (lawyer, "active", Some(x), Some(NOW + 10))
        );
    }

    #[test]
    fn revoked_badge_without_extras_parses() {
        let (host, lawyer) = (Keys::generate(), Keys::generate().public_key());
        let ev = build_badge(&host, &lawyer, STATUS_REVOKED, None, None).unwrap();
        assert_eq!(values(&ev).len(), 4);
        let b = parse_badge(&ev, &host.public_key(), NOW).unwrap();
        assert_eq!(
            (b.status.as_str(), b.reviewed, b.expires_at),
            ("revoked", None, None)
        );
    }

    #[test]
    fn builder_refuses_an_unknown_status() {
        let (host, lawyer) = (Keys::generate(), Keys::generate().public_key());
        assert!(build_badge(&host, &lawyer, "pending", None, None).is_err());
    }

    #[test]
    fn expired_badge_is_refused_from_its_expiration_second() {
        let (host, lawyer) = (Keys::generate(), Keys::generate().public_key());
        let ev = build_badge(&host, &lawyer, STATUS_ACTIVE, None, Some(NOW)).unwrap();
        assert!(parse_badge(&ev, &host.public_key(), NOW - 1).is_ok());
        assert!(parse_badge(&ev, &host.public_key(), NOW).is_err());
    }

    #[test]
    fn parse_refuses_wrong_signer_kind_and_shape() {
        let (host, lawyer) = (Keys::generate(), Keys::generate().public_key());
        let h = host.public_key();
        let ev = build_badge(&host, &lawyer, STATUS_ACTIVE, None, None).unwrap();
        assert!(parse_badge(&ev, &Keys::generate().public_key(), NOW).is_err());

        let hex = lawyer.to_hex();
        let other = Keys::generate().public_key().to_hex();
        let base = |d: &str, p: &str, role: &str, status: &str| {
            vec![
                s(&["d", d]),
                s(&["p", p]),
                s(&["attr", "role", role]),
                s(&["status", status]),
            ]
        };
        let check =
            |kind: u16, tags: Vec<Vec<String>>| parse_badge(&signed(&host, kind, tags), &h, NOW);
        assert!(check(30777, base(&hex, &hex, "lawyer", "active")).is_ok());
        assert!(check(30778, base(&hex, &hex, "lawyer", "active")).is_err());
        assert!(check(30777, base(&hex, &other, "lawyer", "active")).is_err());
        assert!(check(30777, base(&hex, &hex, "client", "active")).is_err());
        assert!(check(30777, base(&hex, &hex, "lawyer", "pending")).is_err());
        assert!(check(30777, base("zz", "zz", "lawyer", "active")).is_err());
        let mut bad_exp = base(&hex, &hex, "lawyer", "active");
        bad_exp.push(s(&["expiration", "soon"]));
        assert!(check(30777, bad_exp).is_err());
        // a later duplicate status cannot turn a revoked badge back to active
        let mut dup = base(&hex, &hex, "lawyer", "revoked");
        dup.push(s(&["status", "active"]));
        assert_eq!(check(30777, dup).unwrap().status, "revoked");
    }

    #[test]
    fn tampered_badge_is_refused() {
        let (host, lawyer) = (Keys::generate(), Keys::generate().public_key());
        let ev = build_badge(&host, &lawyer, STATUS_REVOKED, None, None).unwrap();
        let t = Event::from_json(ev.as_json().replace("\"revoked\"", "\"active\"")).unwrap();
        assert!(parse_badge(&t, &host.public_key(), NOW).is_err());
    }
}