Skip to main content

oxabl_cache_format/
api_token.rs

1//! API token text: `oxc_<id>_<secret>`.
2
3use std::fmt;
4
5use crate::base32;
6use crate::error::{FormatError, Result};
7
8const PREFIX: &str = "oxc_";
9
10/// An API token: a public id and a bearer secret. The secret never appears in `Debug`.
11#[derive(Clone, PartialEq, Eq)]
12pub struct ApiToken {
13    /// 10 bytes, 16 base32 characters.
14    pub id: [u8; 10],
15    /// 32 bytes, 52 base32 characters.
16    pub secret: [u8; 32],
17}
18
19impl ApiToken {
20    pub fn to_text(&self) -> String {
21        format!(
22            "{PREFIX}{}_{}",
23            base32::encode(&self.id),
24            base32::encode(&self.secret)
25        )
26    }
27
28    pub fn from_text(s: &str) -> Result<Self> {
29        let rest = s
30            .strip_prefix(PREFIX)
31            .ok_or(FormatError::Invalid("token prefix"))?;
32        let (id, secret) = rest
33            .split_once('_')
34            .ok_or(FormatError::Invalid("token shape"))?;
35        Ok(Self {
36            id: base32::decode(id)?,
37            secret: base32::decode(secret)?,
38        })
39    }
40}
41
42impl fmt::Debug for ApiToken {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "ApiToken(oxc_{}_…)", base32::encode(&self.id))
45    }
46}