stratum-node-core 0.1.0-alpha.1

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
//! 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, 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> {
    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);
    }
    let json = base64::engine::general_purpose::STANDARD
        .decode(token.trim_start_matches(' '))
        .map_err(|_| VerifyRequestError::InvalidBase64)?;
    let event = SignedEvent::from_json(&json)?;

    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 != expected.url {
        return Err(VerifyRequestError::UrlMismatch);
    }
    if method != expected.method {
        return Err(VerifyRequestError::MethodMismatch);
    }
    let payload = match (expected.body, tags.payload) {
        (Some(body), Some(tag)) => {
            if !(tag.len() == 64 && encoding::is_lower_hex(tag)) {
                return Err(VerifyRequestError::InvalidPayloadTag);
            }
            let digest = Sha256Digest::of(body);
            if digest.to_hex() != tag {
                return Err(VerifyRequestError::PayloadMismatch);
            }
            Some(digest)
        }
        (Some(_), None) => return Err(VerifyRequestError::MissingPayloadTag),
        (None, Some(_)) => return Err(VerifyRequestError::UnexpectedPayloadTag),
        (None, None) => None,
    };

    let created_at = event.created_at();
    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(VerifiedRequest {
        signer: event.author(),
        event_id: event.id(),
        created_at,
        payload,
    })
}

/// 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,
    },
}