gent-daemon 0.2.0

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
//! A peer may administer one named board, or exercise its write grant. Neither
//! operation accepts a daemon request or forwards a local owner credential.
use super::*;
use gent_protocol::{
    MAX_REGISTRATION_GENERATION, OwnerOp, Request, Response,
    dashboard::{GrantAdmin, GrantOp, MAX_HTML_BYTES, valid_grant_key},
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use uuid::Uuid;

pub(super) const ALPN: &[u8] = b"gent/dashboard-grant/1";
const HEADER: usize = 1024;
// A single UTF-8 byte can require six JSON bytes ("\\u0000").
const FRAME: usize = 6 * MAX_HTML_BYTES + 2048;

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct BoardPin {
    pub(crate) checkpoint: [u8; 32],
    pub(crate) publisher: String,
    pub(crate) agent: Uuid,
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum Call {
    Admin { action: GrantAdmin },
    Delegate { secret: String, action: GrantOp },
}

impl Call {
    fn validate(&self) -> Result<()> {
        let revision = match self {
            Self::Admin {
                action:
                    GrantAdmin::Issue {
                        expected_revision,
                        verifier,
                    },
            } => {
                ensure!(valid_grant_key(verifier), "invalid board grant verifier");
                *expected_revision
            }
            Self::Admin {
                action: GrantAdmin::Revoke { expected_revision },
            } => *expected_revision,
            Self::Delegate { secret, action } => {
                ensure!(valid_grant_key(secret), "invalid board grant");
                match action {
                    GrantOp::Get => return Ok(()),
                    GrantOp::Update {
                        expected_revision,
                        html,
                    } => {
                        ensure!(
                            (1..=MAX_HTML_BYTES).contains(&html.len()),
                            "invalid board document size"
                        );
                        *expected_revision
                    }
                }
            }
        };
        ensure!(
            (1..=MAX_REGISTRATION_GENERATION).contains(&revision),
            "invalid board revision"
        );
        Ok(())
    }

    fn local(self, agent: Uuid, credential: Option<String>) -> Result<Request> {
        Ok(match self {
            Self::Admin { action } => Request::Owner {
                credential: credential.context("owner credential required")?,
                action: OwnerOp::DashboardGrant { agent, action },
            },
            Self::Delegate { secret, action } => Request::DashboardDelegate {
                agent,
                secret,
                action,
            },
        })
    }
}

struct Wire {
    board: BoardPin,
    call: Call,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Receipt {
    agent: Uuid,
    revision: u64,
    sha256: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    html: Option<String>,
}

impl Wire {
    fn receipt(&self, receipt: &Receipt) -> bool {
        if receipt.agent != self.board.agent
            || !valid_grant_key(&receipt.sha256)
            || !(1..=MAX_REGISTRATION_GENERATION).contains(&receipt.revision)
        {
            return false;
        }
        match &self.call {
            Call::Delegate {
                action: GrantOp::Get,
                ..
            } => {
                receipt.title.as_ref().is_some_and(|s| {
                    !s.trim().is_empty() && s.len() <= 128 && !s.chars().any(char::is_control)
                }) && receipt.html.as_ref().is_some_and(|html| {
                    (1..=MAX_HTML_BYTES).contains(&html.len())
                        && format!("{:x}", Sha256::digest(html.as_bytes())) == receipt.sha256
                })
            }
            Call::Delegate {
                action:
                    GrantOp::Update {
                        expected_revision,
                        html,
                    },
                ..
            } => {
                receipt.title.is_none()
                    && receipt.html.is_none()
                    && (*expected_revision..=expected_revision + 1).contains(&receipt.revision)
                    && format!("{:x}", Sha256::digest(html.as_bytes())) == receipt.sha256
            }
            Call::Admin {
                action:
                    GrantAdmin::Issue {
                        expected_revision, ..
                    }
                    | GrantAdmin::Revoke { expected_revision },
            } => {
                receipt.title.is_none()
                    && receipt.html.is_none()
                    && (*expected_revision..=expected_revision + 1).contains(&receipt.revision)
            }
        }
    }
}

pub(super) async fn serve(conn: &Connection, store: SharedStore) -> Result<()> {
    loop {
        let (mut send, mut recv) =
            tokio::time::timeout(Duration::from_secs(30), conn.accept_bi()).await??;
        tokio::time::timeout(OPERATION, async {
            let mut size = [0; 2];
            recv.read_exact(&mut size).await?;
            let size = usize::from(u16::from_be_bytes(size));
            ensure!(size <= HEADER, "board grant header too large");
            let mut header = vec![0; size];
            recv.read_exact(&mut header).await?;
            let board: BoardPin = serde_json::from_slice(&header)?;
            let preflight = board.clone();
            let endpoint = conn.remote_id();
            local(store.clone(), move |s| {
                s.check_board_grant_peer(endpoint, &preflight)
            })
            .await?;
            send.write_all(&[1]).await?;
            let call: Call = serde_json::from_slice(&recv.read_to_end(FRAME).await?)?;
            call.validate()?;
            let receipt = local(store.clone(), move |s| {
                s.serve_board_grant(endpoint, board, call)
            })
            .await
            .ok();
            // Only return the bounded board receipt. Local SQL/authentication errors stay local.
            let reply: Option<Receipt> = receipt.map(serde_json::from_value).transpose()?;
            let bytes = serde_json::to_vec(&reply)?;
            ensure!(bytes.len() <= FRAME, "board grant reply too large");
            send.write_all(&bytes).await?;
            send.finish()?;
            Ok::<_, anyhow::Error>(())
        })
        .await??;
    }
}

enum Destination {
    Local(Value),
    Remote(Arc<Direct>, EndpointAddr, Wire),
}

pub(crate) async fn route(store: SharedStore, req: Request) -> Result<Value> {
    let (credential, agent, call) = match req {
        Request::Owner {
            credential,
            action: OwnerOp::DashboardGrant { agent, action },
        } => (Some(credential), agent, Call::Admin { action }),
        Request::DashboardDelegate {
            agent,
            secret,
            action,
        } => (None, agent, Call::Delegate { secret, action }),
        _ => anyhow::bail!("invalid board grant operation"),
    };
    call.validate()?;
    let owner = credential.clone();
    let remote = local(store.clone(), move |s| {
        let (pin, address) = s.board_grant_target(agent, owner.as_deref())?;
        if let Some(address) = address {
            let direct = s
                .board_transport
                .upgrade()
                .context("board transport unavailable")?;
            Ok(Destination::Remote(
                direct,
                address,
                Wire { board: pin, call },
            ))
        } else {
            match s.handle(call.local(agent, owner)?) {
                Response::Ok(value) => Ok(Destination::Local(value)),
                Response::Error(message) => anyhow::bail!("{message}"),
            }
        }
    })
    .await?;
    let (direct, address, wire) = match remote {
        Destination::Remote(direct, address, wire) => (direct, address, wire),
        Destination::Local(value) => return Ok(value),
    };
    let endpoint = address.id;
    let recheck = || {
        let board = wire.board.clone();
        let owner = credential.clone();
        local(store.clone(), move |s| {
            let (current, address) = s.board_grant_target(agent, owner.as_deref())?;
            ensure!(
                board == current && address.is_some_and(|a| a.id == endpoint),
                "board carrier changed"
            );
            Ok(())
        })
    };
    let receipt = tokio::time::timeout(OPERATION, async {
        let conn = direct
            .primary_pull_connection(&direct.grants, address, ALPN, 8)
            .await
            .context("board grant carrier unavailable")?;
        let (mut send, mut recv) = conn.open_bi().await?;
        // Do not send a bearer until the authenticated peer agrees it still
        // carries this publisher at this checkpoint. Recheck our view after that round trip.
        let header = serde_json::to_vec(&wire.board)?;
        ensure!(header.len() <= HEADER, "board grant header too large");
        send.write_all(&(header.len() as u16).to_be_bytes()).await?;
        send.write_all(&header).await?;
        let mut ready = [0];
        recv.read_exact(&mut ready)
            .await
            .context("board carrier did not confirm its route")?;
        ensure!(ready == [1], "board carrier did not confirm its route");
        recheck().await?;
        let bytes = serde_json::to_vec(&wire.call)?;
        ensure!(bytes.len() <= FRAME, "board grant request too large");
        send.write_all(&bytes).await?;
        send.finish()?;
        let limit = if matches!(
            wire.call,
            Call::Delegate {
                action: GrantOp::Get,
                ..
            }
        ) {
            FRAME
        } else {
            256
        };
        let reply = recv.read_to_end(limit).await?;
        let receipt: Receipt = serde_json::from_slice::<Option<Receipt>>(&reply)
            .context("invalid board grant receipt")?
            .context("board grant request rejected; check access and current revision")?;
        ensure!(wire.receipt(&receipt), "invalid board grant receipt");
        Ok::<_, anyhow::Error>(receipt)
    })
    .await??;
    recheck().await?;
    Ok(serde_json::to_value(receipt)?)
}

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

    #[test]
    fn grant_protocol_accepts_only_scoped_actions_and_matching_receipts() -> Result<()> {
        let agent = Uuid::new_v4();
        let html = "Dashboard";
        let digest = format!("{:x}", Sha256::digest(html));
        let board = BoardPin {
            agent,
            checkpoint: [0; 32],
            publisher: "publisher".into(),
        };
        let mut wire = Wire {
            board,
            call: Call::Delegate {
                secret: "a".repeat(64),
                action: GrantOp::Get,
            },
        };
        let mut receipt = Receipt {
            agent,
            revision: 2,
            sha256: digest.clone(),
            title: Some("Trial".into()),
            html: Some(html.into()),
        };
        assert!(wire.receipt(&receipt));
        receipt.agent = Uuid::new_v4();
        assert!(!wire.receipt(&receipt));
        receipt.agent = agent;
        receipt.html = Some("different".into());
        assert!(!wire.receipt(&receipt));
        wire.call = Call::Admin {
            action: GrantAdmin::Issue {
                expected_revision: 1,
                verifier: digest,
            },
        };
        assert!(!wire.receipt(&receipt));
        receipt.title = None;
        receipt.html = None;
        assert!(wire.receipt(&receipt));
        receipt.revision = 3;
        assert!(!wire.receipt(&receipt));
        let admin = serde_json::to_value(&wire.call)?;
        assert_eq!(admin.as_object().unwrap().len(), 2);
        assert!(admin["action"].get("verifier").is_some());
        for field in ["credential", "secret"] {
            let mut extra = admin.clone();
            extra[field] = json!("unexpected");
            assert!(serde_json::from_value::<Call>(extra).is_err());
        }
        assert!(
            serde_json::from_value::<Call>(
                json!({"kind":"delegate","secret":"unused","action":{"op":"status"}})
            )
            .is_err()
        );
        Ok(())
    }
}