From 047619d272bb060bcef4c90a906a121347f3245d Mon Sep 17 00:00:00 2001 From: Ansh-699 Date: Wed, 2 Dec 2026 22:38:31 +0530 Subject: [PATCH] feat(nip98): verify the Authorization header against its request Ports verifyNip98Auth (src/utils/nip98.ts) in place of the Phase 1 stub, in the capture's check order and with its reasons, through CoreError::InvalidNip98. The crate map and the NIP parity table no longer list the verifier as a stub. Replay stays with the admin job (ADR 0010). Refs #1215 (cherry picked from commit d9d1966224e659b54c57ddf1692f06e359e685f0) --- .changeset/nip98-verify.md | 2 + crates/nostream-core/src/error.rs | 5 + crates/nostream-core/src/lib.rs | 3 +- crates/nostream-core/src/messages.rs | 15 +- crates/nostream-core/src/nip98.rs | 697 ++++++++++++++++++++++++++- docs/rewrite/crate-map.md | 10 +- docs/rewrite/nip-parity.md | 2 +- 7 files changed, 712 insertions(+), 22 deletions(-) create mode 100644 .changeset/nip98-verify.md diff --git a/.changeset/nip98-verify.md b/.changeset/nip98-verify.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/nip98-verify.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/crates/nostream-core/src/error.rs b/crates/nostream-core/src/error.rs index 7cad90770..c4ff917a9 100644 --- a/crates/nostream-core/src/error.rs +++ b/crates/nostream-core/src/error.rs @@ -36,6 +36,11 @@ pub enum CoreError { #[error("{0}")] InvalidNip44(String), + /// A NIP-98 `Authorization` header failed verification against its request. The + /// message is the capture's reason, verbatim (`src/utils/nip98.ts:146-273`). + #[error("{0}")] + InvalidNip98(String), + /// NIP-77 storage could not be built from the items offered (negative or /// out-of-range `created_at`, or a set the storage refused). #[error("invalid negentropy storage: {0}")] diff --git a/crates/nostream-core/src/lib.rs b/crates/nostream-core/src/lib.rs index 2a286e551..a43a47c72 100644 --- a/crates/nostream-core/src/lib.rs +++ b/crates/nostream-core/src/lib.rs @@ -31,7 +31,8 @@ //! event schema ([`validation::validate_event`] with the kind 7/17/10002 and geohash //! refinements), the wire codec ([`messages::decode`] and the one encoder //! `RelayMessage::to_text`), NIP-42 ([`nip42::authenticate`], [`nip42::generate_challenge`] -//! and [`nip42::Nip42Session`]), the NIP-43 invite code and its event, the NIP-05 identifier +//! and [`nip42::Nip42Session`]), NIP-98 ([`nip98::verify`]; the replay claim on the event +//! id is the admin job's, ADR 0010), the NIP-43 invite code and its event, the NIP-05 identifier //! helpers and [`nip05::verify`] over its [`nip05::Nip05Fetch`] seam, the //! adaptive-difficulty signal and its WoT policy, [`clock::Clock`] and //! [`random::RandomSource`], and the NIP-77 reconciliation engine (over the `negentropy` diff --git a/crates/nostream-core/src/messages.rs b/crates/nostream-core/src/messages.rs index 6722a9dac..a9738c225 100644 --- a/crates/nostream-core/src/messages.rs +++ b/crates/nostream-core/src/messages.rs @@ -540,6 +540,18 @@ fn integer_value(number: &Number) -> Result { /// this pass reports the schema's own message for whatever is left, which is what the /// NOTICE carries. pub fn validate_event_value(value: &Value) -> Result { + let event = decode_event_fields(value)?; + + crate::validation::validate_event(&event) + .map_err(|error| invalid(&strip_invalid_event(&error.to_string())))?; + + Ok(event) +} + +/// The field schemas and the `.strict()` rule of [`validate_event_value`], without the +/// kind-7/17/10002/geohash refinements. NIP-98 parses its event with exactly these +/// (`nip98EventSchema`, `src/utils/nip98.ts:24-35`). +pub(crate) fn decode_event_fields(value: &Value) -> Result { let Value::Object(object) = value else { return Err(invalid(&format!( "Expected object, received {}", @@ -635,9 +647,6 @@ pub fn validate_event_value(value: &Value) -> Result { .map_err(|error: crate::error::CoreError| invalid(&error.to_string()))?, }; - crate::validation::validate_event(&event) - .map_err(|error| invalid(&strip_invalid_event(&error.to_string())))?; - Ok(event) } diff --git a/crates/nostream-core/src/nip98.rs b/crates/nostream-core/src/nip98.rs index e7f1df86c..1150a29aa 100644 --- a/crates/nostream-core/src/nip98.rs +++ b/crates/nostream-core/src/nip98.rs @@ -1,7 +1,39 @@ -//! NIP-98: HTTP authentication. Mirrors `src/utils/nip98.ts` and `src/utils/nip98-replay.ts`. +//! NIP-98: HTTP authentication. Mirrors `src/utils/nip98.ts`. +//! +//! The replay claim on the event id (`src/utils/nip98-replay.ts`) is not here: it needs the +//! cache and belongs to the admin job (ADR 0010). +use base64::Engine; +use base64::alphabet; +use base64::engine::DecodePaddingMode; +use base64::engine::general_purpose::{GeneralPurpose, GeneralPurposeConfig}; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +use crate::constants::MAX_SAFE_INTEGER; +use crate::crypto::{compute_event_id, verify_event_signature}; use crate::error::CoreError; -use crate::event::Pubkey; +use crate::event::{Kind, Pubkey, Tag}; +use crate::messages::decode_event_fields; + +/// Kind 27235, `EventKinds.HTTP_AUTH`. +pub const HTTP_AUTH_KIND: Kind = Kind(27_235); + +/// NIP-98 suggests a window of about 60 s (`DEFAULT_NIP98_MAX_SKEW_SECONDS`). +pub const DEFAULT_MAX_SKEW_SECONDS: i64 = 60; + +/// A signed kind-27235 event encodes to about 1–2 KB; a longer header is refused before any +/// decoding or signature work (`DEFAULT_NIP98_MAX_AUTHORIZATION_HEADER_LENGTH`). +pub const DEFAULT_MAX_AUTHORIZATION_HEADER_LENGTH: usize = 2048; + +/// `Buffer.from(token, 'base64')`: padding is optional and the final block's unused bits are +/// ignored. The alphabet is already guaranteed by [`is_nostr_authorization_header`]. +const TOKEN: GeneralPurpose = GeneralPurpose::new( + &alphabet::STANDARD, + GeneralPurposeConfig::new() + .with_decode_padding_mode(DecodePaddingMode::Indifferent) + .with_decode_allow_trailing_bits(true), +); /// The claims of a NIP-98 `Authorization: Nostr ` header. #[derive(Debug, Clone, PartialEq, Eq)] @@ -10,21 +42,662 @@ pub struct HttpAuth { pub url: String, pub method: String, pub created_at: i64, + /// The event's `payload` tag as the client sent it, when it has one. pub payload_hash: Option, } -/// Verifies a NIP-98 header against the request it accompanies. +/// How the request body is bound to the event's `payload` tag (`Nip98PayloadPolicy`, +/// `src/utils/nip98.ts:58-63`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PayloadPolicy { + /// A non-empty body must carry a matching `payload` tag: the capture's default, and what + /// its mutating admin routes pass. + RequireWhenBody, + /// NIP-98's "MAY": the tag is checked only when the client sent one. + VerifyIfPresent, + /// The body is not bound to the event. + Ignore, +} + +/// Whether the header has the `Nostr ` shape (`isNostrAuthorizationHeader`, +/// `/^Nostr [A-Za-z0-9+/]+={0,2}$/i`). +pub fn is_nostr_authorization_header(header: &str) -> bool { + let Some((scheme, token)) = header.split_once(' ') else { + return false; + }; + + let data = token.trim_end_matches('='); + + scheme.eq_ignore_ascii_case("Nostr") + && token.len() - data.len() <= 2 + && !data.is_empty() + && data + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/')) +} + +/// The lowercase hex SHA-256 of a request body (`hashNip98Payload`). +pub fn hash_payload(body: &[u8]) -> String { + hex::encode(Sha256::digest(body).as_slice()) +} + +/// Verifies a NIP-98 header against the request it accompanies (`verifyNip98Auth`, +/// `src/utils/nip98.ts:218-281`). /// -/// Phase 1 stub — job 005; will verify the event, the URL/method tags and the replay window; -/// see `src/utils/nip98.ts`. +/// The checks run in the capture's order: the header's shape, length and encoding, the +/// event's schema and kind, the skew window, then the id and signature, and only then the +/// `u`, `method` and `payload` tags that bind the authenticated event to this request. +/// `body` is `None` when the request carries none, which skips the payload check as an +/// omitted body does in the capture. A `max_skew_seconds` that is negative or past +/// `Number.MAX_SAFE_INTEGER` falls back to [`DEFAULT_MAX_SKEW_SECONDS`]. `now` is supplied +/// by the caller because no module in this crate reads the system clock. pub fn verify( - _header: &str, - _url: &str, - _method: &str, - _body: &[u8], - _max_skew_seconds: i64, + header: &str, + url: &str, + method: &str, + body: Option<&[u8]>, + payload_policy: PayloadPolicy, + max_skew_seconds: i64, + now: i64, ) -> Result { - Err(CoreError::NotImplemented { - module: "core::nip98::verify", + let value = decode_header(header)?; + let event = decode_event_fields(&value).map_err(|_| fail("invalid authorization event"))?; + + if event.kind != HTTP_AUTH_KIND { + return Err(fail("invalid: auth event must be kind 27235")); + } + + let max_skew_seconds = if (0..=MAX_SAFE_INTEGER as i64).contains(&max_skew_seconds) { + max_skew_seconds + } else { + DEFAULT_MAX_SKEW_SECONDS + }; + + if now.saturating_sub(event.created_at).saturating_abs() > max_skew_seconds { + return Err(fail("invalid: created_at is too far from the current time")); + } + + if compute_event_id(&event).ok() != Some(event.id) { + return Err(fail("invalid: event id does not match")); + } + + if verify_event_signature(&event).is_err() { + return Err(fail("invalid: event signature verification failed")); + } + + let tags = auth_tags(&event.tags); + + let Some(tag_url) = tags.url else { + return Err(fail("invalid: missing u tag")); + }; + if tag_url != url { + return Err(fail("invalid: u tag does not match request url")); + } + + let Some(tag_method) = tags.method else { + return Err(fail("invalid: missing method tag")); + }; + if tag_method != method { + return Err(fail("invalid: method tag does not match request method")); + } + + if let Some(body) = body { + verify_payload(payload_policy, body, tags.payload)?; + } + + Ok(HttpAuth { + pubkey: event.pubkey, + url: tag_url.to_owned(), + method: tag_method.to_owned(), + created_at: event.created_at, + payload_hash: tags.payload.map(str::to_owned), }) } + +fn fail(reason: &str) -> CoreError { + CoreError::InvalidNip98(reason.to_owned()) +} + +/// `decodeAuthorizationHeader`: the header's shape, then the token's encoding, then JSON. +fn decode_header(header: &str) -> Result { + if header.is_empty() { + return Err(fail("missing authorization header")); + } + + if header.len() > DEFAULT_MAX_AUTHORIZATION_HEADER_LENGTH + || !is_nostr_authorization_header(header) + { + return Err(fail("invalid authorization header")); + } + + let token = header.split_once(' ').map_or("", |(_, token)| token); + let remainder = token.len() % 4; + + if remainder == 1 || (token.ends_with('=') && remainder != 0) { + return Err(fail("invalid authorization encoding")); + } + + let bytes = TOKEN + .decode(token) + .map_err(|_| fail("invalid authorization encoding"))?; + + serde_json::from_str(&String::from_utf8_lossy(&bytes)) + .map_err(|_| fail("invalid authorization event json")) +} + +/// The first `u`, `method` and `payload` tags with a value (`extractAuthTags`). +struct AuthTags<'a> { + url: Option<&'a str>, + method: Option<&'a str>, + payload: Option<&'a str>, +} + +fn auth_tags(tags: &[Tag]) -> AuthTags<'_> { + let first = |name: &str| { + tags.iter() + .find(|tag| tag.len() >= 2 && tag[0] == name) + .map(|tag| tag[1].as_str()) + }; + + AuthTags { + url: first("u"), + method: first("method"), + payload: first("payload"), + } +} + +/// `verifyPayloadBinding`: whether the body is bound to the event's `payload` tag. +fn verify_payload( + policy: PayloadPolicy, + body: &[u8], + payload: Option<&str>, +) -> Result<(), CoreError> { + if policy == PayloadPolicy::Ignore { + return Ok(()); + } + + if policy == PayloadPolicy::RequireWhenBody && !body.is_empty() && payload.is_none() { + return Err(fail("invalid: missing payload tag")); + } + + let Some(payload) = payload else { + return Ok(()); + }; + + // Tags are plain strings, so the digest is lowercased and its shape checked before the + // comparison. + let payload = payload.to_lowercase(); + let is_digest = payload.len() == 64 + && payload + .bytes() + .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')); + + if !is_digest || payload != hash_payload(body) { + return Err(fail("invalid: payload tag does not match request body")); + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used)] + + use super::*; + use crate::crypto::{public_key, sign_event}; + use crate::event::{Event, EventId, Signature}; + use base64::engine::general_purpose::STANDARD; + + // Deterministic fixture key, not a production secret (the capture's `'a'.repeat(64)`). + const SECRET: [u8; 32] = [0xaa; 32]; + const URL: &str = "https://relay.example.com/admin/settings"; + const NOW: i64 = 1_700_000_000; + const BODY: &[u8] = br#"{"enabled":true}"#; + + fn tags(tags: &[&[&str]]) -> Vec { + tags.iter() + .map(|tag| tag.iter().map(|part| (*part).to_owned()).collect()) + .collect() + } + + /// An unsigned kind-27235 event for `GET` on [`URL`] at [`NOW`]. + fn unsigned() -> Event { + Event { + id: EventId::from_byte_array([0; 32]), + pubkey: public_key(&SECRET).expect("the fixture key is a valid secret"), + created_at: NOW, + kind: HTTP_AUTH_KIND, + tags: tags(&[&["u", URL], &["method", "GET"]]), + content: String::new(), + sig: Signature::from_byte_array([0; 64]), + } + } + + fn signed(mut event: Event) -> Event { + sign_event(&SECRET, &mut event).expect("the fixture key signs"); + event + } + + fn with_tags(tag_list: &[&[&str]]) -> Event { + signed(Event { + tags: tags(tag_list), + ..unsigned() + }) + } + + fn header(event: &impl serde::Serialize) -> String { + let json = serde_json::to_vec(event).expect("an event serializes"); + format!("Nostr {}", STANDARD.encode(json)) + } + + fn check(header: &str, method: &str, body: Option<&[u8]>, policy: PayloadPolicy) -> String { + match verify( + header, + URL, + method, + body, + policy, + DEFAULT_MAX_SKEW_SECONDS, + NOW, + ) { + Ok(_) => "ok".to_owned(), + Err(CoreError::InvalidNip98(reason)) => reason, + Err(other) => format!("unexpected error: {other}"), + } + } + + fn get(header: &str) -> String { + check(header, "GET", None, PayloadPolicy::RequireWhenBody) + } + + #[test] + fn hashes_the_body_bytes_as_lowercase_hex() { + assert_eq!( + hash_payload(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + } + + #[test] + fn accepts_a_locally_signed_header_and_returns_its_claims() { + let event = signed(unsigned()); + let auth = verify( + &header(&event), + URL, + "GET", + None, + PayloadPolicy::RequireWhenBody, + DEFAULT_MAX_SKEW_SECONDS, + NOW, + ) + .expect("a fresh, signed, matching header verifies"); + + assert_eq!(auth.pubkey, event.pubkey); + assert_eq!(auth.url, URL); + assert_eq!(auth.method, "GET"); + assert_eq!(auth.created_at, NOW); + assert_eq!(auth.payload_hash, None); + } + + #[test] + fn the_scheme_is_case_insensitive() { + let token = header(&signed(unsigned())); + assert_eq!(get(&token.replacen("Nostr", "nostr", 1)), "ok"); + } + + #[test] + fn accepts_unpadded_base64() { + let padded = ["", "x", "xx"] + .iter() + .map(|content| { + header(&signed(Event { + content: (*content).to_owned(), + ..unsigned() + })) + }) + .find(|header| header.ends_with('=')) + .expect("one of three content lengths pads its token"); + + assert_eq!(get(padded.trim_end_matches('=')), "ok"); + } + + #[test] + fn rejects_a_missing_header() { + assert_eq!(get(""), "missing authorization header"); + } + + #[test] + fn rejects_an_oversized_header_before_decoding() { + let oversized = format!( + "Nostr {}", + "A".repeat(DEFAULT_MAX_AUTHORIZATION_HEADER_LENGTH) + ); + assert_eq!(get(&oversized), "invalid authorization header"); + } + + #[test] + fn rejects_malformed_headers() { + let token = header(&signed(unsigned())); + let base64 = token.trim_start_matches("Nostr "); + + for malformed in [ + token.replacen("Nostr", "Bearer", 1), + "Nostr !!!not-base64!!!".to_owned(), + format!("Nostr {} {}", &base64[..8], &base64[8..]), + format!(" {token}"), + format!("{token} "), + format!("{token}==="), + "Nostr ==".to_owned(), + ] { + assert_eq!( + get(&malformed), + "invalid authorization header", + "{malformed}" + ); + } + } + + #[test] + fn rejects_a_token_whose_length_cannot_be_base64() { + assert_eq!(get("Nostr AAAAA"), "invalid authorization encoding"); + assert_eq!(get("Nostr AAAAA="), "invalid authorization encoding"); + // Padding on a length that is not a multiple of four: the decoder alone would accept + // this short padding, the capture refuses it first. + assert_eq!(get("Nostr AAAAAA="), "invalid authorization encoding"); + } + + #[test] + fn rejects_a_token_that_is_not_json() { + assert_eq!( + get(&format!("Nostr {}", STANDARD.encode("{not-json"))), + "invalid authorization event json" + ); + } + + #[test] + fn rejects_json_that_is_not_an_event() { + let hello = serde_json::json!({ "hello": "world" }); + assert_eq!(get(&header(&hello)), "invalid authorization event"); + + let mut extra = serde_json::to_value(signed(unsigned())).expect("an event serializes"); + extra["extra"] = Value::from(1); + assert_eq!(get(&header(&extra)), "invalid authorization event"); + } + + #[test] + fn checks_the_kind_before_the_window_and_the_signature() { + let mut event = signed(Event { + kind: Kind(22_242), + created_at: NOW - 3_600, + ..unsigned() + }); + event.sig = Signature::from_byte_array([0; 64]); + + assert_eq!( + get(&header(&event)), + "invalid: auth event must be kind 27235" + ); + } + + #[test] + fn the_skew_window_is_inclusive_in_both_directions() { + for (offset, expected) in [ + (-DEFAULT_MAX_SKEW_SECONDS, "ok"), + (DEFAULT_MAX_SKEW_SECONDS, "ok"), + ( + -DEFAULT_MAX_SKEW_SECONDS - 1, + "invalid: created_at is too far from the current time", + ), + ( + DEFAULT_MAX_SKEW_SECONDS + 1, + "invalid: created_at is too far from the current time", + ), + ] { + let event = signed(Event { + created_at: NOW + offset, + ..unsigned() + }); + assert_eq!(get(&header(&event)), expected, "offset {offset}"); + } + } + + #[test] + fn checks_the_window_before_the_id() { + let mut event = signed(Event { + created_at: NOW - 3_600, + ..unsigned() + }); + event.id = EventId::from_byte_array([0xff; 32]); + + assert_eq!( + get(&header(&event)), + "invalid: created_at is too far from the current time" + ); + } + + #[test] + fn respects_a_custom_skew_and_falls_back_on_an_unusable_one() { + let event = signed(Event { + created_at: NOW - 5, + ..unsigned() + }); + let at = |skew| { + verify( + &header(&event), + URL, + "GET", + None, + PayloadPolicy::RequireWhenBody, + skew, + NOW, + ) + .is_ok() + }; + + assert!(!at(1)); + assert!(at(5)); + + let stale = signed(Event { + created_at: NOW - DEFAULT_MAX_SKEW_SECONDS - 1, + ..unsigned() + }); + for unusable in [-1, i64::MAX] { + let result = verify( + &header(&stale), + URL, + "GET", + None, + PayloadPolicy::RequireWhenBody, + unusable, + NOW, + ); + assert!(result.is_err(), "skew {unusable} falls back to the default"); + } + } + + #[test] + fn rejects_an_id_that_is_not_the_events_hash() { + let mut event = signed(unsigned()); + event.id = EventId::from_byte_array([0xff; 32]); + + assert_eq!(get(&header(&event)), "invalid: event id does not match"); + } + + #[test] + fn rejects_a_signature_that_does_not_verify() { + let mut event = signed(unsigned()); + event.sig = Signature::from_byte_array([0; 64]); + + assert_eq!( + get(&header(&event)), + "invalid: event signature verification failed" + ); + } + + #[test] + fn rejects_the_published_nip98_example_because_its_id_does_not_match() { + // The spec's example signs a stated id that is not the hash of the event. + let example = serde_json::json!({ + "id": "fe964e758903360f28d8424d092da8494ed207cba823110be3a57dfe4b578734", + "pubkey": "63fe6318dc58583cfe16810f86dd09e18bfd76aabc24a0081ce2856f330504ed", + "content": "", + "kind": 27235, + "created_at": 1_682_327_852, + "tags": [ + ["u", "https://api.snort.social/api/v1/n5sp/list"], + ["method", "GET"] + ], + "sig": "5ed9d8ec958bc854f997bdc24ac337d005af372324747efe4a00e24f4c30437ff4dd8308684bed467d9d6be3e5a517bb43b1732cc7d33949a3aaf86705c22184" + }); + + let result = verify( + &header(&example), + "https://api.snort.social/api/v1/n5sp/list", + "GET", + None, + PayloadPolicy::RequireWhenBody, + DEFAULT_MAX_SKEW_SECONDS, + 1_682_327_852, + ); + + assert!(matches!( + result, + Err(CoreError::InvalidNip98(reason)) if reason == "invalid: event id does not match" + )); + } + + #[test] + fn binds_the_event_to_the_request_url_and_method() { + let other_url = format!("{URL}?other=1"); + + assert_eq!( + get(&header(&with_tags(&[ + &["u", &other_url], + &["method", "GET"] + ]))), + "invalid: u tag does not match request url" + ); + assert_eq!( + get(&header(&with_tags(&[&["u", URL], &["method", "POST"]]))), + "invalid: method tag does not match request method" + ); + assert_eq!( + get(&header(&with_tags(&[&["method", "GET"]]))), + "invalid: missing u tag" + ); + assert_eq!( + get(&header(&with_tags(&[&["u", URL]]))), + "invalid: missing method tag" + ); + } + + #[test] + fn reads_the_first_valued_tag_of_each_name() { + assert_eq!( + get(&header(&with_tags(&[ + &["u"], + &["u", URL], + &["u", "https://elsewhere.example.com"], + &["method", "GET"], + ]))), + "ok" + ); + assert_eq!( + get(&header(&with_tags(&[ + &["u", "https://elsewhere.example.com"], + &["u", URL], + &["method", "GET"], + ]))), + "invalid: u tag does not match request url" + ); + } + + fn patch(payload: Option<&str>) -> String { + let mut tag_list: Vec<&[&str]> = vec![&["u", URL], &["method", "PATCH"]]; + let payload_tag; + if let Some(payload) = payload { + payload_tag = ["payload", payload]; + tag_list.push(&payload_tag); + } + header(&with_tags(&tag_list)) + } + + #[test] + fn a_non_empty_body_must_carry_a_matching_payload_by_default() { + let digest = hash_payload(BODY); + let check_patch = + |token: &str| check(token, "PATCH", Some(BODY), PayloadPolicy::RequireWhenBody); + + assert_eq!(check_patch(&patch(Some(&digest))), "ok"); + assert_eq!(check_patch(&patch(Some(&digest.to_uppercase()))), "ok"); + assert_eq!(check_patch(&patch(None)), "invalid: missing payload tag"); + assert_eq!( + check_patch(&patch(Some(&hash_payload(b"other")))), + "invalid: payload tag does not match request body" + ); + assert_eq!( + check_patch(&patch(Some("not-a-sha256-digest"))), + "invalid: payload tag does not match request body" + ); + } + + #[test] + fn verify_if_present_checks_only_a_payload_the_client_sent() { + let check_patch = + |token: &str| check(token, "PATCH", Some(BODY), PayloadPolicy::VerifyIfPresent); + + assert_eq!(check_patch(&patch(None)), "ok"); + assert_eq!( + check_patch(&patch(Some(&hash_payload(b"other")))), + "invalid: payload tag does not match request body" + ); + } + + #[test] + fn ignore_and_an_omitted_body_skip_the_payload_check() { + let wrong = patch(Some(&hash_payload(b"other"))); + + assert_eq!( + check(&wrong, "PATCH", Some(BODY), PayloadPolicy::Ignore), + "ok" + ); + assert_eq!( + check(&wrong, "PATCH", None, PayloadPolicy::RequireWhenBody), + "ok" + ); + } + + #[test] + fn an_empty_body_needs_no_payload_tag() { + let event = with_tags(&[&["u", URL], &["method", "POST"]]); + + assert_eq!( + check( + &header(&event), + "POST", + Some(b""), + PayloadPolicy::RequireWhenBody + ), + "ok" + ); + } + + #[test] + fn returns_the_payload_tag_it_bound() { + let digest = hash_payload(BODY); + let event = with_tags(&[&["u", URL], &["method", "PATCH"], &["payload", &digest]]); + + let auth = verify( + &header(&event), + URL, + "PATCH", + Some(BODY), + PayloadPolicy::RequireWhenBody, + DEFAULT_MAX_SKEW_SECONDS, + NOW, + ) + .expect("a body bound by its digest verifies"); + + assert_eq!(auth.payload_hash, Some(digest)); + } +} diff --git a/docs/rewrite/crate-map.md b/docs/rewrite/crate-map.md index e8cdee152..284275c40 100644 --- a/docs/rewrite/crate-map.md +++ b/docs/rewrite/crate-map.md @@ -52,9 +52,9 @@ eight `crates/*/src/lib.rs` files whose crates have a TypeScript ancestor; brace directory tokens were expanded to their files. 305 of the 357 head files are named by a `lib.rs` block; the others are named here from a call site, an ADR, or a recorded reason. -**Totals over the 357 rows**, by the crate named first in column 2: `nostream-admin` 91, `nostreamd` 14, `nostream-services` 38, `nostream-core` 38, `nostream-relay` 37, `nostream-cli` 22, `nostream-storage` 22, `nostream-config` 9; 86 rows -name no crate because nothing replaced them. By class: `moved` 213, `split` 28, -`type-only` 30, and 86 rows that are `not moved`, naming `#865` 19, `#867` 42, `#868` 1, `#1036` 15, `#1336` 9. +**Totals over the 357 rows**, by the crate named first in column 2: `nostream-admin` 91, `nostreamd` 14, `nostream-services` 38, `nostream-core` 39, `nostream-relay` 37, `nostream-cli` 22, `nostream-storage` 22, `nostream-config` 9; 85 rows +name no crate because nothing replaced them. By class: `moved` 214, `split` 28, +`type-only` 30, and 85 rows that are `not moved`, naming `#865` 19, `#867` 41, `#868` 1, `#1036` 15, `#1336` 9. ## How to read a row @@ -349,8 +349,8 @@ The disposition's first word is the class, from the list the spec fixes: | `src/utils/nip66-events.ts` | `crates/nostream-core/src/nip66.rs` | `crates/nostream-core/src/lib.rs:19` | moved | | `src/utils/nip66-nip11-tags.ts` | `crates/nostream-core/src/nip66.rs` | `crates/nostream-core/src/lib.rs:19` | moved | | `src/utils/nip66-schedule.ts` | `crates/nostream-core/src/nip66.rs` | `crates/nostream-core/src/lib.rs:20` | moved | -| `src/utils/nip98-replay.ts` | — | `crates/nostream-core/src/nip98.rs:18` | not moved (#867) — dropped: the replay claim is stubbed with the verifier | -| `src/utils/nip98.ts` | — | `crates/nostream-core/src/nip98.rs:18` | not moved (#867) — dropped: the verifier is a Phase 1 stub; the claims type is modelled | +| `src/utils/nip98-replay.ts` | — | `crates/nostream-core/src/nip98.rs:3-4` | not moved (#867) — dropped: the replay claim needs the cache and belongs to the admin job (ADR 0010) | +| `src/utils/nip98.ts` | `crates/nostream-core/src/nip98.rs` | `crates/nostream-core/src/lib.rs:20` | moved | | `src/utils/operator-notification-enqueue.ts` | `crates/nostream-services/src/services/operator_notification_service.rs` | `crates/nostream-services/src/services/operator_notification_service.rs:162` | moved | | `src/utils/prometheus-client.ts` | — | `crates/nostream-admin/src/utils/mod.rs:1-4` | not moved (#867) — dropped: the console's Prometheus query client has no counterpart | | `src/utils/proof-of-work.ts` | `crates/nostream-core/src/pow.rs` | `crates/nostream-core/src/lib.rs:21` | moved | diff --git a/docs/rewrite/nip-parity.md b/docs/rewrite/nip-parity.md index 3900b3699..276cea5e2 100644 --- a/docs/rewrite/nip-parity.md +++ b/docs/rewrite/nip-parity.md @@ -1045,7 +1045,7 @@ no relay-side test reaches them. | 77 | `core/negentropy.rs` | `vectors-only: negentropy_parity::answers_that_message_exactly_like_the_reference` *(nostream-core; the `NEG-*` handlers are #865's)* | | 89 | the generic path | `session nip-generic-events` | | 90 | `core/event.rs`; `relay/strategies/dvm_job_request.rs`; `services/workers/dvm_orchestrator.rs` | `vectors-only: strategies::dvm_job_request_creates_the_event` | -| 98 | `core/nip98.rs` (stub) | `no-wire-surface: header verification needs the admin HTTP surface (D1, #865)` | +| 98 | `core/nip98.rs` | `no-wire-surface: header verification needs the admin HTTP surface (D1, #865)` | Two limits of the map, stated so a later reader does not take it for more than it is. **NIP-50's ranking** is split twice over. The SQL backend's `ts_rank` needs Postgres, so its