moreinlaw-kernel 0.3.0

The MoreInLaw federation protocol: what every instance must agree on to stay on the network.
Documentation
//! Decides whether an organization really owns the address it claims, so every server proves
//! organizations the same way. An organization fails when its site answers with another slug or
//! key, its API sits off its own site, or its signed registration names another key or address.
//!
//! This runs when the user opens an organization in the federation list or another organization
//! is proved. Users would report an organization stuck as "unproved" or "address check failed".

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

use nostr::{Event, PublicKey};
use serde::{Deserialize, Serialize};

use crate::registration::{parse_registration, HostRegistration};

const OWN_SITE_ERROR: &str = "API address must be on the organization's own site";
pub const NO_REGISTRATION_ERROR: &str = "No signed registration found for this key";

/// `GET /api/host_identity`: what a site answers when asked who it is.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct HostIdentityResponse {
    pub slug: String,
    pub operator_npub: String,
    /// The directory name, shown as the organization header in the phone app's pages. Optional so
    /// an older Host's answer, which has none, still parses during registration checks.
    #[serde(default)]
    pub name: Option<String>,
}

fn is_public_v4(ip: Ipv4Addr) -> bool {
    let o = ip.octets();
    let carrier_grade_nat = o[0] == 100 && (o[1] & 0xc0) == 64;
    let benchmarking = o[0] == 198 && (o[1] & 0xfe) == 18;
    let protocol_assignments = o[0] == 192 && o[1] == 0 && o[2] == 0;
    !(ip.is_loopback()
        || ip.is_private()
        || ip.is_link_local()
        || ip.is_broadcast()
        || ip.is_unspecified()
        || ip.is_multicast()
        || ip.is_documentation()
        || o[0] == 0
        || o[0] >= 240
        || carrier_grade_nat
        || benchmarking
        || protocol_assignments)
}

fn is_public_v6(ip: Ipv6Addr) -> bool {
    if let Some(v4) = ip.to_ipv4_mapped() {
        return is_public_v4(v4);
    }
    let seg = ip.segments();
    // 64:ff9b::/96 carries an IPv4 address in its last 32 bits.
    if seg[0] == 0x64 && seg[1] == 0xff9b {
        let v4 = Ipv4Addr::new(
            (seg[6] >> 8) as u8,
            seg[6] as u8,
            (seg[7] >> 8) as u8,
            seg[7] as u8,
        );
        return is_public_v4(v4);
    }
    let unique_local = (seg[0] & 0xfe00) == 0xfc00;
    let link_local = (seg[0] & 0xffc0) == 0xfe80;
    let documentation = seg[0] == 0x2001 && seg[1] == 0x0db8;
    !(ip.is_loopback()
        || ip.is_unspecified()
        || ip.is_multicast()
        || unique_local
        || link_local
        || documentation)
}

/// Whether a connection to this address could only reach the public internet.
pub fn is_public_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => is_public_v4(v4),
        IpAddr::V6(v6) => is_public_v6(v6),
    }
}

/// Compares what a site answered at `/api/host_identity` with what the registration claimed.
pub fn check_identity(slug: &str, operator_npub: &str, body: &[u8]) -> Result<(), String> {
    let answered: HostIdentityResponse = serde_json::from_slice(body)
        .map_err(|_| "the site's identity answer is not the expected JSON".to_string())?;
    if answered.slug != slug {
        return Err("the site answered with a different slug".to_string());
    }
    if answered.operator_npub != operator_npub {
        return Err("the site answered with a different operator key".to_string());
    }
    Ok(())
}

/// The API the proof calls must live on the organization's own site: same host, or a subdomain
/// of it, over https. Otherwise a registration could name a victim's URL and an attacker's API.
pub fn api_on_own_site(portal_url: &str, api_url: Option<&str>) -> Result<(), String> {
    let Some(api) = api_url else {
        return Ok(());
    };
    let (portal, api) = match (::url::Url::parse(portal_url), ::url::Url::parse(api)) {
        (Ok(p), Ok(a)) => (p, a),
        _ => return Err(OWN_SITE_ERROR.to_string()),
    };
    let (Some(ph), Some(ah)) = (portal.host_str(), api.host_str()) else {
        return Err(OWN_SITE_ERROR.to_string());
    };
    let same = ah == ph;
    let subdomain = ah.ends_with(&format!(".{ph}"));
    let port_ok = same && api.port_or_known_default() == portal.port_or_known_default();
    if api.scheme() == "https" && ((same && port_ok) || subdomain) {
        Ok(())
    } else {
        Err(OWN_SITE_ERROR.to_string())
    }
}

/// A signed registration is acceptable for (key, slug) if it parses and is from that key.
pub fn registration_for(
    event: &Event,
    pubkey: &PublicKey,
    slug: &str,
) -> Result<HostRegistration, String> {
    let reg = parse_registration(event)?;
    if &event.pubkey != pubkey || reg.slug != slug {
        return Err(NO_REGISTRATION_ERROR.to_string());
    }
    Ok(reg)
}

