Skip to main content

bitbucket_cli/auth/
mod.rs

1pub mod api_key;
2pub mod credential_store;
3pub mod file_store;
4pub mod keyring_store;
5pub mod oauth;
6
7use anyhow::Result;
8use base64::Engine;
9use serde::{Deserialize, Serialize};
10
11pub use api_key::*;
12pub use credential_store::*;
13pub use file_store::*;
14pub use keyring_store::*;
15pub use oauth::*;
16
17/// Credential types for Bitbucket authentication
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub enum Credential {
20    /// OAuth 2.0 credentials (preferred method)
21    OAuth {
22        access_token: String,
23        refresh_token: Option<String>,
24        expires_at: Option<i64>,
25        #[serde(default, skip_serializing_if = "Option::is_none")]
26        client_id: Option<String>,
27        #[serde(default, skip_serializing_if = "Option::is_none")]
28        client_secret: Option<String>,
29    },
30    /// API Key / HTTP Access Token (for automation/CI)
31    ApiKey { username: String, api_key: String },
32}
33
34impl Credential {
35    /// Get the authorization header value for API requests
36    #[inline]
37    pub fn auth_header(&self) -> String {
38        match self {
39            Credential::OAuth { access_token, .. } => {
40                let mut result = String::with_capacity(7 + access_token.len());
41                result.push_str("Bearer ");
42                result.push_str(access_token);
43                result
44            }
45            Credential::ApiKey { username, api_key } => {
46                let basic = format!("{}:{}", username, api_key);
47                let encoded = base64::engine::general_purpose::STANDARD.encode(basic.as_bytes());
48                let mut result = String::with_capacity(6 + encoded.len());
49                result.push_str("Basic ");
50                result.push_str(&encoded);
51                result
52            }
53        }
54    }
55
56    /// Get the credential type name for display
57    #[inline]
58    pub fn type_name(&self) -> &'static str {
59        match self {
60            Credential::OAuth { .. } => "OAuth 2.0",
61            Credential::ApiKey { .. } => "API Key",
62        }
63    }
64
65    /// Check if the credential needs refresh
66    #[inline]
67    pub fn needs_refresh(&self) -> bool {
68        match self {
69            Credential::OAuth {
70                expires_at: Some(expires),
71                ..
72            } => {
73                // Refresh if expiring within 5 minutes (300 seconds)
74                *expires < chrono::Utc::now().timestamp() + 300
75            }
76            _ => false,
77        }
78    }
79
80    /// Get stored OAuth consumer credentials (client_id, client_secret)
81    pub fn oauth_consumer_credentials(&self) -> Option<(&str, &str)> {
82        match self {
83            Credential::OAuth {
84                client_id: Some(id),
85                client_secret: Some(secret),
86                ..
87            } => Some((id, secret)),
88            _ => None,
89        }
90    }
91
92    /// Get username (only available for API key credentials)
93    pub fn username(&self) -> Option<&str> {
94        match self {
95            Credential::ApiKey { username, .. } => Some(username),
96            _ => None,
97        }
98    }
99}
100
101/// Authentication manager - uses the platform secret store with file fallback
102pub struct AuthManager {
103    store: CredentialStore,
104}
105
106impl AuthManager {
107    pub fn new() -> Result<Self> {
108        Ok(Self {
109            store: CredentialStore::new()?,
110        })
111    }
112
113    /// Get stored credentials
114    pub fn get_credentials(&self) -> Result<Option<Credential>> {
115        self.store.get_credential()
116    }
117
118    /// Store credentials
119    pub fn store_credentials(&self, credential: &Credential) -> Result<()> {
120        self.store.store_credential(credential)
121    }
122
123    /// Clear stored credentials
124    pub fn clear_credentials(&self) -> Result<()> {
125        self.store.delete_credential()
126    }
127
128    /// Check if authenticated
129    pub fn is_authenticated(&self) -> bool {
130        self.get_credentials().map(|c| c.is_some()).unwrap_or(false)
131    }
132}
133
134impl Default for AuthManager {
135    fn default() -> Self {
136        Self::new().expect("Failed to create auth manager")
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    fn oauth_credential(expires_at: Option<i64>) -> Credential {
145        Credential::OAuth {
146            access_token: "test-access-token".to_string(),
147            refresh_token: None,
148            expires_at,
149            client_id: None,
150            client_secret: None,
151        }
152    }
153
154    #[test]
155    fn oauth_auth_header_is_bearer_token() {
156        let credential = oauth_credential(None);
157        assert_eq!(credential.auth_header(), "Bearer test-access-token");
158    }
159
160    #[test]
161    fn api_key_auth_header_is_basic_base64() {
162        let credential = Credential::ApiKey {
163            username: "alice".to_string(),
164            api_key: "s3cret-key".to_string(),
165        };
166        let expected = format!(
167            "Basic {}",
168            base64::engine::general_purpose::STANDARD.encode("alice:s3cret-key")
169        );
170        assert_eq!(credential.auth_header(), expected);
171    }
172
173    #[test]
174    fn api_key_never_needs_refresh() {
175        let credential = Credential::ApiKey {
176            username: "alice".to_string(),
177            api_key: "s3cret-key".to_string(),
178        };
179        assert!(!credential.needs_refresh());
180    }
181
182    #[test]
183    fn oauth_without_expiry_never_needs_refresh() {
184        let credential = oauth_credential(None);
185        assert!(!credential.needs_refresh());
186    }
187
188    #[test]
189    fn oauth_expiring_beyond_five_minutes_does_not_need_refresh() {
190        // 10 minutes from now: well past the 5-minute refresh window
191        let expires_at = chrono::Utc::now().timestamp() + 600;
192        let credential = oauth_credential(Some(expires_at));
193        assert!(!credential.needs_refresh());
194    }
195
196    #[test]
197    fn oauth_expiring_within_five_minutes_needs_refresh() {
198        // 1 minute from now: inside the 5-minute refresh window
199        let expires_at = chrono::Utc::now().timestamp() + 60;
200        let credential = oauth_credential(Some(expires_at));
201        assert!(credential.needs_refresh());
202    }
203
204    #[test]
205    fn oauth_already_expired_needs_refresh() {
206        let expires_at = chrono::Utc::now().timestamp() - 600;
207        let credential = oauth_credential(Some(expires_at));
208        assert!(credential.needs_refresh());
209    }
210}