astrs-wire 0.1.0

AstRS control-plane protocol types, framed codec and version negotiation.
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
//! [`AuthToken`] — the cluster authentication secret carried by every
//! [`crate::Hello`].
//!
//! Blueprint §16: *"64-hex cluster token (`<working_dir>/.astrs-token`, 0600),
//! generated by `astrs up`, required in every `Hello`, constant-time compare
//! (oxicrypto). QUIC legs derive a PSK from it."*
//!
//! Four properties make this type safe to hold and hard to leak:
//!
//! - **Constant-time comparison.** `PartialEq` routes through
//!   [`oxicrypto::ct_eq`], so comparing a presented token against the expected
//!   one takes the same time whatever the first differing byte is. A
//!   short-circuiting `==` on the hex string would leak the token one byte per
//!   round trip.
//! - **Redacted `Debug` and `Display`.** Neither renders the secret; a token
//!   that lands in a `tracing` span or an error message prints
//!   `AuthToken(<redacted>)`. The real value is only produced by the
//!   explicitly-named [`AuthToken::reveal_hex`].
//! - **Zeroed on drop.** The backing bytes are overwritten when the token goes
//!   out of scope (`oxicrypto`'s `Zeroize`), so a core dump or a reused
//!   allocation is less likely to contain it.
//! - **Byte-oriented storage.** The token is thirty-two bytes, rendered as
//!   sixty-four lower-case hex characters on demand. It costs 32 bytes on the
//!   wire, not 65.
//!
//! # Examples
//!
//! ```
//! use astrs_wire::AuthToken;
//!
//! let token = AuthToken::from_bytes([0x11; 32]);
//! assert_eq!(token.reveal_hex().len(), 64);
//! assert_eq!(format!("{token:?}"), "AuthToken(<redacted>)");
//!
//! let same: AuthToken = token.reveal_hex().parse()?;
//! assert_eq!(same, token);
//! # Ok::<(), astrs_wire::AuthTokenError>(())
//! ```

use core::fmt;
use core::str::FromStr;

use oxicode::de::{Decode, Decoder};
use oxicode::enc::{Encode, Encoder};
use oxicrypto::{Zeroize, ct_eq};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::{AuthTokenError, codec_invalid};

/// The token's length in bytes.
pub const AUTH_TOKEN_LEN: usize = 32;

/// The token's length in its canonical hexadecimal text form.
pub const AUTH_TOKEN_HEX_LEN: usize = AUTH_TOKEN_LEN * 2;

/// The placeholder rendered by [`AuthToken`]'s `Debug` and `Display`.
pub const REDACTED: &str = "<redacted>";

/// The lower-case hexadecimal alphabet, indexed by nibble.
const HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";

/// A 256-bit cluster authentication token.
///
/// # Examples
///
/// ```
/// use astrs_wire::AuthToken;
///
/// let a = AuthToken::from_bytes([1; 32]);
/// let b = AuthToken::from_bytes([1; 32]);
/// let c = AuthToken::from_bytes([2; 32]);
/// assert_eq!(a, b);
/// assert_ne!(a, c);
/// ```
#[derive(Clone)]
pub struct AuthToken {
    /// The raw secret. Never rendered except through
    /// [`AuthToken::reveal_hex`] / [`AuthToken::reveal_bytes`].
    bytes: [u8; AUTH_TOKEN_LEN],
}

impl AuthToken {
    /// The all-zero token.
    ///
    /// Useful as an explicit "no authentication configured" placeholder on a
    /// UDS leg, where filesystem permissions and the peer-credential check are
    /// the real access control (blueprint §16). It is a legal token value, so
    /// a deployment that wants to reject it must do so by policy.
    pub const ZERO: Self = Self {
        bytes: [0u8; AUTH_TOKEN_LEN],
    };

    /// Wraps thirty-two raw bytes as a token.
    ///
    /// Every byte string is a valid token, so this cannot fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use astrs_wire::AuthToken;
    ///
    /// let token = AuthToken::from_bytes([0xAB; 32]);
    /// assert!(token.reveal_hex().starts_with("abab"));
    /// ```
    #[must_use]
    pub const fn from_bytes(bytes: [u8; AUTH_TOKEN_LEN]) -> Self {
        Self { bytes }
    }

