hyperi-rustlib 2.8.5

There's plenty of sage advice out there about how to run Rust services in production at scale — config cascades, structured logging, masking secrets, multi-backend secrets management, Prometheus, OpenTelemetry, Kafka transports, tiered disk-spillover sinks, adaptive worker pools, graceful shutdown — but almost none of it as code you can just install and use. This is that code. Opinionated, drop-in, working out of the box. The patterns from blog posts, watercooler chats and beers with your Google mates as actual library — not a framework you assemble from twenty crates and 8 weeks of munging.
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
// Project:   hyperi-rustlib
// File:      src/sensitive.rs
// Purpose:   Compile-time safe sensitive string type that never serialises its value
// Language:  Rust
//
// License:   BUSL-1.1
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Sensitive string type for fields that must never be exposed.
//!
//! [`SensitiveString`] wraps a `String` but always serialises as
//! `"***REDACTED***"`. This provides compile-time guarantees that the
//! value cannot leak through serialisation -- not in the config registry,
//! not in logs, not in debug output, not in API responses.
//!
//! This module is always available (no feature gate) so that any module
//! can use `SensitiveString` regardless of which features are enabled.
//!
//! # Three layers of secret protection
//!
//! | Layer | Mechanism | Catches |
//! |-------|-----------|---------|
//! | `#[serde(skip_serializing)]` | Field absent from output | Fields that should never appear |
//! | Heuristic auto-redaction | Field name pattern matching | Common names: password, secret, token, key |
//! | `SensitiveString` type | Value always serialises as redacted | Non-obvious fields: connection_string, dsn |
//!
//! # Usage
//!
//! ```rust
//! use hyperi_rustlib::SensitiveString;
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct DbConfig {
//!     host: String,
//!     port: u16,
//!     connection_string: SensitiveString,  // Always redacted
//! }
//! ```

use std::cell::Cell;
use std::fmt;

use serde::de::Deserializer;
use serde::ser::Serializer;

const REDACTED: &str = "***REDACTED***";

thread_local! {
    /// Per-thread serde-exposure flag. When set (via [`expose_during`])
    /// [`SensitiveString::serialize`] writes the inner value verbatim
    /// instead of `***REDACTED***`. Default: `false` -- every other call
    /// site continues to redact.
    static EXPOSE: Cell<bool> = const { Cell::new(false) };
}

/// Drop-guard for the thread-local exposure flag.
///
/// Using a guard (rather than a try/finally pair) ensures the flag is
/// restored even if the closure passed to [`expose_during`] panics. Held
/// for the duration of the `expose_during` body, dropped at scope-exit.
struct ExposeGuard {
    prev: bool,
}

impl ExposeGuard {
    fn enter() -> Self {
        EXPOSE.with(|e| {
            let prev = e.get();
            e.set(true);
            Self { prev }
        })
    }
}

impl Drop for ExposeGuard {
    fn drop(&mut self) {
        let prev = self.prev;
        EXPOSE.with(|e| e.set(prev));
    }
}

/// Run `f` with [`SensitiveString`]'s `Serialize` impl exposing inner values.
///
/// Use this around code paths that need to serialise-and-deserialise a
/// config struct without destroying its secrets -- typically the
/// `figment::Figment::from(Serialized::defaults(&config))` + `.extract()`
/// round-trip in a consumer's config loader.
///
/// # Scope and reentrancy
///
/// The flag is thread-local. Calls from inside the closure on the same
/// thread observe exposure; calls from other threads do not. Nested
/// calls compose correctly (inner guards restore the outer state on
/// drop). Async callers should be aware that the flag does NOT cross
/// `.await` boundaries to other threads -- keep the round-trip on one
/// thread, or wrap each thread's section in its own
/// `expose_during`.
///
/// # Panic safety
///
/// If `f` panics, the previous flag value is restored via an RAII
/// drop guard before the panic unwinds further.
///
/// # Examples
///
/// ```rust
/// use hyperi_rustlib::{SensitiveString, expose_during};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct Cfg {
///     password: SensitiveString,
/// }
///
/// let cfg = Cfg { password: SensitiveString::new("hunter2") };
///
/// // Default: serialise redacts.
/// let json = serde_json::to_string(&cfg).unwrap();
/// assert!(json.contains("***REDACTED***"));
///
/// // Inside expose_during: serialise reveals so a round-trip preserves the value.
/// let round_tripped: Cfg = expose_during(|| {
///     let v = serde_json::to_value(&cfg).unwrap();
///     serde_json::from_value(v).unwrap()
/// });
/// assert_eq!(round_tripped.password.expose(), "hunter2");
///
/// // After the call, default redaction resumes.
/// let json = serde_json::to_string(&cfg).unwrap();
/// assert!(json.contains("***REDACTED***"));
/// ```
pub fn expose_during<F, R>(f: F) -> R
where
    F: FnOnce() -> R,
{
    let _guard = ExposeGuard::enter();
    f()
}

/// A string value that is always redacted when serialised.
///
/// Use this for config fields that contain secrets but don't have
/// obviously-sensitive names (e.g., `connection_string`, `dsn`, `uri`).
///
/// - `Serialize` always outputs `"***REDACTED***"`
/// - `Deserialize` reads the actual value normally
/// - `Display` shows `***REDACTED***`
/// - `Debug` shows `SensitiveString(***REDACTED***)`
/// - Inner value accessible via `.expose()` for application logic
#[derive(Clone, Default, PartialEq, Eq)]
pub struct SensitiveString(String);

impl SensitiveString {
    /// Create a new sensitive string.
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Expose the inner value for application logic.
    ///
    /// This is the only way to access the actual value. The name is
    /// intentionally explicit to make usage grep-able in code review.
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.0
    }

    /// Check if the inner value is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl serde::Serialize for SensitiveString {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // Honour the thread-local exposure flag set by `expose_during`.
        // Without exposure (the default), every serialise path --
        // serde_json::to_string, config-registry dump, logger output --
        // emits the redacted constant. Inside `expose_during`, the
        // serializer emits the inner value verbatim, which is what
        // figment / serde round-trips need to avoid destroying secrets
        // (see hyperi-rustlib#41).
        if EXPOSE.with(Cell::get) {
            serializer.serialize_str(&self.0)
        } else {
            serializer.serialize_str(REDACTED)
        }
    }
}

