Skip to main content

bitbucket_cli/auth/
mod.rs

1pub mod api_key;
2pub mod file_store;
3pub mod keyring_store;
4pub mod oauth;
5
6use anyhow::Result;
7use base64::Engine;
8use serde::{Deserialize, Serialize};
9
10pub use api_key::*;
11pub use file_store::*;
12pub use keyring_store::*;
13pub use oauth::*;
14
15/// Credential types for Bitbucket authentication
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub enum Credential {
18    /// OAuth 2.0 credentials (preferred method)
19    OAuth {
20        access_token: String,
21        refresh_token: Option<String>,
22        expires_at: Option<i64>,
23        #[serde(default, skip_serializing_if = "Option::is_none")]
24        client_id: Option<String>,
25        #[serde(default, skip_serializing_if = "Option::is_none")]
26        client_secret: Option<String>,
27    },
28    /// API Key / HTTP Access Token (for automation/CI)
29    ApiKey { username: String, api_key: String },
30}
31
32impl Credential {
33    /// Get the authorization header value for API requests
34    #[inline]
35    pub fn auth_header(&self) -> String {
36        match self {
37            Credential::OAuth { access_token, .. } => {
38                let mut result = String::with_capacity(7 + access_token.len());
39                result.push_str("Bearer ");
40                result.push_str(access_token);
41                result
42            }
43            Credential::ApiKey { username, api_key } => {
44                let basic = format!("{}:{}", username, api_key);
45                let encoded = base64::engine::general_purpose::STANDARD.encode(basic.as_bytes());
46                let mut result = String::with_capacity(6 + encoded.len());
47                result.push_str("Basic ");
48                result.push_str(&encoded);
49                result
50            }
51        }
52    }
53
54    /// Get the credential type name for display
55    #[inline]
56    pub fn type_name(&self) -> &'static str {
57        match self {
58            Credential::OAuth { .. } => "OAuth 2.0",
59            Credential::ApiKey { .. } => "API Key",
60        }
61    }
62
63    /// Check if the credential needs refresh
64    #[inline]
65    pub fn needs_refresh(&self) -> bool {
66        match self {
67            Credential::OAuth {
68                expires_at: Some(expires),
69                ..
70            } => {
71                // Refresh if expiring within 5 minutes (300 seconds)
72                *expires < chrono::Utc::now().timestamp() + 300
73            }
74            _ => false,
75        }
76    }
77
78    /// Get stored OAuth consumer credentials (client_id, client_secret)
79    pub fn oauth_consumer_credentials(&self) -> Option<(&str, &str)> {
80        match self {
81            Credential::OAuth {
82                client_id: Some(id),
83                client_secret: Some(secret),
84                ..
85            } => Some((id, secret)),
86            _ => None,
87        }
88    }
89
90    /// Get username (only available for API key credentials)
91    pub fn username(&self) -> Option<&str> {
92        match self {
93            Credential::ApiKey { username, .. } => Some(username),
94            _ => None,
95        }
96    }
97}
98
99/// Authentication manager - uses file-based credential storage
100pub struct AuthManager {
101    store: FileStore,
102}
103
104impl AuthManager {
105    pub fn new() -> Result<Self> {
106        Ok(Self {
107            store: FileStore::new()?,
108        })
109    }
110
111    /// Get stored credentials
112    pub fn get_credentials(&self) -> Result<Option<Credential>> {
113        self.store.get_credential()
114    }
115
116    /// Store credentials
117    pub fn store_credentials(&self, credential: &Credential) -> Result<()> {
118        self.store.store_credential(credential)
119    }
120
121    /// Clear stored credentials
122    pub fn clear_credentials(&self) -> Result<()> {
123        self.store.delete_credential()
124    }
125
126    /// Check if authenticated
127    pub fn is_authenticated(&self) -> bool {
128        self.get_credentials().map(|c| c.is_some()).unwrap_or(false)
129    }
130}
131
132impl Default for AuthManager {
133    fn default() -> Self {
134        Self::new().expect("Failed to create auth manager")
135    }
136}