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, ParsedEvent, 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 UnverifiedRequest::parse(authorization, policy)?.verify(expected, now)
248}
249
250/// Verifies an `Authorization` header in every respect except the body
251/// digest, for a caller that never sees the body.
252///
253/// This is [`verify_request`] for a proxy such as the Stratum gate, which
254/// must name the requester before it forwards a request whose body the
255/// server behind it will hash. It checks the header size and scheme, the
256/// event's structure, ID and BIP-340 signature, the kind, exactly one `u`
257/// tag equal to `target.url`, exactly one `method` tag equal to
258/// `target.method`, at most one `payload` tag that, if present, is 64
259/// lowercase hexadecimal digits, and the time window, with the same errors in
260/// the same order as [`verify_request`].
261///
262/// It does **not** compare the `payload` tag with any body, and it does not
263/// require a `payload` tag to be present or absent: it cannot know whether
264/// the request has a body worth binding. The result is therefore a
265/// [`BodyUncheckedRequest`], not a [`VerifiedRequest`]. A server that holds
266/// the body must still verify the request with [`verify_request`].
267///
268/// To look the author up before spending a signature verification, use
269/// [`UnverifiedRequest::parse`] followed by
270/// [`UnverifiedRequest::verify_without_body`] instead.
271///
272/// # Examples
273///
274/// ```
275/// use stratum_node_core::{
276/// verify_request_without_body, ExpectedRequest, NostrSecretKey, RequestPolicy, RequestTarget,
277/// Sha256Digest, UnixTime,
278/// };
279///
280/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
281/// let key = NostrSecretKey::from_hex(&"05".repeat(32))?;
282/// let url = "https://stratum.example.org/pods/abc/x.txt";
283/// let now = UnixTime::from_secs(1_700_000_000);
284/// let header = key.sign_request(&ExpectedRequest::new("PUT", url, Some(b"hello")), now, &[0; 32])?;
285///
286/// let checked = verify_request_without_body(
287/// &header,
288/// &RequestTarget::new("PUT", url),
289/// now,
290/// &RequestPolicy::new(),
291/// )?;
292/// assert_eq!(checked.signer(), key.public());
293/// // The digest the signer claims; nothing has hashed a body.
294/// assert_eq!(checked.claimed_payload(), Some(Sha256Digest::of(b"hello")));
295/// # Ok(())
296/// # }
297/// ```
298///
299/// # Errors
300///
301/// Returns the [`VerifyRequestError`] variant naming the first failed check.
302/// It never returns [`VerifyRequestError::MissingPayloadTag`],
303/// [`VerifyRequestError::UnexpectedPayloadTag`] or
304/// [`VerifyRequestError::PayloadMismatch`].
305pub fn verify_request_without_body(
306 authorization: &str,
307 target: &RequestTarget<'_>,
308 now: UnixTime,
309 policy: &RequestPolicy,
310) -> Result<BodyUncheckedRequest, VerifyRequestError> {
311 UnverifiedRequest::parse(authorization, policy)?.verify_without_body(target, now)
312}
313
314/// The method and URL a signed header is bound to, without a body.
315///
316/// Used by [`verify_request_without_body`] and
317/// [`UnverifiedRequest::verify_without_body`]. As for [`ExpectedRequest`], the
318/// URL must be the one the server trusts, never a value copied from the
319/// token.
320///
321/// # Examples
322///
323/// ```
324/// use stratum_node_core::RequestTarget;
325///
326/// let target = RequestTarget::new("GET", "https://stratum.example.org/pods/abc/");
327/// assert_eq!(target.method, "GET");
328/// ```
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub struct RequestTarget<'a> {
331 /// The HTTP method token, compared byte for byte with the `method` tag.
332 pub method: &'a str,
333 /// The absolute URL, compared byte for byte with the `u` tag.
334 pub url: &'a str,
335}
336
337impl<'a> RequestTarget<'a> {
338 /// Groups a method and a URL.
339 pub const fn new(method: &'a str, url: &'a str) -> Self {
340 Self { method, url }
341 }
342}
343
344/// A signed request checked in every respect except its body.
345///
346/// Returned by [`verify_request_without_body`] and
347/// [`UnverifiedRequest::verify_without_body`]. The signer, event ID and
348/// creation time are verified exactly as in a [`VerifiedRequest`]. The
349/// payload is only what the signer **claims** the body hashes to: no body has
350/// been compared with it. Use it for routing and authorisation decisions that
351/// depend on who signed, never as proof of what was sent.
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
353pub struct BodyUncheckedRequest {
354 signer: DidNostr,
355 event_id: EventId,
356 created_at: UnixTime,
357 claimed_payload: Option<Sha256Digest>,
358}
359
360impl BodyUncheckedRequest {
361 /// Returns the principal that signed the request.
362 pub fn signer(&self) -> DidNostr {
363 self.signer
364 }
365
366 /// Returns the event ID: the key for replay protection.
367 pub fn event_id(&self) -> EventId {
368 self.event_id
369 }
370
371 /// Returns the signed creation time.
372 pub fn created_at(&self) -> UnixTime {
373 self.created_at
374 }
375
376 /// Returns the `payload` tag as a digest, if the event carries one.
377 ///
378 /// This is the signer's claim about the body, **unverified**: nothing
379 /// has hashed a body and compared it.
380 pub fn claimed_payload(&self) -> Option<Sha256Digest> {
381 self.claimed_payload
382 }
383}
384
385/// An `Authorization: Nostr` header that has been decoded and parsed but
386/// **not verified**.
387///
388/// [`UnverifiedRequest::parse`] applies the header size limit, the scheme,
389/// base64 and every structural check on the event (JSON shape, field
390/// encodings, a public key on the curve, no empty tag, supported
391/// characters). It does not recompute the event ID or verify the signature,
392/// so [`claimed_author`](Self::claimed_author) and
393/// [`claimed_event_id`](Self::claimed_event_id) are only what the header
394/// says. Their sole safe use is to decide whether verification is worth
395/// spending, for example by looking the author up in a member directory.
396///
397/// Verify with [`verify`](Self::verify) (body known) or
398/// [`verify_without_body`](Self::verify_without_body) (body not seen); the
399/// header is not parsed again. Both consume the value, and the result of
400/// either is the same as [`verify_request`] or
401/// [`verify_request_without_body`] on the original header.
402///
403/// # Examples
404///
405/// ```
406/// use stratum_node_core::{
407/// ExpectedRequest, NostrSecretKey, RequestPolicy, RequestTarget, UnixTime, UnverifiedRequest,
408/// };
409///
410/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
411/// let key = NostrSecretKey::from_hex(&"05".repeat(32))?;
412/// let url = "https://stratum.example.org/pods/abc/";
413/// let now = UnixTime::from_secs(1_700_000_000);
414/// let header = key.sign_request(&ExpectedRequest::new("GET", url, None), now, &[0; 32])?;
415///
416/// let unverified = UnverifiedRequest::parse(&header, &RequestPolicy::new())?;
417/// // Cheap: no signature has been checked yet.
418/// let members = [key.public()];
419/// assert!(members.contains(&unverified.claimed_author()));
420///
421/// let checked = unverified.verify_without_body(&RequestTarget::new("GET", url), now)?;
422/// assert_eq!(checked.signer(), key.public());
423/// # Ok(())
424/// # }
425/// ```
426#[derive(Debug, Clone)]
427pub struct UnverifiedRequest {
428 event: ParsedEvent,
429 policy: RequestPolicy,
430}
431
432impl UnverifiedRequest {
433 /// Decodes and parses an `Authorization` header value without verifying
434 /// the event ID or the signature.
435 ///
436 /// `policy` supplies the header size limit now and the clock window
437 /// later, when the request is verified.
438 ///
439 /// # Errors
440 ///
441 /// Returns [`VerifyRequestError::TokenTooLarge`],
442 /// [`VerifyRequestError::InvalidScheme`],
443 /// [`VerifyRequestError::InvalidBase64`] or
444 /// [`VerifyRequestError::Event`] with a structural
445 /// [`ParseEventError`]. It never returns
446 /// [`ParseEventError::IdMismatch`] or [`ParseEventError::BadSignature`];
447 /// those come from verification.
448 pub fn parse(authorization: &str, policy: &RequestPolicy) -> Result<Self, VerifyRequestError> {
449 let json = decode_header(authorization, policy)?;
450 let event = ParsedEvent::from_json(&json)?;
451 Ok(Self {
452 event,
453 policy: *policy,
454 })
455 }
456
457 /// Returns the author the event names, **unverified**.
458 pub fn claimed_author(&self) -> DidNostr {
459 self.event.claimed_author()
460 }
461
462 /// Returns the event ID as the event states it, **unverified** and not
463 /// recomputed.
464 pub fn claimed_event_id(&self) -> EventId {
465 self.event.claimed_id()
466 }
467
468 /// Completes verification against the request the server received,
469 /// body included.
470 ///
471 /// The checks and their order are those of [`verify_request`].
472 ///
473 /// # Errors
474 ///
475 /// Returns the [`VerifyRequestError`] variant naming the first failed
476 /// check.
477 pub fn verify(
478 self,
479 expected: &ExpectedRequest<'_>,
480 now: UnixTime,
481 ) -> Result<VerifiedRequest, VerifyRequestError> {
482 let target = RequestTarget::new(expected.method, expected.url);
483 let policy = self.policy;
484 let (event, payload_tag) = self.check_profile(&target)?;
485 let payload = match (expected.body, payload_tag) {
486 (Some(body), Some(tag)) => {
487 let claimed = parse_payload_tag(&tag)?;
488 let digest = Sha256Digest::of(body);
489 if digest != claimed {
490 return Err(VerifyRequestError::PayloadMismatch);
491 }
492 Some(digest)
493 }
494 (Some(_), None) => return Err(VerifyRequestError::MissingPayloadTag),
495 (None, Some(_)) => return Err(VerifyRequestError::UnexpectedPayloadTag),
496 (None, None) => None,
497 };
498 check_window(event.created_at(), now, &policy)?;
499 Ok(VerifiedRequest {
500 signer: event.author(),
501 event_id: event.id(),
502 created_at: event.created_at(),
503 payload,
504 })
505 }
506
507 /// Completes verification in every respect except the body digest.
508 ///
509 /// The checks and their order are those of
510 /// [`verify_request_without_body`]; read its documentation for what is
511 /// and is not checked.
512 ///
513 /// # Errors
514 ///
515 /// Returns the [`VerifyRequestError`] variant naming the first failed
516 /// check.
517 pub fn verify_without_body(
518 self,
519 target: &RequestTarget<'_>,
520 now: UnixTime,
521 ) -> Result<BodyUncheckedRequest, VerifyRequestError> {
522 let policy = self.policy;
523 let (event, payload_tag) = self.check_profile(target)?;
524 let claimed_payload = payload_tag.as_deref().map(parse_payload_tag).transpose()?;
525 check_window(event.created_at(), now, &policy)?;
526 Ok(BodyUncheckedRequest {
527 signer: event.author(),
528 event_id: event.id(),
529 created_at: event.created_at(),
530 claimed_payload,
531 })
532 }
533
534 /// Verifies the event ID and signature, then the kind, the tags, the URL
535 /// and the method, in that order. Returns the verified event and its
536 /// `payload` tag value, if any, for the caller to check.
537 fn check_profile(
538 self,
539 target: &RequestTarget<'_>,
540 ) -> Result<(SignedEvent, Option<String>), VerifyRequestError> {
541 let event = self.event.verify()?;
542 if event.kind() != HTTP_AUTH_KIND {
543 return Err(VerifyRequestError::WrongKind { kind: event.kind() });
544 }
545 let tags = ProfileTags::collect(event.tags())?;
546 let url = tags.url.ok_or(VerifyRequestError::MissingUrlTag)?;
547 let method = tags.method.ok_or(VerifyRequestError::MissingMethodTag)?;
548 if url != target.url {
549 return Err(VerifyRequestError::UrlMismatch);
550 }
551 if method != target.method {
552 return Err(VerifyRequestError::MethodMismatch);
553 }
554 let payload = tags.payload.map(str::to_owned);
555 Ok((event, payload))
556 }
557}
558
559/// Applies the size limit and the scheme, and decodes the base64 token.
560fn decode_header(
561 authorization: &str,
562 policy: &RequestPolicy,
563) -> Result<Vec<u8>, VerifyRequestError> {
564 if authorization.len() > policy.max_token_bytes {
565 return Err(VerifyRequestError::TokenTooLarge {
566 len: authorization.len(),
567 max: policy.max_token_bytes,
568 });
569 }
570 let (scheme, token) = authorization
571 .split_once(' ')
572 .ok_or(VerifyRequestError::InvalidScheme)?;
573 if !scheme.eq_ignore_ascii_case(AUTHORIZATION_SCHEME) {
574 return Err(VerifyRequestError::InvalidScheme);
575 }
576 base64::engine::general_purpose::STANDARD
577 .decode(token.trim_start_matches(' '))
578 .map_err(|_| VerifyRequestError::InvalidBase64)
579}
580
581/// Parses a `payload` tag value, which must be 64 lowercase hex digits.
582fn parse_payload_tag(tag: &str) -> Result<Sha256Digest, VerifyRequestError> {
583 if !(tag.len() == 64 && encoding::is_lower_hex(tag)) {
584 return Err(VerifyRequestError::InvalidPayloadTag);
585 }
586 tag.parse()
587 .map_err(|_| VerifyRequestError::InvalidPayloadTag)
588}
589
590/// Checks `created_at` against `now` within the policy's clock skew.
591fn check_window(
592 created_at: UnixTime,
593 now: UnixTime,
594 policy: &RequestPolicy,
595) -> Result<(), VerifyRequestError> {
596 let skew = policy.max_clock_skew.as_secs();
597 if created_at > now && created_at.abs_diff(now) > skew {
598 return Err(VerifyRequestError::CreatedTooFarInFuture { created_at, now });
599 }
600 if created_at < now && created_at.abs_diff(now) > skew {
601 return Err(VerifyRequestError::CreatedTooLongAgo { created_at, now });
602 }
603 Ok(())
604}
605
606/// The `u`, `method` and `payload` tag values, each seen at most once.
607struct ProfileTags<'e> {
608 url: Option<&'e str>,
609 method: Option<&'e str>,
610 payload: Option<&'e str>,
611}
612
613impl<'e> ProfileTags<'e> {
614 fn collect(tags: &'e [Vec<String>]) -> Result<Self, VerifyRequestError> {
615 let mut found = Self {
616 url: None,
617 method: None,
618 payload: None,
619 };
620 for tag in tags {
621 let Some(name) = tag.first() else { continue };
622 let (slot, duplicate, tag_name) = match name.as_str() {
623 "u" => (&mut found.url, VerifyRequestError::DuplicateUrlTag, "u"),
624 "method" => (
625 &mut found.method,
626 VerifyRequestError::DuplicateMethodTag,
627 "method",
628 ),
629 "payload" => (
630 &mut found.payload,
631 VerifyRequestError::DuplicatePayloadTag,
632 "payload",
633 ),
634 _ => continue,
635 };
636 if slot.is_some() {
637 return Err(duplicate);
638 }
639 let [_, value] = tag.as_slice() else {
640 return Err(VerifyRequestError::MalformedTag { tag: tag_name });
641 };
642 *slot = Some(value.as_str());
643 }
644 Ok(found)
645 }
646}
647
648/// The reasons [`verify_request`] can refuse a request, one per check.
649///
650/// No variant carries text from the request, so errors are safe to log.
651#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
652#[non_exhaustive]
653pub enum VerifyRequestError {
654 /// The header is longer than [`RequestPolicy::max_token_bytes`].
655 #[error("authorization header is {len} bytes, more than the {max} allowed")]
656 TokenTooLarge {
657 /// The header length in bytes.
658 len: usize,
659 /// The policy limit in bytes.
660 max: usize,
661 },
662 /// The header is not `Nostr` followed by a space and a token.
663 #[error("invalid authorization scheme")]
664 InvalidScheme,
665 /// The token is not standard padded base64.
666 #[error("authorization token is not valid base64")]
667 InvalidBase64,
668 /// The decoded token is not a valid, correctly signed Nostr event.
669 #[error("authorization event is invalid")]
670 Event(#[from] ParseEventError),
671 /// The event kind is not [`HTTP_AUTH_KIND`].
672 #[error("event kind {kind} is not 27235")]
673 WrongKind {
674 /// The kind the event carries.
675 kind: u16,
676 },
677 /// A `u`, `method` or `payload` tag does not have exactly one value.
678 #[error("{tag} tag must have exactly one value")]
679 MalformedTag {
680 /// The tag name.
681 tag: &'static str,
682 },
683 /// There is no `u` tag.
684 #[error("missing u tag")]
685 MissingUrlTag,
686 /// There is more than one `u` tag.
687 #[error("duplicate u tag")]
688 DuplicateUrlTag,
689 /// There is no `method` tag.
690 #[error("missing method tag")]
691 MissingMethodTag,
692 /// There is more than one `method` tag.
693 #[error("duplicate method tag")]
694 DuplicateMethodTag,
695 /// There is more than one `payload` tag.
696 #[error("duplicate payload tag")]
697 DuplicatePayloadTag,
698 /// The `u` tag is not byte-for-byte the expected URL.
699 #[error("signed url does not match the request")]
700 UrlMismatch,
701 /// The `method` tag is not the expected method.
702 #[error("signed method does not match the request")]
703 MethodMismatch,
704 /// The request has a body but the event has no `payload` tag.
705 #[error("request has a body but no payload tag")]
706 MissingPayloadTag,
707 /// The request has no body but the event has a `payload` tag.
708 #[error("request has no body but a payload tag is present")]
709 UnexpectedPayloadTag,
710 /// The `payload` tag is not 64 lowercase hexadecimal digits.
711 #[error("payload tag is not 64 lowercase hex digits")]
712 InvalidPayloadTag,
713 /// The `payload` tag is not the SHA-256 of the body.
714 #[error("payload tag does not match the body")]
715 PayloadMismatch,
716 /// `created_at` is later than `now` by more than the allowed skew.
717 #[error("event created at {created_at} is too far after {now}")]
718 CreatedTooFarInFuture {
719 /// The signed creation time.
720 created_at: UnixTime,
721 /// The time the server supplied.
722 now: UnixTime,
723 },
724 /// `created_at` is earlier than `now` by more than the allowed skew.
725 #[error("event created at {created_at} is too long before {now}")]
726 CreatedTooLongAgo {
727 /// The signed creation time.
728 created_at: UnixTime,
729 /// The time the server supplied.
730 now: UnixTime,
731 },
732}
733
734/// The reasons a [`RequestPolicy`] setting can be refused.
735#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
736#[non_exhaustive]
737pub enum RequestPolicyError {
738 /// The requested clock skew is wider than the profile allows.
739 #[error("clock skew {requested:?} is wider than the {max:?} the profile allows")]
740 ClockSkewTooWide {
741 /// The skew the caller asked for.
742 requested: Duration,
743 /// The widest skew allowed,
744 /// [`RequestPolicy::DEFAULT_MAX_CLOCK_SKEW`].
745 max: Duration,
746 },
747}