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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! The signed-request profile: a strict NIP-98 HTTP authorisation verifier.

use std::time::Duration;

use base64::Engine as _;

use crate::did::DidNostr;
use crate::encoding;
use crate::event::{ParseEventError, ParsedEvent, SignedEvent};
use crate::id::{EventId, Sha256Digest, UnixTime};

/// The Nostr event kind for HTTP authorisation (NIP-98).
pub const HTTP_AUTH_KIND: u16 = 27235;

/// The HTTP authorisation scheme name, as this crate writes it.
pub(crate) const AUTHORIZATION_SCHEME: &str = "Nostr";

/// The request a signed header is bound to: method, URL and optional body.
///
/// The verifier compares the signed event against these values, so the URL
/// must be the one the server trusts (for example rebuilt from a validated
/// `Host` and the request path), never a value copied from the token. `body`
/// is `None` for a request without a body and `Some` (possibly empty) for a
/// request with one. The signer uses the same type to say what it signs.
///
/// # Examples
///
/// ```
/// use stratum_node_core::ExpectedRequest;
///
/// let get = ExpectedRequest::new("GET", "http://127.0.0.1:7070/api/v1/config", None);
/// let post = ExpectedRequest { method: "POST", url: get.url, body: Some(b"{}") };
/// assert_eq!(post.url, get.url);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpectedRequest<'a> {
    /// The HTTP method token, compared byte for byte with the `method` tag.
    ///
    /// HTTP method names are case-sensitive (RFC 9110, section 9.1), so
    /// `POST` and `post` are different methods. Pass the method exactly as
    /// the request line carried it.
    pub method: &'a str,
    /// The absolute URL, compared byte for byte with the `u` tag.
    pub url: &'a str,
    /// The request body, if the request has one.
    pub body: Option<&'a [u8]>,
}

impl<'a> ExpectedRequest<'a> {
    /// Groups a method, URL and optional body.
    pub const fn new(method: &'a str, url: &'a str, body: Option<&'a [u8]>) -> Self {
        Self { method, url, body }
    }
}

/// Limits applied by [`verify_request`].
///
/// The clock-skew window can be narrowed below the profile's ±60 seconds but
/// never widened past it, so every policy enforces at least the freshness the
/// Stratum signed-request profile fixes.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use stratum_node_core::{RequestPolicy, RequestPolicyError};
///
/// # fn main() -> Result<(), RequestPolicyError> {
/// let policy = RequestPolicy::new().with_max_clock_skew(Duration::from_secs(30))?;
/// assert_eq!(policy.max_clock_skew(), Duration::from_secs(30));
/// assert_eq!(policy.max_token_bytes(), RequestPolicy::DEFAULT_MAX_TOKEN_BYTES);
///
/// let wider = RequestPolicy::new().with_max_clock_skew(Duration::from_secs(61));
/// assert!(matches!(wider, Err(RequestPolicyError::ClockSkewTooWide { .. })));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RequestPolicy {
    max_clock_skew: Duration,
    max_token_bytes: usize,
}

impl RequestPolicy {
    /// The default and largest clock skew allowed on either side of `now`:
    /// 60 seconds, the window the Stratum signed-request profile fixes.
    pub const DEFAULT_MAX_CLOCK_SKEW: Duration = Duration::from_secs(60);

    /// The default largest `Authorization` header accepted: 64 KiB, far
    /// above a three-tag request event and small enough to bound the work
    /// spent on an unauthenticated header.
    pub const DEFAULT_MAX_TOKEN_BYTES: usize = 64 * 1024;

    /// Returns the default policy.
    pub const fn new() -> Self {
        Self {
            max_clock_skew: Self::DEFAULT_MAX_CLOCK_SKEW,
            max_token_bytes: Self::DEFAULT_MAX_TOKEN_BYTES,
        }
    }

