base64-ng-serde 1.3.0

Optional serde wrappers for base64-ng
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
#![cfg_attr(not(feature = "std"), no_std)]
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![deny(clippy::all)]
#![deny(clippy::pedantic)]

//! Optional `serde` integration for `base64-ng`.
//!
//! This crate keeps serialization support out of the core package. It provides
//! explicit wrappers and `#[serde(with = "...")]` modules so applications must
//! choose the alphabet and padding policy at the field boundary.
//!
//! # Security
//!
//! Deserialization helpers in this crate use `base64_ng::Engine::decode_vec`,
//! the strict timing-variable decoder. They map decode failures to redacted
//! error classes, but they are not constant-time-oriented secret decoders. Do
//! not use these serde modules for API keys, bearer tokens, private keys, or
//! other secret-bearing fields when malformed-input timing matters. Decode
//! those values explicitly with `base64_ng::ct` or with
//! `base64_ng_sanitization::CtDecodeSanitizationExt` instead.

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::{string::String, vec::Vec};

#[cfg(feature = "alloc")]
use base64_ng::{
    Alphabet, DecodeError, Engine, MIME, PEM, Profile, STANDARD, STANDARD_NO_PAD, URL_SAFE,
    URL_SAFE_NO_PAD, clear_bytes, constant_time_eq,
};
#[cfg(feature = "alloc")]
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};

/// Owned bytes serialized as strict standard padded Base64.
///
/// This wrapper is still an interoperability type, not a secret container.
/// It clears its initialized bytes on drop as a retention-reduction measure,
/// but clones are independent copies and serialization intentionally exposes
/// the Base64 text to the serializer.
#[cfg(feature = "alloc")]
#[derive(Clone)]
pub struct Base64Standard(Vec<u8>);

/// Owned bytes serialized as URL-safe unpadded Base64.
///
/// This wrapper is still an interoperability type, not a secret container.
/// It clears its initialized bytes on drop as a retention-reduction measure,
/// but clones are independent copies and serialization intentionally exposes
/// the Base64 text to the serializer.
#[cfg(feature = "alloc")]
#[derive(Clone)]
pub struct Base64UrlSafeNoPad(Vec<u8>);

#[cfg(feature = "alloc")]
impl Base64Standard {
    /// Wraps bytes for standard Base64 serialization.
    #[must_use]
    pub const fn new(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }

    /// Returns the wrapped bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Consumes the wrapper and returns the owned bytes.
    ///
    /// The returned vector is no longer cleared by this wrapper on drop.
    /// Callers handling sensitive values must apply their own cleanup policy.
    #[must_use]
    pub fn into_inner(mut self) -> Vec<u8> {
        core::mem::take(&mut self.0)
    }
}

#[cfg(feature = "alloc")]
impl Base64UrlSafeNoPad {
    /// Wraps bytes for URL-safe no-padding Base64 serialization.
    #[must_use]
    pub const fn new(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }

    /// Returns the wrapped bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Consumes the wrapper and returns the owned bytes.
    ///
    /// The returned vector is no longer cleared by this wrapper on drop.
    /// Callers handling sensitive values must apply their own cleanup policy.
    #[must_use]
    pub fn into_inner(mut self) -> Vec<u8> {
        core::mem::take(&mut self.0)
    }
}

#[cfg(feature = "alloc")]
impl Drop for Base64Standard {
    fn drop(&mut self) {
        clear_bytes(&mut self.0);
    }
}

#[cfg(feature = "alloc")]
impl Drop for Base64UrlSafeNoPad {
    fn drop(&mut self) {
        clear_bytes(&mut self.0);
    }
}

#[cfg(feature = "alloc")]
impl PartialEq for Base64Standard {
    fn eq(&self, other: &Self) -> bool {
        constant_time_eq(self.as_bytes(), other.as_bytes())
    }
}

#[cfg(feature = "alloc")]
impl Eq for Base64Standard {}

#[cfg(feature = "alloc")]
impl PartialEq for Base64UrlSafeNoPad {
    fn eq(&self, other: &Self) -> bool {
        constant_time_eq(self.as_bytes(), other.as_bytes())
    }
}

#[cfg(feature = "alloc")]
impl Eq for Base64UrlSafeNoPad {}

#[cfg(feature = "alloc")]
impl core::fmt::Debug for Base64Standard {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("Base64Standard")
            .field("bytes", &"<redacted>")
            .field("len", &self.0.len())
            .finish()
    }
}

