base64-ng 2.0.1

no_std-first Base64 encoding and decoding with strict RFC 4648 APIs and optional SIMD
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
498
499
500
use super::{
    Backend, BackendHealthPosture, BackendPolicy, CandidateDetectionMode, CtGatePosture,
    MemoryLockPosture, OperationBackendReport, OperationKind, OperationSecurityPosture,
    SecurityPosture, WasmArtifactPosture, WasmRuntimePosture, WipePosture,
    operation::{wasm_artifact_posture, wasm_runtime_posture},
};
/// Runtime backend policy failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BackendPolicyError {
    /// Policy that was requested.
    pub policy: BackendPolicy,
    /// Backend report observed when the policy failed.
    pub report: BackendReport,
}
impl core::fmt::Display for BackendPolicyError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            formatter,
            "runtime backend policy `{}` was not satisfied ({})",
            self.policy, self.report,
        )
    }
}

#[cfg(feature = "std")]
impl std::error::Error for BackendPolicyError {}
/// Backend report for the current build and target.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(clippy::struct_excessive_bools)]
pub struct BackendReport {
    /// Compatibility alias for ordinary encode. New code should use
    /// [`Self::encode_backend`] and inspect the separate decode reports.
    pub active: Backend,
    /// Whether ordinary encode is accelerated; this does not describe strict
    /// decode. New code should inspect the operation-specific reports.
    pub accelerated_backend_active: bool,
    /// Compatibility posture for ordinary encode and its candidate. New code
    /// should use the operation-specific security postures.
    pub security_posture: SecurityPosture,
    /// Strongest healthy ordinary encode backend for qualifying inputs.
    ///
    /// Per-call length and alphabet policy can select a narrower backend or
    /// scalar fallback without changing this capability-oriented report.
    pub encode_backend: OperationBackendReport,
    /// Selected ordinary strict-decode backend.
    pub strict_decode_backend: OperationBackendReport,
    /// Secret decode backend, independently fixed to the scalar
    /// constant-time-oriented boundary.
    pub secret_decode_backend: OperationBackendReport,
    /// Strongest backend candidate visible to the current build.
    pub candidate: Backend,
    /// Whether candidate visibility came from runtime CPU probing,
    /// compile-time target features, or a disabled SIMD feature.
    pub candidate_detection_mode: CandidateDetectionMode,
    /// Whether the `simd` feature is enabled in this build.
    pub simd_feature_enabled: bool,
    /// Whether either ordinary operation selects acceleration.
    pub ordinary_acceleration_active: bool,
    /// Whether this build keeps the high-assurance scalar unsafe boundary.
    ///
    /// This is a conservative compile-time posture signal. It is `true`
    /// only when the reserved `simd` feature is disabled; `simd` builds
    /// expose additional private prototype boundaries and must use the
    /// release evidence scripts for boundary validation.
    pub unsafe_boundary_enforced: bool,
    /// Wasm artifact selection, distinct from native runtime CPU dispatch.
    pub wasm_artifact_posture: WasmArtifactPosture,
    /// Wasm host-runtime identification posture.
    pub wasm_runtime_posture: WasmRuntimePosture,
    /// Current wipe-barrier posture.
    pub wipe_posture: WipePosture,
    /// Current constant-time result-gate barrier posture.
    pub ct_gate_posture: CtGatePosture,
}
/// Compact structured backend snapshot for logging and policy evidence.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(clippy::struct_excessive_bools)]
pub struct BackendSnapshot {
    /// Stable compatibility alias for the ordinary encode backend.
    pub active: &'static str,
    /// Compatibility alias reporting whether ordinary encode is accelerated.
    pub accelerated_backend_active: bool,
    /// Stable compatibility posture for ordinary encode and its candidate.
    pub security_posture: &'static str,
    /// Stable ordinary encode report.
    pub encode_backend: super::OperationBackendSnapshot,
    /// Stable ordinary strict-decode report.
    pub strict_decode_backend: super::OperationBackendSnapshot,
    /// Stable secret decode report.
    pub secret_decode_backend: super::OperationBackendSnapshot,
    /// Stable detected candidate identifier.
    pub candidate: &'static str,
    /// Stable SIMD candidate detection-mode identifier.
    pub candidate_detection_mode: &'static str,
    /// CPU features required by the detected candidate.
    pub candidate_required_cpu_features: &'static [&'static str],
    /// Whether the `simd` feature is enabled in this build.
    pub simd_feature_enabled: bool,
    /// Whether either ordinary operation selects acceleration.
    pub ordinary_acceleration_active: bool,
    /// Whether this build keeps the high-assurance scalar unsafe boundary.
    ///
    /// This is `false` for `simd` builds even while execution remains
    /// scalar-only, because those builds include additional private
    /// prototype boundaries.
    pub unsafe_boundary_enforced: bool,
    /// Stable Wasm artifact posture identifier.
    pub wasm_artifact_posture: &'static str,
    /// Stable Wasm host-runtime posture identifier.
    pub wasm_runtime_posture: &'static str,
    /// Stable wipe-barrier posture identifier.
    pub wipe_posture: &'static str,
    /// Stable constant-time result-gate barrier posture identifier.
    pub ct_gate_posture: &'static str,
}

