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
//! Reading a request header before verifying it, and verifying a request
//! without its body.

use base64::Engine as _;
use stratum_node_core::{
    verify_request, verify_request_without_body, ExpectedRequest, NostrSecretKey, ParseEventError,
    RequestPolicy, RequestTarget, Sha256Digest, SignedEvent, UnixTime, UnsignedEvent,
    UnverifiedRequest, VerifyRequestError, HTTP_AUTH_KIND,
};

const URL: &str = "https://stratum.example.org/pods/abc/private/x.txt";
const BODY: &[u8] = b"hello pod";
const NOW: UnixTime = UnixTime::from_secs(1_764_720_000);
const AUX: [u8; 32] = [0x5a; 32];

fn key() -> NostrSecretKey {
    NostrSecretKey::from_hex(&"11".repeat(32)).expect("test key is valid")
}

fn target() -> RequestTarget<'static> {
    RequestTarget::new("PUT", URL)
}

fn signed_put() -> String {
    key()
        .sign_request(&ExpectedRequest::new("PUT", URL, Some(BODY)), NOW, &AUX)
        .expect("signs")
}

fn event_with(kind: u16, created_at: UnixTime, tags: &[&[&str]]) -> SignedEvent {
    let unsigned = tags
        .iter()
        .fold(UnsignedEvent::new(kind, created_at), |event, tag| {
            event.with_tag(tag.iter().copied())
        });
    key().sign_event(&unsigned, &AUX).expect("event signs")
}

fn header_for_json(json: &str) -> String {
    format!(
        "Nostr {}",
        base64::engine::general_purpose::STANDARD.encode(json)
    )
}

fn header_for(event: &SignedEvent) -> String {
    header_for_json(&event.to_json())
}

fn without_body(
    header: &str,
) -> Result<stratum_node_core::BodyUncheckedRequest, VerifyRequestError> {
    verify_request_without_body(header, &target(), NOW, &RequestPolicy::new())
}

/// Replaces one top-level string field of an event's JSON.
fn with_field(event: &SignedEvent, field: &str, value: &str) -> String {
    let mut json: serde_json::Value = serde_json::from_str(&event.to_json()).expect("json");
    json[field] = serde_json::Value::from(value);
    json.to_string()
}

#[test]
fn claimed_author_and_id_are_read_without_verifying() {
    let event = event_with(HTTP_AUTH_KIND, NOW, &[&["u", URL], &["method", "PUT"]]);
    let forged_sig = with_field(&event, "sig", &"ab".repeat(64));
    let parsed = UnverifiedRequest::parse(&header_for_json(&forged_sig), &RequestPolicy::new())
        .expect("structure is fine");
    assert_eq!(parsed.claimed_author(), key().public(), "author as claimed");
    assert_eq!(parsed.claimed_event_id(), event.id(), "id as claimed");
    assert_eq!(
        parsed
            .verify_without_body(&target(), NOW)
            .map(|_| ())
            .expect_err("signature must fail"),
        VerifyRequestError::Event(ParseEventError::BadSignature),
        "verification catches the forged signature"
    );
}

#[test]
fn claimed_event_id_is_not_recomputed() {
    let event = event_with(HTTP_AUTH_KIND, NOW, &[&["u", URL], &["method", "PUT"]]);
    let other_id = "cd".repeat(32);
    let json = with_field(&event, "id", &other_id);
    let parsed =
        UnverifiedRequest::parse(&header_for_json(&json), &RequestPolicy::new()).expect("parses");
    assert_eq!(
        parsed.claimed_event_id().to_hex(),
        other_id,
        "the id the header states"
    );
    let err = parsed
        .verify_without_body(&target(), NOW)
        .map(|_| ())
        .expect_err("id must fail");
    assert_eq!(
        err,
        VerifyRequestError::Event(ParseEventError::IdMismatch),
        "verification recomputes the id"
    );
}