    /// Narrows the clock skew allowed on either side of `now`.
    ///
    /// `skew` may be anything up to and including
    /// [`DEFAULT_MAX_CLOCK_SKEW`](Self::DEFAULT_MAX_CLOCK_SKEW). The
    /// comparison is exact, so 60.5 seconds is refused. Within the limit,
    /// sub-second precision is ignored when verifying, because `created_at`
    /// is in whole seconds.
    ///
    /// # Errors
    ///
    /// Returns [`RequestPolicyError::ClockSkewTooWide`] when `skew` is longer
    /// than [`DEFAULT_MAX_CLOCK_SKEW`](Self::DEFAULT_MAX_CLOCK_SKEW). The
    /// policy is `Copy`, so the caller still holds the unchanged original.
    pub const fn with_max_clock_skew(mut self, skew: Duration) -> Result<Self, RequestPolicyError> {
        if skew.as_nanos() > Self::DEFAULT_MAX_CLOCK_SKEW.as_nanos() {
            return Err(RequestPolicyError::ClockSkewTooWide {
                requested: skew,
                max: Self::DEFAULT_MAX_CLOCK_SKEW,
            });
        }
        self.max_clock_skew = skew;
        Ok(self)
    }

    /// Sets the largest `Authorization` header length accepted, in bytes.
    #[must_use]
    pub const fn with_max_token_bytes(mut self, bytes: usize) -> Self {
        self.max_token_bytes = bytes;
        self
    }

    /// Returns the clock skew allowed on either side of `now`.
    pub const fn max_clock_skew(&self) -> Duration {
        self.max_clock_skew
    }

    /// Returns the largest `Authorization` header length accepted, in bytes.
    pub const fn max_token_bytes(&self) -> usize {
        self.max_token_bytes
    }
}

impl Default for RequestPolicy {
    fn default() -> Self {
        Self::new()
    }
}

/// The outcome of a successful [`verify_request`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VerifiedRequest {
    signer: DidNostr,
    event_id: EventId,
    created_at: UnixTime,
    payload: Option<Sha256Digest>,
}

impl VerifiedRequest {
    /// Returns the principal that signed the request.
    pub fn signer(&self) -> DidNostr {
        self.signer
    }

    /// Returns the event ID: the key for durable replay protection.
    pub fn event_id(&self) -> EventId {
        self.event_id
    }

    /// Returns the signed creation time.
    pub fn created_at(&self) -> UnixTime {
        self.created_at
    }

    /// Returns the verified body digest, present exactly when the expected
    /// request had a body.
    pub fn payload(&self) -> Option<Sha256Digest> {
        self.payload
    }
}

