stratum-node-core 0.1.0-alpha.2

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
//! Admission to a node: the notice a tenant reads, the claim a tenant signs
//! to redeem an invitation, and the states a membership moves through.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::did::DidNostr;
use crate::id::{InvitationId, Sha256Digest};

/// The admission notice, version 1: what a tenant is told before joining.
///
/// A prospective tenant reads this text and signs its SHA-256
/// ([`admission_notice_v1_sha256`]) into the [`AdmissionClaim`], so the node
/// can show which text the tenant accepted. The text is pure ASCII with no
/// trailing newline, so a client that receives it as a JSON string and
/// hashes its UTF-8 bytes gets the same digest. It never changes: different
/// wording would be a new constant with a new version.
pub const ADMISSION_NOTICE_V1: &str =
    "Before you join this Stratum node, please note three things. \
First, the operator of this node can read the data in your pod while it is stored on the node. \
Second, backups of this node hold your pod data, encrypted to recipients the operator chose; \
whoever holds the key for one of those recipients can read it. \
Third, once the node is served on its public origin, Cloudflare terminates TLS for it and \
can read your pod traffic in transit. \
By signing your admission request you confirm that you have read this notice.";

/// Returns the SHA-256 of [`ADMISSION_NOTICE_V1`]: the value an admission
/// claim's `notice_sha256` must carry for this notice.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{admission_notice_v1_sha256, Sha256Digest, ADMISSION_NOTICE_V1};
///
/// assert_eq!(admission_notice_v1_sha256(), Sha256Digest::of(ADMISSION_NOTICE_V1.as_bytes()));
/// ```
pub fn admission_notice_v1_sha256() -> Sha256Digest {
    Sha256Digest::of(ADMISSION_NOTICE_V1.as_bytes())
}

/// The value of an admission claim's `purpose` member.
pub const ADMISSION_CLAIM_PURPOSE: &str = "stratum.admission.v1";

/// The fields of an admission claim, for [`AdmissionClaim::new`].
///
/// Every field is required; the `purpose` member is added by
/// [`AdmissionClaim::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AdmissionFields {
    /// The node being joined.
    pub node: DidNostr,
    /// The invited identity, who must sign the redemption request.
    pub subject: DidNostr,
    /// The invitation being redeemed.
    pub invitation: InvitationId,
    /// The SHA-256 of the admission notice the subject read.
    pub notice_sha256: Sha256Digest,
}

/// The body of a redemption request, together with its exact JSON bytes.
///
/// The JSON shape is an object with exactly these members: `purpose` (always
/// [`ADMISSION_CLAIM_PURPOSE`]), `node`, `subject`, `invitation` and
/// `notice_sha256`. Unknown, duplicate and missing members are rejected, and
/// so is any other `purpose`.
///
/// Unlike the bootstrap [`ClaimBody`](crate::ClaimBody), an admission claim
/// carries no nonce and no expiry. The signed request that carries it is
/// already fresh (±60 s), single use (its event ID is stored) and bound to
/// the node's canonical URL, and the invitation is consumed when it is
/// accepted. The client writes the body itself; there is no server-issued
/// copy to compare against.
///
/// Equality compares the fields and the bytes. The type has no serde
/// implementations on purpose: send the bytes from
/// [`as_bytes`](Self::as_bytes) and parse them with [`parse`](Self::parse).
///
/// # Accepting a claim
///
/// [`AdmissionClaim::check`] is one step and proves nothing on its own. To
/// accept a redemption the server must, committing nothing unless every step
/// succeeds:
///
/// 1. Verify the signed request with [`verify_request`], passing the
///    received body as [`ExpectedRequest::body`] and the canonical URL.
/// 2. Parse the same bytes with [`AdmissionClaim::parse`].
/// 3. Call [`check`](Self::check) with its own node DID, the signer from
///    [`VerifiedRequest::signer`] and the digest of the notice it serves.
/// 4. Look up [`invitation`](Self::invitation) and require it to be issued,
///    unexpired and bound to [`subject`](Self::subject).
/// 5. In one transaction, consume the invitation, record the request's event
///    ID for replay protection and create the membership.
///
/// [`verify_request`]: crate::verify_request
/// [`ExpectedRequest::body`]: crate::ExpectedRequest::body
/// [`VerifiedRequest::signer`]: crate::VerifiedRequest::signer
///
/// # Examples
///
/// ```
/// use stratum_node_core::{
///     admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, CheckAdmissionError,
///     InvitationId, NostrSecretKey,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let node = NostrSecretKey::from_hex(&"06".repeat(32))?.public();
/// let tenant = NostrSecretKey::from_hex(&"07".repeat(32))?.public();
///
/// // Client side: build the body and sign a request over its bytes.
/// let claim = AdmissionClaim::new(AdmissionFields {
///     node,
///     subject: tenant,
///     invitation: InvitationId::from_bytes([1; 16]),
///     notice_sha256: admission_notice_v1_sha256(),
/// });
///
/// // Server side, after verifying the signed request over these bytes:
/// let received = AdmissionClaim::parse(claim.as_bytes())?;
/// received.check(&node, &tenant, &admission_notice_v1_sha256())?;
///
/// // A request signed by anyone else fails.
/// let other = NostrSecretKey::from_hex(&"08".repeat(32))?.public();
/// assert_eq!(
///     received.check(&node, &other, &admission_notice_v1_sha256()),
///     Err(CheckAdmissionError::SubjectMismatch),
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AdmissionClaim {
    fields: AdmissionFields,
    bytes: Vec<u8>,
}