#[test]
fn parse_applies_the_header_and_structural_checks() {
    let policy = RequestPolicy::new();
    let cases: Vec<(String, VerifyRequestError)> = vec![
        (
            format!(
                "Nostr {}",
                "A".repeat(RequestPolicy::DEFAULT_MAX_TOKEN_BYTES)
            ),
            VerifyRequestError::TokenTooLarge {
                len: RequestPolicy::DEFAULT_MAX_TOKEN_BYTES + 6,
                max: RequestPolicy::DEFAULT_MAX_TOKEN_BYTES,
            },
        ),
        ("Bearer abc".into(), VerifyRequestError::InvalidScheme),
        ("Nostr".into(), VerifyRequestError::InvalidScheme),
        ("Nostr !!!".into(), VerifyRequestError::InvalidBase64),
        (
            header_for_json("[]"),
            VerifyRequestError::Event(ParseEventError::MalformedJson),
        ),
        (
            header_for_json(&with_field(
                &event_with(HTTP_AUTH_KIND, NOW, &[]),
                "pubkey",
                &"AB".repeat(32),
            )),
            VerifyRequestError::Event(ParseEventError::InvalidPubkey),
        ),
    ];
    for (header, want) in cases {
        let got = UnverifiedRequest::parse(&header, &policy)
            .map(|_| ())
            .expect_err("must fail");
        assert_eq!(got, want, "header {header:.40}");
        assert_eq!(
            verify_request(
                &header,
                &ExpectedRequest::new("PUT", URL, Some(BODY)),
                NOW,
                &policy
            )
            .map(|_| ())
            .expect_err("full verifier fails too"),
            want,
            "same error from verify_request"
        );
    }
}

#[test]
fn parse_then_verify_matches_verify_request() {
    let header = signed_put();
    let expected = ExpectedRequest::new("PUT", URL, Some(BODY));
    let policy = RequestPolicy::new();
    let direct = verify_request(&header, &expected, NOW, &policy).expect("verifies");
    let staged = UnverifiedRequest::parse(&header, &policy)
        .expect("parses")
        .verify(&expected, NOW)
        .expect("verifies");
    assert_eq!(direct, staged, "same result");
    assert_eq!(
        staged.payload(),
        Some(Sha256Digest::of(BODY)),
        "body digest"
    );

    let other_body = ExpectedRequest::new("PUT", URL, Some(b"other".as_slice()));
    assert_eq!(
        UnverifiedRequest::parse(&header, &policy)
            .expect("parses")
            .verify(&other_body, NOW)
            .map(|_| ())
            .expect_err("body differs"),
        VerifyRequestError::PayloadMismatch,
        "full verification still hashes the body"
    );
}

#[test]
fn without_body_names_the_signer_and_reports_the_claimed_digest() {
    let header = signed_put();
    let checked = without_body(&header).expect("verifies");
    let full = verify_request(
        &header,
        &ExpectedRequest::new("PUT", URL, Some(BODY)),
        NOW,
        &RequestPolicy::new(),
    )
    .expect("verifies");
    assert_eq!(checked.signer(), full.signer(), "signer");
    assert_eq!(checked.event_id(), full.event_id(), "event id");
    assert_eq!(checked.created_at(), full.created_at(), "created at");
    assert_eq!(
        checked.claimed_payload(),
        Some(Sha256Digest::of(BODY)),
        "claimed digest is the signed tag"
    );
}

#[test]
fn without_body_accepts_any_or_no_payload_tag() {
    let none = event_with(HTTP_AUTH_KIND, NOW, &[&["u", URL], &["method", "PUT"]]);
    assert_eq!(
        without_body(&header_for(&none))
            .expect("no payload tag is accepted")
            .claimed_payload(),
        None,
        "no claim"
    );
    let digest = Sha256Digest::of(b"anything").to_hex();
    let some = event_with(
        HTTP_AUTH_KIND,
        NOW,
        &[&["u", URL], &["method", "PUT"], &["payload", &digest]],
    );
    assert_eq!(
        without_body(&header_for(&some))
            .expect("a well-formed tag is accepted")
            .claimed_payload()
            .map(|d| d.to_hex()),
        Some(digest),
        "the tag, not any body"
    );
}

