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
//! Nostr secret keys and signing.

use std::fmt;

use base64::Engine as _;
use k256::schnorr::SigningKey;
use zeroize::Zeroizing;

use crate::did::DidNostr;
use crate::encoding::{self, Bech32Error};
use crate::event::{SignedEvent, UnsignedEvent};
use crate::id::{Sha256Digest, UnixTime};
use crate::request::{ExpectedRequest, AUTHORIZATION_SCHEME, HTTP_AUTH_KIND};
use crate::schnorr::SchnorrSignError;

/// The NIP-19 human-readable prefix for secret keys.
const NSEC_HRP: &str = "nsec";

/// A secp256k1 secret key used to sign Nostr events with BIP-340.
///
/// The key is zeroised when dropped. It does not implement `Clone`,
/// `Serialize` or `Display`, and its `Debug` output shows only the public
/// principal. This crate offers no way to export the secret again. Zeroising
/// is best effort: temporary copies made on the stack while parsing are not
/// all reachable, and memory dumps and swap are outside what it can promise.
///
/// # Examples
///
/// ```
/// use stratum_node_core::NostrSecretKey;
///
/// # fn main() -> Result<(), stratum_node_core::ParseKeyError> {
/// let key = NostrSecretKey::from_hex(&"03".repeat(32))?;
/// let debug = format!("{key:?}");
/// assert!(!debug.contains(&"03".repeat(32)));
/// assert!(debug.contains(&key.public().to_string()));
/// # Ok(())
/// # }
/// ```
///
/// It cannot be cloned or serialised:
///
/// ```compile_fail
/// fn needs_clone<T: Clone>() {}
/// needs_clone::<stratum_node_core::NostrSecretKey>();
/// ```
///
/// ```compile_fail
/// fn needs_serialize<T: serde::Serialize>() {}
/// needs_serialize::<stratum_node_core::NostrSecretKey>();
/// ```
pub struct NostrSecretKey {
    key: SigningKey,
    public: DidNostr,
}

impl NostrSecretKey {
    /// Builds a key from its 32 big-endian bytes.
    ///
    /// The caller remains responsible for zeroising its own copy.
    ///
    /// # Errors
    ///
    /// Returns [`ParseKeyError::OutOfRange`] when the value is zero or not
    /// below the secp256k1 group order.
    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, ParseKeyError> {
        let key = SigningKey::from_slice(bytes).map_err(|_| ParseKeyError::OutOfRange)?;
        let public_bytes: [u8; 32] = key.verifying_key().to_bytes().into();
        let public = DidNostr::from_bytes(public_bytes).map_err(|_| ParseKeyError::OutOfRange)?;
        Ok(Self { key, public })
    }

    /// Parses a key from 64 lowercase hexadecimal digits.
    ///
    /// # Errors
    ///
    /// Returns [`ParseKeyError::InvalidHex`] for anything other than 64
    /// lowercase hex digits, and [`ParseKeyError::OutOfRange`] as for
    /// [`from_bytes`](Self::from_bytes).
    pub fn from_hex(hex: &str) -> Result<Self, ParseKeyError> {
        let mut bytes = Zeroizing::new([0u8; 32]);
        if !encoding::decode_lower_hex_into(hex, bytes.as_mut_slice()) {
            return Err(ParseKeyError::InvalidHex);
        }
        Self::from_bytes(&bytes)
    }

    /// Parses a NIP-19 `nsec1…` bech32 secret key.
    ///
    /// # Errors
    ///
    /// Returns [`ParseKeyError::InvalidBech32`] for a malformed string, a
    /// bech32m checksum or non-zero padding bits (so each key has exactly
    /// one accepted encoding, up to letter case), [`ParseKeyError::WrongBech32Prefix`] for a prefix
    /// other than `nsec`, [`ParseKeyError::InvalidLength`] when the payload
    /// is not 32 bytes, and [`ParseKeyError::OutOfRange`] as for
    /// [`from_bytes`](Self::from_bytes).
    pub fn from_nsec(nsec: &str) -> Result<Self, ParseKeyError> {
        let mut bytes = Zeroizing::new([0u8; 32]);
        encoding::decode_bech32(nsec, NSEC_HRP, &mut bytes).map_err(|err| match err {
            Bech32Error::Invalid => ParseKeyError::InvalidBech32,
            Bech32Error::WrongPrefix => ParseKeyError::WrongBech32Prefix,
            Bech32Error::WrongLength => ParseKeyError::InvalidLength,
        })?;
        Self::from_bytes(&bytes)
    }