/// Verifies an `Authorization` header against the signed-request profile.
///
/// `authorization` is the raw header value. `expected` is the request the
/// server actually received, with the URL it trusts. `now` is the server's
/// current time.
///
/// The header value is `Nostr <base64>`, where the base64 decodes to a
/// kind-27235 Nostr event. The profile is stricter than NIP-98 requires:
///
/// - the scheme is `Nostr` (matched case-insensitively, as HTTP schemes are),
///   followed by one or more spaces and standard padded base64;
/// - the header is at most [`RequestPolicy::max_token_bytes`] long;
/// - the event parses and its ID and BIP-340 signature verify
///   ([`SignedEvent::from_json`]);
/// - the kind is [`HTTP_AUTH_KIND`];
/// - there is exactly one `u` tag and exactly one `method` tag, at most one
///   `payload` tag, and each of those has exactly one value;
/// - `u` equals the expected URL byte for byte;
/// - `method` equals the expected method byte for byte (HTTP methods are
///   case-sensitive, so a header signed for `POST` does not verify as
///   `post`);
/// - when the request has a body (even an empty one) the `payload` tag is
///   mandatory and equals the lowercase hex SHA-256 of the body; when it has
///   none, a `payload` tag is rejected;
/// - `created_at` is within [`RequestPolicy::max_clock_skew`] of `now`, on
///   either side, inclusive; that window is never more than ±60 seconds.
///
/// Other non-empty tags are ignored; an empty tag fails event parsing. The
/// verifier does **not** provide single use: the
/// same header verifies again until it leaves the time window. Durable replay
/// protection belongs to the caller, keyed by
/// [`VerifiedRequest::event_id`].
///
/// # Examples
///
/// ```
/// use stratum_node_core::{
///     verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime, VerifyRequestError,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let key = NostrSecretKey::from_hex(&"05".repeat(32))?;
/// let request = ExpectedRequest::new("GET", "http://127.0.0.1:7070/api/v1/config", None);
/// let signed_at = UnixTime::from_secs(1_700_000_000);
/// let header = key.sign_request(&request, signed_at, &[0u8; 32])?;
///
/// let policy = RequestPolicy::new();
/// let ok = verify_request(&header, &request, UnixTime::from_secs(1_700_000_060), &policy)?;
/// assert_eq!(ok.signer(), key.public());
///
/// let late = verify_request(&header, &request, UnixTime::from_secs(1_700_000_061), &policy);
/// assert!(matches!(late, Err(VerifyRequestError::CreatedTooLongAgo { .. })));
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns the [`VerifyRequestError`] variant naming the first failed check.
pub fn verify_request(
    authorization: &str,
    expected: &ExpectedRequest<'_>,
    now: UnixTime,
    policy: &RequestPolicy,
) -> Result<VerifiedRequest, VerifyRequestError> {
    UnverifiedRequest::parse(authorization, policy)?.verify(expected, now)
}

/// Verifies an `Authorization` header in every respect except the body
/// digest, for a caller that never sees the body.
///
/// This is [`verify_request`] for a proxy such as the Stratum gate, which
/// must name the requester before it forwards a request whose body the
/// server behind it will hash. It checks the header size and scheme, the
/// event's structure, ID and BIP-340 signature, the kind, exactly one `u`
/// tag equal to `target.url`, exactly one `method` tag equal to
/// `target.method`, at most one `payload` tag that, if present, is 64
/// lowercase hexadecimal digits, and the time window, with the same errors in
/// the same order as [`verify_request`].
///
/// It does **not** compare the `payload` tag with any body, and it does not
/// require a `payload` tag to be present or absent: it cannot know whether
/// the request has a body worth binding. The result is therefore a
/// [`BodyUncheckedRequest`], not a [`VerifiedRequest`]. A server that holds
/// the body must still verify the request with [`verify_request`].
///
/// To look the author up before spending a signature verification, use
/// [`UnverifiedRequest::parse`] followed by
/// [`UnverifiedRequest::verify_without_body`] instead.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{
///     verify_request_without_body, ExpectedRequest, NostrSecretKey, RequestPolicy, RequestTarget,
///     Sha256Digest, UnixTime,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let key = NostrSecretKey::from_hex(&"05".repeat(32))?;
/// let url = "https://stratum.example.org/pods/abc/x.txt";
/// let now = UnixTime::from_secs(1_700_000_000);
/// let header = key.sign_request(&ExpectedRequest::new("PUT", url, Some(b"hello")), now, &[0; 32])?;
///
/// let checked = verify_request_without_body(
///     &header,
///     &RequestTarget::new("PUT", url),
///     now,
///     &RequestPolicy::new(),
/// )?;
/// assert_eq!(checked.signer(), key.public());
/// // The digest the signer claims; nothing has hashed a body.
/// assert_eq!(checked.claimed_payload(), Some(Sha256Digest::of(b"hello")));
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns the [`VerifyRequestError`] variant naming the first failed check.
/// It never returns [`VerifyRequestError::MissingPayloadTag`],
/// [`VerifyRequestError::UnexpectedPayloadTag`] or
/// [`VerifyRequestError::PayloadMismatch`].
pub fn verify_request_without_body(
    authorization: &str,
    target: &RequestTarget<'_>,
    now: UnixTime,
    policy: &RequestPolicy,
) -> Result<BodyUncheckedRequest, VerifyRequestError> {
    UnverifiedRequest::parse(authorization, policy)?.verify_without_body(target, now)
}