#[test]
fn without_body_refuses_kind_tag_url_and_method_failures() {
    let cases: Vec<(SignedEvent, VerifyRequestError)> = vec![
        (
            event_with(1, NOW, &[&["u", URL], &["method", "PUT"]]),
            VerifyRequestError::WrongKind { kind: 1 },
        ),
        (
            event_with(HTTP_AUTH_KIND, NOW, &[&["method", "PUT"]]),
            VerifyRequestError::MissingUrlTag,
        ),
        (
            event_with(HTTP_AUTH_KIND, NOW, &[&["u", URL]]),
            VerifyRequestError::MissingMethodTag,
        ),
        (
            event_with(
                HTTP_AUTH_KIND,
                NOW,
                &[&["u", URL], &["u", URL], &["method", "PUT"]],
            ),
            VerifyRequestError::DuplicateUrlTag,
        ),
        (
            event_with(
                HTTP_AUTH_KIND,
                NOW,
                &[&["u", URL], &["method", "PUT"], &["method", "PUT"]],
            ),
            VerifyRequestError::DuplicateMethodTag,
        ),
        (
            event_with(
                HTTP_AUTH_KIND,
                NOW,
                &[
                    &["u", "https://other.example.org/pods/abc/private/x.txt"],
                    &["method", "PUT"],
                ],
            ),
            VerifyRequestError::UrlMismatch,
        ),
        (
            event_with(HTTP_AUTH_KIND, NOW, &[&["u", URL], &["method", "put"]]),
            VerifyRequestError::MethodMismatch,
        ),
    ];
    for (event, want) in cases {
        let got = without_body(&header_for(&event))
            .map(|_| ())
            .expect_err("must fail");
        assert_eq!(got, want, "tags {:?}", event.tags());
    }
}

#[test]
fn without_body_refuses_payload_tag_and_time_failures() {
    let digest = Sha256Digest::of(BODY).to_hex();
    let upper = digest.to_uppercase();
    let past = UnixTime::from_secs(NOW.as_secs() - 61);
    let future = UnixTime::from_secs(NOW.as_secs() + 61);
    let cases: Vec<(SignedEvent, VerifyRequestError)> = vec![
        (
            event_with(
                HTTP_AUTH_KIND,
                NOW,
                &[
                    &["u", URL],
                    &["method", "PUT"],
                    &["payload", &digest],
                    &["payload", &digest],
                ],
            ),
            VerifyRequestError::DuplicatePayloadTag,
        ),
        (
            event_with(
                HTTP_AUTH_KIND,
                NOW,
                &[&["u", URL], &["method", "PUT"], &["payload", &upper]],
            ),
            VerifyRequestError::InvalidPayloadTag,
        ),
        (
            event_with(
                HTTP_AUTH_KIND,
                NOW,
                &[&["u", URL], &["method", "PUT"], &["payload", "abc"]],
            ),
            VerifyRequestError::InvalidPayloadTag,
        ),
        (
            event_with(
                HTTP_AUTH_KIND,
                NOW,
                &[&["u", URL], &["method", "PUT"], &["payload"]],
            ),
            VerifyRequestError::MalformedTag { tag: "payload" },
        ),
        (
            event_with(HTTP_AUTH_KIND, past, &[&["u", URL], &["method", "PUT"]]),
            VerifyRequestError::CreatedTooLongAgo {
                created_at: past,
                now: NOW,
            },
        ),
        (
            event_with(HTTP_AUTH_KIND, future, &[&["u", URL], &["method", "PUT"]]),
            VerifyRequestError::CreatedTooFarInFuture {
                created_at: future,
                now: NOW,
            },
        ),
    ];
    for (event, want) in cases {
        let got = without_body(&header_for(&event))
            .map(|_| ())
            .expect_err("must fail");
        assert_eq!(got, want, "tags {:?}", event.tags());
    }
}

#[test]
fn without_body_window_is_inclusive_and_policy_bound() {
    let at = |secs: u64| {
        let created = UnixTime::from_secs(secs);
        header_for(&event_with(
            HTTP_AUTH_KIND,
            created,
            &[&["u", URL], &["method", "PUT"]],
        ))
    };
    assert!(without_body(&at(NOW.as_secs() - 60)).is_ok(), "-60 s");
    assert!(without_body(&at(NOW.as_secs() + 60)).is_ok(), "+60 s");

    let narrow = RequestPolicy::new()
        .with_max_clock_skew(std::time::Duration::from_secs(10))
        .expect("narrower is allowed");
    let header = at(NOW.as_secs() - 11);
    let parsed = UnverifiedRequest::parse(&header, &narrow).expect("parses");
    assert!(
        matches!(
            parsed.verify_without_body(&target(), NOW),
            Err(VerifyRequestError::CreatedTooLongAgo { .. })
        ),
        "the policy given to parse governs the window"
    );
}

#[test]
fn a_different_body_is_not_detected_without_the_body() {
    // The documented limit: the gate cannot tell which body was signed.
    let header = signed_put();
    let checked = without_body(&header).expect("verifies");
    assert_ne!(
        checked.claimed_payload(),
        Some(Sha256Digest::of(b"another body")),
        "the claim is the signer's, whatever body arrives"
    );
}