hessra_token_core/
utils.rs

1use base64::{engine::general_purpose::URL_SAFE, Engine};
2use std::fs::read_to_string;
3
4use crate::error::TokenError;
5
6pub use biscuit_auth::{Biscuit, PublicKey};
7
8/// Encode binary token data to URL-safe base64 string
9///
10/// # Arguments
11///
12/// * `token_bytes` - Binary token data
13///
14/// # Returns
15///
16/// URL-safe base64 encoded token string
17pub fn encode_token(token_bytes: &[u8]) -> String {
18    URL_SAFE.encode(token_bytes)
19}
20
21/// Decode a URL-safe base64 encoded token string to binary
22///
23/// # Arguments
24///
25/// * `token_string` - URL-safe base64 encoded token string
26///
27/// # Returns
28///
29/// Binary token data or TokenError if decoding fails
30pub fn decode_token(token_string: &str) -> Result<Vec<u8>, TokenError> {
31    URL_SAFE
32        .decode(token_string)
33        .map_err(|e| TokenError::generic(format!("Failed to decode base64 token: {e}")))
34}
35
36pub fn public_key_from_pem_file(path: &str) -> Result<PublicKey, TokenError> {
37    let key_string = read_to_string(path)
38        .map_err(|e| TokenError::generic(format!("Failed to read file: {e}")))?;
39    let key = PublicKey::from_pem(&key_string)
40        .map_err(|e| TokenError::generic(format!("Failed to parse PEM: {e}")))?;
41    Ok(key)
42}
43
44/// Extracts and parses a Biscuit token from a URL-safe base64 string
45///
46/// This is useful when you need to inspect the token contents directly
47///
48/// # Arguments
49///
50/// * `token_string` - URL-safe base64 encoded token string
51/// * `public_key` - The public key used to verify the token signature
52///
53/// # Returns
54///
55/// The parsed Biscuit token or an error
56pub fn parse_token(token_string: &str, public_key: PublicKey) -> Result<Biscuit, TokenError> {
57    Ok(Biscuit::from_base64(token_string, public_key)?)
58}