impl<'de> serde::Deserialize<'de> for SensitiveString {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer).map(SensitiveString)
    }
}

impl fmt::Display for SensitiveString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{REDACTED}")
    }
}

impl fmt::Debug for SensitiveString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SensitiveString({REDACTED})")
    }
}

impl From<String> for SensitiveString {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for SensitiveString {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn serialize_always_redacted() {
        let s = SensitiveString::new("my_actual_secret");
        let json = serde_json::to_string(&s).unwrap();
        assert_eq!(json, format!("\"{REDACTED}\""));
        assert!(!json.contains("my_actual_secret"));
    }

    #[test]
    fn deserialize_reads_actual_value() {
        let json = "\"my_actual_secret\"";
        let s: SensitiveString = serde_json::from_str(json).unwrap();
        assert_eq!(s.expose(), "my_actual_secret");
    }

    #[test]
    fn display_is_redacted() {
        let s = SensitiveString::new("secret123");
        assert_eq!(format!("{s}"), REDACTED);
        assert!(!format!("{s}").contains("secret123"));
    }

    #[test]
    fn debug_is_redacted() {
        let s = SensitiveString::new("secret123");
        let debug = format!("{s:?}");
        assert!(debug.contains(REDACTED));
        assert!(!debug.contains("secret123"));
    }

    #[test]
    fn expose_returns_actual_value() {
        let s = SensitiveString::new("the_real_value");
        assert_eq!(s.expose(), "the_real_value");
    }

    #[test]
    fn default_is_empty() {
        let s = SensitiveString::default();
        assert!(s.is_empty());
        assert_eq!(s.expose(), "");
    }

    #[test]
    fn from_string() {
        let s: SensitiveString = "hello".into();
        assert_eq!(s.expose(), "hello");

        let s: SensitiveString = String::from("world").into();
        assert_eq!(s.expose(), "world");
    }

    #[test]
    fn struct_with_sensitive_field_serialises_safely() {
        #[derive(serde::Serialize, serde::Deserialize)]
        struct Config {
            host: String,
            connection_string: SensitiveString,
        }

        let config = Config {
            host: "db.example.com".into(),
            connection_string: SensitiveString::new("postgres://user:pass@host/db"),
        };

        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("db.example.com"));
        assert!(json.contains(REDACTED));
        assert!(!json.contains("postgres://"));
        assert!(!json.contains("user:pass"));
    }

    #[test]
    fn struct_with_sensitive_field_deserialises_correctly() {
        #[derive(serde::Serialize, serde::Deserialize)]
        struct Config {
            host: String,
            connection_string: SensitiveString,
        }

        let json =
            r#"{"host":"db.example.com","connection_string":"postgres://user:pass@host/db"}"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert_eq!(config.host, "db.example.com");
        assert_eq!(
            config.connection_string.expose(),
            "postgres://user:pass@host/db"
        );
    }

    #[test]
    fn no_leak_through_any_serialisation_path() {
        let secret = "super_secret_value_12345";
        let s = SensitiveString::new(secret);

        // serde_json
        assert!(!serde_json::to_string(&s).unwrap().contains(secret));
        // Display
        assert!(!format!("{s}").contains(secret));
        // Debug
        assert!(!format!("{s:?}").contains(secret));
        // Only expose() reveals it
        assert_eq!(s.expose(), secret);
    }