/// The method and URL a signed header is bound to, without a body.
///
/// Used by [`verify_request_without_body`] and
/// [`UnverifiedRequest::verify_without_body`]. As for [`ExpectedRequest`], the
/// URL must be the one the server trusts, never a value copied from the
/// token.
///
/// # Examples
///
/// ```
/// use stratum_node_core::RequestTarget;
///
/// let target = RequestTarget::new("GET", "https://stratum.example.org/pods/abc/");
/// assert_eq!(target.method, "GET");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RequestTarget<'a> {
    /// The HTTP method token, compared byte for byte with the `method` tag.
    pub method: &'a str,
    /// The absolute URL, compared byte for byte with the `u` tag.
    pub url: &'a str,
}

impl<'a> RequestTarget<'a> {
    /// Groups a method and a URL.
    pub const fn new(method: &'a str, url: &'a str) -> Self {
        Self { method, url }
    }
}

/// A signed request checked in every respect except its body.
///
/// Returned by [`verify_request_without_body`] and
/// [`UnverifiedRequest::verify_without_body`]. The signer, event ID and
/// creation time are verified exactly as in a [`VerifiedRequest`]. The
/// payload is only what the signer **claims** the body hashes to: no body has
/// been compared with it. Use it for routing and authorisation decisions that
/// depend on who signed, never as proof of what was sent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BodyUncheckedRequest {
    signer: DidNostr,
    event_id: EventId,
    created_at: UnixTime,
    claimed_payload: Option<Sha256Digest>,
}

impl BodyUncheckedRequest {
    /// Returns the principal that signed the request.
    pub fn signer(&self) -> DidNostr {
        self.signer
    }

    /// Returns the event ID: the key for replay protection.
    pub fn event_id(&self) -> EventId {
        self.event_id
    }

    /// Returns the signed creation time.
    pub fn created_at(&self) -> UnixTime {
        self.created_at
    }

    /// Returns the `payload` tag as a digest, if the event carries one.
    ///
    /// This is the signer's claim about the body, **unverified**: nothing
    /// has hashed a body and compared it.
    pub fn claimed_payload(&self) -> Option<Sha256Digest> {
        self.claimed_payload
    }
}

/// An `Authorization: Nostr` header that has been decoded and parsed but
/// **not verified**.
///
/// [`UnverifiedRequest::parse`] applies the header size limit, the scheme,
/// base64 and every structural check on the event (JSON shape, field
/// encodings, a public key on the curve, no empty tag, supported
/// characters). It does not recompute the event ID or verify the signature,
/// so [`claimed_author`](Self::claimed_author) and
/// [`claimed_event_id`](Self::claimed_event_id) are only what the header
/// says. Their sole safe use is to decide whether verification is worth
/// spending, for example by looking the author up in a member directory.
///
/// Verify with [`verify`](Self::verify) (body known) or
/// [`verify_without_body`](Self::verify_without_body) (body not seen); the
/// header is not parsed again. Both consume the value, and the result of
/// either is the same as [`verify_request`] or
/// [`verify_request_without_body`] on the original header.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{
///     ExpectedRequest, NostrSecretKey, RequestPolicy, RequestTarget, UnixTime, UnverifiedRequest,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let key = NostrSecretKey::from_hex(&"05".repeat(32))?;
/// let url = "https://stratum.example.org/pods/abc/";
/// let now = UnixTime::from_secs(1_700_000_000);
/// let header = key.sign_request(&ExpectedRequest::new("GET", url, None), now, &[0; 32])?;
///
/// let unverified = UnverifiedRequest::parse(&header, &RequestPolicy::new())?;
/// // Cheap: no signature has been checked yet.
/// let members = [key.public()];
/// assert!(members.contains(&unverified.claimed_author()));
///
/// let checked = unverified.verify_without_body(&RequestTarget::new("GET", url), now)?;
/// assert_eq!(checked.signer(), key.public());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct UnverifiedRequest {
    event: ParsedEvent,
    policy: RequestPolicy,
}

