Skip to main content

nextcloud_auth/bearer/
token.rs

1use std::fmt;
2
3use crate::SecretString;
4
5/// An OAuth2 access token issued by a Nextcloud instance.
6///
7/// The token is kept behind [`SecretString`] so no `Debug` or log line can
8/// reveal it; request the plaintext through [`BearerToken::expose`].
9#[derive(Clone)]
10pub struct BearerToken {
11    secret: SecretString,
12}
13
14impl BearerToken {
15    /// Wraps a token string.
16    pub fn new(token: impl Into<String>) -> Self {
17        Self {
18            secret: SecretString::new(token),
19        }
20    }
21
22    /// Borrows the token plaintext.
23    pub fn expose(&self) -> &str {
24        self.secret.expose()
25    }
26}
27
28impl fmt::Debug for BearerToken {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        f.debug_tuple("BearerToken").field(&self.secret).finish()
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::BearerToken;
37
38    #[test]
39    fn debug_redacts_the_token() {
40        let token = BearerToken::new("ghp-s3cr3t-access-token");
41        let rendered = format!("{token:?}");
42        assert!(!rendered.contains("ghp-s3cr3t-access-token"));
43        assert!(rendered.contains("<redacted>"));
44    }
45
46    #[test]
47    fn expose_returns_the_token() {
48        assert_eq!(BearerToken::new("abc").expose(), "abc");
49    }
50}