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
//! Admission claim, admission notice, invitation identifiers and member
//! states.

use stratum_node_core::{
    admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, CheckAdmissionError, DidNostr,
    InvitationId, MemberState, NostrSecretKey, ParseAdmissionError, ParseIdError,
    ParseMemberStateError, Sha256Digest, ADMISSION_CLAIM_PURPOSE, ADMISSION_NOTICE_V1,
};

fn did(n: u8) -> DidNostr {
    NostrSecretKey::from_bytes(&[n; 32])
        .expect("valid secret key")
        .public()
}

fn fields() -> AdmissionFields {
    AdmissionFields {
        node: did(1),
        subject: did(2),
        invitation: InvitationId::from_bytes([0x0f; 16]),
        notice_sha256: admission_notice_v1_sha256(),
    }
}

fn wire(extra: &str, omit: &str) -> String {
    let members = [
        ("purpose", format!("\"{ADMISSION_CLAIM_PURPOSE}\"")),
        ("node", format!("\"{}\"", did(1))),
        ("subject", format!("\"{}\"", did(2))),
        ("invitation", format!("\"{}\"", "0f".repeat(16))),
        (
            "notice_sha256",
            format!("\"{}\"", admission_notice_v1_sha256()),
        ),
    ];
    let mut parts: Vec<String> = members
        .iter()
        .filter(|(name, _)| *name != omit)
        .map(|(name, value)| format!("\"{name}\":{value}"))
        .collect();
    if !extra.is_empty() {
        parts.push(extra.to_owned());
    }
    format!("{{{}}}", parts.join(","))
}

#[test]
fn notice_digest_is_pinned() {
    // Computed outside the crate: `printf '%s' "<notice text>" | sha256sum`.
    // Changing the text must be a new versioned constant, never an edit.
    assert_eq!(
        admission_notice_v1_sha256().to_hex(),
        "1607dc552d2d8122ad5bd06854145a183abeaf1ea8eb432aa3f437779e47aecd",
        "admission notice v1 changed"
    );
}

#[test]
fn notice_is_plain_ascii_and_states_the_three_facts() {
    assert!(ADMISSION_NOTICE_V1.is_ascii(), "ascii only");
    assert!(!ADMISSION_NOTICE_V1.ends_with('\n'), "no trailing newline");
    assert!(!ADMISSION_NOTICE_V1.contains("  "), "no doubled spaces");
    for needle in [
        "operator of this node can read the data in your pod while it is stored",
        "backups of this node hold your pod data, encrypted to recipients the operator chose",
        "Cloudflare terminates TLS",
        "can read your pod traffic in transit",
    ] {
        assert!(ADMISSION_NOTICE_V1.contains(needle), "states: {needle}");
    }
    let json = serde_json::to_string(ADMISSION_NOTICE_V1).expect("serialises");
    let back: String = serde_json::from_str(&json).expect("parses");
    assert_eq!(
        Sha256Digest::of(back.as_bytes()),
        admission_notice_v1_sha256(),
        "a client hashing the JSON-decoded text gets the same digest"
    );
}

#[test]
fn built_claim_has_the_exact_wire_shape_and_round_trips() {
    let claim = AdmissionClaim::new(fields());
    assert_eq!(
        String::from_utf8(claim.as_bytes().to_vec()).expect("utf-8"),
        wire("", ""),
        "member order and encoding"
    );
    let parsed = AdmissionClaim::parse(claim.as_bytes()).expect("parses");
    assert_eq!(parsed, claim, "round trip");
    assert_eq!(parsed.fields(), &fields(), "fields");
    assert_eq!(parsed.node(), did(1), "node");
    assert_eq!(parsed.subject(), did(2), "subject");
    assert_eq!(
        parsed.invitation(),
        InvitationId::from_bytes([0x0f; 16]),
        "invitation"
    );
    assert_eq!(
        parsed.notice_sha256(),
        admission_notice_v1_sha256(),
        "notice"
    );
    assert_eq!(parsed.into_bytes(), claim.as_bytes(), "bytes kept");
}

#[test]
fn parse_keeps_the_bytes_as_given() {
    let spaced = wire("", "").replace(',', ", ");
    let parsed = AdmissionClaim::parse(spaced.as_bytes()).expect("whitespace is valid json");
    assert_eq!(parsed.as_bytes(), spaced.as_bytes(), "exact bytes");
    assert_eq!(parsed.fields(), &fields(), "same fields");
}