impl core::fmt::Display for BackendReport {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            formatter,
            "active={} accelerated_backend_active={} security_posture={} encode_backend={} strict_decode_backend={} secret_decode_backend={} candidate={} candidate_detection_mode={} candidate_required_cpu_features=",
            self.active,
            self.accelerated_backend_active,
            self.security_posture,
            self.encode_backend.backend,
            self.strict_decode_backend.backend,
            self.secret_decode_backend.backend,
            self.candidate,
            self.candidate_detection_mode,
        )?;
        write_feature_list(formatter, self.candidate_required_cpu_features())?;
        write!(
            formatter,
            " simd_feature_enabled={} ordinary_acceleration_active={} unsafe_boundary_enforced={} wasm_artifact_posture={} wasm_runtime_posture={} wipe_posture={} ct_gate_posture={}",
            self.simd_feature_enabled,
            self.ordinary_acceleration_active,
            self.unsafe_boundary_enforced,
            self.wasm_artifact_posture.as_str(),
            self.wasm_runtime_posture.as_str(),
            self.wipe_posture,
            self.ct_gate_posture,
        )
    }
}

impl BackendReport {
    /// Returns whether this report satisfies `policy`.
    ///
    /// ```
    /// let report = base64_ng::runtime::backend_report();
    ///
    /// let scalar_only =
    ///     report.satisfies(base64_ng::runtime::BackendPolicy::ScalarExecutionOnly);
    /// assert!(!scalar_only || !report.ordinary_acceleration_active);
    /// ```
    #[must_use]
    pub const fn satisfies(self, policy: BackendPolicy) -> bool {
        match policy {
            BackendPolicy::ScalarExecutionOnly => {
                stably_scalar(self.encode_backend)
                    && stably_scalar(self.strict_decode_backend)
                    && !self.ordinary_acceleration_active
            }
            BackendPolicy::SimdFeatureDisabled => !self.simd_feature_enabled,
            BackendPolicy::NoDetectedSimdCandidate => matches!(self.candidate, Backend::Scalar),
            BackendPolicy::HighAssuranceScalarOnly => {
                matches!(
                    self.encode_backend.security_posture,
                    OperationSecurityPosture::OrdinaryScalar
                ) && matches!(
                    self.strict_decode_backend.security_posture,
                    OperationSecurityPosture::OrdinaryScalar
                ) && matches!(
                    self.secret_decode_backend.security_posture,
                    OperationSecurityPosture::ScalarConstantTimeOriented
                ) && matches!(self.candidate, Backend::Scalar)
                    && !self.simd_feature_enabled
                    && !self.ordinary_acceleration_active
                    && self.unsafe_boundary_enforced
                    && matches!(
                        self.ct_gate_posture,
                        CtGatePosture::HardwareSpeculationBarrier
                            | CtGatePosture::HardwareSpeculationBarrierBuildAsserted
                    )
            }
        }
    }