    /// Returns the public principal for this key.
    pub fn public(&self) -> DidNostr {
        self.public
    }

    /// Signs an event.
    ///
    /// `aux_rand` is the 32 bytes of BIP-340 auxiliary randomness. It should
    /// come from a secure random source; BIP-340 signatures stay secure with
    /// fixed auxiliary data, but fresh randomness hardens against
    /// side-channel and fault attacks.
    ///
    /// # Errors
    ///
    /// Returns [`SignError::EmptyTag`] when a tag has no elements,
    /// [`SignError::UnsupportedCharacter`] when the content or a tag holds a
    /// control character this crate cannot serialise as NIP-01 requires (see
    /// [`SignedEvent`](crate::SignedEvent#character-restriction)),
    /// [`SignError::ZeroNonce`] in the negligible case that the derived nonce
    /// is zero, and [`SignError::AuxRandNotUsed`] if the BIP-340 backend did
    /// not take `aux_rand` as its single 32-byte auxiliary input. No
    /// signature is ever made with auxiliary data other than `aux_rand`.
    pub fn sign_event(
        &self,
        event: &UnsignedEvent,
        aux_rand: &[u8; 32],
    ) -> Result<SignedEvent, SignError> {
        if event.has_empty_tag() {
            return Err(SignError::EmptyTag);
        }
        if !event.is_supported_text() {
            return Err(SignError::UnsupportedCharacter);
        }
        let id = event.id_for(&self.public);
        let sig =
            crate::schnorr::sign(&self.key, id.as_bytes(), aux_rand).map_err(|err| match err {
                SchnorrSignError::ZeroNonce => SignError::ZeroNonce,
                SchnorrSignError::AuxRandNotUsed => SignError::AuxRandNotUsed,
            })?;
        Ok(event.clone().into_signed(id, self.public, sig))
    }

    /// Builds and signs a kind-27235 request event and returns the complete
    /// `Authorization` header value, `Nostr <base64 of event JSON>`.
    ///
    /// The event carries a `u` tag with `request.url`, a `method` tag with
    /// `request.method` exactly as given (no case folding: HTTP methods are
    /// case-sensitive, and the verifier compares them byte for byte) and, when `request.body` is `Some`
    /// (even if empty), a `payload` tag with the lowercase hex SHA-256 of the
    /// body. Content is empty. The result passes [`verify_request`] for the
    /// same request within the clock-skew window around `created_at`.
    ///
    /// The event ID covers `created_at` in whole seconds and these tags, not
    /// the signature, so two identical requests signed in the same second
    /// are the same event, and a server that keeps event IDs against replay
    /// refuses the second. A client that may repeat a request within a second
    /// should use [`sign_request_with_nonce`](Self::sign_request_with_nonce).
    ///
    /// [`verify_request`]: crate::verify_request
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let key = NostrSecretKey::from_hex(&"04".repeat(32))?;
    /// let request = ExpectedRequest::new("POST", "http://127.0.0.1:7070/api/v1/config/apply", Some(b"{}"));
    /// let now = UnixTime::from_secs(1_700_000_000);
    /// let header = key.sign_request(&request, now, &[0u8; 32])?;
    /// let verified = verify_request(&header, &request, now, &RequestPolicy::new())?;
    /// assert_eq!(verified.signer(), key.public());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// As for [`sign_event`](Self::sign_event); a URL containing an
    /// unsupported control character gives [`SignError::UnsupportedCharacter`].
    pub fn sign_request(
        &self,
        request: &ExpectedRequest<'_>,
        created_at: UnixTime,
        aux_rand: &[u8; 32],
    ) -> Result<String, SignError> {
        self.sign_request_tagged(request, created_at, None, aux_rand)
    }