#[cfg(feature = "alloc")]
impl core::fmt::Debug for Base64UrlSafeNoPad {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("Base64UrlSafeNoPad")
            .field("bytes", &"<redacted>")
            .field("len", &self.0.len())
            .finish()
    }
}

#[cfg(feature = "alloc")]
impl Serialize for Base64Standard {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        standard::serialize(&self.0, serializer)
    }
}

#[cfg(feature = "alloc")]
impl<'de> Deserialize<'de> for Base64Standard {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        standard::deserialize(deserializer).map(Self)
    }
}

#[cfg(feature = "alloc")]
impl Serialize for Base64UrlSafeNoPad {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        url_safe_no_pad::serialize(&self.0, serializer)
    }
}

#[cfg(feature = "alloc")]
impl<'de> Deserialize<'de> for Base64UrlSafeNoPad {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        url_safe_no_pad::deserialize(deserializer).map(Self)
    }
}

/// Serde helpers for strict standard padded Base64 fields.
///
/// # Security
///
/// Deserialization uses the strict timing-variable decoder. Use this module
/// for interoperability-oriented fields, not secret-bearing fields where
/// malformed-input timing matters.
#[cfg(feature = "alloc")]
pub mod standard {
    use super::{STANDARD, Vec, deserialize_with_engine, serialize_with_engine};
    use serde::{Deserializer, Serializer};

    /// Serializes bytes as strict standard padded Base64 text.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if Base64 encoding fails or the
    /// serializer rejects the string value.
    pub fn serialize<S>(bytes: impl AsRef<[u8]>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serialize_with_engine(STANDARD, bytes.as_ref(), serializer)
    }

    /// Deserializes strict standard padded Base64 text into owned bytes.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the value is not a string or if the
    /// string is not valid strict standard padded Base64.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserialize_with_engine(STANDARD, deserializer)
    }
}

/// Serde helpers for strict standard unpadded Base64 fields.
///
/// # Security
///
/// Deserialization uses the strict timing-variable decoder. Use this module
/// for interoperability-oriented fields, not secret-bearing fields where
/// malformed-input timing matters.
#[cfg(feature = "alloc")]
pub mod standard_no_pad {
    use super::{STANDARD_NO_PAD, Vec, deserialize_with_engine, serialize_with_engine};
    use serde::{Deserializer, Serializer};

    /// Serializes bytes as strict standard unpadded Base64 text.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if Base64 encoding fails or the
    /// serializer rejects the string value.
    pub fn serialize<S>(bytes: impl AsRef<[u8]>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serialize_with_engine(STANDARD_NO_PAD, bytes.as_ref(), serializer)
    }

    /// Deserializes strict standard unpadded Base64 text into owned bytes.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the value is not a string or if the
    /// string is not valid strict standard unpadded Base64.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserialize_with_engine(STANDARD_NO_PAD, deserializer)
    }
}

/// Serde helpers for URL-safe padded Base64 fields.
///
/// # Security
///
/// Deserialization uses the strict timing-variable decoder. Use this module
/// for interoperability-oriented fields, not secret-bearing fields where
/// malformed-input timing matters.
#[cfg(feature = "alloc")]
pub mod url_safe {
    use super::{URL_SAFE, Vec, deserialize_with_engine, serialize_with_engine};
    use serde::{Deserializer, Serializer};

    /// Serializes bytes as URL-safe padded Base64 text.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if Base64 encoding fails or the
    /// serializer rejects the string value.
    pub fn serialize<S>(bytes: impl AsRef<[u8]>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serialize_with_engine(URL_SAFE, bytes.as_ref(), serializer)
    }

    /// Deserializes URL-safe padded Base64 text into owned bytes.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the value is not a string or if the
    /// string is not valid URL-safe padded Base64.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserialize_with_engine(URL_SAFE, deserializer)
    }
}

/// Serde helpers for URL-safe unpadded Base64 fields.
///
/// # Security
///
/// Deserialization uses the strict timing-variable decoder. Use this module
/// for interoperability-oriented fields, not secret-bearing fields where
/// malformed-input timing matters.
#[cfg(feature = "alloc")]
pub mod url_safe_no_pad {
    use super::{URL_SAFE_NO_PAD, Vec, deserialize_with_engine, serialize_with_engine};
    use serde::{Deserializer, Serializer};