impl UnverifiedRequest {
    /// Decodes and parses an `Authorization` header value without verifying
    /// the event ID or the signature.
    ///
    /// `policy` supplies the header size limit now and the clock window
    /// later, when the request is verified.
    ///
    /// # Errors
    ///
    /// Returns [`VerifyRequestError::TokenTooLarge`],
    /// [`VerifyRequestError::InvalidScheme`],
    /// [`VerifyRequestError::InvalidBase64`] or
    /// [`VerifyRequestError::Event`] with a structural
    /// [`ParseEventError`]. It never returns
    /// [`ParseEventError::IdMismatch`] or [`ParseEventError::BadSignature`];
    /// those come from verification.
    pub fn parse(authorization: &str, policy: &RequestPolicy) -> Result<Self, VerifyRequestError> {
        let json = decode_header(authorization, policy)?;
        let event = ParsedEvent::from_json(&json)?;
        Ok(Self {
            event,
            policy: *policy,
        })
    }

    /// Returns the author the event names, **unverified**.
    pub fn claimed_author(&self) -> DidNostr {
        self.event.claimed_author()
    }

    /// Returns the event ID as the event states it, **unverified** and not
    /// recomputed.
    pub fn claimed_event_id(&self) -> EventId {
        self.event.claimed_id()
    }

    /// Completes verification against the request the server received,
    /// body included.
    ///
    /// The checks and their order are those of [`verify_request`].
    ///
    /// # Errors
    ///
    /// Returns the [`VerifyRequestError`] variant naming the first failed
    /// check.
    pub fn verify(
        self,
        expected: &ExpectedRequest<'_>,
        now: UnixTime,
    ) -> Result<VerifiedRequest, VerifyRequestError> {
        let target = RequestTarget::new(expected.method, expected.url);
        let policy = self.policy;
        let (event, payload_tag) = self.check_profile(&target)?;
        let payload = match (expected.body, payload_tag) {
            (Some(body), Some(tag)) => {
                let claimed = parse_payload_tag(&tag)?;
                let digest = Sha256Digest::of(body);
                if digest != claimed {
                    return Err(VerifyRequestError::PayloadMismatch);
                }
                Some(digest)
            }
            (Some(_), None) => return Err(VerifyRequestError::MissingPayloadTag),
            (None, Some(_)) => return Err(VerifyRequestError::UnexpectedPayloadTag),
            (None, None) => None,
        };
        check_window(event.created_at(), now, &policy)?;
        Ok(VerifiedRequest {
            signer: event.author(),
            event_id: event.id(),
            created_at: event.created_at(),
            payload,
        })
    }

    /// Completes verification in every respect except the body digest.
    ///
    /// The checks and their order are those of
    /// [`verify_request_without_body`]; read its documentation for what is
    /// and is not checked.
    ///
    /// # Errors
    ///
    /// Returns the [`VerifyRequestError`] variant naming the first failed
    /// check.
    pub fn verify_without_body(
        self,
        target: &RequestTarget<'_>,
        now: UnixTime,
    ) -> Result<BodyUncheckedRequest, VerifyRequestError> {
        let policy = self.policy;
        let (event, payload_tag) = self.check_profile(target)?;
        let claimed_payload = payload_tag.as_deref().map(parse_payload_tag).transpose()?;
        check_window(event.created_at(), now, &policy)?;
        Ok(BodyUncheckedRequest {
            signer: event.author(),
            event_id: event.id(),
            created_at: event.created_at(),
            claimed_payload,
        })
    }

