engawa-chat 0.5.0

A peer-to-peer chat lobby for editors and browsers
//! A private veranda is a bearer capability. Display names are never key material.

use std::{borrow::Cow, fmt, sync::Arc};

use anyhow::{Result, ensure};
use chacha20poly1305::{AeadInOut, KeyInit, XChaCha20Poly1305};
use iroh::EndpointId;
use iroh_gossip::TopicId;

use crate::{
    lobby_wire::lobby_topic,
    protocol::{MAX_ROOM_FRAME, ROOM_TRAILER, Room, digest, is_hex},
};

// v2: ciphertext | random nonce | version marker | authentication tag. With the v1
// room trailer stripped, the marker is still present and cannot be part of valid UTF-8 JSON.
const MARKER: &[u8] = b"\xffEG2";
const NONCE: usize = 24;
const TAG: usize = 16;
const OVERHEAD: usize = NONCE + MARKER.len() + TAG;

#[derive(Clone)]
pub(crate) enum Scope {
    Public,
    Private(Arc<PrivateScope>),
}

pub(crate) struct PrivateScope {
    root: [u8; 32],
    lobby: TopicId,
    cipher: XChaCha20Poly1305,
}

impl fmt::Debug for Scope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Public => "Public",
            Self::Private(_) => "Private([REDACTED])",
        })
    }
}

pub(crate) fn valid_veranda_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 96
        && name.trim() == name
        && !name.chars().any(char::is_control)
        && !["{{", "{%", "{#"].iter().any(|s| name.contains(s))
}

impl PrivateScope {
    fn room_id(&self, name: &str, history: bool) -> Result<blake3::Hash> {
        let identity = Room::identity(name, history)?;
        Ok(digest(
            "engawa/v2/private-room",
            &[&self.root, identity.as_bytes()],
        ))
    }

    fn seal(&self, topic: TopicId, mut data: Vec<u8>) -> Result<Vec<u8>> {
        let mut nonce = [0u8; NONCE];
        getrandom::fill(&mut nonce)?;
        let tag = self.cipher.encrypt_inout_detached(
            (&nonce).into(),
            topic.as_bytes(),
            data.as_mut_slice().into(),
        )?;
        data.reserve(OVERHEAD);
        data.extend_from_slice(&nonce);
        data.extend_from_slice(MARKER);
        data.extend_from_slice(&tag);
        Ok(data)
    }

    fn open(&self, topic: TopicId, wire: &[u8], max: usize) -> Option<Vec<u8>> {
        if wire.len() <= OVERHEAD || wire.len() > max + OVERHEAD {
            return None;
        }
        let (body, tag) = wire.split_last_chunk::<TAG>()?;
        let (ciphertext, nonce) = body.strip_suffix(MARKER)?.split_last_chunk::<NONCE>()?;
        let mut data = ciphertext.to_vec();
        self.cipher
            .decrypt_inout_detached(
                nonce.into(),
                topic.as_bytes(),
                data.as_mut_slice().into(),
                tag.into(),
            )
            .ok()?;
        Some(data)
    }
}

impl Scope {
    pub(crate) fn from_key_hex(key: &str) -> Result<Self> {
        ensure!(
            is_hex(key, 64),
            "縁側の鍵は64桁の小文字の16進数で指定してください"
        );
        let mut root = [0; 32];
        hex::decode_to_slice(key, &mut root)?;
        let lobby = TopicId::from_bytes(blake3::derive_key("engawa/v2/private-lobby", &root));
        let cipher =
            XChaCha20Poly1305::new(&blake3::derive_key("engawa/v2/private-payload", &root).into());
        Ok(Self::Private(Arc::new(PrivateScope {
            root,
            lobby,
            cipher,
        })))
    }

    pub(crate) fn key_hex(&self) -> Option<String> {
        match self {
            Self::Public => None,
            Self::Private(p) => Some(hex::encode(p.root)),
        }
    }