    /// Returns the CPU features required by the detected candidate.
    ///
    /// ```
    /// let report = base64_ng::runtime::backend_report();
    ///
    /// assert_eq!(
    ///     report.candidate_required_cpu_features(),
    ///     report.candidate.required_cpu_features(),
    /// );
    /// ```
    #[must_use]
    pub const fn candidate_required_cpu_features(self) -> &'static [&'static str] {
        self.candidate.required_cpu_features()
    }

    /// Returns the typed backend selected by ordinary strict decode.
    ///
    /// Prefer [`Self::strict_decode_backend`] for stable logging.
    #[must_use]
    pub fn active_decode_backend(self) -> Backend {
        let _ = self;
        active_decode_backend()
    }

    /// Returns whether `base64-ng` itself locks secret buffers into physical
    /// memory.
    ///
    /// This crate intentionally has no OS-specific `mlock`/`VirtualLock`
    /// integration. High-assurance deployments should pair secret buffers with
    /// their own platform-approved memory-locking, swap, hibernation, and
    /// crash-dump controls.
    #[must_use]
    pub const fn memory_lock_posture(self) -> MemoryLockPosture {
        let _ = self;
        MemoryLockPosture::NotProvided
    }

    /// Returns a compact structured snapshot with stable string values.
    ///
    /// ```
    /// let snapshot = base64_ng::runtime::backend_report().snapshot();
    ///
    /// assert_eq!(
    ///     snapshot.ordinary_acceleration_active,
    ///     snapshot.encode_backend.backend != "scalar"
    ///         || snapshot.strict_decode_backend.backend != "scalar",
    /// );
    /// ```
    #[must_use]
    pub const fn snapshot(self) -> BackendSnapshot {
        BackendSnapshot {
            active: self.active.as_str(),
            accelerated_backend_active: self.accelerated_backend_active,
            security_posture: self.security_posture.as_str(),
            encode_backend: self.encode_backend.snapshot(),
            strict_decode_backend: self.strict_decode_backend.snapshot(),
            secret_decode_backend: self.secret_decode_backend.snapshot(),
            candidate: self.candidate.as_str(),
            candidate_detection_mode: self.candidate_detection_mode.as_str(),
            candidate_required_cpu_features: self.candidate_required_cpu_features(),
            simd_feature_enabled: self.simd_feature_enabled,
            ordinary_acceleration_active: self.ordinary_acceleration_active,
            unsafe_boundary_enforced: self.unsafe_boundary_enforced,
            wasm_artifact_posture: self.wasm_artifact_posture.as_str(),
            wasm_runtime_posture: self.wasm_runtime_posture.as_str(),
            wipe_posture: self.wipe_posture.as_str(),
            ct_gate_posture: self.ct_gate_posture.as_str(),
        }
    }
}

const fn stably_scalar(report: OperationBackendReport) -> bool {
    matches!(
        report.security_posture,
        OperationSecurityPosture::OrdinaryScalar
    ) && matches!(
        report.health_posture,
        BackendHealthPosture::ScalarFixed
            | BackendHealthPosture::Quarantined
            | BackendHealthPosture::SynchronizationUnavailable
    )
}

/// Returns the runtime backend report for this build and target.
///
/// ```
/// let report = base64_ng::runtime::backend_report();
///
/// assert_eq!(
///     report.secret_decode_backend.backend.as_str(),
///     "scalar-constant-time-oriented",
/// );
/// ```
#[must_use]
pub fn backend_report() -> BackendReport {
    let encode = active_backend();
    let strict_decode = active_decode_backend();
    let encode_candidate = encode_candidate_backend();
    let decode_candidate = decode_candidate_backend();
    let candidate = detected_candidate();
    let candidate_detection_mode = candidate_detection_mode();
    let accelerated_backend_active = encode != Backend::Scalar;
    let ordinary_acceleration_active =
        encode != Backend::Scalar || strict_decode != Backend::Scalar;
    let unsafe_boundary_enforced = !cfg!(feature = "simd");
    let security_posture = if accelerated_backend_active {
        SecurityPosture::Accelerated
    } else if candidate == Backend::Scalar {
        SecurityPosture::ScalarOnly
    } else {
        SecurityPosture::SimdCandidateScalarActive
    };

    BackendReport {
        active: encode,
        accelerated_backend_active,
        security_posture,
        encode_backend: OperationBackendReport::ordinary(
            OperationKind::Encode,
            encode,
            encode_candidate,
        ),
        strict_decode_backend: OperationBackendReport::ordinary(
            OperationKind::StrictDecode,
            strict_decode,
            decode_candidate,
        ),
        secret_decode_backend: OperationBackendReport::secret_decode(),
        candidate,
        candidate_detection_mode,
        simd_feature_enabled: cfg!(feature = "simd"),
        ordinary_acceleration_active,
        unsafe_boundary_enforced,
        wasm_artifact_posture: wasm_artifact_posture(),
        wasm_runtime_posture: wasm_runtime_posture(),
        wipe_posture: wipe_posture(),
        ct_gate_posture: ct_gate_posture(),
    }
}

const fn wipe_posture() -> WipePosture {
    if cfg!(any(
        target_arch = "aarch64",
        target_arch = "arm",
        target_arch = "riscv32",
        target_arch = "riscv64",
        target_arch = "x86",
        target_arch = "x86_64",
    )) {
        WipePosture::HardwareFence
    } else {
        WipePosture::CompilerFenceOnly
    }
}

