stratum-node-core 0.1.0-alpha.4

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
Documentation
//! The bootstrap claim body an administrator signs to claim a node.

use serde::{Deserialize, Serialize};

use crate::did::DidNostr;
use crate::id::{ChallengeId, Revision, Sha256Digest, UnixTime};

/// The claim-body format version this crate reads and writes.
pub const CLAIM_BODY_VERSION: u32 = 1;

/// The fields of a version-1 claim body, for [`ClaimBody::new`].
///
/// Every field is required; the format version is added by
/// [`ClaimBody::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClaimFields {
    /// The single-use challenge this claim answers.
    pub nonce: ChallengeId,
    /// The node being claimed.
    pub node: DidNostr,
    /// The principal claiming the node, who must sign the claim request.
    pub claimant: DidNostr,
    /// The first second at which the claim is no longer accepted.
    pub expires_at: UnixTime,
    /// The configuration revision the initial configuration is based on.
    pub base_revision: Revision,
    /// The SHA-256 of the exact initial configuration text.
    pub config_sha256: Sha256Digest,
}

/// An immutable bootstrap claim body together with its exact JSON bytes.
///
/// The server builds the body once with [`ClaimBody::new`], stores it as the
/// outstanding challenge and hands out its exact bytes. The client signs a
/// request whose `payload` tag is the SHA-256 of those bytes and sends them
/// back verbatim. Nothing is ever re-serialised for hashing, so the bytes
/// that were signed are the bytes that are checked.
///
/// The JSON shape of version [`CLAIM_BODY_VERSION`] is an object with exactly
/// these fields: `version`, `nonce`, `node`, `claimant`, `expires_at`,
/// `base_revision` and `config_sha256`. Unknown fields, duplicate fields and
/// other versions are rejected.
///
/// Equality compares the bytes. The type has no serde implementations on
/// purpose: transport the bytes from [`as_bytes`](Self::as_bytes) and parse
/// them with [`parse`](Self::parse).
///
/// # Accepting a claim
///
/// [`ClaimBody::check`] is only one step, and on its own it proves nothing
/// about where a body came from. It looks at expiry, node and claimant. A
/// client can write a body of its own with any nonce, a later expiry, another
/// base revision or another configuration digest, sign it, and it will pass
/// `check`. A signature shows what the claimant signed, not that the server
/// issued it. To accept a claim the server must do all of the following, and
/// commit nothing unless every step succeeds:
///
/// 1. Verify the signed request with [`verify_request`], passing the
///    received body as [`ExpectedRequest::body`]. This checks the signature
///    and that the `payload` tag is the SHA-256 of exactly those bytes.
/// 2. Parse the same bytes with [`ClaimBody::parse`].
/// 3. Look up the outstanding challenge the server issued for
///    [`nonce`](Self::nonce), and compare its stored bytes with the received
///    bytes for equality (`==` on two `ClaimBody` values compares bytes).
///    A nonce the server never issued, or any difference in the bytes, is a
///    refusal.
/// 4. Call [`check`](Self::check) with the server's clock, its own node DID
///    and the request signer from [`VerifiedRequest::signer`].
/// 5. In one transaction, consume the challenge so that the nonce can never
///    be accepted again, record the request's event ID for replay
///    protection, bind the administrator and commit the initial
///    configuration. Commit only values bound by the body: the configuration
///    text must hash to [`config_sha256`](Self::config_sha256) and apply on
///    top of [`base_revision`](Self::base_revision). Values taken from
///    anywhere else in the request must not affect what is committed.
///
/// [`verify_request`]: crate::verify_request
/// [`ExpectedRequest::body`]: crate::ExpectedRequest::body
/// [`VerifiedRequest::signer`]: crate::VerifiedRequest::signer
///
/// # Examples
///
/// ```
/// use stratum_node_core::{
///     ChallengeId, ClaimBody, ClaimFields, DidNostr, NostrSecretKey, Revision, Sha256Digest,
///     UnixTime,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let node = NostrSecretKey::from_hex(&"06".repeat(32))?.public();
/// let admin = NostrSecretKey::from_hex(&"07".repeat(32))?.public();
/// // The server issues the body and keeps it as the outstanding challenge.
/// let issued = ClaimBody::new(ClaimFields {
///     nonce: ChallengeId::from_bytes([9; 16]),
///     node,
///     claimant: admin,
///     expires_at: UnixTime::from_secs(1_700_000_300),
///     base_revision: Revision::new(0),
///     config_sha256: Sha256Digest::of(b"[node]\n"),
/// });
///
/// // The client returns the bytes verbatim (inside a signed request, which
/// // the server verifies first). The server parses them and finds the
/// // challenge it issued under that nonce.
/// let returned = ClaimBody::parse(issued.as_bytes())?;
/// assert_eq!(returned.nonce(), issued.nonce());
///
/// // Security check, not a formality: the returned bytes must be exactly the
/// // bytes the server issued. `check` alone would accept a body the client
/// // wrote itself.
/// assert_eq!(returned, issued);
/// returned.check(UnixTime::from_secs(1_700_000_000), &node, &admin)?;
///
/// // Then, atomically: consume the nonce, record the event ID, bind the
/// // administrator and commit the configuration the body names.
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ClaimBody {
    fields: ClaimFields,
    bytes: Vec<u8>,
}