impl AdmissionClaim {
    /// Serialises `fields` once, with `purpose` set to
    /// [`ADMISSION_CLAIM_PURPOSE`], and keeps the bytes.
    ///
    /// The members are written in the order `purpose`, `node`, `subject`,
    /// `invitation`, `notice_sha256`, as compact JSON.
    ///
    /// # Panics
    ///
    /// Does not panic: `serde_json` has no failure path for this struct of
    /// strings.
    pub fn new(fields: AdmissionFields) -> Self {
        let wire = WireAdmission {
            purpose: ADMISSION_CLAIM_PURPOSE.to_owned(),
            node: fields.node,
            subject: fields.subject,
            invitation: fields.invitation,
            notice_sha256: fields.notice_sha256,
        };
        let bytes =
            serde_json::to_vec(&wire).expect("serde_json cannot fail on a struct of strings");
        Self { fields, bytes }
    }

    /// Parses admission-claim bytes strictly and keeps them exactly as
    /// given.
    ///
    /// # Errors
    ///
    /// Returns [`ParseAdmissionError::WrongPurpose`] when the body is an
    /// object whose `purpose` is a string other than
    /// [`ADMISSION_CLAIM_PURPOSE`], and [`ParseAdmissionError::Malformed`]
    /// for any other deviation: not a single JSON object, a missing,
    /// unknown or duplicate member, or an invalid member value.
    pub fn parse(bytes: &[u8]) -> Result<Self, ParseAdmissionError> {
        let probe: PurposeProbe =
            serde_json::from_slice(bytes).map_err(|_| ParseAdmissionError::Malformed)?;
        if probe.purpose != ADMISSION_CLAIM_PURPOSE {
            return Err(ParseAdmissionError::WrongPurpose);
        }
        let wire: WireAdmission =
            serde_json::from_slice(bytes).map_err(|_| ParseAdmissionError::Malformed)?;
        Ok(Self {
            fields: AdmissionFields {
                node: wire.node,
                subject: wire.subject,
                invitation: wire.invitation,
                notice_sha256: wire.notice_sha256,
            },
            bytes: bytes.to_vec(),
        })
    }

    /// Checks the claim against the node's own DID, the verified signer of
    /// the request that carried it and the digest of the notice the node
    /// serves.
    ///
    /// This is a **partial** check; see
    /// [Accepting a claim](Self#accepting-a-claim) for the full procedure.
    ///
    /// # Errors
    ///
    /// Returns [`CheckAdmissionError::NodeMismatch`] when the claim names
    /// another node, [`CheckAdmissionError::SubjectMismatch`] when its
    /// subject is not `signer`, and [`CheckAdmissionError::NoticeMismatch`]
    /// when its notice digest is not `expected_notice`, checked in that
    /// order.
    pub fn check(
        &self,
        expected_node: &DidNostr,
        signer: &DidNostr,
        expected_notice: &Sha256Digest,
    ) -> Result<(), CheckAdmissionError> {
        if self.fields.node != *expected_node {
            return Err(CheckAdmissionError::NodeMismatch);
        }
        if self.fields.subject != *signer {
            return Err(CheckAdmissionError::SubjectMismatch);
        }
        if self.fields.notice_sha256 != *expected_notice {
            return Err(CheckAdmissionError::NoticeMismatch);
        }
        Ok(())
    }

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

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

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

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

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

