redacted-error 0.2.0

Stable public error messages with debug-only diagnostic detail
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
//! Stable public error messages with debug-only diagnostic detail.
//!
//! `redacted-error` gives applications a small facade for errors that cross
//! crate, process, API, or protocol boundaries:
//!
//! - static public messages go through [`message!`] / [`message_string!`]
//! - runtime diagnostic details go through [`detail!`], [`detail`], or [`display`]
//! - backend-facing behavior uses [`ErrorCode`] or [`PublicError`]
//! - release `Debug` output can delegate to redacted `Display` with
//!   [`impl_redacted_debug!`]
//!
//! The default build uses `obfstr` internally for static public messages. Build
//! with `default-features = false` to use plain literals instead. The public
//! macros stay the same either way.
//!
//! # Security
//!
//! This crate is a leakage-reduction tool, not a confidentiality boundary.
//!
//! - The `obfuscate` feature only raises the bar against trivial `strings`-style
//!   inspection of compiled binaries. It is **not** a defense against a debugger,
//!   dynamic instrumentation, symbol tables, or any motivated reverse engineer.
//!   Do not treat obfuscated literals as secret.
//!
//! - Diagnostic-detail stripping is gated on `cfg(debug_assertions)`. That cfg
//!   is on in the `dev` profile and off in the standard `release` profile, but
//!   Cargo lets users opt back in with `[profile.release] debug-assertions = true`.
//!   Under that override every [`detail!`] / [`display`] / [`detail`] call leaks
//!   runtime detail in release builds. Avoid that combination if redaction
//!   matters.
//!
//! - The [`detail!`] macro skips evaluating its format arguments in release.
//!   The [`detail`] and [`display`] free functions still evaluate (and drop)
//!   their argument, because the cfg branch lives inside the function body.
//!   Prefer the macro when the argument has nontrivial cost or side effects.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

#[cfg(feature = "obfuscate")]
#[doc(hidden)]
pub mod __private {
    pub use obfstr::obfstring;
}

use std::{borrow::Cow, fmt, ops::Deref};

/// Public-facing message text.
///
/// With plain literals this can borrow a static string. With the obfuscating
/// backend it owns the decoded string, avoiding backend-specific lifetime
/// behavior in the public API.
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Message(Cow<'static, str>);

impl Message {
    /// Creates a message from a static string.
    #[must_use]
    pub fn from_static(value: &'static str) -> Self {
        Self(Cow::Borrowed(value))
    }

    /// Creates a message from an owned string.
    #[must_use]
    pub fn from_string(value: String) -> Self {
        Self(Cow::Owned(value))
    }

    /// Borrows the message as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }

    /// Converts the message into an owned string.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0.into_owned()
    }
}

impl Default for Message {
    fn default() -> Self {
        Self(Cow::Borrowed(""))
    }
}