#[test]
fn parse_is_strict() {
    let wrong_purpose =
        wire("", "purpose").replacen('{', "{\"purpose\":\"stratum.admission.v2\",", 1);
    let cases: Vec<(String, ParseAdmissionError)> = vec![
        (wrong_purpose, ParseAdmissionError::WrongPurpose),
        (wire("\"extra\":1", ""), ParseAdmissionError::Malformed),
        (wire("", "purpose"), ParseAdmissionError::Malformed),
        (wire("", "node"), ParseAdmissionError::Malformed),
        (wire("", "subject"), ParseAdmissionError::Malformed),
        (wire("", "invitation"), ParseAdmissionError::Malformed),
        (wire("", "notice_sha256"), ParseAdmissionError::Malformed),
        (
            wire(&format!("\"node\":\"{}\"", did(1)), ""),
            ParseAdmissionError::Malformed,
        ),
        (
            wire("", "").replace(&"0f".repeat(16), &"0F".repeat(16)),
            ParseAdmissionError::Malformed,
        ),
        (
            wire("", "").replace(&"0f".repeat(16), &"0f".repeat(15)),
            ParseAdmissionError::Malformed,
        ),
        (
            wire("", "").replace(&format!("{}", did(2)), &did(2).to_npub()),
            ParseAdmissionError::Malformed,
        ),
        (
            wire("", "purpose").replacen('{', "{\"purpose\":1,", 1),
            ParseAdmissionError::Malformed,
        ),
        ("[]".to_owned(), ParseAdmissionError::Malformed),
        (
            format!("{} {{}}", wire("", "")),
            ParseAdmissionError::Malformed,
        ),
        (String::new(), ParseAdmissionError::Malformed),
    ];
    for (body, want) in cases {
        assert_eq!(
            AdmissionClaim::parse(body.as_bytes()).map(|_| ()),
            Err(want),
            "{body}"
        );
    }
}

#[test]
fn check_names_the_failing_binding_in_order() {
    let claim = AdmissionClaim::new(fields());
    let notice = admission_notice_v1_sha256();
    let other_notice = Sha256Digest::of(b"another notice");
    assert_eq!(claim.check(&did(1), &did(2), &notice), Ok(()), "valid");
    assert_eq!(
        claim.check(&did(3), &did(2), &notice),
        Err(CheckAdmissionError::NodeMismatch),
        "node"
    );
    assert_eq!(
        claim.check(&did(1), &did(3), &notice),
        Err(CheckAdmissionError::SubjectMismatch),
        "subject"
    );
    assert_eq!(
        claim.check(&did(1), &did(2), &other_notice),
        Err(CheckAdmissionError::NoticeMismatch),
        "notice"
    );
    assert_eq!(
        claim.check(&did(3), &did(3), &other_notice),
        Err(CheckAdmissionError::NodeMismatch),
        "node is checked first"
    );
    assert_eq!(
        claim.check(&did(1), &did(3), &other_notice),
        Err(CheckAdmissionError::SubjectMismatch),
        "subject before notice"
    );
}

#[test]
fn invitation_ids_are_lowercase_hex() {
    let id = InvitationId::from_bytes([0xa5; 16]);
    assert_eq!(id.to_hex(), "a5".repeat(16), "hex");
    assert_eq!(
        format!("{id:?}"),
        format!("InvitationId({})", "a5".repeat(16)),
        "debug"
    );
    assert_eq!(
        serde_json::to_string(&id).expect("serialises"),
        format!("\"{}\"", "a5".repeat(16)),
        "serde"
    );
    for bad in [
        "A5".repeat(16),
        "a5".repeat(15),
        "a5".repeat(17),
        String::new(),
    ] {
        assert_eq!(
            bad.parse::<InvitationId>(),
            Err(ParseIdError::InvalidHex { expected: 32 }),
            "{bad}"
        );
    }
}

#[test]
fn member_states_have_one_lowercase_text_form() {
    let all = [
        (MemberState::Reserved, "reserved", true),
        (MemberState::Provisioned, "provisioned", true),
        (MemberState::Active, "active", true),
        (MemberState::Cancelled, "cancelled", false),
        (MemberState::Suspended, "suspended", true),
        (MemberState::Removed, "removed", false),
    ];
    assert_eq!(
        MemberState::ALL.to_vec(),
        all.iter().map(|(state, _, _)| *state).collect::<Vec<_>>(),
        "ALL lists every state once, in order"
    );
    for (state, text, slot) in all {
        assert_eq!(state.as_str(), text, "as_str");
        assert_eq!(state.to_string(), text, "display");
        assert_eq!(text.parse::<MemberState>(), Ok(state), "from_str");
        assert_eq!(state.holds_slot(), slot, "{text} holds a slot");
        let json = serde_json::to_string(&state).expect("serialises");
        assert_eq!(json, format!("\"{text}\""), "serde");
        assert_eq!(
            serde_json::from_str::<MemberState>(&json).expect("parses"),
            state,
            "serde round trip"
        );
    }
    for bad in [
        "Active",
        "ACTIVE",
        "canceled",
        "Suspended",
        "unknown",
        "",
        " active",
    ] {
        assert_eq!(
            bad.parse::<MemberState>(),
            Err(ParseMemberStateError::Unknown),
            "{bad:?}"
        );
    }
    assert!(
        serde_json::from_str::<MemberState>("\"Active\"").is_err(),
        "serde refuses other cases"
    );
}