    pub(crate) fn scope_id(&self) -> Option<String> {
        match self {
            Self::Public => None,
            Self::Private(p) => Some(hex::encode(blake3::derive_key(
                "engawa/v2/private-storage",
                &p.root,
            ))),
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn rendezvous_secret(&self) -> Option<[u8; 32]> {
        match self {
            Self::Public => None,
            Self::Private(p) => Some(blake3::derive_key("engawa/v2/private-rendezvous", &p.root)),
        }
    }

    pub(crate) fn lobby_topic(&self) -> TopicId {
        match self {
            Self::Public => lobby_topic(),
            Self::Private(p) => p.lobby,
        }
    }

    pub(crate) fn room(&self, name: &str, history: bool) -> Result<Room> {
        match self {
            Self::Public => Room::new(name, history),
            Self::Private(p) => Ok(Room {
                id: p.room_id(name, history)?.to_hex().to_string(),
                name: name.to_owned(),
                history,
            }),
        }
    }

    pub(crate) fn accepts(&self, room: &Room) -> bool {
        match self {
            Self::Public => room.consistent(),
            Self::Private(p) => p
                .room_id(&room.name, room.history)
                .is_ok_and(|id| id.to_hex().as_str() == room.id),
        }
    }

    pub(crate) fn seal_notice(&self, notice: Vec<u8>) -> Result<Vec<u8>> {
        match self {
            Self::Public => Ok(notice),
            Self::Private(p) => p.seal(p.lobby, notice),
        }
    }

    pub(crate) fn open_notice<'a>(&self, wire: &'a [u8], max: usize) -> Option<Cow<'a, [u8]>> {
        match self {
            Self::Public => (wire.len() <= max).then_some(Cow::Borrowed(wire)),
            Self::Private(p) => p.open(p.lobby, wire, max).map(Cow::Owned),
        }
    }

    pub(crate) fn seal_room(
        &self,
        topic: TopicId,
        mut payload: Vec<u8>,
        me: EndpointId,
        seq: u64,
    ) -> Result<Vec<u8>> {
        ensure!(
            topic != self.lobby_topic(),
            "ロビーには部屋のパケットを送信できません"
        );
        ensure!(
            !payload.is_empty() && payload.len() <= MAX_ROOM_FRAME,
            "部屋のパケットの長さが不正です"
        );
        match self {
            Self::Public => {
                // v1 uses the origin and sequence to avoid content-hash deduplication.
                payload.reserve(ROOM_TRAILER);
                payload.extend_from_slice(&me.as_bytes()[..8]);
                payload.extend_from_slice(&seq.to_be_bytes());
                Ok(payload)
            }
            Self::Private(p) => p.seal(topic, payload),
        }
    }

    pub(crate) fn open_room<'a>(&self, topic: TopicId, wire: &'a [u8]) -> Option<Cow<'a, [u8]>> {
        if topic == self.lobby_topic() {
            return None;
        }
        match self {
            Self::Public => {
                let (payload, _) = wire.split_last_chunk::<ROOM_TRAILER>()?;
                (!payload.is_empty()
                    && payload.len() <= MAX_ROOM_FRAME
                    && !payload.ends_with(MARKER))
                .then_some(Cow::Borrowed(payload))
            }
            Self::Private(p) => p.open(topic, wire, MAX_ROOM_FRAME).map(Cow::Owned),
        }
    }
}

#[cfg(test)]
mod tests {
    use iroh::SecretKey;

    use super::*;
    use crate::protocol::{Packet, Record};

    #[test]
    fn veranda_labels_are_bounded_literal_text_not_templates() {
        assert!(valid_veranda_name("yukimemi さん家の縁側"));
        assert!(valid_veranda_name(&"家".repeat(32)));
        assert!(!valid_veranda_name(&"家".repeat(33)));
        for bad in ["", " 家", "家 ", "家\n族", "{{ x }}", "a{% b", "{# c"] {
            assert!(!valid_veranda_name(bad));
        }
    }