    /// As [`sign_request`](Self::sign_request), with one more tag,
    /// `["nonce", <32 lowercase hex digits of nonce>]`, after the others
    /// (after `payload` when there is a body, otherwise after `method`).
    ///
    /// A request event's ID covers the whole-second `created_at`, the URL,
    /// the method and the body digest, but not the signature. Without a
    /// nonce, two identical requests signed in one second are one event,
    /// and a server that keeps event IDs for replay protection refuses the
    /// second. A distinct nonce makes each signing a distinct event, so a
    /// client need not wait for the clock to move on.
    ///
    /// `nonce` should be 16 fresh bytes from the operating system's random
    /// source for every request; this crate never reads a random source
    /// itself, so it is a parameter. It is not secret: it travels in the
    /// clear inside the header and only has to differ between requests.
    /// [`verify_request`] and [`verify_request_without_body`] ignore tags
    /// outside the profile, so they accept the result exactly as they accept
    /// one from [`sign_request`](Self::sign_request).
    ///
    /// [`verify_request`]: crate::verify_request
    /// [`verify_request_without_body`]: crate::verify_request_without_body
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let key = NostrSecretKey::from_hex(&"04".repeat(32))?;
    /// let request = ExpectedRequest::new("GET", "http://127.0.0.1:7070/api/v1/status", None);
    /// let now = UnixTime::from_secs(1_700_000_000);
    /// // In real use each nonce comes from the OS random source.
    /// let first = key.sign_request_with_nonce(&request, now, &[1; 16], &[0; 32])?;
    /// let second = key.sign_request_with_nonce(&request, now, &[2; 16], &[0; 32])?;
    /// let policy = RequestPolicy::new();
    /// let first = verify_request(&first, &request, now, &policy)?;
    /// let second = verify_request(&second, &request, now, &policy)?;
    /// assert_ne!(first.event_id(), second.event_id(), "same second, two events");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// As for [`sign_request`](Self::sign_request).
    pub fn sign_request_with_nonce(
        &self,
        request: &ExpectedRequest<'_>,
        created_at: UnixTime,
        nonce: &[u8; 16],
        aux_rand: &[u8; 32],
    ) -> Result<String, SignError> {
        self.sign_request_tagged(request, created_at, Some(nonce), aux_rand)
    }

    /// The body of [`sign_request`](Self::sign_request) and
    /// [`sign_request_with_nonce`](Self::sign_request_with_nonce).
    fn sign_request_tagged(
        &self,
        request: &ExpectedRequest<'_>,
        created_at: UnixTime,
        nonce: Option<&[u8; 16]>,
        aux_rand: &[u8; 32],
    ) -> Result<String, SignError> {
        let mut event = UnsignedEvent::new(HTTP_AUTH_KIND, created_at)
            .with_tag(["u", request.url])
            .with_tag(["method", request.method]);
        if let Some(body) = request.body {
            event = event.with_tag(["payload".to_owned(), Sha256Digest::of(body).to_hex()]);
        }
        if let Some(nonce) = nonce {
            event = event.with_tag(["nonce".to_owned(), hex::encode(nonce)]);
        }
        let signed = self.sign_event(&event, aux_rand)?;
        let token = base64::engine::general_purpose::STANDARD.encode(signed.to_json());
        Ok(format!("{AUTHORIZATION_SCHEME} {token}"))
    }
}

impl fmt::Debug for NostrSecretKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NostrSecretKey")
            .field("public", &self.public)
            .finish_non_exhaustive()
    }
}

/// The reasons a secret key can fail to parse.
///
/// No variant carries any part of the input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseKeyError {
    /// The text is not exactly 64 lowercase hexadecimal digits.
    #[error("secret key is not 64 lowercase hex digits")]
    InvalidHex,
    /// The string is not valid bech32 with a bech32 (not bech32m) checksum
    /// and zero padding bits.
    #[error("invalid bech32 secret key")]
    InvalidBech32,
    /// The bech32 prefix is not `nsec`.
    #[error("bech32 prefix is not nsec")]
    WrongBech32Prefix,
    /// The decoded payload is not 32 bytes.
    #[error("secret key is not 32 bytes")]
    InvalidLength,
    /// The value is zero or not below the secp256k1 group order.
    #[error("secret key is out of range")]
    OutOfRange,
}

