teter-core 26.11.5

What teter's clients share without I/O: end-to-end encryption, account crypto, signed commands
Documentation
//! Signed commands to a machine (#88), without I/O: a device seals a
//! command to the one-time key of a challenge the machine signed, and opens
//! the machine's signed reply. The channel that carries them is
//! `teter_client::command`'s.

use std::io;

use teter_common::command::{
    Command, Outcome, Signed, challenge_bytes, command_bytes, command_info, reply_bytes, reply_info,
};

use crate::account::{AccountKeys, seal_to, verify};

/// A challenge the machine signed.
#[derive(Debug, Clone)]
pub struct Challenge {
    /// The nonce a command is bound to.
    pub nonce: Vec<u8>,
    /// The one-time key a command is sealed to.
    pub key: Vec<u8>,
}

/// The challenge `nonce` and `key`, if `signature` is machine `machine`'s
/// (whose public key is `machine_key`) of them.
#[must_use]
pub fn check_challenge(
    machine: &str,
    machine_key: &[u8],
    nonce: Vec<u8>,
    key: Vec<u8>,
    signature: &[u8],
) -> Option<Challenge> {
    verify(
        machine_key,
        &challenge_bytes(machine, &nonce, &key),
        signature,
    )
    .then_some(Challenge { nonce, key })
}

/// `command` signed by `account` for `machine` and `challenge`, sealed to the
/// challenge's one-time key.
///
/// # Errors
///
/// A random source that fails.
pub fn seal_command(
    account: &AccountKeys,
    machine: &str,
    challenge: &Challenge,
    command: Command,
) -> io::Result<Vec<u8>> {
    let signature = account.sign(&command_bytes(machine, &challenge.nonce, &command));
    let signed = serde_json::to_vec(&Signed { command, signature }).map_err(io::Error::other)?;
    seal_to(
        &challenge.key,
        &command_info(machine, &challenge.nonce),
        &signed,
    )
}

/// The outcome in machine `machine`'s reply to the command bound to `nonce`:
/// checked against its signature by `machine_key`, and opened with
/// `account`.
///
/// # Errors
///
/// A reply the machine did not sign, or one that does not open.
pub fn open_reply(
    account: &AccountKeys,
    machine: &str,
    machine_key: &[u8],
    nonce: &[u8],
    sealed: &[u8],
    signature: &[u8],
) -> io::Result<Outcome> {
    if !verify(machine_key, &reply_bytes(machine, nonce, sealed), signature) {
        return Err(io::Error::other("the reply is not signed by the machine"));
    }
    let plain = account
        .open_sealed(&reply_info(machine, nonce), sealed)
        .map_err(io::Error::other)?;
    serde_json::from_slice(&plain).map_err(io::Error::other)
}