Skip to main content

webhook_verify/core/
secret.rs

1//! The [`Secret`] wrapper: keeps signing material out of logs, errors, and
2//! debug output.
3
4use alloc::string::String;
5use core::fmt;
6
7/// Wraps webhook signing material (an HMAC key, or — for asymmetric schemes
8/// such as Discord — a hex-encoded public key; see the provider's docs for
9/// which one applies).
10///
11/// `Debug` and `Display` print `Secret(**redacted**)` only. The inner value is
12/// deliberately not readable through the public API.
13#[must_use]
14#[derive(Clone, Default)]
15pub struct Secret(String);
16
17impl Secret {
18    /// Creates a secret from any string-like value.
19    pub fn new(value: impl Into<String>) -> Self {
20        Self(value.into())
21    }
22
23    /// Raw key bytes. Crate-internal: verification helpers need the key
24    /// material, but it must never be exposed through the public API or
25    /// printed anywhere.
26    #[must_use]
27    pub(crate) fn as_bytes(&self) -> &[u8] {
28        self.0.as_bytes()
29    }
30}
31
32impl fmt::Debug for Secret {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        f.write_str("Secret(**redacted**)")
35    }
36}
37
38impl fmt::Display for Secret {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str("Secret(**redacted**)")
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::Secret;
47
48    #[test]
49    fn debug_and_display_are_redacted() {
50        let s = Secret::new("super-secret-hmac-key");
51        assert_eq!(format!("{s:?}"), "Secret(**redacted**)");
52        assert_eq!(s.to_string(), "Secret(**redacted**)");
53        assert!(!format!("{s:?}").contains("super"));
54    }
55
56    #[test]
57    fn debug_of_containing_struct_does_not_leak_via_derive_chain() {
58        // If someone wraps a Secret in a derived-Debug struct, the Secret's own
59        // redacted Debug is what renders — never the inner value.
60        let s = Secret::new("leak-me");
61        assert_eq!(format!("{s:?}"), "Secret(**redacted**)");
62    }
63}