const fn ct_gate_posture() -> CtGatePosture {
    if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
        CtGatePosture::HardwareSpeculationBarrier
    } else if cfg!(all(
        target_arch = "aarch64",
        base64_ng_aarch64_csdb_attested
    )) {
        CtGatePosture::HardwareSpeculationBarrierBuildAsserted
    } else if cfg!(target_arch = "aarch64") {
        CtGatePosture::HardwareSpeculationBarrierUnattested
    } else if cfg!(any(
        target_arch = "arm",
        target_arch = "riscv32",
        target_arch = "riscv64"
    )) {
        CtGatePosture::OrderingFence
    } else {
        CtGatePosture::CompilerFenceOnly
    }
}

/// Requires the current runtime backend report to satisfy `policy`.
///
/// ```
/// let result = base64_ng::runtime::require_backend_policy(
///     base64_ng::runtime::BackendPolicy::ScalarExecutionOnly,
/// );
///
/// if result.is_ok() {
///     assert!(!base64_ng::runtime::backend_report().ordinary_acceleration_active);
/// }
/// ```
pub fn require_backend_policy(policy: BackendPolicy) -> Result<(), BackendPolicyError> {
    let report = backend_report();
    if report.satisfies(policy) {
        Ok(())
    } else {
        Err(BackendPolicyError { policy, report })
    }
}

fn write_feature_list(
    formatter: &mut core::fmt::Formatter<'_>,
    features: &[&str],
) -> core::fmt::Result {
    formatter.write_str("[")?;
    let mut index = 0;
    while index < features.len() {
        if index != 0 {
            formatter.write_str(",")?;
        }
        formatter.write_str(features[index])?;
        index += 1;
    }
    formatter.write_str("]")
}

#[cfg(feature = "simd")]
fn active_backend() -> Backend {
    crate::encode_backend::active_encode_backend().reported()
}

#[cfg(not(feature = "simd"))]
const fn active_backend() -> Backend {
    Backend::Scalar
}

#[cfg(feature = "simd")]
fn active_decode_backend() -> Backend {
    crate::decode_backend::active_decode_backend().reported()
}

#[cfg(not(feature = "simd"))]
const fn active_decode_backend() -> Backend {
    Backend::Scalar
}

#[cfg(feature = "simd")]
fn encode_candidate_backend() -> Backend {
    crate::encode_backend::candidate_encode_backend().reported()
}

#[cfg(not(feature = "simd"))]
const fn encode_candidate_backend() -> Backend {
    Backend::Scalar
}

#[cfg(feature = "simd")]
fn decode_candidate_backend() -> Backend {
    crate::decode_backend::candidate_decode_backend().reported()
}

#[cfg(not(feature = "simd"))]
const fn decode_candidate_backend() -> Backend {
    Backend::Scalar
}

#[cfg(feature = "simd")]
fn detected_candidate() -> Backend {
    match crate::simd::detected_candidate() {
        crate::simd::Candidate::Scalar => Backend::Scalar,
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        crate::simd::Candidate::Avx512Vbmi => Backend::Avx512Vbmi,
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        crate::simd::Candidate::Avx2 => Backend::Avx2,
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        crate::simd::Candidate::Ssse3Sse41 => Backend::Ssse3Sse41,
        #[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
        crate::simd::Candidate::Neon => Backend::Neon,
        #[cfg(target_arch = "wasm32")]
        crate::simd::Candidate::WasmSimd128 => Backend::WasmSimd128,
        #[cfg(target_arch = "riscv64")]
        crate::simd::Candidate::Rvv => Backend::Rvv,
        #[cfg(all(target_arch = "aarch64", base64_ng_sve_candidate))]
        crate::simd::Candidate::Sve => Backend::Sve,
    }
}

#[cfg(not(feature = "simd"))]
const fn detected_candidate() -> Backend {
    Backend::Scalar
}

#[cfg(all(
    feature = "simd",
    feature = "std",
    any(
        target_arch = "x86",
        target_arch = "x86_64",
        all(target_arch = "aarch64", base64_ng_sve_candidate),
        target_arch = "riscv64"
    )
))]
const fn candidate_detection_mode() -> CandidateDetectionMode {
    CandidateDetectionMode::RuntimeCpuFeatures
}

#[cfg(all(
    feature = "simd",
    not(all(
        feature = "std",
        any(
            target_arch = "x86",
            target_arch = "x86_64",
            all(target_arch = "aarch64", base64_ng_sve_candidate),
            target_arch = "riscv64"
        )
    ))
))]
const fn candidate_detection_mode() -> CandidateDetectionMode {
    CandidateDetectionMode::CompileTimeTargetFeatures
}

#[cfg(not(feature = "simd"))]
const fn candidate_detection_mode() -> CandidateDetectionMode {
    CandidateDetectionMode::SimdFeatureDisabled
}