impl fmt::Display for Message {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl fmt::Debug for Message {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

impl AsRef<str> for Message {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Message {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl PartialEq<&str> for Message {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<Message> for &str {
    fn eq(&self, other: &Message) -> bool {
        *self == other.as_str()
    }
}

impl From<&'static str> for Message {
    fn from(value: &'static str) -> Self {
        Self::from_static(value)
    }
}

impl From<String> for Message {
    fn from(value: String) -> Self {
        Self::from_string(value)
    }
}

impl From<Message> for String {
    fn from(value: Message) -> Self {
        value.into_string()
    }
}

/// Returns a public-facing message for a string literal.
///
/// With the default `obfuscate` feature this uses the crate's current
/// obfuscation backend. With default features disabled this wraps a borrowed
/// literal.
///
/// Accepts only a string literal — not a `const`, `&'static str` binding, or
/// `concat!()` expansion. The obfuscation backend requires a literal token, and
/// the macro enforces this for both feature configurations to keep behavior
/// consistent.
///
/// ```
/// let message = redacted_error::message!("request failed");
/// assert_eq!(message.as_str(), "request failed");
/// ```
#[cfg(feature = "obfuscate")]
#[macro_export]
macro_rules! message {
    ($literal:literal) => {
        $crate::Message::from_string($crate::__private::obfstring!($literal))
    };
}

/// Returns a public-facing message for a string literal.
///
/// See [`message!`] for details.
#[cfg(not(feature = "obfuscate"))]
#[macro_export]
macro_rules! message {
    ($literal:literal) => {
        $crate::Message::from_static($literal)
    };
}

/// Returns an owned public-facing message.
///
/// With the default `obfuscate` feature this uses the crate's current
/// obfuscation backend. With default features disabled this allocates from the
/// literal.
///
/// Accepts only a string literal; see [`message!`] for the rationale.
///
/// ```
/// let owned = redacted_error::message_string!("request failed");
/// assert_eq!(owned, String::from("request failed"));
/// ```
#[cfg(feature = "obfuscate")]
#[macro_export]
macro_rules! message_string {
    ($literal:literal) => {
        $crate::message!($literal).into_string()
    };
}

/// Returns an owned public-facing message.
///
/// See [`message_string!`] for details.
#[cfg(not(feature = "obfuscate"))]
#[macro_export]
macro_rules! message_string {
    ($literal:literal) => {
        $crate::message!($literal).into_string()
    };
}

/// Captures runtime diagnostic detail in debug builds and strips it in release builds.
///
/// The argument is always evaluated, then either converted to a `String` (debug)
/// or dropped (release). Prefer [`detail!`] when constructing the value is
/// nontrivial or has side effects, because the macro avoids evaluation entirely
/// in release builds.
///
/// In debug builds the result is the input string; in release builds it is empty.
///
/// ```
/// let _ = redacted_error::detail("addr=127.0.0.1:8080");
/// ```
#[must_use]
pub fn detail(value: impl Into<String>) -> String {
    #[cfg(debug_assertions)]
    {
        value.into()
    }

    #[cfg(not(debug_assertions))]
    {
        let _ = value;
        String::new()
    }
}

/// Formats runtime diagnostic detail in debug builds and strips it in release builds.
///
/// The argument is always evaluated, then either rendered (debug) or dropped
/// (release). Prefer [`detail!`] when the argument has nontrivial cost or side
/// effects.
///
/// In debug builds the result is the rendered value; in release builds it is empty.
///
/// ```
/// let _ = redacted_error::display("127.0.0.1:8080");
/// ```
#[must_use]
pub fn display(value: impl std::fmt::Display) -> String {
    #[cfg(debug_assertions)]
    {
        value.to_string()
    }

    #[cfg(not(debug_assertions))]
    {
        let _ = value;
        String::new()
    }
}

/// Formats runtime diagnostic detail in debug builds and strips it in release builds.
///
/// In release builds the format arguments are not evaluated — any side effects
/// in the argument expressions are skipped.
///
/// ```
/// let detail = redacted_error::detail!("addr={}", "127.0.0.1");
/// # #[cfg(debug_assertions)]
/// assert_eq!(detail, "addr=127.0.0.1");
/// ```
#[macro_export]
macro_rules! detail {
    ($($arg:tt)*) => {{
        #[cfg(debug_assertions)]
        {
            format!($($arg)*)
        }

        #[cfg(not(debug_assertions))]
        {
            ::std::string::String::new()
        }
    }};
}

/// Machine-readable code for errors that cross process or API boundaries.
pub trait ErrorCode {
    /// Returns a stable code for control flow and public API responses.
    ///
    /// Use [`message!`] to keep the code literal out of the binary, or
    /// [`Message::from_static`] for a plain literal. Comparison against `&str`
    /// works directly via [`Message`]'s `PartialEq<&str>`:
    ///
    /// ```
    /// use redacted_error::{ErrorCode, Message};
    /// # struct E;
    /// # impl ErrorCode for E {
    /// #     fn code(&self) -> Message { redacted_error::message!("x.y") }
    /// # }
    /// # let err = E;
    /// if err.code() == "x.y" { /* ... */ }
    /// ```
    fn code(&self) -> Message;
}

/// Stable public message for errors that cross process or API boundaries.
///
/// This should be safe to expose in release builds. It should not include
/// paths, addresses, tokens, remote messages, OS errors, SQL errors, config
/// values, or other runtime detail.
pub trait PublicError: ErrorCode {
    /// Returns the stable public-facing message.
    fn public_message(&self) -> Message;
}

/// Implements release `Debug` by delegating to `Display`.
///
/// Pair this with `#[cfg_attr(debug_assertions, derive(Debug))]` on error types
/// whose fields may contain sensitive runtime detail. Do **not** use
/// `#[derive(Debug)]` unconditionally: in release that either conflicts with
/// the impl emitted here or, if this macro is omitted, leaks every field
/// through the derived `Debug`.
///
/// ```
/// #[cfg_attr(debug_assertions, derive(Debug))]
/// struct MyError(String);
///
/// impl std::fmt::Display for MyError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         f.write_str("public")
///     }
/// }
///
/// redacted_error::impl_redacted_debug!(MyError);
///
/// let err = MyError("secret".into());
/// let _ = format!("{err:?}");
/// ```
#[macro_export]
macro_rules! impl_redacted_debug {
    ($ty:ty) => {
        #[cfg(not(debug_assertions))]
        impl ::std::fmt::Debug for $ty {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                ::std::fmt::Display::fmt(self, f)
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use super::Message;
    use std::fmt;

    #[test]
    fn message_returns_public_literal() {
        assert_eq!(crate::message!("request failed"), "request failed");
    }

    #[test]
    fn message_string_returns_owned_public_literal() {
        assert_eq!(
            crate::message_string!("request failed"),
            String::from("request failed")
        );
    }

    #[test]
    fn message_default_is_empty() {
        assert_eq!(Message::default(), "");
    }

    #[test]
    fn message_from_static_and_string() {
        let from_static: Message = "literal".into();
        let from_owned: Message = String::from("literal").into();
        assert_eq!(from_static, from_owned);
        assert_eq!(from_static.as_str(), "literal");
    }

    #[test]
    fn detail_is_available_only_in_debug_builds() {
        let value = super::detail("secret");

        #[cfg(debug_assertions)]
        assert_eq!(value, "secret");

        #[cfg(not(debug_assertions))]
        assert!(value.is_empty());
    }

    #[test]
    fn display_is_available_only_in_debug_builds() {
        let value = super::display("secret");

        #[cfg(debug_assertions)]
        assert_eq!(value, "secret");

        #[cfg(not(debug_assertions))]
        assert!(value.is_empty());
    }

    #[test]
    fn detail_macro_is_available_only_in_debug_builds() {
        let value = crate::detail!("secret {}", 42);

        #[cfg(debug_assertions)]
        assert_eq!(value, "secret 42");

        #[cfg(not(debug_assertions))]
        assert!(value.is_empty());
    }

    #[cfg_attr(debug_assertions, derive(Debug))]
    #[allow(dead_code)]
    struct SampleError(String);

    impl fmt::Display for SampleError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            #[cfg(debug_assertions)]
            {
                write!(f, "{} {}", crate::message!("sample failed:"), self.0)
            }

            #[cfg(not(debug_assertions))]
            {
                write!(f, "{}", crate::message!("sample failed"))
            }
        }
    }

    crate::impl_redacted_debug!(SampleError);

    impl super::ErrorCode for SampleError {
        fn code(&self) -> Message {
            crate::message!("sample.failed")
        }
    }

    impl super::PublicError for SampleError {
        fn public_message(&self) -> Message {
            crate::message!("sample failed")
        }
    }

    #[test]
    fn release_debug_delegates_to_display() {
        let err = SampleError("secret".to_owned());
        let debug = format!("{err:?}");

        #[cfg(debug_assertions)]
        assert!(debug.contains("secret"));

        #[cfg(not(debug_assertions))]
        assert_eq!(debug, "sample failed");
    }

    #[test]
    fn public_error_exposes_stable_code_and_message() {
        let err = SampleError("secret".to_owned());
        assert_eq!(super::ErrorCode::code(&err), "sample.failed");
        assert_eq!(super::PublicError::public_message(&err), "sample failed");
    }
}