/// The reasons signing can fail.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SignError {
    /// The content or a tag contains a control character outside the set
    /// NIP-01 escapes by name; see
    /// [`SignedEvent`](crate::SignedEvent#character-restriction).
    #[error("event text contains an unsupported control character")]
    UnsupportedCharacter,
    /// A tag has no elements; NIP-01 requires at least one.
    #[error("event has an empty tag")]
    EmptyTag,
    /// The BIP-340 nonce derived from this key, message and auxiliary
    /// randomness is zero. The probability is negligible; retry with fresh
    /// auxiliary randomness.
    #[error("derived signing nonce is zero; retry with fresh auxiliary randomness")]
    ZeroNonce,
    /// The BIP-340 backend did not take the auxiliary randomness as exactly
    /// one 32-byte draw, so no signature is returned rather than one made
    /// with substitute auxiliary data. This points at an incompatible
    /// dependency version, not at the input; retrying does not help.
    #[error("signing backend did not take the auxiliary randomness as one 32-byte draw")]
    AuxRandNotUsed,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::request::{RequestPolicy, RequestTarget};
    use crate::{verify_request, verify_request_without_body};

    const URL: &str = "http://127.0.0.1:7070/api/v1/config/apply";
    const AT: UnixTime = UnixTime::from_secs(1_700_000_000);

    fn key() -> NostrSecretKey {
        NostrSecretKey::from_hex(&"05".repeat(32)).expect("key")
    }

    /// The verified event inside an `Authorization` value.
    fn event(header: &str) -> SignedEvent {
        let token = header.strip_prefix("Nostr ").expect("scheme");
        let json = base64::engine::general_purpose::STANDARD
            .decode(token)
            .expect("base64");
        SignedEvent::from_json(&json).expect("valid event")
    }

    #[test]
    fn different_nonces_in_one_second_are_different_events() {
        let request = ExpectedRequest::new("POST", URL, Some(b"{}"));
        let a = key()
            .sign_request_with_nonce(&request, AT, &[1; 16], &[0; 32])
            .expect("signs");
        let b = key()
            .sign_request_with_nonce(&request, AT, &[2; 16], &[0; 32])
            .expect("signs");
        assert_ne!(event(&a).id(), event(&b).id());
    }

    #[test]
    fn the_same_nonce_is_the_same_event_whatever_the_aux_rand() {
        let request = ExpectedRequest::new("POST", URL, Some(b"{}"));
        let a = key()
            .sign_request_with_nonce(&request, AT, &[7; 16], &[0; 32])
            .expect("signs");
        let b = key()
            .sign_request_with_nonce(&request, AT, &[7; 16], &[9; 32])
            .expect("signs");
        assert_ne!(a, b, "the signatures differ");
        assert_eq!(event(&a).id(), event(&b).id());
    }

    #[test]
    fn a_nonce_signed_request_verifies_with_and_without_the_body() {
        let policy = RequestPolicy::new();
        for (method, body) in [("PUT", Some(&b"hello"[..])), ("GET", None)] {
            let request = ExpectedRequest::new(method, URL, body);
            let header = key()
                .sign_request_with_nonce(&request, AT, &[3; 16], &[0; 32])
                .expect("signs");
            let full = verify_request(&header, &request, AT, &policy).expect("verifies");
            assert_eq!(full.signer(), key().public());
            let unchecked =
                verify_request_without_body(&header, &RequestTarget::new(method, URL), AT, &policy)
                    .expect("verifies without body");
            assert_eq!(unchecked.event_id(), full.event_id());
        }
    }

    #[test]
    fn the_nonce_tag_comes_last() {
        let nonce = [0xab; 16];
        let post = key()
            .sign_request_with_nonce(
                &ExpectedRequest::new("POST", URL, Some(b"{}")),
                AT,
                &nonce,
                &[0; 32],
            )
            .expect("signs");
        let tags = event(&post).tags().to_vec();
        assert_eq!(tags.len(), 4, "{tags:?}");
        assert_eq!(tags[0], ["u", URL]);
        assert_eq!(tags[1], ["method", "POST"]);
        assert_eq!(tags[2][0], "payload");
        assert_eq!(tags[3], ["nonce", "ab".repeat(16).as_str()]);

        let get = key()
            .sign_request_with_nonce(
                &ExpectedRequest::new("GET", URL, None),
                AT,
                &nonce,
                &[0; 32],
            )
            .expect("signs");
        let tags = event(&get).tags().to_vec();
        assert_eq!(tags.len(), 3, "{tags:?}");
        assert_eq!(tags[2], ["nonce", "ab".repeat(16).as_str()]);
    }

    #[test]
    fn sign_request_carries_no_nonce() {
        let header = key()
            .sign_request(&ExpectedRequest::new("GET", URL, None), AT, &[0; 32])
            .expect("signs");
        let tags = event(&header).tags().to_vec();
        assert_eq!(tags.len(), 2, "{tags:?}");
        assert!(tags.iter().all(|tag| tag[0] != "nonce"));
    }
}