    #[test]
    fn capability_is_canonical_redacted_and_distinct_from_identifiers() {
        let hex = "ab".repeat(32);
        let a = Scope::from_key_hex(&hex).unwrap();
        for bad in [hex.to_uppercase(), hex[..63].to_string(), "g0".repeat(32)] {
            let err = Scope::from_key_hex(&bad).unwrap_err().to_string();
            assert!(!err.contains(&bad));
        }
        assert_eq!(a.key_hex().as_deref(), Some(hex.as_str()));
        assert!(!format!("{a:?}").contains(&hex));
        let b = Scope::from_key_hex(&"bc".repeat(32)).unwrap();
        let room = a.room("本棚", true).unwrap();
        assert!(a.accepts(&room));
        assert!(!b.accepts(&room));
        assert!(!Scope::Public.accepts(&room));
        assert!(!a.accepts(&Scope::Public.room("本棚", true).unwrap()));
        assert_ne!(a.room("本棚", false).unwrap().id, room.id);
        assert_ne!(a.scope_id(), b.scope_id());
        assert_ne!(a.lobby_topic(), b.lobby_topic());
        let ids = [
            hex,
            a.scope_id().unwrap(),
            a.lobby_topic().to_string(),
            room.id,
        ];
        for (i, id) in ids.iter().enumerate() {
            assert!(!ids[..i].contains(id));
        }
    }

    #[test]
    fn every_room_packet_requires_the_same_capability_and_topic() {
        let a = Scope::from_key_hex(&"ab".repeat(32)).unwrap();
        let b = Scope::from_key_hex(&"bc".repeat(32)).unwrap();
        let room = a.room("本棚", true).unwrap();
        let topic = room.id.parse().unwrap();
        let other_room = a.room("台所", true).unwrap().id.parse().unwrap();
        let signer = ed25519_dalek::SigningKey::from_bytes(&[1; 32]);
        let me = SecretKey::generate().public();
        let post = Record::new(&signer, &room.id, 1000, "秘密のメッセージ").unwrap();
        let id = post.id(&room.id);
        let mut dead = post.clone();
        dead.erase(&signer, &room.id).unwrap();
        for packet in [
            Packet::Hello,
            Packet::Item(post),
            Packet::Offer(vec![(id.clone(), false)]),
            Packet::Need(vec![(id, true)]),
            Packet::Item(dead),
        ] {
            let bytes = packet.encode().unwrap();
            let wire = a.seal_room(topic, bytes.clone(), me, 7).unwrap();
            assert_eq!(a.open_room(topic, &wire).unwrap(), bytes);
            assert_ne!(a.seal_room(topic, bytes.clone(), me, 7).unwrap(), wire);
            assert!(b.open_room(topic, &wire).is_none());
            assert!(a.open_room(other_room, &wire).is_none());
            assert!(Scope::Public.open_room(topic, &wire).is_none());
            assert!(a.open_room(topic, &bytes).is_none());
            assert!(a.open_notice(&wire, MAX_ROOM_FRAME).is_none());
            let public = Scope::Public
                .seal_room(topic, bytes.clone(), me, 7)
                .unwrap();
            assert_eq!(&public[..bytes.len()], bytes);
            assert_eq!(&public[bytes.len()..bytes.len() + 8], &me.as_bytes()[..8]);
            assert_eq!(&public[bytes.len() + 8..], &7_u64.to_be_bytes());
            assert!(a.open_room(topic, &public).is_none());
            for offset in [0, bytes.len(), wire.len() - TAG - 1, wire.len() - 1] {
                let mut bad = wire.clone();
                bad[offset] ^= 1;
                assert!(a.open_room(topic, &bad).is_none());
            }
        }
    }

    #[test]
    fn room_wire_limits_apply_to_plaintext_before_and_after_wrapping() {
        let me = SecretKey::generate().public();
        for scope in [
            Scope::Public,
            Scope::from_key_hex(&"01".repeat(32)).unwrap(),
        ] {
            let topic = scope.room("本棚", false).unwrap().id.parse().unwrap();
            assert!(scope.seal_room(topic, vec![], me, 0).is_err());
            assert!(
                scope
                    .seal_room(topic, vec![0; MAX_ROOM_FRAME + 1], me, 0)
                    .is_err()
            );
            let mut wire = scope
                .seal_room(topic, vec![0; MAX_ROOM_FRAME], me, 0)
                .unwrap();
            assert_eq!(scope.open_room(topic, &wire).unwrap().len(), MAX_ROOM_FRAME);
            wire.push(0);
            assert!(scope.open_room(topic, &wire).is_none());
            assert!(scope.open_room(topic, &[]).is_none());
        }
    }
}