    /// Mints a fresh token from the platform CSPRNG.
    ///
    /// Randomness comes from `oxicrypto`'s `random_bytes`, which is seeded
    /// from the operating system's entropy source. There is no fallback to a
    /// weaker generator: if the platform cannot produce entropy, this returns
    /// [`AuthTokenError::RandomnessUnavailable`] rather than emitting a
    /// predictable cluster secret.
    ///
    /// # Errors
    ///
    /// [`AuthTokenError::RandomnessUnavailable`] if the CSPRNG fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use astrs_wire::AuthToken;
    ///
    /// let a = AuthToken::generate()?;
    /// let b = AuthToken::generate()?;
    /// assert_ne!(a, b);
    /// # Ok::<(), astrs_wire::AuthTokenError>(())
    /// ```
    pub fn generate() -> Result<Self, AuthTokenError> {
        let random = oxicrypto::random_bytes(AUTH_TOKEN_LEN).map_err(|err| {
            AuthTokenError::RandomnessUnavailable {
                reason: err.to_string(),
            }
        })?;
        let bytes: [u8; AUTH_TOKEN_LEN] =
            random
                .as_slice()
                .try_into()
                .map_err(|_| AuthTokenError::RandomnessUnavailable {
                    reason: format!(
                        "csprng returned {} bytes, expected {AUTH_TOKEN_LEN}",
                        random.len()
                    ),
                })?;
        Ok(Self { bytes })
    }

    /// Parses the canonical sixty-four-character lower-case hex form.
    ///
    /// # Errors
    ///
    /// - [`AuthTokenError::BadLength`] if the string is not exactly
    ///   [`AUTH_TOKEN_HEX_LEN`] characters.
    /// - [`AuthTokenError::NotLowercaseHex`] for any character outside
    ///   `[0-9a-f]`. Upper-case is rejected deliberately: with two spellings
    ///   of the same token, a text comparison somewhere would eventually get
    ///   it wrong.
    ///
    /// # Examples
    ///
    /// ```
    /// use astrs_wire::AuthToken;
    ///
    /// assert!(AuthToken::parse_hex(&"0".repeat(64)).is_ok());
    /// assert!(AuthToken::parse_hex(&"0".repeat(63)).is_err());
    /// assert!(AuthToken::parse_hex(&"A".repeat(64)).is_err());
    /// ```
    pub fn parse_hex(text: &str) -> Result<Self, AuthTokenError> {
        let count = text.chars().count();
        if count != AUTH_TOKEN_HEX_LEN {
            return Err(AuthTokenError::BadLength {
                expected: AUTH_TOKEN_HEX_LEN,
                found: count,
            });
        }

        let mut bytes = [0u8; AUTH_TOKEN_LEN];
        let mut nibbles = text.chars().enumerate();
        for byte in &mut bytes {
            let (high_index, high) = nibbles.next().ok_or(AuthTokenError::BadLength {
                expected: AUTH_TOKEN_HEX_LEN,
                found: count,
            })?;
            let (low_index, low) = nibbles.next().ok_or(AuthTokenError::BadLength {
                expected: AUTH_TOKEN_HEX_LEN,
                found: count,
            })?;
            *byte = (nibble(high, high_index)? << 4) | nibble(low, low_index)?;
        }
        Ok(Self { bytes })
    }

    /// The token in its canonical sixty-four-character lower-case hex form.
    ///
    /// Named `reveal_*` so that every site producing the plaintext secret is
    /// greppable.
    ///
    /// # Examples
    ///
    /// ```
    /// use astrs_wire::AuthToken;
    ///
    /// assert_eq!(AuthToken::ZERO.reveal_hex(), "0".repeat(64));
    /// ```
    #[must_use]
    pub fn reveal_hex(&self) -> String {
        let mut out = String::with_capacity(AUTH_TOKEN_HEX_LEN);
        for byte in self.bytes {
            out.push(char::from(HEX_DIGITS[usize::from(byte >> 4)]));
            out.push(char::from(HEX_DIGITS[usize::from(byte & 0x0F)]));
        }
        out
    }

    /// The token's raw bytes.
    ///
    /// The QUIC leg derives its pre-shared key from these (blueprint §16).
    #[must_use]
    pub const fn reveal_bytes(&self) -> &[u8; AUTH_TOKEN_LEN] {
        &self.bytes
    }

    /// Whether this is the all-zero token.
    ///
    /// # Examples
    ///
    /// ```
    /// use astrs_wire::AuthToken;
    ///
    /// assert!(AuthToken::ZERO.is_zero());
    /// assert!(!AuthToken::from_bytes([1; 32]).is_zero());
    /// ```
    #[must_use]
    pub fn is_zero(&self) -> bool {
        ct_eq(&self.bytes, &[0u8; AUTH_TOKEN_LEN])
    }

    /// Constant-time comparison against another token.
    ///
    /// Identical to `==`; spelled out for call sites where the timing
    /// property is the point and should be visible in the code.
    ///
    /// # Examples
    ///
    /// ```
    /// use astrs_wire::AuthToken;
    ///
    /// let expected = AuthToken::from_bytes([7; 32]);
    /// assert!(expected.verify(&AuthToken::from_bytes([7; 32])));
    /// assert!(!expected.verify(&AuthToken::ZERO));
    /// ```
    #[must_use]
    pub fn verify(&self, presented: &Self) -> bool {
        ct_eq(&self.bytes, &presented.bytes)
    }
}