    /// Verifies the event ID and signature, then the kind, the tags, the URL
    /// and the method, in that order. Returns the verified event and its
    /// `payload` tag value, if any, for the caller to check.
    fn check_profile(
        self,
        target: &RequestTarget<'_>,
    ) -> Result<(SignedEvent, Option<String>), VerifyRequestError> {
        let event = self.event.verify()?;
        if event.kind() != HTTP_AUTH_KIND {
            return Err(VerifyRequestError::WrongKind { kind: event.kind() });
        }
        let tags = ProfileTags::collect(event.tags())?;
        let url = tags.url.ok_or(VerifyRequestError::MissingUrlTag)?;
        let method = tags.method.ok_or(VerifyRequestError::MissingMethodTag)?;
        if url != target.url {
            return Err(VerifyRequestError::UrlMismatch);
        }
        if method != target.method {
            return Err(VerifyRequestError::MethodMismatch);
        }
        let payload = tags.payload.map(str::to_owned);
        Ok((event, payload))
    }
}

/// Applies the size limit and the scheme, and decodes the base64 token.
fn decode_header(
    authorization: &str,
    policy: &RequestPolicy,
) -> Result<Vec<u8>, VerifyRequestError> {
    if authorization.len() > policy.max_token_bytes {
        return Err(VerifyRequestError::TokenTooLarge {
            len: authorization.len(),
            max: policy.max_token_bytes,
        });
    }
    let (scheme, token) = authorization
        .split_once(' ')
        .ok_or(VerifyRequestError::InvalidScheme)?;
    if !scheme.eq_ignore_ascii_case(AUTHORIZATION_SCHEME) {
        return Err(VerifyRequestError::InvalidScheme);
    }
    base64::engine::general_purpose::STANDARD
        .decode(token.trim_start_matches(' '))
        .map_err(|_| VerifyRequestError::InvalidBase64)
}

/// Parses a `payload` tag value, which must be 64 lowercase hex digits.
fn parse_payload_tag(tag: &str) -> Result<Sha256Digest, VerifyRequestError> {
    if !(tag.len() == 64 && encoding::is_lower_hex(tag)) {
        return Err(VerifyRequestError::InvalidPayloadTag);
    }
    tag.parse()
        .map_err(|_| VerifyRequestError::InvalidPayloadTag)
}

/// Checks `created_at` against `now` within the policy's clock skew.
fn check_window(
    created_at: UnixTime,
    now: UnixTime,
    policy: &RequestPolicy,
) -> Result<(), VerifyRequestError> {
    let skew = policy.max_clock_skew.as_secs();
    if created_at > now && created_at.abs_diff(now) > skew {
        return Err(VerifyRequestError::CreatedTooFarInFuture { created_at, now });
    }
    if created_at < now && created_at.abs_diff(now) > skew {
        return Err(VerifyRequestError::CreatedTooLongAgo { created_at, now });
    }
    Ok(())
}

/// The `u`, `method` and `payload` tag values, each seen at most once.
struct ProfileTags<'e> {
    url: Option<&'e str>,
    method: Option<&'e str>,
    payload: Option<&'e str>,
}

impl<'e> ProfileTags<'e> {
    fn collect(tags: &'e [Vec<String>]) -> Result<Self, VerifyRequestError> {
        let mut found = Self {
            url: None,
            method: None,
            payload: None,
        };
        for tag in tags {
            let Some(name) = tag.first() else { continue };
            let (slot, duplicate, tag_name) = match name.as_str() {
                "u" => (&mut found.url, VerifyRequestError::DuplicateUrlTag, "u"),
                "method" => (
                    &mut found.method,
                    VerifyRequestError::DuplicateMethodTag,
                    "method",
                ),
                "payload" => (
                    &mut found.payload,
                    VerifyRequestError::DuplicatePayloadTag,
                    "payload",
                ),
                _ => continue,
            };
            if slot.is_some() {
                return Err(duplicate);
            }
            let [_, value] = tag.as_slice() else {
                return Err(VerifyRequestError::MalformedTag { tag: tag_name });
            };
            *slot = Some(value.as_str());
        }
        Ok(found)
    }
}