    /// Returns the invitation being redeemed.
    pub fn invitation(&self) -> InvitationId {
        self.fields.invitation
    }

    /// Returns the notice digest the subject signed.
    pub fn notice_sha256(&self) -> Sha256Digest {
        self.fields.notice_sha256
    }
}

/// The reasons admission-claim bytes can fail to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseAdmissionError {
    /// The `purpose` member is not [`ADMISSION_CLAIM_PURPOSE`].
    #[error("admission claim purpose is not {ADMISSION_CLAIM_PURPOSE}")]
    WrongPurpose,
    /// The bytes are not a valid admission claim.
    #[error("malformed admission claim")]
    Malformed,
}

/// The reasons a parsed admission claim can fail [`AdmissionClaim::check`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CheckAdmissionError {
    /// The claim names a different node.
    #[error("admission claim names a different node")]
    NodeMismatch,
    /// The claim's subject is not the signer of the request.
    #[error("admission claim subject is not the request signer")]
    SubjectMismatch,
    /// The claim's notice digest is not the digest of the node's notice.
    #[error("admission claim notice digest does not match the node's notice")]
    NoticeMismatch,
}

/// The first parsing pass: only the purpose, ignoring other members.
#[derive(Deserialize)]
struct PurposeProbe {
    purpose: String,
}

/// The wire shape of an admission claim.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WireAdmission {
    purpose: String,
    node: DidNostr,
    subject: DidNostr,
    invitation: InvitationId,
    notice_sha256: Sha256Digest,
}

/// The state of a tenant's membership of a node.
///
/// The text form is the lowercase name (`reserved`, `provisioned`, `active`,
/// `cancelled`), used by [`Display`](fmt::Display), [`FromStr`] and serde.
///
/// # Examples
///
/// ```
/// use stratum_node_core::MemberState;
///
/// # fn main() -> Result<(), stratum_node_core::ParseMemberStateError> {
/// let state: MemberState = "provisioned".parse()?;
/// assert_eq!(state, MemberState::Provisioned);
/// assert_eq!(state.to_string(), "provisioned");
/// assert!(state.holds_slot());
/// assert!(!MemberState::Cancelled.holds_slot());
/// assert!("Active".parse::<MemberState>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum MemberState {
    /// The invitation was consumed and a slot is held; the pod is not yet
    /// confirmed created.
    Reserved,
    /// The pod server created the pod.
    Provisioned,
    /// The owner stated that a read and a write to their pod worked.
    Active,
    /// The administrator cancelled a reserved member; no slot is held.
    Cancelled,
}

impl MemberState {
    /// Returns the lowercase name.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Reserved => "reserved",
            Self::Provisioned => "provisioned",
            Self::Active => "active",
            Self::Cancelled => "cancelled",
        }
    }

    /// Returns `true` for the states that count against the node's tenant
    /// capacity: reserved, provisioned and active.
    pub fn holds_slot(self) -> bool {
        matches!(self, Self::Reserved | Self::Provisioned | Self::Active)
    }
}

impl fmt::Display for MemberState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for MemberState {
    type Err = ParseMemberStateError;

    /// Parses the lowercase name exactly; other cases are refused.
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        match text {
            "reserved" => Ok(Self::Reserved),
            "provisioned" => Ok(Self::Provisioned),
            "active" => Ok(Self::Active),
            "cancelled" => Ok(Self::Cancelled),
            _ => Err(ParseMemberStateError::Unknown),
        }
    }
}

impl Serialize for MemberState {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for MemberState {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        text.parse().map_err(serde::de::Error::custom)
    }
}

/// The reasons a [`MemberState`] can fail to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseMemberStateError {
    /// The text is not one of the lowercase state names.
    #[error("unknown member state")]
    Unknown,
}