secure_gate/traits/decoding/base64_url.rs
1// secure-gate/src/traits/decoding/base64_url.rs
2//! # FromBase64UrlStr Trait
3//!
4//! Extension trait for decoding URL-safe base64 strings to byte data.
5//!
6//! This trait provides secure, explicit decoding of base64url strings to byte vectors.
7//! Input should be treated as untrusted; use fallible methods.
8//!
9//! ## Security Warning
10//!
11//! Decoding input from untrusted sources should use fallible `try_` methods.
12//! Invalid input may indicate tampering or errors.
13//!
14/// ## Example
15///
16/// ```rust
17/// # #[cfg(feature = "encoding-base64")]
18/// use secure_gate::FromBase64UrlStr;
19/// # #[cfg(feature = "encoding-base64")]
20/// let base64_string = "QkJC";
21/// # #[cfg(feature = "encoding-base64")]
22/// let bytes = base64_string.try_from_base64url().unwrap();
23/// // bytes is now Vec<u8>: [66, 66, 66]
24/// ```
25/// This trait is gated behind the `encoding-base64` feature.
26#[cfg(feature = "encoding-base64")]
27use ::base64 as base64_crate;
28#[cfg(feature = "encoding-base64")]
29use base64_crate::engine::general_purpose::URL_SAFE_NO_PAD;
30#[cfg(feature = "encoding-base64")]
31use base64_crate::Engine;
32
33#[cfg(feature = "encoding-base64")]
34use crate::error::Base64Error;
35
36/// Extension trait for decoding URL-safe base64 strings to byte data.
37///
38/// Input should be treated as untrusted; use fallible methods.
39///
40/// # Security Warning
41///
42/// Decoding input from untrusted sources should use fallible `try_` methods.
43/// Invalid input may indicate tampering or errors.
44///
45/// ## Example
46///
47/// ```rust
48/// # #[cfg(feature = "encoding-base64")]
49/// use secure_gate::FromBase64UrlStr;
50/// # #[cfg(feature = "encoding-base64")]
51/// let base64_string = "QkJC";
52/// # #[cfg(feature = "encoding-base64")]
53/// let bytes = base64_string.try_from_base64url().unwrap();
54/// // bytes is now Vec<u8>: [66, 66, 66]
55/// ```
56#[cfg(feature = "encoding-base64")]
57pub trait FromBase64UrlStr {
58 /// Fallibly decode a URL-safe base64 string to bytes.
59 fn try_from_base64url(&self) -> Result<Vec<u8>, Base64Error>;
60}
61
62// Blanket impl to cover any AsRef<str> (e.g., &str, String, etc.)
63#[cfg(feature = "encoding-base64")]
64impl<T: AsRef<str> + ?Sized> FromBase64UrlStr for T {
65 fn try_from_base64url(&self) -> Result<Vec<u8>, Base64Error> {
66 URL_SAFE_NO_PAD
67 .decode(self.as_ref())
68 .map_err(|_| Base64Error::InvalidBase64)
69 }
70}