Skip to main content

azure_devops/
auth.rs

1use secrecy::{ExposeSecret, SecretString};
2use std::fmt;
3
4/// Authentication credentials for Azure DevOps.
5///
6/// Currently supports Personal Access Token (PAT) authentication.
7/// Additional mechanisms (Basic, Bearer, etc.) can be added as needed.
8pub enum Credentials {
9    /// Authenticate using a Personal Access Token.
10    Pat(SecretString),
11}
12
13impl Credentials {
14    /// Create credentials from a PAT string.
15    ///
16    /// The token is stored in a [`SecretString`] to prevent accidental
17    /// exposure in logs or debug output.
18    pub fn from_pat(token: impl Into<String>) -> Self {
19        Credentials::Pat(SecretString::new(token.into().into()))
20    }
21
22    /// Apply the credentials to an HTTP request.
23    ///
24    /// For PAT: uses HTTP Basic auth with an empty username and the PAT as password,
25    /// which is how Azure DevOps expects PATs to be sent.
26    pub(crate) fn apply(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
27        match self {
28            Credentials::Pat(token) => request.basic_auth("", Some(token.expose_secret())),
29        }
30    }
31}
32
33impl fmt::Debug for Credentials {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Credentials::Pat(_) => write!(f, "Pat(<redacted>)"),
37        }
38    }
39}
40
41impl Clone for Credentials {
42    fn clone(&self) -> Self {
43        match self {
44            Credentials::Pat(t) => Credentials::Pat(t.clone()),
45        }
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn from_pat_creates_pat_variant() {
55        let creds = Credentials::from_pat("my-token");
56        match creds {
57            Credentials::Pat(_) => {}
58        }
59    }
60
61    #[test]
62    fn debug_does_not_expose_token() {
63        let creds = Credentials::from_pat("super-secret-token");
64        let debug_str = format!("{:?}", creds);
65        assert!(!debug_str.contains("super-secret-token"));
66        assert!(debug_str.contains("redacted"));
67    }
68
69    #[test]
70    fn clone_preserves_token() {
71        let creds = Credentials::from_pat("my-token");
72        let cloned = creds.clone();
73        // Verify the token is the same by checking Debug output is identical
74        assert_eq!(format!("{:?}", creds), format!("{:?}", cloned));
75    }
76}