/// Converts one hexadecimal character to its numeric value.
fn nibble(ch: char, index: usize) -> Result<u8, AuthTokenError> {
    match ch {
        '0'..='9' => Ok(ch as u8 - b'0'),
        'a'..='f' => Ok(ch as u8 - b'a' + 10),
        _ => Err(AuthTokenError::NotLowercaseHex { ch, index }),
    }
}

impl PartialEq for AuthToken {
    /// Constant-time equality — see the module documentation.
    fn eq(&self, other: &Self) -> bool {
        ct_eq(&self.bytes, &other.bytes)
    }
}

impl Eq for AuthToken {}

impl fmt::Debug for AuthToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AuthToken({REDACTED})")
    }
}

impl fmt::Display for AuthToken {
    /// Renders the redaction placeholder, never the secret.
    ///
    /// # Examples
    ///
    /// ```
    /// use astrs_wire::AuthToken;
    ///
    /// assert_eq!(AuthToken::ZERO.to_string(), "<redacted>");
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(REDACTED)
    }
}

impl Default for AuthToken {
    fn default() -> Self {
        Self::ZERO
    }
}

impl Drop for AuthToken {
    fn drop(&mut self) {
        self.bytes.zeroize();
    }
}

impl FromStr for AuthToken {
    type Err = AuthTokenError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        Self::parse_hex(text)
    }
}

impl Serialize for AuthToken {
    /// Serialises the plaintext hex form.
    ///
    /// `serde` is used at human and file boundaries — the `.astrs-token` file
    /// and `--json` payloads that a deployment has chosen to emit — where the
    /// secret must actually be present. Everything that merely *displays* a
    /// token goes through `Debug`/`Display`, which redact.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.reveal_hex())
    }
}

impl<'de> Deserialize<'de> for AuthToken {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        Self::parse_hex(&text).map_err(D::Error::custom)
    }
}

impl Encode for AuthToken {
    /// Encodes the thirty-two raw bytes, with no length prefix.
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), oxicode::error::Error> {
        self.bytes.encode(encoder)
    }
}