    /// Serializes bytes as URL-safe unpadded Base64 text.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if Base64 encoding fails or the
    /// serializer rejects the string value.
    pub fn serialize<S>(bytes: impl AsRef<[u8]>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serialize_with_engine(URL_SAFE_NO_PAD, bytes.as_ref(), serializer)
    }

    /// Deserializes URL-safe unpadded Base64 text into owned bytes.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the value is not a string or if the
    /// string is not valid URL-safe unpadded Base64.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserialize_with_engine(URL_SAFE_NO_PAD, deserializer)
    }
}

/// Serde helpers for MIME Base64 fields with 76-column CRLF wrapping.
///
/// # Security
///
/// Deserialization uses the strict timing-variable decoder. Use this module
/// for interoperability-oriented fields, not secret-bearing fields where
/// malformed-input timing matters.
#[cfg(feature = "alloc")]
pub mod mime {
    use super::{MIME, Vec, deserialize_with_profile, serialize_with_profile};
    use serde::{Deserializer, Serializer};

    /// Serializes bytes as MIME Base64 text with 76-column CRLF wrapping.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if Base64 encoding fails or the
    /// serializer rejects the string value.
    pub fn serialize<S>(bytes: impl AsRef<[u8]>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serialize_with_profile(&MIME, bytes.as_ref(), serializer)
    }

    /// Deserializes MIME Base64 text into owned bytes.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the value is not a string or if the
    /// string is not valid strict MIME Base64 for the configured wrapping
    /// profile.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserialize_with_profile(&MIME, deserializer)
    }
}

/// Serde helpers for PEM Base64 fields with 64-column LF wrapping.
///
/// # Security
///
/// Deserialization uses the strict timing-variable decoder. Use this module
/// for interoperability-oriented fields, not secret-bearing fields where
/// malformed-input timing matters.
#[cfg(feature = "alloc")]
pub mod pem {
    use super::{PEM, Vec, deserialize_with_profile, serialize_with_profile};
    use serde::{Deserializer, Serializer};

    /// Serializes bytes as PEM Base64 text with 64-column LF wrapping.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if Base64 encoding fails or the
    /// serializer rejects the string value.
    pub fn serialize<S>(bytes: impl AsRef<[u8]>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serialize_with_profile(&PEM, bytes.as_ref(), serializer)
    }

    /// Deserializes PEM Base64 text into owned bytes.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the value is not a string or if the
    /// string is not valid strict PEM Base64 for the configured wrapping
    /// profile.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserialize_with_profile(&PEM, deserializer)
    }
}

#[cfg(feature = "alloc")]
fn serialize_with_engine<A, const PAD: bool, S>(
    engine: Engine<A, PAD>,
    bytes: &[u8],
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    A: base64_ng::Alphabet,
    S: Serializer,
{
    let encoded = engine
        .encode_string(bytes)
        .map_err(serde::ser::Error::custom)?;
    serializer.serialize_str(&encoded)
}

#[cfg(feature = "alloc")]
fn serialize_with_profile<A, const PAD: bool, S>(
    profile: &Profile<A, PAD>,
    bytes: &[u8],
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    A: Alphabet,
    S: Serializer,
{
    let encoded = profile
        .encode_string(bytes)
        .map_err(serde::ser::Error::custom)?;
    serializer.serialize_str(&encoded)
}

#[cfg(feature = "alloc")]
fn deserialize_with_engine<'de, A, const PAD: bool, D>(
    engine: Engine<A, PAD>,
    deserializer: D,
) -> Result<Vec<u8>, D::Error>
where
    A: base64_ng::Alphabet,
    D: Deserializer<'de>,
{
    let encoded = String::deserialize(deserializer)?;
    engine
        .decode_vec(encoded.as_bytes())
        .map_err(|error: DecodeError| D::Error::custom(error.kind()))
}

#[cfg(feature = "alloc")]
fn deserialize_with_profile<'de, A, const PAD: bool, D>(
    profile: &Profile<A, PAD>,
    deserializer: D,
) -> Result<Vec<u8>, D::Error>
where
    A: Alphabet,
    D: Deserializer<'de>,
{
    let encoded = String::deserialize(deserializer)?;
    profile
        .decode_vec(encoded.as_bytes())
        .map_err(|error: DecodeError| D::Error::custom(error.kind()))
}