gent-daemon 0.2.5

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
//! A board grant authorizes only a carrier-local read or revision-checked document update.
use super::*;
use gent_protocol::dashboard::{GrantAdmin, GrantOp, valid_grant_key};

pub fn grant_verifier(cluster: &str, agent: uuid::Uuid, secret: &str) -> Result<String> {
    ensure!(valid_grant_key(secret), "invalid dashboard grant");
    let mut digest = Sha256::new();
    digest.update(b"gent/dashboard/publisher/v1\0");
    digest.update(cluster.as_bytes());
    digest.update([0]);
    digest.update(agent.as_bytes());
    digest.update(secret.as_bytes());
    Ok(format!("{:x}", digest.finalize()))
}

pub(super) fn schema(db: &Connection) -> Result<()> {
    db.execute_batch(
        "CREATE TABLE IF NOT EXISTS dashboard_grants(
        agent TEXT PRIMARY KEY REFERENCES dashboard_publications(agent) ON DELETE CASCADE,
        verifier TEXT NOT NULL);
        CREATE TRIGGER IF NOT EXISTS dashboard_grant_revoked AFTER UPDATE OF revoked ON agents
        WHEN NEW.revoked=1 BEGIN DELETE FROM dashboard_grants WHERE agent=NEW.id; END;",
    )?;
    Ok(())
}

impl StoreSession<'_> {
    pub(in crate::store) fn authorize_dashboard_grant_admin(&self, peer: &str) -> Result<()> {
        let member = self
            .state
            .state()
            .nodes
            .get(peer)
            .context("unknown grant administrator")?;
        self.state
            .authorize_node(peer, &member.signing_key, self.timestamp as u64)?;
        ensure!(
            member.can_configure
                || if peer == self.identity.node.id() {
                    self.identity.signing_owner(self.db).is_ok()
                } else {
                    self.configuration_writer().is_ok_and(|id| id == peer)
                },
            "board grant administration requires cluster administration"
        );
        Ok(())
    }

    pub(super) fn current_board_grant(&self, id: &str) -> Result<Option<String>> {
        Ok(self
            .db
            .query_row(
                "SELECT verifier FROM dashboard_grants WHERE agent=?1",
                [id],
                |r| r.get(0),
            )
            .optional()?)
    }

    pub(super) fn save_board_grant(&self, id: &str, verifier: &str) -> Result<()> {
        self.db.execute(
            "INSERT INTO dashboard_grants(agent,verifier) VALUES(?1,?2)",
            params![id, verifier],
        )?;
        Ok(())
    }

    fn grant_publisher(&self, id: &str) -> Result<Agent> {
        self.require_local_membership()?;
        let who = self.get_agent(id)?;
        ensure!(
            !who.revoked && self.local_node(&who.node_id),
            "dashboard publisher unavailable"
        );
        let member = self
            .state
            .state()
            .nodes
            .get(&who.node_id)
            .context("dashboard publisher unavailable")?;
        self.state
            .authorize_node(&who.node_id, &member.signing_key, self.timestamp as u64)?;
        self.require_web_lease(&who.node_id)?;
        require_pro(self.home, &self.config, "Dashboard access")?;
        Ok(who)
    }

    pub(in crate::store) fn dashboard_grant(&self, id: &str, action: GrantAdmin) -> Result<Value> {
        let who = self.grant_publisher(id)?;
        let (revision, board, last) = self.board(id)?;
        let mut board = board.context("board unavailable")?;
        let fingerprint = hash(&format!(
            "dashboard-grant:{}",
            serde_json::to_string(&action)?
        ));
        let (expected, next, initial_html) = match action {
            GrantAdmin::Issue {
                expected_revision,
                verifier,
            } => (expected_revision, Some(verifier), None),
            GrantAdmin::MigrateAndIssue {
                expected_revision,
                verifier,
                html,
            } => {
                let html = self.publication_input(&who, None, Some(html))?;
                (expected_revision, Some(verifier), Some(html))
            }
            GrantAdmin::Revoke { expected_revision } => (expected_revision, None, None),
        };
        ensure!(
            next.as_deref().is_none_or(valid_grant_key),
            "invalid dashboard grant verifier"
        );
        if last.as_ref() == Some(&fingerprint) {
            ensure!(self.current_board_grant(id)? == next, "board grant changed");
            return self.publication_receipt(id, revision);
        }
        ensure!(expected == revision, "dashboard revision conflict");
        let (sha, html) = if let Some(html) = initial_html {
            ensure!(
                publication::pin(&board).is_none() && !self.publication_exists(id, revision)?,
                "initial HTML requires an existing legacy dashboard"
            );
            let sha = hash(&html);
            board = publication::fallback(board.title.clone(), &sha, None, Some(&board))?;
            (sha, html)
        } else {
            let document: (String, String) = self
                .db
                .query_row(
                    "SELECT sha256,html FROM dashboard_publications WHERE agent=?1 AND revision=?2",
                    params![id, revision],
                    |r| Ok((r.get(0)?, r.get(1)?)),
                )
                .context("publish an HTML dashboard first")?;
            if self.current_board_grant(id)? == next {
                return self.publication_receipt(id, revision);
            }
            document
        };
        let revision = self.commit_board(&who, revision, Some(&board), &fingerprint)?;
        self.save_publication(id, revision, &sha, &html)?;
        if let Some(verifier) = next {
            self.save_board_grant(id, &verifier)?;
        }
        self.sync_board()?;
        self.publication_receipt(id, revision)
    }

    pub(in crate::store) fn dashboard_delegate(
        &self,
        id: &str,
        secret: &str,
        action: GrantOp,
    ) -> Result<Value> {
        let verifier = grant_verifier(&self.config.cluster.id, uuid::Uuid::parse_str(id)?, secret)?;
        ensure!(
            self.db
                .prepare_cached("SELECT 1 FROM dashboard_grants WHERE agent=?1 AND verifier=?2")?
                .exists(params![id, verifier])?,
            "invalid dashboard grant"
        );
        let who = self.grant_publisher(id)?;
        let (revision, board, _) = self.board(id)?;
        let board = board.context("dashboard unavailable")?;
        match action {
            GrantOp::Get => {
                let (sha, html): (String, String) = self.db.query_row(
                    "SELECT sha256,html FROM dashboard_publications
                    WHERE agent=?1 AND revision=?2",
                    params![id, revision],
                    |r| Ok((r.get(0)?, r.get(1)?)),
                )?;
                Ok(
                    json!({"agent":id,"revision":revision,"title":board.title,"sha256":sha,"html":html}),
                )
            }
            GrantOp::Update {
                expected_revision,
                html,
            } => self.dashboard_mutate(
                &who,
                AgentOp::DashboardPublish {
                    expected_revision,
                    html: Some(html),
                    file_id: None,
                    title: board.title,
                    actions: None,
                },
            ),
        }
    }
}