/// The reasons [`verify_request`] can refuse a request, one per check.
///
/// No variant carries text from the request, so errors are safe to log.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum VerifyRequestError {
    /// The header is longer than [`RequestPolicy::max_token_bytes`].
    #[error("authorization header is {len} bytes, more than the {max} allowed")]
    TokenTooLarge {
        /// The header length in bytes.
        len: usize,
        /// The policy limit in bytes.
        max: usize,
    },
    /// The header is not `Nostr` followed by a space and a token.
    #[error("invalid authorization scheme")]
    InvalidScheme,
    /// The token is not standard padded base64.
    #[error("authorization token is not valid base64")]
    InvalidBase64,
    /// The decoded token is not a valid, correctly signed Nostr event.
    #[error("authorization event is invalid")]
    Event(#[from] ParseEventError),
    /// The event kind is not [`HTTP_AUTH_KIND`].
    #[error("event kind {kind} is not 27235")]
    WrongKind {
        /// The kind the event carries.
        kind: u16,
    },
    /// A `u`, `method` or `payload` tag does not have exactly one value.
    #[error("{tag} tag must have exactly one value")]
    MalformedTag {
        /// The tag name.
        tag: &'static str,
    },
    /// There is no `u` tag.
    #[error("missing u tag")]
    MissingUrlTag,
    /// There is more than one `u` tag.
    #[error("duplicate u tag")]
    DuplicateUrlTag,
    /// There is no `method` tag.
    #[error("missing method tag")]
    MissingMethodTag,
    /// There is more than one `method` tag.
    #[error("duplicate method tag")]
    DuplicateMethodTag,
    /// There is more than one `payload` tag.
    #[error("duplicate payload tag")]
    DuplicatePayloadTag,
    /// The `u` tag is not byte-for-byte the expected URL.
    #[error("signed url does not match the request")]
    UrlMismatch,
    /// The `method` tag is not the expected method.
    #[error("signed method does not match the request")]
    MethodMismatch,
    /// The request has a body but the event has no `payload` tag.
    #[error("request has a body but no payload tag")]
    MissingPayloadTag,
    /// The request has no body but the event has a `payload` tag.
    #[error("request has no body but a payload tag is present")]
    UnexpectedPayloadTag,
    /// The `payload` tag is not 64 lowercase hexadecimal digits.
    #[error("payload tag is not 64 lowercase hex digits")]
    InvalidPayloadTag,
    /// The `payload` tag is not the SHA-256 of the body.
    #[error("payload tag does not match the body")]
    PayloadMismatch,
    /// `created_at` is later than `now` by more than the allowed skew.
    #[error("event created at {created_at} is too far after {now}")]
    CreatedTooFarInFuture {
        /// The signed creation time.
        created_at: UnixTime,
        /// The time the server supplied.
        now: UnixTime,
    },
    /// `created_at` is earlier than `now` by more than the allowed skew.
    #[error("event created at {created_at} is too long before {now}")]
    CreatedTooLongAgo {
        /// The signed creation time.
        created_at: UnixTime,
        /// The time the server supplied.
        now: UnixTime,
    },
}

/// The reasons a [`RequestPolicy`] setting can be refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RequestPolicyError {
    /// The requested clock skew is wider than the profile allows.
    #[error("clock skew {requested:?} is wider than the {max:?} the profile allows")]
    ClockSkewTooWide {
        /// The skew the caller asked for.
        requested: Duration,
        /// The widest skew allowed,
        /// [`RequestPolicy::DEFAULT_MAX_CLOCK_SKEW`].
        max: Duration,
    },
}