/// ...and for an address too when it also names exactly that portal URL.
pub fn accept_registration(
    event: &Event,
    pubkey: &PublicKey,
    slug: &str,
    portal_url: &str,
) -> Result<HostRegistration, String> {
    let reg = registration_for(event, pubkey, slug)?;
    if reg.portal_url != portal_url {
        return Err(NO_REGISTRATION_ERROR.to_string());
    }
    Ok(reg)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registration::{build_registration_event, RegistrationInput};
    use nostr::Keys;

    const NPUB: &str = "npub1m7lzt4jmcutc0c9v0dgk8uzu6ae4xqn6s4sk8thl6nzxw5dyyqksdgansu";
    const OTHER_NPUB: &str = "npub1juzsrwp5q8hrcawhu2rw4q4m8dsj7fnd2fuxcpmaf5v2z3agdq0q58djak";

    #[test]
    fn is_public_ip_refuses_every_private_range() {
        let refused = [
            "127.0.0.1",
            "10.0.0.5",
            "172.16.0.1",
            "172.31.255.255",
            "192.168.1.1",
            "169.254.169.254",
            "100.64.0.1",
            "0.0.0.0",
            "198.18.0.1",
            "224.0.0.1",
            "255.255.255.255",
            "::1",
            "::",
            "fe80::1",
            "fc00::1",
            "fd12:3456::1",
            "ff02::1",
            "::ffff:127.0.0.1",
            "::ffff:10.0.0.1",
        ];
        for ip in refused {
            assert!(!is_public_ip(ip.parse().unwrap()), "{ip} must be refused");
        }
        for ip in ["8.8.8.8", "9.9.9.9", "172.32.0.1", "2606:4700:4700::1111"] {
            assert!(is_public_ip(ip.parse().unwrap()), "{ip} must be allowed");
        }
    }

    #[test]
    fn check_identity_accepts_matching_slug_and_key() {
        let body = format!(r#"{{"slug":"main-org","operator_npub":"{NPUB}"}}"#);
        assert!(check_identity("main-org", NPUB, body.as_bytes()).is_ok());
    }

    #[test]
    fn check_identity_rejects_wrong_key_wrong_slug_and_garbage() {
        let wrong_key = format!(r#"{{"slug":"main-org","operator_npub":"{OTHER_NPUB}"}}"#);
        assert!(check_identity("main-org", NPUB, wrong_key.as_bytes()).is_err());
        let wrong_slug = format!(r#"{{"slug":"other","operator_npub":"{NPUB}"}}"#);
        assert!(check_identity("main-org", NPUB, wrong_slug.as_bytes()).is_err());
        assert!(check_identity("main-org", NPUB, b"<html>not json</html>").is_err());
    }

    #[test]
    fn host_identity_without_name_parses() {
        let body = format!(r#"{{"slug":"main-org","operator_npub":"{NPUB}"}}"#);
        let answered: HostIdentityResponse = serde_json::from_str(&body).unwrap();
        assert_eq!(answered.name, None);
    }

    #[test]
    fn api_must_live_on_the_organizations_own_site() {
        let portal = "https://morein.ph";
        let ok = |api: &str| api_on_own_site(portal, Some(api)).is_ok();
        assert!(api_on_own_site(portal, None).is_ok());
        assert!(ok("https://morein.ph/backend"), "same host");
        assert!(ok("https://api.morein.ph"), "subdomain");
        assert!(
            ok("https://api.morein.ph:8443/backend"),
            "subdomain, other port"
        );
        assert!(!ok("https://api.attacker.com/backend"), "other site");
        assert!(!ok("https://evilmorein.ph"), "suffix trick");
        assert!(
            !ok("https://morein.ph:8443/backend"),
            "same host, other port"
        );
        assert!(!ok("http://morein.ph/backend"), "not https");
        assert!(!ok("https://morein.ph.attacker.com"), "prefix trick");
        assert!(
            api_on_own_site("https://morein.ph:8443", Some("https://morein.ph:8443/b")).is_ok()
        );
    }

    #[test]
    fn a_registration_counts_only_for_its_own_key_slug_and_url() {
        let keys = Keys::generate();
        let input = RegistrationInput {
            slug: "alpha-law".into(),
            name: "Alpha".into(),
            portal_url: "https://alpha.example".into(),
            api_url: None,
            relays: vec!["wss://nos.lol".into()],
            geohash: None,
            picture: None,
        };
        let ev = build_registration_event(&keys, &input).unwrap();
        let pk = keys.public_key();
        assert!(accept_registration(&ev, &pk, "alpha-law", "https://alpha.example").is_ok());
        assert!(accept_registration(&ev, &pk, "alpha-law", "https://victim.ph").is_err());
        assert!(accept_registration(&ev, &pk, "other-law", "https://alpha.example").is_err());
        let stranger = Keys::generate().public_key();
        assert!(accept_registration(&ev, &stranger, "alpha-law", "https://alpha.example").is_err());
    }
}