Skip to main content

nautilus_lighter/signing/
auth_token.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Lighter REST/WebSocket auth-token builder.
17//!
18//! The Lighter venue authenticates long-running clients against a Schnorr
19//! signature over an ASCII message describing `(deadline, account_index,
20//! api_key_index)`. The signed string is sent verbatim in the `Authorization`
21//! header and on the WebSocket subscribe handshake.
22//!
23//! Pipeline (matching the Go reference `ConstructAuthToken`):
24//!
25//! 1. Render `message = "{deadline}:{account_index}:{api_key_index}"`.
26//! 2. Split the ASCII bytes into 8-byte little-endian chunks, zero-padding the
27//!    final chunk if needed, and decode each chunk as a canonical Goldilocks
28//!    `Fp` element.
29//! 3. Run [`hash_to_quintic_extension`] over the resulting `[Fp]` to derive a
30//!    single `Fp5` digest.
31//! 4. Sign with the supplied `(sk, k)` using the standard Schnorr binding.
32//! 5. Concatenate `"{message}:{hex(sig)}"` where `sig` is the canonical
33//!    80-byte `s_le || e_le` Schnorr layout encoded as lowercase hex.
34//!
35//! The hash path here is not the body-element pipeline `tx::compute_tx_hash`
36//! uses; the auth token treats the message as opaque ASCII and packs it into
37//! limbs by raw little-endian bytes, while transactions encode each field as
38//! an `Fp`-domain integer.
39
40use std::{
41    fmt::Write,
42    time::{SystemTime, UNIX_EPOCH},
43};
44
45use anyhow::Context;
46use nautilus_core::string::secret::SecretString;
47use rand::{TryRng, rngs::SysRng};
48use thiserror::Error;
49
50use crate::{
51    common::consts::LIGHTER_AUTH_TOKEN_MAX_TTL,
52    signing::{
53        curve::{SCALAR_BYTES, Scalar},
54        field::Fp,
55        hash::hash_to_quintic_extension,
56        schnorr::{PrivateKey, SIG_BYTES},
57    },
58};
59
60/// Errors raised by [`build_auth_token`].
61#[derive(Debug, Error, PartialEq, Eq)]
62pub enum AuthTokenError {
63    /// The supplied deadline is at or before `now`.
64    #[error("auth-token deadline {deadline} is not in the future of now {now}")]
65    DeadlineNotInFuture {
66        /// Caller-supplied deadline (UNIX seconds).
67        deadline: i64,
68        /// Reference `now` (UNIX seconds).
69        now: i64,
70    },
71    /// The supplied deadline exceeds the venue's maximum TTL.
72    #[error("auth-token deadline {deadline} exceeds max TTL {max_ttl_secs}s from now {now}")]
73    TtlTooLarge {
74        /// Caller-supplied deadline (UNIX seconds).
75        deadline: i64,
76        /// Reference `now` (UNIX seconds).
77        now: i64,
78        /// Configured maximum TTL in seconds.
79        max_ttl_secs: i64,
80    },
81    /// The system clock is before the UNIX epoch.
82    #[error("system clock is before UNIX epoch")]
83    ClockBeforeEpoch,
84    /// An 8-byte chunk of the message decoded to a non-canonical Goldilocks
85    /// element (`>= p`).
86    ///
87    /// Cannot occur for the auth-token format (`"{deadline}:{account}:{key}"`)
88    /// since every byte is ASCII; surfaced as a typed error rather than a
89    /// panic so callers of [`hash_auth_message`] with arbitrary input get a
90    /// recoverable failure.
91    #[error("non-canonical Goldilocks limb at byte offset {offset}")]
92    MessageEncoding {
93        /// Byte offset of the offending 8-byte chunk in the input.
94        offset: usize,
95    },
96}
97
98/// Default deadline applied by [`build_auth_token_for`] when the caller does
99/// not supply one: 7 hours from the current wall clock. Sits inside the
100/// venue's [`LIGHTER_AUTH_TOKEN_MAX_TTL`] (8 hours) with an hour of head room
101/// so a long-running session can pre-fetch and rotate before expiry.
102pub const DEFAULT_AUTH_TOKEN_TTL_SECS: i64 = 7 * 60 * 60;
103
104/// Mint an auth token from a [`crate::common::credential::Credential`] using
105/// the default 7-hour TTL and a fresh CSPRNG nonce.
106///
107/// The token format matches the Go reference's `ConstructAuthToken`. The
108/// returned string is the value the WebSocket subscribe handshake sends in
109/// the `auth` field of an `account_*` channel subscription.
110///
111/// # Errors
112///
113/// Returns an error if the private key cannot be decoded, the system clock predates the UNIX epoch,
114/// deadline computation or validation fails, or the operating system's random number source fails.
115pub fn build_auth_token_for(
116    credential: &crate::common::credential::Credential,
117) -> anyhow::Result<SecretString> {
118    let now = SystemTime::now()
119        .duration_since(UNIX_EPOCH)
120        .map_err(|_| anyhow::anyhow!("system clock is before UNIX epoch"))?
121        .as_secs();
122    let now_i64 = i64::try_from(now)
123        .map_err(|_| anyhow::anyhow!("system clock overflowed when converting to i64"))?;
124    let deadline = now_i64
125        .checked_add(DEFAULT_AUTH_TOKEN_TTL_SECS)
126        .ok_or_else(|| anyhow::anyhow!("deadline computation overflowed"))?;
127    let sk = credential.private_key()?;
128    build_auth_token(
129        deadline,
130        credential.account_index(),
131        credential.api_key_index(),
132        &sk,
133        fresh_k()?,
134    )
135    .map_err(|e| anyhow::anyhow!("failed to mint Lighter auth token: {e}"))
136}
137
138/// Draws a fresh nonzero canonical [`Scalar`] from the operating system's
139/// cryptographic random number source for the per-signature `k` nonce.
140///
141/// The Schnorr binding requires `k` to be drawn from a cryptographic RNG and
142/// used at most once per signature; see [`PrivateKey::sign`] for the full
143/// contract. Rejection sampling gives a uniform scalar in `[1, n)`, where
144/// `n` is the curve order. Direct OS randomness avoids duplicating a userspace RNG's state
145/// across a process fork.
146///
147/// # Errors
148///
149/// Returns an error if the operating system's random number source fails.
150pub fn fresh_k() -> anyhow::Result<Scalar> {
151    let mut bytes = [0u8; SCALAR_BYTES];
152
153    loop {
154        SysRng
155            .try_fill_bytes(&mut bytes)
156            .context("failed to draw Lighter signing nonce")?;
157        let k = Scalar::from_le_bytes_reduce(bytes);
158        if !k.is_zero() && k.to_le_bytes() == bytes {
159            return Ok(k);
160        }
161    }
162}
163
164/// Build a Lighter auth token using the system clock as the `now` reference.
165///
166/// Validates the deadline against [`LIGHTER_AUTH_TOKEN_MAX_TTL`]. See
167/// [`build_auth_token_at`] for an injectable-`now` variant suitable for tests.
168///
169/// # Errors
170///
171/// Returns an error if `deadline_unix_secs <= now`, if it exceeds the venue cap, or if the system
172/// clock predates the UNIX epoch.
173pub fn build_auth_token(
174    deadline_unix_secs: i64,
175    account_index: i64,
176    api_key_index: u8,
177    sk: &PrivateKey,
178    k: Scalar,
179) -> Result<SecretString, AuthTokenError> {
180    let now = SystemTime::now()
181        .duration_since(UNIX_EPOCH)
182        .map_err(|_| AuthTokenError::ClockBeforeEpoch)?
183        .as_secs();
184    let now_i64 = i64::try_from(now).map_err(|_| AuthTokenError::ClockBeforeEpoch)?;
185    build_auth_token_at(
186        now_i64,
187        deadline_unix_secs,
188        account_index,
189        api_key_index,
190        sk,
191        k,
192    )
193}
194
195/// Variant of [`build_auth_token`] accepting an explicit `now_unix_secs`.
196///
197/// Pure of `SystemTime`, so callers can drive the validation deterministically
198/// from a wall-clock provider or a test fixture. Same error semantics as
199/// [`build_auth_token`].
200///
201/// # Errors
202///
203/// Returns an error if [`build_auth_token`] fails.
204pub fn build_auth_token_at(
205    now_unix_secs: i64,
206    deadline_unix_secs: i64,
207    account_index: i64,
208    api_key_index: u8,
209    sk: &PrivateKey,
210    k: Scalar,
211) -> Result<SecretString, AuthTokenError> {
212    if deadline_unix_secs <= now_unix_secs {
213        return Err(AuthTokenError::DeadlineNotInFuture {
214            deadline: deadline_unix_secs,
215            now: now_unix_secs,
216        });
217    }
218
219    let ttl_secs = deadline_unix_secs - now_unix_secs;
220    let max_ttl_secs = i64::try_from(LIGHTER_AUTH_TOKEN_MAX_TTL.as_secs()).unwrap_or(i64::MAX);
221
222    if ttl_secs > max_ttl_secs {
223        return Err(AuthTokenError::TtlTooLarge {
224            deadline: deadline_unix_secs,
225            now: now_unix_secs,
226            max_ttl_secs,
227        });
228    }
229
230    build_auth_token_unchecked(deadline_unix_secs, account_index, api_key_index, sk, k)
231}
232
233/// Sign the auth-token message without TTL validation.
234///
235/// Public so tests and oracle round-trips can produce tokens whose deadline
236/// would otherwise trip the venue cap. Production callers should use
237/// [`build_auth_token`] or [`build_auth_token_at`].
238///
239/// # Errors
240///
241/// Returns an error if the rendered message contains an 8-byte chunk that does not decode as a
242/// canonical Goldilocks element. The auth-token format keeps every byte ASCII, so this case is
243/// unreachable for the production callers.
244pub fn build_auth_token_unchecked(
245    deadline_unix_secs: i64,
246    account_index: i64,
247    api_key_index: u8,
248    sk: &PrivateKey,
249    k: Scalar,
250) -> Result<SecretString, AuthTokenError> {
251    let message = auth_token_message(deadline_unix_secs, account_index, api_key_index);
252    let sig = sign_message(&message, sk, k)?;
253    Ok(format_token(&message, &sig))
254}
255
256/// ASCII auth-token message: `"{deadline}:{account}:{api_key}"`.
257///
258/// Public for the rare caller that needs to recompute the signed preimage
259/// (e.g., to verify a token against a known public key). The message format
260/// matches the Go reference verbatim.
261#[must_use]
262pub fn auth_token_message(
263    deadline_unix_secs: i64,
264    account_index: i64,
265    api_key_index: u8,
266) -> String {
267    format!("{deadline_unix_secs}:{account_index}:{api_key_index}")
268}
269
270/// Hash the auth-token ASCII message to its 40-byte `Fp5` digest.
271///
272/// Splits the bytes into 8-byte little-endian Goldilocks limbs (zero-padding
273/// the trailing chunk) and runs [`hash_to_quintic_extension`] over the limbs.
274/// Returns the canonical 40-byte little-endian encoding the Schnorr binding
275/// signs over.
276///
277/// # Errors
278///
279/// Returns an error if any 8-byte chunk decodes to a non-canonical Goldilocks element. The
280/// auth-token format is ASCII (`'0'..='9'` and `':'`), so every byte sits in `0..=0x3A` and the
281/// case is unreachable for tokens emitted by [`auth_token_message`]; the error path exists for
282/// callers that pass arbitrary preimages.
283pub fn hash_auth_message(message: &str) -> Result<[u8; 40], AuthTokenError> {
284    let elems = ascii_to_fp_limbs(message.as_bytes())?;
285    Ok(hash_to_quintic_extension(&elems).to_le_bytes())
286}
287
288fn sign_message(
289    message: &str,
290    sk: &PrivateKey,
291    k: Scalar,
292) -> Result<[u8; SIG_BYTES], AuthTokenError> {
293    let elems = ascii_to_fp_limbs(message.as_bytes())?;
294    let digest = hash_to_quintic_extension(&elems);
295    Ok(sk.sign(digest, k).to_le_bytes())
296}
297
298fn ascii_to_fp_limbs(bytes: &[u8]) -> Result<Vec<Fp>, AuthTokenError> {
299    let mut out = Vec::with_capacity(bytes.len().div_ceil(8));
300    let mut i = 0;
301
302    while i < bytes.len() {
303        let end = core::cmp::min(i + 8, bytes.len());
304        let mut limb = [0u8; 8];
305        limb[..end - i].copy_from_slice(&bytes[i..end]);
306        let fp =
307            Fp::try_from_le_bytes(limb).ok_or(AuthTokenError::MessageEncoding { offset: i })?;
308        out.push(fp);
309        i = end;
310    }
311
312    Ok(out)
313}
314
315fn format_token(message: &str, sig: &[u8; SIG_BYTES]) -> SecretString {
316    // Lowercase, no `0x` prefix: matches `ethCommon.Bytes2Hex` in the Go
317    // reference, which is what the venue's REST/WS handshake expects.
318    let mut out = String::with_capacity(message.len() + 1 + SIG_BYTES * 2);
319    out.push_str(message);
320    out.push(':');
321    for b in sig {
322        write!(&mut out, "{b:02x}").expect("writing into String never fails");
323    }
324    out.into()
325}
326
327#[cfg(test)]
328mod tests {
329    use proptest::prelude::*;
330    use rstest::rstest;
331
332    use super::*;
333    use crate::signing::{
334        curve::SCALAR_BYTES, field::Fp5, fixtures::hex_to_array, schnorr::Signature,
335    };
336
337    fn fixed_sk() -> PrivateKey {
338        // Same seed bytes as the tx-oracle fixture; keeps the auth-token
339        // tests self-contained without piggybacking on the tx fixture file.
340        let bytes: [u8; SCALAR_BYTES] = [
341            0x0b, 0x8e, 0x0f, 0x63, 0xc2, 0x4d, 0x8b, 0xaa, 0xcd, 0x9d, 0x29, 0xad, 0x4e, 0x9a,
342            0x4b, 0x73, 0xc4, 0xa8, 0xd2, 0xbb, 0x8b, 0x16, 0xdc, 0x4f, 0xa9, 0xd7, 0xc2, 0xe1,
343            0xd3, 0xa8, 0xb1, 0xf0, 0xe8, 0xd3, 0xa4, 0xc5, 0xb6, 0xe7, 0xf0, 0x01,
344        ];
345        PrivateKey::from_le_bytes_reduce(bytes)
346    }
347
348    fn nonzero_k() -> Scalar {
349        let mut bytes = [0u8; SCALAR_BYTES];
350        bytes[0] = 0x42;
351        bytes[7] = 0x01;
352        Scalar::from_le_bytes_reduce(bytes)
353    }
354
355    #[rstest]
356    fn message_format_matches_go_reference() {
357        let m = auth_token_message(1_777_809_907, 12345, 5);
358        assert_eq!(m, "1777809907:12345:5", "was {m}");
359    }
360
361    #[rstest]
362    fn build_auth_token_smoke_test() {
363        // Smoke-test the system-clock variant: seed a deadline 600s ahead of
364        // wall-clock now and verify the token's structural shape. The signing
365        // pipeline is exercised by the *_at variant; this test just gates the
366        // SystemTime plumbing and Result threading.
367        let now = SystemTime::now()
368            .duration_since(UNIX_EPOCH)
369            .unwrap()
370            .as_secs();
371        let now_i64 = i64::try_from(now).unwrap();
372        let deadline = now_i64 + 600;
373        let account_index = 12345i64;
374        let api_key_index = 5u8;
375        let token = build_auth_token(
376            deadline,
377            account_index,
378            api_key_index,
379            &fixed_sk(),
380            nonzero_k(),
381        )
382        .expect("future deadline must sign");
383        let token = token.expose_secret();
384
385        let prefix = format!("{deadline}:{account_index}:{api_key_index}:");
386        assert!(
387            token.starts_with(&prefix),
388            "token must start with deadline:account:key:, was {token}",
389        );
390        let sig_hex = &token[prefix.len()..];
391        assert_eq!(
392            sig_hex.len(),
393            SIG_BYTES * 2,
394            "hex sig must span 160 chars, was {}",
395            sig_hex.len(),
396        );
397    }
398
399    #[rstest]
400    fn token_is_message_colon_hex_sig() {
401        let token =
402            build_auth_token_at(1_000_000, 1_000_300, 12345, 5, &fixed_sk(), nonzero_k()).unwrap();
403        let token = token.expose_secret();
404        let mut parts = token.rsplitn(2, ':');
405        let sig_hex = parts.next().expect("token must have sig component");
406        let prefix = parts.next().expect("token must have message prefix");
407
408        assert_eq!(prefix, "1000300:12345:5", "was {prefix}");
409        assert_eq!(
410            sig_hex.len(),
411            SIG_BYTES * 2,
412            "hex sig must span 160 chars, was {}",
413            sig_hex.len(),
414        );
415        assert!(
416            sig_hex
417                .chars()
418                .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()),
419            "sig must be lowercase hex, was {sig_hex}",
420        );
421    }
422
423    #[rstest]
424    fn token_signature_verifies_under_derived_pubkey() {
425        let sk = fixed_sk();
426        let pk = sk.public_key();
427        let deadline = 1_000_300;
428        let token = build_auth_token_at(1_000_000, deadline, 12345, 5, &sk, nonzero_k()).unwrap();
429
430        let (message, sig_hex) = split_token(token.expose_secret());
431        let digest_bytes = hash_auth_message(&message).expect("ASCII input must hash");
432        let digest = Fp5::try_from_le_bytes(digest_bytes).expect("digest must be canonical");
433        let sig = decode_sig(&sig_hex);
434
435        assert!(
436            pk.verify(digest, &sig),
437            "self-issued token must verify under derived pubkey",
438        );
439    }
440
441    #[rstest]
442    fn deadline_in_past_errors() {
443        let err = build_auth_token_at(1_000, 999, 1, 0, &fixed_sk(), nonzero_k())
444            .expect_err("must reject past deadline");
445        assert_eq!(
446            err,
447            AuthTokenError::DeadlineNotInFuture {
448                deadline: 999,
449                now: 1_000,
450            },
451        );
452    }
453
454    #[rstest]
455    fn deadline_equal_to_now_errors() {
456        let err = build_auth_token_at(1_000, 1_000, 1, 0, &fixed_sk(), nonzero_k())
457            .expect_err("must reject equal deadline");
458        assert_eq!(
459            err,
460            AuthTokenError::DeadlineNotInFuture {
461                deadline: 1_000,
462                now: 1_000,
463            },
464        );
465    }
466
467    #[rstest]
468    fn deadline_beyond_max_ttl_errors() {
469        let now = 1_000_000;
470        let max_ttl = i64::try_from(LIGHTER_AUTH_TOKEN_MAX_TTL.as_secs()).unwrap();
471        let deadline = now + max_ttl + 1;
472        let err = build_auth_token_at(now, deadline, 1, 0, &fixed_sk(), nonzero_k())
473            .expect_err("must reject TTL above cap");
474        assert_eq!(
475            err,
476            AuthTokenError::TtlTooLarge {
477                deadline,
478                now,
479                max_ttl_secs: max_ttl,
480            },
481        );
482    }
483
484    #[rstest]
485    fn deadline_at_max_ttl_succeeds() {
486        let now = 1_000_000;
487        let max_ttl = i64::try_from(LIGHTER_AUTH_TOKEN_MAX_TTL.as_secs()).unwrap();
488        let deadline = now + max_ttl;
489        let token = build_auth_token_at(now, deadline, 1, 0, &fixed_sk(), nonzero_k())
490            .expect("max-TTL deadline must sign");
491        let token = token.expose_secret();
492        assert!(
493            token.starts_with(&format!("{deadline}:1:0:")),
494            "was {token}"
495        );
496    }
497
498    #[rstest]
499    fn hash_input_packs_eight_bytes_per_limb() {
500        // "abc" -> single limb [0x61, 0x62, 0x63, 0, 0, 0, 0, 0].
501        let elems = super::ascii_to_fp_limbs(b"abc").expect("ASCII input must encode");
502        assert_eq!(elems.len(), 1);
503        let limb = u64::from_le_bytes([b'a', b'b', b'c', 0, 0, 0, 0, 0]);
504        assert_eq!(elems[0].to_u64(), limb);
505
506        // 9 bytes spill into two limbs: first full, second carries one byte.
507        let elems = super::ascii_to_fp_limbs(b"abcdefghI").expect("ASCII input must encode");
508        assert_eq!(elems.len(), 2);
509        assert_eq!(elems[1].to_u64(), u64::from(b'I'));
510    }
511
512    #[rstest]
513    fn hash_input_rejects_non_canonical_limb() {
514        // u64::MAX > MODULUS so the 8-byte chunk is non-canonical.
515        let mut bytes = [0xFFu8; 8];
516        bytes[7] = 0xFF;
517        let err = super::ascii_to_fp_limbs(&bytes).expect_err("must reject non-canonical");
518        assert_eq!(err, AuthTokenError::MessageEncoding { offset: 0 });
519    }
520
521    fn split_token(token: &str) -> (String, String) {
522        let mut parts = token.rsplitn(2, ':');
523        let sig_hex = parts.next().unwrap().to_string();
524        let message = parts.next().unwrap().to_string();
525        (message, sig_hex)
526    }
527
528    fn decode_sig(hex: &str) -> Signature {
529        assert_eq!(hex.len(), SIG_BYTES * 2);
530        let mut buf = [0u8; SIG_BYTES];
531        for (i, slot) in buf.iter_mut().enumerate() {
532            *slot = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).unwrap();
533        }
534        Signature::from_le_bytes_reduce(buf)
535    }
536
537    proptest! {
538        /// Any ASCII (high-bit-clear) byte sequence packs into Fp limbs and
539        /// unpacks back to the original bytes, zero-padded on the right to a
540        /// multiple of 8. ASCII bytes keep each 8-byte chunk's `u64` strictly
541        /// below the Goldilocks modulus, so encoding never errors.
542        #[rstest]
543        fn prop_ascii_to_fp_limbs_round_trip(
544            input in proptest::collection::vec(0u8..=0x7F, 0..64),
545        ) {
546            let limbs = super::ascii_to_fp_limbs(&input).expect("ASCII input must encode");
547            prop_assert_eq!(limbs.len(), input.len().div_ceil(8));
548
549            let mut unpacked = Vec::with_capacity(limbs.len() * 8);
550            for fp in &limbs {
551                unpacked.extend_from_slice(&fp.to_u64().to_le_bytes());
552            }
553
554            let mut padded = input;
555            while padded.len() % 8 != 0 {
556                padded.push(0);
557            }
558            prop_assert_eq!(unpacked, padded);
559        }
560
561        /// `hash_auth_message` is deterministic over arbitrary ASCII inputs.
562        #[rstest]
563        fn prop_hash_auth_message_deterministic(s in "[ -~]{0,128}") {
564            let h1 = super::hash_auth_message(&s).expect("ASCII must hash");
565            let h2 = super::hash_auth_message(&s).expect("ASCII must hash");
566            prop_assert_eq!(h1, h2);
567        }
568
569        /// Self-issued tokens always verify under the derived public key for
570        /// any non-zero `k` and any in-range deadline.
571        #[rstest]
572        fn prop_self_issued_token_verifies(
573            account_index in 0i64..1_000_000_000,
574            api_key_index in 0u8..=255,
575            ttl_secs in 1i64..(LIGHTER_AUTH_TOKEN_MAX_TTL.as_secs() as i64),
576            k_seed in 1u64..u64::MAX,
577        ) {
578            let sk = fixed_sk();
579            let pk = sk.public_key();
580            let now = 1_700_000_000;
581            let deadline = now + ttl_secs;
582
583            let mut k_bytes = [0u8; SCALAR_BYTES];
584            k_bytes[..8].copy_from_slice(&k_seed.to_le_bytes());
585            let k = Scalar::from_le_bytes_reduce(k_bytes);
586            prop_assume!(!k.is_zero());
587
588            let token = build_auth_token_at(
589                now, deadline, account_index, api_key_index, &sk, k,
590            )
591            .unwrap();
592            let (message, sig_hex) = split_token(token.expose_secret());
593            let expected = format!("{deadline}:{account_index}:{api_key_index}");
594            prop_assert_eq!(&message, &expected);
595
596            let digest_bytes = hash_auth_message(&message).expect("ASCII input must hash");
597            let digest = Fp5::try_from_le_bytes(digest_bytes).unwrap();
598            let sig = decode_sig(&sig_hex);
599            prop_assert!(pk.verify(digest, &sig));
600        }
601    }
602
603    /// Layer 2 oracle: the closed-source signer's auth tokens must verify
604    /// under the same public key our `PrivateKey::sign` derives, against the
605    /// same `hash_auth_message` digest.
606    #[rstest]
607    fn oracle_auth_tokens_verify_against_our_hash() {
608        const ORACLE_JSON: &str = include_str!(concat!(
609            env!("CARGO_MANIFEST_DIR"),
610            "/test_data/signing_auth_token_oracle.json",
611        ));
612
613        #[derive(serde::Deserialize)]
614        struct File {
615            vectors: Vec<Vector>,
616        }
617
618        #[derive(serde::Deserialize)]
619        struct Vector {
620            sk: String,
621            account_index: i64,
622            api_key_index: u8,
623            deadline: i64,
624            token: String,
625        }
626
627        let suite: File = serde_json::from_str(ORACLE_JSON).expect("parse oracle");
628        assert!(!suite.vectors.is_empty(), "oracle vectors empty");
629
630        for (i, v) in suite.vectors.iter().enumerate() {
631            let sk_bytes = hex_to_array::<SCALAR_BYTES>(&v.sk);
632            let sk = PrivateKey::from_le_bytes_reduce(sk_bytes);
633            let pk = sk.public_key();
634
635            let expected_message = auth_token_message(v.deadline, v.account_index, v.api_key_index);
636            let (message, sig_hex) = split_token(&v.token);
637            assert_eq!(
638                message, expected_message,
639                "vector {i}: token prefix diverged, was {message}",
640            );
641
642            let digest_bytes = hash_auth_message(&message).expect("oracle message must hash");
643            let digest =
644                Fp5::try_from_le_bytes(digest_bytes).expect("auth-token digest must be canonical");
645            let sig = decode_sig(&sig_hex);
646            assert!(
647                pk.verify(digest, &sig),
648                "vector {i}: oracle sig must verify against our recomputed digest",
649            );
650        }
651    }
652
653    #[rstest]
654    fn fresh_k_returns_canonical_nonzero_scalar() {
655        for _ in 0..16 {
656            let k = fresh_k().unwrap();
657            assert!(
658                k.is_canonical(),
659                "fresh_k must return a canonical scalar, was {k:?}",
660            );
661            assert!(!k.is_zero(), "fresh_k must return a nonzero scalar");
662        }
663    }
664
665    #[rstest]
666    fn fresh_k_yields_distinct_scalars() {
667        // A collision in three draws from the 319-bit scalar field is negligible
668        let a = fresh_k().unwrap();
669        let b = fresh_k().unwrap();
670        let c = fresh_k().unwrap();
671
672        assert_ne!(a, b);
673        assert_ne!(a, c);
674        assert_ne!(b, c);
675    }
676
677    #[rstest]
678    fn build_auth_token_for_round_trips_against_credential() {
679        // Mint a token for the credential and verify the embedded signature
680        // against the credential's public key. End-to-end check that the
681        // `build_auth_token_for` threads private_key, account_index, and api_key_index
682        // through the message and signature correctly.
683        const PRIVATE_KEY_HEX: &str =
684            "0b8e0f63c24d8baacd9d29ad4e9a4b73c4a8d2bb8b16dc4fa9d7c2e1d3a8b1f0e8d3a4c5b6e7f001";
685        let credential = crate::common::credential::Credential::new(5, PRIVATE_KEY_HEX, 12_345)
686            .expect("credential must construct");
687
688        let token = build_auth_token_for(&credential).expect("token mint must succeed");
689
690        let pk = credential.private_key().unwrap().public_key();
691        let (message, sig_hex) = token
692            .expose_secret()
693            .rsplit_once(':')
694            .expect("token must end with `:hex(sig)`");
695        let digest_bytes = hash_auth_message(message).expect("hash must succeed");
696        let digest = Fp5::try_from_le_bytes(digest_bytes).expect("digest must be canonical");
697        let sig_bytes = hex_to_array::<{ SIG_BYTES }>(sig_hex);
698        let sig = Signature::from_le_bytes_reduce(sig_bytes);
699        assert!(
700            pk.verify(digest, &sig),
701            "minted token must verify against credential public key",
702        );
703
704        // Sanity check that the message body is shaped `deadline:account:api_key`.
705        let parts: Vec<&str> = message.splitn(3, ':').collect();
706        assert_eq!(parts.len(), 3);
707        assert_eq!(parts[1], "12345");
708        assert_eq!(parts[2], "5");
709    }
710}