impl ClaimBody {
    /// Serialises `fields` once, as version [`CLAIM_BODY_VERSION`], and keeps
    /// the bytes.
    ///
    /// # Panics
    ///
    /// Does not panic: `serde_json` has no failure path for this struct of
    /// strings and integers.
    pub fn new(fields: ClaimFields) -> Self {
        let wire = WireClaim {
            version: CLAIM_BODY_VERSION,
            nonce: fields.nonce,
            node: fields.node,
            claimant: fields.claimant,
            expires_at: fields.expires_at,
            base_revision: fields.base_revision,
            config_sha256: fields.config_sha256,
        };
        let bytes = serde_json::to_vec(&wire)
            .expect("serde_json cannot fail on a struct of strings and integers");
        Self { fields, bytes }
    }

    /// Parses claim-body bytes and keeps them exactly as given.
    ///
    /// # Errors
    ///
    /// Returns [`ParseClaimError::UnsupportedVersion`] when `version` is
    /// anything other than [`CLAIM_BODY_VERSION`], and
    /// [`ParseClaimError::Malformed`] for any other deviation from the
    /// format, including a missing `version`, unknown or duplicate fields
    /// and invalid field values.
    pub fn parse(bytes: &[u8]) -> Result<Self, ParseClaimError> {
        let probe: VersionProbe =
            serde_json::from_slice(bytes).map_err(|_| ParseClaimError::Malformed)?;
        if probe.version != u64::from(CLAIM_BODY_VERSION) {
            return Err(ParseClaimError::UnsupportedVersion {
                version: probe.version,
            });
        }
        let wire: WireClaim =
            serde_json::from_slice(bytes).map_err(|_| ParseClaimError::Malformed)?;
        let fields = ClaimFields {
            nonce: wire.nonce,
            node: wire.node,
            claimant: wire.claimant,
            expires_at: wire.expires_at,
            base_revision: wire.base_revision,
            config_sha256: wire.config_sha256,
        };
        Ok(Self {
            fields,
            bytes: bytes.to_vec(),
        })
    }

    /// Checks the claim's expiry, node and claimant against the server's
    /// time and expectations.
    ///
    /// This is a **partial** check. It does not show that the server issued
    /// this body, that the nonce is outstanding or unused, or that the
    /// request carrying it was signed; see
    /// [Accepting a claim](Self#accepting-a-claim) for the full procedure.
    ///
    /// The claim is live while `now` is strictly before
    /// [`expires_at`](Self::expires_at).
    ///
    /// # Errors
    ///
    /// Returns [`CheckClaimError::Expired`] at or after the expiry,
    /// [`CheckClaimError::NodeMismatch`] when the body names another node and
    /// [`CheckClaimError::ClaimantMismatch`] when it names another claimant,
    /// checked in that order.
    pub fn check(
        &self,
        now: UnixTime,
        expected_node: &DidNostr,
        expected_claimant: &DidNostr,
    ) -> Result<(), CheckClaimError> {
        if now >= self.fields.expires_at {
            return Err(CheckClaimError::Expired {
                expires_at: self.fields.expires_at,
                now,
            });
        }
        if self.fields.node != *expected_node {
            return Err(CheckClaimError::NodeMismatch);
        }
        if self.fields.claimant != *expected_claimant {
            return Err(CheckClaimError::ClaimantMismatch);
        }
        Ok(())
    }

    /// Returns the exact bytes this body was built or parsed from.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Consumes the body and returns its exact bytes.
    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }

    /// Returns the SHA-256 of [`as_bytes`](Self::as_bytes): the value the
    /// claim request's `payload` tag must carry.
    pub fn sha256(&self) -> Sha256Digest {
        Sha256Digest::of(&self.bytes)
    }

    /// Returns all fields.
    pub fn fields(&self) -> &ClaimFields {
        &self.fields
    }

    /// Returns the challenge this claim answers.
    pub fn nonce(&self) -> ChallengeId {
        self.fields.nonce
    }

    /// Returns the node being claimed.
    pub fn node(&self) -> DidNostr {
        self.fields.node
    }

    /// Returns the claimant.
    pub fn claimant(&self) -> DidNostr {
        self.fields.claimant
    }

    /// Returns the first second at which the claim is no longer accepted.
    pub fn expires_at(&self) -> UnixTime {
        self.fields.expires_at
    }

    /// Returns the base configuration revision.
    pub fn base_revision(&self) -> Revision {
        self.fields.base_revision
    }

    /// Returns the SHA-256 of the initial configuration text.
    pub fn config_sha256(&self) -> Sha256Digest {
        self.fields.config_sha256
    }
}

/// The reasons claim-body bytes can fail to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseClaimError {
    /// The `version` field names a format this crate does not read.
    #[error("unsupported claim body version {version}")]
    UnsupportedVersion {
        /// The version the body declares.
        version: u64,
    },
    /// The bytes are not a valid claim body of the supported version.
    #[error("malformed claim body")]
    Malformed,
}

/// The reasons a parsed claim can fail [`ClaimBody::check`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CheckClaimError {
    /// `now` is at or after the claim's expiry.
    #[error("claim expired at {expires_at} (now {now})")]
    Expired {
        /// The claim's expiry.
        expires_at: UnixTime,
        /// The time the server supplied.
        now: UnixTime,
    },
    /// The claim names a different node.
    #[error("claim names a different node")]
    NodeMismatch,
    /// The claim names a different claimant.
    #[error("claim names a different claimant")]
    ClaimantMismatch,
}

/// The first parsing pass: only the version, ignoring other fields.
#[derive(Deserialize)]
struct VersionProbe {
    version: u64,
}

/// The wire shape of a version-1 claim body.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WireClaim {
    version: u32,
    nonce: ChallengeId,
    node: DidNostr,
    claimant: DidNostr,
    expires_at: UnixTime,
    base_revision: Revision,
    config_sha256: Sha256Digest,
}