Skip to main content

stratum_node_core/
request.rs

1//! The signed-request profile: a strict NIP-98 HTTP authorisation verifier.
2
3use std::time::Duration;
4
5use base64::Engine as _;
6
7use crate::did::DidNostr;
8use crate::encoding;
9use crate::event::{ParseEventError, SignedEvent};
10use crate::id::{EventId, Sha256Digest, UnixTime};
11
12/// The Nostr event kind for HTTP authorisation (NIP-98).
13pub const HTTP_AUTH_KIND: u16 = 27235;
14
15/// The HTTP authorisation scheme name, as this crate writes it.
16pub(crate) const AUTHORIZATION_SCHEME: &str = "Nostr";
17
18/// The request a signed header is bound to: method, URL and optional body.
19///
20/// The verifier compares the signed event against these values, so the URL
21/// must be the one the server trusts (for example rebuilt from a validated
22/// `Host` and the request path), never a value copied from the token. `body`
23/// is `None` for a request without a body and `Some` (possibly empty) for a
24/// request with one. The signer uses the same type to say what it signs.
25///
26/// # Examples
27///
28/// ```
29/// use stratum_node_core::ExpectedRequest;
30///
31/// let get = ExpectedRequest::new("GET", "http://127.0.0.1:7070/api/v1/config", None);
32/// let post = ExpectedRequest { method: "POST", url: get.url, body: Some(b"{}") };
33/// assert_eq!(post.url, get.url);
34/// ```
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct ExpectedRequest<'a> {
37    /// The HTTP method token, compared byte for byte with the `method` tag.
38    ///
39    /// HTTP method names are case-sensitive (RFC 9110, section 9.1), so
40    /// `POST` and `post` are different methods. Pass the method exactly as
41    /// the request line carried it.
42    pub method: &'a str,
43    /// The absolute URL, compared byte for byte with the `u` tag.
44    pub url: &'a str,
45    /// The request body, if the request has one.
46    pub body: Option<&'a [u8]>,
47}
48
49impl<'a> ExpectedRequest<'a> {
50    /// Groups a method, URL and optional body.
51    pub const fn new(method: &'a str, url: &'a str, body: Option<&'a [u8]>) -> Self {
52        Self { method, url, body }
53    }
54}
55
56/// Limits applied by [`verify_request`].
57///
58/// The clock-skew window can be narrowed below the profile's ±60 seconds but
59/// never widened past it, so every policy enforces at least the freshness the
60/// Stratum signed-request profile fixes.
61///
62/// # Examples
63///
64/// ```
65/// use std::time::Duration;
66/// use stratum_node_core::{RequestPolicy, RequestPolicyError};
67///
68/// # fn main() -> Result<(), RequestPolicyError> {
69/// let policy = RequestPolicy::new().with_max_clock_skew(Duration::from_secs(30))?;
70/// assert_eq!(policy.max_clock_skew(), Duration::from_secs(30));
71/// assert_eq!(policy.max_token_bytes(), RequestPolicy::DEFAULT_MAX_TOKEN_BYTES);
72///
73/// let wider = RequestPolicy::new().with_max_clock_skew(Duration::from_secs(61));
74/// assert!(matches!(wider, Err(RequestPolicyError::ClockSkewTooWide { .. })));
75/// # Ok(())
76/// # }
77/// ```
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79pub struct RequestPolicy {
80    max_clock_skew: Duration,
81    max_token_bytes: usize,
82}
83
84impl RequestPolicy {
85    /// The default and largest clock skew allowed on either side of `now`:
86    /// 60 seconds, the window the Stratum signed-request profile fixes.
87    pub const DEFAULT_MAX_CLOCK_SKEW: Duration = Duration::from_secs(60);
88
89    /// The default largest `Authorization` header accepted: 64 KiB, far
90    /// above a three-tag request event and small enough to bound the work
91    /// spent on an unauthenticated header.
92    pub const DEFAULT_MAX_TOKEN_BYTES: usize = 64 * 1024;
93
94    /// Returns the default policy.
95    pub const fn new() -> Self {
96        Self {
97            max_clock_skew: Self::DEFAULT_MAX_CLOCK_SKEW,
98            max_token_bytes: Self::DEFAULT_MAX_TOKEN_BYTES,
99        }
100    }
101
102    /// Narrows the clock skew allowed on either side of `now`.
103    ///
104    /// `skew` may be anything up to and including
105    /// [`DEFAULT_MAX_CLOCK_SKEW`](Self::DEFAULT_MAX_CLOCK_SKEW). The
106    /// comparison is exact, so 60.5 seconds is refused. Within the limit,
107    /// sub-second precision is ignored when verifying, because `created_at`
108    /// is in whole seconds.
109    ///
110    /// # Errors
111    ///
112    /// Returns [`RequestPolicyError::ClockSkewTooWide`] when `skew` is longer
113    /// than [`DEFAULT_MAX_CLOCK_SKEW`](Self::DEFAULT_MAX_CLOCK_SKEW). The
114    /// policy is `Copy`, so the caller still holds the unchanged original.
115    pub const fn with_max_clock_skew(mut self, skew: Duration) -> Result<Self, RequestPolicyError> {
116        if skew.as_nanos() > Self::DEFAULT_MAX_CLOCK_SKEW.as_nanos() {
117            return Err(RequestPolicyError::ClockSkewTooWide {
118                requested: skew,
119                max: Self::DEFAULT_MAX_CLOCK_SKEW,
120            });
121        }
122        self.max_clock_skew = skew;
123        Ok(self)
124    }
125
126    /// Sets the largest `Authorization` header length accepted, in bytes.
127    #[must_use]
128    pub const fn with_max_token_bytes(mut self, bytes: usize) -> Self {
129        self.max_token_bytes = bytes;
130        self
131    }
132
133    /// Returns the clock skew allowed on either side of `now`.
134    pub const fn max_clock_skew(&self) -> Duration {
135        self.max_clock_skew
136    }
137
138    /// Returns the largest `Authorization` header length accepted, in bytes.
139    pub const fn max_token_bytes(&self) -> usize {
140        self.max_token_bytes
141    }
142}
143
144impl Default for RequestPolicy {
145    fn default() -> Self {
146        Self::new()
147    }
148}
149
150/// The outcome of a successful [`verify_request`].
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152pub struct VerifiedRequest {
153    signer: DidNostr,
154    event_id: EventId,
155    created_at: UnixTime,
156    payload: Option<Sha256Digest>,
157}
158
159impl VerifiedRequest {
160    /// Returns the principal that signed the request.
161    pub fn signer(&self) -> DidNostr {
162        self.signer
163    }
164
165    /// Returns the event ID: the key for durable replay protection.
166    pub fn event_id(&self) -> EventId {
167        self.event_id
168    }
169
170    /// Returns the signed creation time.
171    pub fn created_at(&self) -> UnixTime {
172        self.created_at
173    }
174
175    /// Returns the verified body digest, present exactly when the expected
176    /// request had a body.
177    pub fn payload(&self) -> Option<Sha256Digest> {
178        self.payload
179    }
180}
181
182/// Verifies an `Authorization` header against the signed-request profile.
183///
184/// `authorization` is the raw header value. `expected` is the request the
185/// server actually received, with the URL it trusts. `now` is the server's
186/// current time.
187///
188/// The header value is `Nostr <base64>`, where the base64 decodes to a
189/// kind-27235 Nostr event. The profile is stricter than NIP-98 requires:
190///
191/// - the scheme is `Nostr` (matched case-insensitively, as HTTP schemes are),
192///   followed by one or more spaces and standard padded base64;
193/// - the header is at most [`RequestPolicy::max_token_bytes`] long;
194/// - the event parses and its ID and BIP-340 signature verify
195///   ([`SignedEvent::from_json`]);
196/// - the kind is [`HTTP_AUTH_KIND`];
197/// - there is exactly one `u` tag and exactly one `method` tag, at most one
198///   `payload` tag, and each of those has exactly one value;
199/// - `u` equals the expected URL byte for byte;
200/// - `method` equals the expected method byte for byte (HTTP methods are
201///   case-sensitive, so a header signed for `POST` does not verify as
202///   `post`);
203/// - when the request has a body (even an empty one) the `payload` tag is
204///   mandatory and equals the lowercase hex SHA-256 of the body; when it has
205///   none, a `payload` tag is rejected;
206/// - `created_at` is within [`RequestPolicy::max_clock_skew`] of `now`, on
207///   either side, inclusive; that window is never more than ±60 seconds.
208///
209/// Other non-empty tags are ignored; an empty tag fails event parsing. The
210/// verifier does **not** provide single use: the
211/// same header verifies again until it leaves the time window. Durable replay
212/// protection belongs to the caller, keyed by
213/// [`VerifiedRequest::event_id`].
214///
215/// # Examples
216///
217/// ```
218/// use stratum_node_core::{
219///     verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime, VerifyRequestError,
220/// };
221///
222/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
223/// let key = NostrSecretKey::from_hex(&"05".repeat(32))?;
224/// let request = ExpectedRequest::new("GET", "http://127.0.0.1:7070/api/v1/config", None);
225/// let signed_at = UnixTime::from_secs(1_700_000_000);
226/// let header = key.sign_request(&request, signed_at, &[0u8; 32])?;
227///
228/// let policy = RequestPolicy::new();
229/// let ok = verify_request(&header, &request, UnixTime::from_secs(1_700_000_060), &policy)?;
230/// assert_eq!(ok.signer(), key.public());
231///
232/// let late = verify_request(&header, &request, UnixTime::from_secs(1_700_000_061), &policy);
233/// assert!(matches!(late, Err(VerifyRequestError::CreatedTooLongAgo { .. })));
234/// # Ok(())
235/// # }
236/// ```
237///
238/// # Errors
239///
240/// Returns the [`VerifyRequestError`] variant naming the first failed check.
241pub fn verify_request(
242    authorization: &str,
243    expected: &ExpectedRequest<'_>,
244    now: UnixTime,
245    policy: &RequestPolicy,
246) -> Result<VerifiedRequest, VerifyRequestError> {
247    if authorization.len() > policy.max_token_bytes {
248        return Err(VerifyRequestError::TokenTooLarge {
249            len: authorization.len(),
250            max: policy.max_token_bytes,
251        });
252    }
253    let (scheme, token) = authorization
254        .split_once(' ')
255        .ok_or(VerifyRequestError::InvalidScheme)?;
256    if !scheme.eq_ignore_ascii_case(AUTHORIZATION_SCHEME) {
257        return Err(VerifyRequestError::InvalidScheme);
258    }
259    let json = base64::engine::general_purpose::STANDARD
260        .decode(token.trim_start_matches(' '))
261        .map_err(|_| VerifyRequestError::InvalidBase64)?;
262    let event = SignedEvent::from_json(&json)?;
263
264    if event.kind() != HTTP_AUTH_KIND {
265        return Err(VerifyRequestError::WrongKind { kind: event.kind() });
266    }
267
268    let tags = ProfileTags::collect(event.tags())?;
269    let url = tags.url.ok_or(VerifyRequestError::MissingUrlTag)?;
270    let method = tags.method.ok_or(VerifyRequestError::MissingMethodTag)?;
271    if url != expected.url {
272        return Err(VerifyRequestError::UrlMismatch);
273    }
274    if method != expected.method {
275        return Err(VerifyRequestError::MethodMismatch);
276    }
277    let payload = match (expected.body, tags.payload) {
278        (Some(body), Some(tag)) => {
279            if !(tag.len() == 64 && encoding::is_lower_hex(tag)) {
280                return Err(VerifyRequestError::InvalidPayloadTag);
281            }
282            let digest = Sha256Digest::of(body);
283            if digest.to_hex() != tag {
284                return Err(VerifyRequestError::PayloadMismatch);
285            }
286            Some(digest)
287        }
288        (Some(_), None) => return Err(VerifyRequestError::MissingPayloadTag),
289        (None, Some(_)) => return Err(VerifyRequestError::UnexpectedPayloadTag),
290        (None, None) => None,
291    };
292
293    let created_at = event.created_at();
294    let skew = policy.max_clock_skew.as_secs();
295    if created_at > now && created_at.abs_diff(now) > skew {
296        return Err(VerifyRequestError::CreatedTooFarInFuture { created_at, now });
297    }
298    if created_at < now && created_at.abs_diff(now) > skew {
299        return Err(VerifyRequestError::CreatedTooLongAgo { created_at, now });
300    }
301
302    Ok(VerifiedRequest {
303        signer: event.author(),
304        event_id: event.id(),
305        created_at,
306        payload,
307    })
308}
309
310/// The `u`, `method` and `payload` tag values, each seen at most once.
311struct ProfileTags<'e> {
312    url: Option<&'e str>,
313    method: Option<&'e str>,
314    payload: Option<&'e str>,
315}
316
317impl<'e> ProfileTags<'e> {
318    fn collect(tags: &'e [Vec<String>]) -> Result<Self, VerifyRequestError> {
319        let mut found = Self {
320            url: None,
321            method: None,
322            payload: None,
323        };
324        for tag in tags {
325            let Some(name) = tag.first() else { continue };
326            let (slot, duplicate, tag_name) = match name.as_str() {
327                "u" => (&mut found.url, VerifyRequestError::DuplicateUrlTag, "u"),
328                "method" => (
329                    &mut found.method,
330                    VerifyRequestError::DuplicateMethodTag,
331                    "method",
332                ),
333                "payload" => (
334                    &mut found.payload,
335                    VerifyRequestError::DuplicatePayloadTag,
336                    "payload",
337                ),
338                _ => continue,
339            };
340            if slot.is_some() {
341                return Err(duplicate);
342            }
343            let [_, value] = tag.as_slice() else {
344                return Err(VerifyRequestError::MalformedTag { tag: tag_name });
345            };
346            *slot = Some(value.as_str());
347        }
348        Ok(found)
349    }
350}
351
352/// The reasons [`verify_request`] can refuse a request, one per check.
353///
354/// No variant carries text from the request, so errors are safe to log.
355#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
356#[non_exhaustive]
357pub enum VerifyRequestError {
358    /// The header is longer than [`RequestPolicy::max_token_bytes`].
359    #[error("authorization header is {len} bytes, more than the {max} allowed")]
360    TokenTooLarge {
361        /// The header length in bytes.
362        len: usize,
363        /// The policy limit in bytes.
364        max: usize,
365    },
366    /// The header is not `Nostr` followed by a space and a token.
367    #[error("invalid authorization scheme")]
368    InvalidScheme,
369    /// The token is not standard padded base64.
370    #[error("authorization token is not valid base64")]
371    InvalidBase64,
372    /// The decoded token is not a valid, correctly signed Nostr event.
373    #[error("authorization event is invalid")]
374    Event(#[from] ParseEventError),
375    /// The event kind is not [`HTTP_AUTH_KIND`].
376    #[error("event kind {kind} is not 27235")]
377    WrongKind {
378        /// The kind the event carries.
379        kind: u16,
380    },
381    /// A `u`, `method` or `payload` tag does not have exactly one value.
382    #[error("{tag} tag must have exactly one value")]
383    MalformedTag {
384        /// The tag name.
385        tag: &'static str,
386    },
387    /// There is no `u` tag.
388    #[error("missing u tag")]
389    MissingUrlTag,
390    /// There is more than one `u` tag.
391    #[error("duplicate u tag")]
392    DuplicateUrlTag,
393    /// There is no `method` tag.
394    #[error("missing method tag")]
395    MissingMethodTag,
396    /// There is more than one `method` tag.
397    #[error("duplicate method tag")]
398    DuplicateMethodTag,
399    /// There is more than one `payload` tag.
400    #[error("duplicate payload tag")]
401    DuplicatePayloadTag,
402    /// The `u` tag is not byte-for-byte the expected URL.
403    #[error("signed url does not match the request")]
404    UrlMismatch,
405    /// The `method` tag is not the expected method.
406    #[error("signed method does not match the request")]
407    MethodMismatch,
408    /// The request has a body but the event has no `payload` tag.
409    #[error("request has a body but no payload tag")]
410    MissingPayloadTag,
411    /// The request has no body but the event has a `payload` tag.
412    #[error("request has no body but a payload tag is present")]
413    UnexpectedPayloadTag,
414    /// The `payload` tag is not 64 lowercase hexadecimal digits.
415    #[error("payload tag is not 64 lowercase hex digits")]
416    InvalidPayloadTag,
417    /// The `payload` tag is not the SHA-256 of the body.
418    #[error("payload tag does not match the body")]
419    PayloadMismatch,
420    /// `created_at` is later than `now` by more than the allowed skew.
421    #[error("event created at {created_at} is too far after {now}")]
422    CreatedTooFarInFuture {
423        /// The signed creation time.
424        created_at: UnixTime,
425        /// The time the server supplied.
426        now: UnixTime,
427    },
428    /// `created_at` is earlier than `now` by more than the allowed skew.
429    #[error("event created at {created_at} is too long before {now}")]
430    CreatedTooLongAgo {
431        /// The signed creation time.
432        created_at: UnixTime,
433        /// The time the server supplied.
434        now: UnixTime,
435    },
436}
437
438/// The reasons a [`RequestPolicy`] setting can be refused.
439#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
440#[non_exhaustive]
441pub enum RequestPolicyError {
442    /// The requested clock skew is wider than the profile allows.
443    #[error("clock skew {requested:?} is wider than the {max:?} the profile allows")]
444    ClockSkewTooWide {
445        /// The skew the caller asked for.
446        requested: Duration,
447        /// The widest skew allowed,
448        /// [`RequestPolicy::DEFAULT_MAX_CLOCK_SKEW`].
449        max: Duration,
450    },
451}