1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use anyhow::Result;
use clap::Subcommand;
use colored::Colorize;
use dialoguer::Input;
use crate::auth::{ApiKeyAuth, AuthManager, OAuthFlow};
use crate::config::Config;
#[derive(Subcommand)]
pub enum AuthCommands {
/// Authenticate with Bitbucket (OAuth 2.0 or API key)
Login {
/// Use API key authentication (for automation/CI)
#[arg(long)]
api_key: bool,
/// OAuth Client ID (for OAuth authentication)
#[arg(long, env = "BITBUCKET_CLIENT_ID")]
client_id: Option<String>,
/// OAuth Client Secret (for OAuth authentication)
#[arg(long, env = "BITBUCKET_CLIENT_SECRET")]
client_secret: Option<String>,
},
/// Remove stored credentials
Logout,
/// Show authentication status
Status,
}
impl AuthCommands {
pub async fn run(self) -> Result<()> {
match self {
AuthCommands::Login {
api_key,
client_id,
client_secret,
} => {
let auth_manager = AuthManager::new()?;
// If --api-key flag is set, use API key authentication
if api_key {
ApiKeyAuth::authenticate(&auth_manager).await?;
return Ok(());
}
// Otherwise, use OAuth 2.0 authentication
// Resolve consumer credentials from (in priority):
// 1. CLI flags / env vars
// 2. Previously stored credentials
// 3. Interactive prompt (first-time only)
let stored_consumer = auth_manager.get_credentials().ok().flatten().and_then(|c| {
c.oauth_consumer_credentials()
.map(|(id, secret)| (id.to_owned(), secret.to_owned()))
});
let client_id = client_id
.or_else(|| stored_consumer.as_ref().map(|(id, _)| id.clone()))
.or_else(|| {
println!();
println!("📋 OAuth Consumer Setup Required");
println!();
println!("To use OAuth authentication, create an OAuth consumer in Bitbucket:");
println!("1. Go to: https://bitbucket.org/[workspace]/workspace/settings/oauth-consumers/new");
println!("2. Set callback URL to ONE of these (pick any available port):");
println!(" • http://127.0.0.1:8080/callback");
println!(" • http://127.0.0.1:3000/callback");
println!(" • http://127.0.0.1:8888/callback");
println!(" • http://127.0.0.1:9000/callback");
println!("3. Select required permissions:");
println!(" ✓ Account (Read)");
println!(" ✓ Repositories (Read)");
println!(" ✓ Pull requests (Read, Write)");
println!(" ✓ Issues (Read, Write)");
println!(" ✓ Pipelines (Read, Write)");
println!("4. Copy the Key (Client ID) and Secret");
println!();
Input::<String>::new()
.with_prompt("OAuth Client ID (Key)")
.interact_text()
.ok()
})
.ok_or_else(|| anyhow::anyhow!("OAuth Client ID is required"))?;
let client_secret = client_secret
.or_else(|| stored_consumer.map(|(_, secret)| secret))
.or_else(|| {
Input::<String>::new()
.with_prompt("OAuth Client Secret")
.interact_text()
.ok()
})
.ok_or_else(|| anyhow::anyhow!("OAuth Client Secret is required"))?;
let oauth = OAuthFlow::new(client_id, client_secret);
oauth.authenticate(&auth_manager).await?;
Ok(())
}
AuthCommands::Logout => {
let auth_manager = AuthManager::new()?;
auth_manager.clear_credentials()?;
let mut config = Config::load()?;
config.clear_auth();
config.save()?;
println!("{} Logged out successfully", "✓".green());
Ok(())
}
AuthCommands::Status => {
let auth_manager = AuthManager::new()?;
let config = Config::load()?;
if auth_manager.is_authenticated() {
println!("{} Authenticated", "✓".green());
if let Ok(Some(credential)) = auth_manager.get_credentials() {
println!(" {} {}", "Method:".dimmed(), credential.type_name());
// Show username from credential for API keys, or config for OAuth
if let Some(username) = credential.username() {
println!(" {} {}", "Username:".dimmed(), username);
} else if let Some(username) = config.username() {
println!(" {} {}", "Username:".dimmed(), username);
}
if credential.needs_refresh() {
println!(
" {} {}",
"Status:".dimmed(),
"Token needs refresh (will auto-refresh on next use)".yellow()
);
}
}
if let Some(workspace) = config.default_workspace() {
println!(" {} {}", "Workspace:".dimmed(), workspace);
}
match crate::api::BitbucketClient::from_stored().await {
Ok(client) => match client.get::<serde_json::Value>("/user").await {
Ok(user) => {
if let Some(display_name) = user.get("display_name") {
println!(
" {} {}",
"Display name:".dimmed(),
display_name.as_str().unwrap_or("Unknown")
);
}
}
Err(e) => {
println!("{} Credentials may be invalid: {}", "âš ".yellow(), e);
}
},
Err(e) => {
println!("{} Failed to create client: {}", "✗".red(), e);
}
}
} else {
println!("{} Not authenticated", "✗".red());
println!();
println!("Run {} to authenticate", "bitbucket auth login".cyan());
}
Ok(())
}
}
}
}