doido_controller/secret.rs
1//! The process-global secret key base used to sign/encrypt cookies (session,
2//! flash, signed cookie jar).
3//!
4//! An app installs its real secret once at boot with [`set_key_base`] (from
5//! config/credentials); until then a fixed **dev-insecure** default is used so
6//! things work out of the box in development. Never ship the default.
7
8use std::sync::OnceLock;
9
10static SECRET: OnceLock<Vec<u8>> = OnceLock::new();
11
12/// The insecure development default. Real apps must override it at boot.
13const DEV_SECRET: &[u8] = b"doido-dev-insecure-secret-key-base-change-me";
14
15/// Install the app's secret key base. Idempotent: a second call is rejected and
16/// returns the passed-in secret back. Call once at boot before serving.
17pub fn set_key_base(secret: impl Into<Vec<u8>>) -> Result<(), Vec<u8>> {
18 SECRET.set(secret.into())
19}
20
21/// The configured secret key base, or the dev-insecure default when unset.
22pub fn key_base() -> Vec<u8> {
23 SECRET.get().cloned().unwrap_or_else(|| DEV_SECRET.to_vec())
24}