| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Tokens: `brd_<id>_<secret>`, with an 8-character id and a 52-character |
| 5 | //! secret (32 random bytes), both lowercase base32 without padding. |
| 6 | |
| 7 | use std::fmt; |
| 8 | |
| 9 | /// The prefix every token starts with. |
| 10 | pub const PREFIX: &str = "brd_"; |
| 11 | /// Characters in a token's id. |
| 12 | pub const ID_LEN: usize = 8; |
| 13 | /// Characters in a token's secret: 32 bytes in base32. |
| 14 | pub const SECRET_LEN: usize = 52; |
| 15 | /// Random bytes a token's id is made from. |
| 16 | pub const ID_BYTES: usize = 5; |
| 17 | /// Random bytes a token's secret is made from. |
| 18 | pub const SECRET_BYTES: usize = 32; |
| 19 | |
| 20 | const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567"; |
| 21 | |
| 22 | /// Why a string is not a token. |
| 23 | #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] |
| 24 | pub enum TokenError { |
| 25 | /// It does not have the shape of one. |
| 26 | #[error( |
| 27 | "not a braid hub token: expected brd_ then an 8-character id, _ and a 52-character secret" |
| 28 | )] |
| 29 | Shape, |
| 30 | } |
| 31 | |
| 32 | /// A token. Its [`Debug`](fmt::Debug) form shows the id only. |
| 33 | #[derive(Clone, PartialEq, Eq)] |
| 34 | pub struct Token { |
| 35 | id: String, |
| 36 | secret: String, |
| 37 | } |
| 38 | |
| 39 | impl Token { |
| 40 | /// A token from random bytes the caller drew from the operating system. |
| 41 | pub fn from_random(id: [u8; ID_BYTES], secret: [u8; SECRET_BYTES]) -> Token { |
| 42 | Token { |
| 43 | id: base32(&id), |
| 44 | secret: base32(&secret), |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | /// Reads a token, rejecting anything not exactly of its shape. |
| 49 | pub fn parse(text: &str) -> Result<Token, TokenError> { |
| 50 | let rest = text.strip_prefix(PREFIX).ok_or(TokenError::Shape)?; |
| 51 | let (id, secret) = rest.split_once('_').ok_or(TokenError::Shape)?; |
| 52 | if !is_id(id) || !is_base32(secret, SECRET_LEN) { |
| 53 | return Err(TokenError::Shape); |
| 54 | } |
| 55 | Ok(Token { |
| 56 | id: id.to_owned(), |
| 57 | secret: secret.to_owned(), |
| 58 | }) |
| 59 | } |
| 60 | |
| 61 | /// The public id, which logs and lists name. |
| 62 | pub fn id(&self) -> &str { |
| 63 | &self.id |
| 64 | } |
| 65 | |
| 66 | /// The whole token, `brd_<id>_<secret>`: what a client sends. Never log |
| 67 | /// it. |
| 68 | pub fn expose(&self) -> String { |
| 69 | format!("{PREFIX}{}_{}", self.id, self.secret) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | impl fmt::Debug for Token { |
| 74 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 75 | write!(f, "Token({PREFIX}{}_…)", self.id) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Whether `text` has the shape of a token's id, as lists and |
| 80 | /// `DELETE /v1/tokens/{id}` name it: 8 characters of lowercase base32. |
| 81 | pub fn is_id(text: &str) -> bool { |
| 82 | is_base32(text, ID_LEN) |
| 83 | } |
| 84 | |
| 85 | fn is_base32(text: &str, len: usize) -> bool { |
| 86 | text.len() == len && text.bytes().all(|b| ALPHABET.contains(&b)) |
| 87 | } |
| 88 | |
| 89 | /// Lowercase RFC 4648 base32, without padding. |
| 90 | pub fn base32(bytes: &[u8]) -> String { |
| 91 | let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8); |
| 92 | let mut buffer: u64 = 0; |
| 93 | let mut bits = 0; |
| 94 | for &byte in bytes { |
| 95 | buffer = (buffer << 8) | u64::from(byte); |
| 96 | bits += 8; |
| 97 | while bits >= 5 { |
| 98 | bits -= 5; |
| 99 | out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char); |
| 100 | } |
| 101 | } |
| 102 | if bits > 0 { |
| 103 | out.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char); |
| 104 | } |
| 105 | out |
| 106 | } |
| 107 | |
| 108 | #[cfg(test)] |
| 109 | mod tests { |
| 110 | use super::*; |
| 111 | |
| 112 | #[test] |
| 113 | fn base32_matches_rfc_4648() { |
| 114 | // RFC 4648, section 10, lowercased and without padding. |
| 115 | for (input, expected) in [ |
| 116 | ("", ""), |
| 117 | ("f", "my"), |
| 118 | ("fo", "mzxq"), |
| 119 | ("foo", "mzxw6"), |
| 120 | ("foob", "mzxw6yq"), |
| 121 | ("fooba", "mzxw6ytb"), |
| 122 | ("foobar", "mzxw6ytboi"), |
| 123 | ] { |
| 124 | assert_eq!(base32(input.as_bytes()), expected); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | #[test] |
| 129 | fn round_trip_and_shape() { |
| 130 | let token = Token::from_random([1; ID_BYTES], [7; SECRET_BYTES]); |
| 131 | let text = token.expose(); |
| 132 | assert!(text.starts_with("brd_")); |
| 133 | assert_eq!(text.len(), 4 + ID_LEN + 1 + SECRET_LEN); |
| 134 | assert_eq!(Token::parse(&text), Ok(token.clone())); |
| 135 | assert!(!format!("{token:?}").contains(&text[13..])); |
| 136 | assert!(is_id(token.id())); |
| 137 | assert!(!is_id("abcdefg") && !is_id("abcdefgh1") && !is_id("ABCDEFGH")); |
| 138 | for bad in [ |
| 139 | "", |
| 140 | "brd_", |
| 141 | &text[1..], |
| 142 | &text.replace("brd_", "brx_"), |
| 143 | &text.to_uppercase(), |
| 144 | &format!("{text}a"), |
| 145 | &text.replacen('_', "-", 2), |
| 146 | ] { |
| 147 | assert_eq!(Token::parse(bad), Err(TokenError::Shape), "{bad}"); |
| 148 | } |
| 149 | } |
| 150 | } |