impl<Context> Decode<Context> for AuthToken {
    fn decode<D: Decoder<Context = Context>>(
        decoder: &mut D,
    ) -> Result<Self, oxicode::error::Error> {
        let bytes = <[u8; AUTH_TOKEN_LEN]>::decode(decoder)
            .map_err(|_| codec_invalid("auth token must be exactly 32 bytes"))?;
        Ok(Self { bytes })
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    use super::*;
    use crate::codec::{WireDecode, WireEncode};

    #[test]
    fn hex_form_is_sixty_four_lowercase_characters() {
        let token = AuthToken::from_bytes([0xDE; AUTH_TOKEN_LEN]);
        let hex = token.reveal_hex();
        assert_eq!(hex.len(), AUTH_TOKEN_HEX_LEN);
        assert_eq!(hex, "de".repeat(32));
        assert!(
            hex.chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
        );
    }

    #[test]
    fn hex_round_trips_for_every_byte_value() {
        let mut bytes = [0u8; AUTH_TOKEN_LEN];
        for (index, byte) in bytes.iter_mut().enumerate() {
            *byte = (index as u8).wrapping_mul(8).wrapping_add(3);
        }
        let token = AuthToken::from_bytes(bytes);
        let parsed = AuthToken::parse_hex(&token.reveal_hex()).unwrap();
        assert_eq!(parsed, token);
        assert_eq!(parsed.reveal_bytes(), &bytes);
    }

    #[test]
    fn nibble_order_is_high_then_low() {
        let mut bytes = [0u8; AUTH_TOKEN_LEN];
        bytes[0] = 0x1F;
        assert!(AuthToken::from_bytes(bytes).reveal_hex().starts_with("1f"));
    }

    #[test]
    fn wrong_lengths_are_rejected() {
        for len in [0usize, 1, 63, 65, 128] {
            match AuthToken::parse_hex(&"a".repeat(len)) {
                Err(AuthTokenError::BadLength { expected, found }) => {
                    assert_eq!(expected, AUTH_TOKEN_HEX_LEN);
                    assert_eq!(found, len);
                }
                other => panic!("length {len} should be rejected, got {other:?}"),
            }
        }
    }

    #[test]
    fn uppercase_hex_is_rejected() {
        let text = format!("A{}", "0".repeat(63));
        match AuthToken::parse_hex(&text) {
            Err(AuthTokenError::NotLowercaseHex { ch, index }) => {
                assert_eq!(ch, 'A');
                assert_eq!(index, 0);
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn non_hex_characters_are_rejected_with_their_position() {
        let mut text = "0".repeat(64);
        text.replace_range(17..18, "z");
        match AuthToken::parse_hex(&text) {
            Err(AuthTokenError::NotLowercaseHex { ch, index }) => {
                assert_eq!(ch, 'z');
                assert_eq!(index, 17);
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn multibyte_input_of_the_right_char_count_is_rejected_cleanly() {
        // Sixty-four characters, none of them hex — must not panic on the
        // byte-vs-char length difference.
        let text = "é".repeat(64);
        assert!(matches!(
            AuthToken::parse_hex(&text),
            Err(AuthTokenError::NotLowercaseHex { .. })
        ));
    }

    #[test]
    fn equality_is_value_based() {
        let a = AuthToken::from_bytes([9; AUTH_TOKEN_LEN]);
        let b = AuthToken::from_bytes([9; AUTH_TOKEN_LEN]);
        let mut differs_last = [9u8; AUTH_TOKEN_LEN];
        differs_last[AUTH_TOKEN_LEN - 1] = 8;
        let mut differs_first = [9u8; AUTH_TOKEN_LEN];
        differs_first[0] = 8;

        assert_eq!(a, b);
        assert!(a.verify(&b));
        assert_ne!(a, AuthToken::from_bytes(differs_last));
        assert_ne!(a, AuthToken::from_bytes(differs_first));
        assert!(!a.verify(&AuthToken::from_bytes(differs_first)));
    }

    #[test]
    fn debug_and_display_never_leak_the_secret() {
        let token = AuthToken::from_bytes([0xAB; AUTH_TOKEN_LEN]);
        let hex = token.reveal_hex();
        let rendered = format!("{token:?} {token}");
        assert!(!rendered.contains(&hex));
        assert!(!rendered.contains("abab"));
        assert_eq!(format!("{token:?}"), "AuthToken(<redacted>)");
        assert_eq!(token.to_string(), REDACTED);
    }

    #[test]
    fn zero_token_is_recognised() {
        assert!(AuthToken::ZERO.is_zero());
        assert_eq!(AuthToken::default(), AuthToken::ZERO);
        assert_eq!(AuthToken::ZERO.reveal_hex(), "0".repeat(64));
        assert!(
            !AuthToken::from_bytes([
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 1
            ])
            .is_zero()
        );
    }

    #[test]
    fn generate_produces_distinct_high_entropy_tokens() {
        let a = AuthToken::generate().unwrap();
        let b = AuthToken::generate().unwrap();
        assert_ne!(a, b);
        assert!(!a.is_zero());
        // A CSPRNG must not produce a constant byte pattern.
        let first = a.reveal_bytes()[0];
        assert!(a.reveal_bytes().iter().any(|byte| *byte != first));
    }

    #[test]
    fn codec_encodes_thirty_two_raw_bytes() {
        let token = AuthToken::from_bytes([0x5A; AUTH_TOKEN_LEN]);
        let bytes = token.encode_to_vec().unwrap();
        assert_eq!(bytes.len(), AUTH_TOKEN_LEN);
        assert_eq!(bytes, vec![0x5A; AUTH_TOKEN_LEN]);
        assert_eq!(AuthToken::decode_exact(&bytes).unwrap(), token);
    }

    #[test]
    fn a_short_encoded_token_is_rejected() {
        let bytes = vec![0u8; AUTH_TOKEN_LEN - 1];
        assert!(AuthToken::decode_exact(&bytes).is_err());
    }

    #[test]
    fn serde_uses_the_hex_form() {
        let token = AuthToken::from_bytes([0x0F; AUTH_TOKEN_LEN]);
        let json = serde_json::to_string(&token).unwrap();
        assert_eq!(json, format!("\"{}\"", "0f".repeat(32)));
        assert_eq!(serde_json::from_str::<AuthToken>(&json).unwrap(), token);
        assert!(serde_json::from_str::<AuthToken>("\"short\"").is_err());
    }

    #[test]
    fn from_str_matches_parse_hex() {
        let hex = "f".repeat(64);
        assert_eq!(
            hex.parse::<AuthToken>().unwrap(),
            AuthToken::parse_hex(&hex).unwrap()
        );
    }

    #[test]
    fn cloning_preserves_the_value() {
        let token = AuthToken::from_bytes([3; AUTH_TOKEN_LEN]);
        let copy = token.clone();
        assert_eq!(token, copy);
        drop(copy);
        // The original must survive the clone's zeroing drop.
        assert_eq!(token.reveal_bytes(), &[3u8; AUTH_TOKEN_LEN]);
    }
}