    // ----- Round-trip preservation (hyperi-rustlib#41) -----

    /// The motivating case from hyperi-rustlib#41: serialise to a serde
    /// `Value`, then deserialise back. Without `expose_during` the
    /// inner string is destroyed (replaced by `***REDACTED***`); inside
    /// the helper, the value survives.
    #[test]
    fn round_trip_inside_expose_during_preserves_value() {
        let s = SensitiveString::new("hunter2");
        let v = expose_during(|| serde_json::to_value(&s).unwrap());
        let round_tripped: SensitiveString = serde_json::from_value(v).unwrap();
        assert_eq!(round_tripped.expose(), "hunter2");
    }

    #[test]
    fn round_trip_outside_expose_during_redacts() {
        let s = SensitiveString::new("hunter2");
        // Default path -- no `expose_during` wrap.
        let v = serde_json::to_value(&s).unwrap();
        let round_tripped: SensitiveString = serde_json::from_value(v).unwrap();
        // The serialised form was the literal "***REDACTED***", so the
        // deserialised value is that literal. This is the bug being
        // fixed for the consumer who wraps their round-trip -- but the
        // default behaviour is preserved verbatim.
        assert_eq!(round_tripped.expose(), REDACTED);
    }

    #[test]
    fn expose_during_restores_after_body() {
        let s = SensitiveString::new("secret");
        // Before: redacted
        assert!(serde_json::to_string(&s).unwrap().contains(REDACTED));
        // Inside: exposed
        expose_during(|| {
            assert!(serde_json::to_string(&s).unwrap().contains("secret"));
        });
        // After: redacted again -- guard restored the flag
        assert!(serde_json::to_string(&s).unwrap().contains(REDACTED));
        assert!(!serde_json::to_string(&s).unwrap().contains("secret"));
    }

    #[test]
    fn expose_during_restores_after_panic() {
        let s = SensitiveString::new("secret");
        let result = std::panic::catch_unwind(|| {
            expose_during(|| {
                // Confirm we're exposed inside the closure.
                assert!(serde_json::to_string(&s).unwrap().contains("secret"));
                panic!("simulated panic");
            })
        });
        assert!(result.is_err(), "panic should have propagated");
        // The drop guard must have restored the flag despite the panic.
        assert!(serde_json::to_string(&s).unwrap().contains(REDACTED));
        assert!(!serde_json::to_string(&s).unwrap().contains("secret"));
    }

    #[test]
    fn expose_during_nests_correctly() {
        let s = SensitiveString::new("secret");
        expose_during(|| {
            assert!(serde_json::to_string(&s).unwrap().contains("secret"));
            expose_during(|| {
                assert!(serde_json::to_string(&s).unwrap().contains("secret"));
            });
            // Inner guard restored OUTER state (which was also exposed).
            assert!(serde_json::to_string(&s).unwrap().contains("secret"));
        });
        // Outer guard restored the original (redacted) state.
        assert!(serde_json::to_string(&s).unwrap().contains(REDACTED));
    }

    #[test]
    fn struct_round_trip_inside_expose_during_preserves_values() {
        // Mirrors the dfe-loader bug: serialise a Config containing a
        // SensitiveString password, merge env overrides via figment,
        // deserialise back. Without expose_during, password becomes
        // "***REDACTED***".
        #[derive(serde::Serialize, serde::Deserialize)]
        struct Config {
            host: String,
            password: SensitiveString,
        }
        let original = Config {
            host: "db.example.com".into(),
            password: SensitiveString::new("env-resolved-secret"),
        };
        let round_tripped: Config = expose_during(|| {
            let v = serde_json::to_value(&original).unwrap();
            serde_json::from_value(v).unwrap()
        });
        assert_eq!(round_tripped.host, "db.example.com");
        assert_eq!(round_tripped.password.expose(), "env-resolved-secret");
    }

    /// Cross-thread isolation: thread A's `expose_during` does NOT
    /// affect thread B's serialisation.
    #[test]
    fn expose_flag_is_thread_local() {
        use std::sync::{Arc, Mutex};
        let s = Arc::new(SensitiveString::new("secret"));
        let observed = Arc::new(Mutex::new(String::new()));

        let s2 = Arc::clone(&s);
        let observed2 = Arc::clone(&observed);
        let handle = std::thread::spawn(move || {
            // Thread B: no expose_during. Must observe REDACTED.
            let out = serde_json::to_string(&*s2).unwrap();
            *observed2.lock().unwrap() = out;
        });

        // Thread A: inside expose_during. Spawn happened above; let it
        // race the closure.
        expose_during(|| {
            std::thread::yield_now();
        });
        handle.join().unwrap();
        let b_output = observed.lock().unwrap().clone();
        assert!(
            b_output.contains(REDACTED),
            "thread B should have observed REDACTED, got: {b_output}"
        );
    }
}