-
Notifications
You must be signed in to change notification settings - Fork 36
/
main.rs
629 lines (557 loc) · 18.6 KB
/
main.rs
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use std::{path::PathBuf, process, str::FromStr};
use bitwarden::{
auth::login::AccessTokenLoginRequest,
client::{client_settings::ClientSettings, AccessToken},
secrets_manager::{
projects::{
ProjectCreateRequest, ProjectGetRequest, ProjectPutRequest, ProjectsDeleteRequest,
ProjectsListRequest,
},
secrets::{
SecretCreateRequest, SecretGetRequest, SecretIdentifiersByProjectRequest,
SecretIdentifiersRequest, SecretPutRequest, SecretsDeleteRequest,
},
},
};
use clap::{ArgGroup, CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use color_eyre::eyre::{bail, Result};
use log::error;
mod config;
mod render;
use config::ProfileKey;
use render::{serialize_response, Color, Output};
use uuid::Uuid;
#[derive(Parser, Debug)]
#[command(name = "bws", version, about = "Bitwarden Secrets CLI", long_about = None)]
struct Cli {
// Optional as a workaround for https://github.com/clap-rs/clap/issues/3572
#[command(subcommand)]
command: Option<Commands>,
#[arg(short = 'o', long, global = true, value_enum, default_value_t = Output::JSON, help="Output format", hide = true)]
output: Output,
#[arg(short = 'c', long, global = true, value_enum, default_value_t = Color::Auto, help="Use colors in the output")]
color: Color,
#[arg(short = 't', long, global = true, env = ACCESS_TOKEN_KEY_VAR_NAME, hide_env_values = true, help="Specify access token for the service account")]
access_token: Option<String>,
#[arg(
short = 'f',
long,
global = true,
help = format!("[default: ~/{}/{}] Config file to use", config::DIRECTORY, config::FILENAME)
)]
config_file: Option<PathBuf>,
#[arg(short = 'p', long, global = true, env = PROFILE_KEY_VAR_NAME, help="Profile to use from the config file")]
profile: Option<String>,
#[arg(short = 'u', long, global = true, env = SERVER_URL_KEY_VAR_NAME, help="Override the server URL from the config file")]
server_url: Option<String>,
}
#[derive(Subcommand, Debug)]
enum Commands {
#[command(long_about = "Configure the CLI", arg_required_else_help(true))]
Config {
name: Option<ProfileKey>,
value: Option<String>,
#[arg(short = 'd', long)]
delete: bool,
},
#[command(long_about = "Generate shell completion files")]
Completions { shell: Option<Shell> },
#[command(long_about = "Commands available on Projects")]
Project {
#[command(subcommand)]
cmd: ProjectCommand,
},
#[command(long_about = "Commands available on Secrets")]
Secret {
#[command(subcommand)]
cmd: SecretCommand,
},
#[command(long_about = "Create a single item (deprecated)", hide(true))]
Create {
#[command(subcommand)]
cmd: CreateCommand,
},
#[command(long_about = "Delete one or more items (deprecated)", hide(true))]
Delete {
#[command(subcommand)]
cmd: DeleteCommand,
},
#[command(long_about = "Edit a single item (deprecated)", hide(true))]
Edit {
#[command(subcommand)]
cmd: EditCommand,
},
#[command(long_about = "Retrieve a single item (deprecated)", hide(true))]
Get {
#[command(subcommand)]
cmd: GetCommand,
},
#[command(long_about = "List items (deprecated)", hide(true))]
List {
#[command(subcommand)]
cmd: ListCommand,
},
}
#[derive(Subcommand, Debug)]
enum SecretCommand {
Create {
key: String,
value: String,
#[arg(help = "The ID of the project this secret will be added to")]
project_id: Uuid,
#[arg(long, help = "An optional note to add to the secret")]
note: Option<String>,
},
Delete {
secret_ids: Vec<Uuid>,
},
#[clap(group = ArgGroup::new("edit_field").required(true).multiple(true))]
Edit {
secret_id: Uuid,
#[arg(long, group = "edit_field")]
key: Option<String>,
#[arg(long, group = "edit_field")]
value: Option<String>,
#[arg(long, group = "edit_field")]
note: Option<String>,
#[arg(long, group = "edit_field")]
project_id: Option<Uuid>,
},
Get {
secret_id: Uuid,
},
List {
project_id: Option<Uuid>,
},
}
#[derive(Subcommand, Debug)]
enum ProjectCommand {
Create {
name: String,
},
Delete {
project_ids: Vec<Uuid>,
},
Edit {
project_id: Uuid,
#[arg(long, group = "edit_field")]
name: String,
},
Get {
project_id: Uuid,
},
List,
}
#[derive(Subcommand, Debug)]
enum ListCommand {
Projects,
Secrets { project_id: Option<Uuid> },
}
#[derive(Subcommand, Debug)]
enum GetCommand {
Project { project_id: Uuid },
Secret { secret_id: Uuid },
}
#[derive(Subcommand, Debug)]
enum CreateCommand {
Project {
name: String,
},
Secret {
key: String,
value: String,
#[arg(long, help = "An optional note to add to the secret")]
note: Option<String>,
#[arg(long, help = "The ID of the project this secret will be added to")]
project_id: Uuid,
},
}
#[derive(Subcommand, Debug)]
enum EditCommand {
#[clap(group = ArgGroup::new("edit_field").required(true).multiple(true))]
Project {
project_id: Uuid,
#[arg(long, group = "edit_field")]
name: String,
},
#[clap(group = ArgGroup::new("edit_field").required(true).multiple(true))]
Secret {
secret_id: Uuid,
#[arg(long, group = "edit_field")]
key: Option<String>,
#[arg(long, group = "edit_field")]
value: Option<String>,
#[arg(long, group = "edit_field")]
note: Option<String>,
#[arg(long, group = "edit_field")]
project_id: Option<Uuid>,
},
}
#[derive(Subcommand, Debug)]
enum DeleteCommand {
Project { project_ids: Vec<Uuid> },
Secret { secret_ids: Vec<Uuid> },
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
process_commands().await
}
const ACCESS_TOKEN_KEY_VAR_NAME: &str = "BWS_ACCESS_TOKEN";
const PROFILE_KEY_VAR_NAME: &str = "BWS_PROFILE";
const SERVER_URL_KEY_VAR_NAME: &str = "BWS_SERVER_URL";
#[allow(clippy::comparison_chain)]
async fn process_commands() -> Result<()> {
let cli = Cli::parse();
let color = cli.color.is_enabled();
if color {
color_eyre::install()?;
} else {
// Use an empty theme to disable error coloring
color_eyre::config::HookBuilder::new()
.theme(color_eyre::config::Theme::new())
.install()?;
}
let Some(command) = cli.command else {
let mut cmd = Cli::command();
eprintln!("{}", cmd.render_help());
return Ok(());
};
// These commands don't require authentication, so we process them first
match command {
Commands::Completions { shell } => {
let Some(shell) = shell.or_else(Shell::from_env) else {
eprintln!("Couldn't autodetect a valid shell. Run `bws completions --help` for more info.");
std::process::exit(1);
};
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
clap_complete::generate(shell, &mut cmd, name, &mut std::io::stdout());
return Ok(());
}
Commands::Config {
name,
value,
delete,
} => {
let profile = if let Some(profile) = cli.profile {
profile
} else if let Some(access_token) = cli.access_token {
AccessToken::from_str(&access_token)?
.service_account_id
.to_string()
} else {
String::from("default")
};
if delete {
config::delete_profile(cli.config_file.as_deref(), profile)?;
println!("Profile deleted successfully!");
} else {
let (name, value) = match (name, value) {
(None, None) => bail!("Missing `name` and `value`"),
(None, Some(_)) => bail!("Missing `value`"),
(Some(_), None) => bail!("Missing `name`"),
(Some(name), Some(value)) => (name, value),
};
config::update_profile(cli.config_file.as_deref(), profile, name, value)?;
println!("Profile updated successfully!");
};
return Ok(());
}
_ => (),
}
let access_token = match cli.access_token {
Some(key) => key,
None => bail!("Missing access token"),
};
let profile = get_config_profile(
&cli.server_url,
&cli.profile,
&cli.config_file,
&access_token,
)?;
let settings = profile
.map(|p| -> Result<_> {
Ok(ClientSettings {
identity_url: p.identity_url()?,
api_url: p.api_url()?,
..Default::default()
})
})
.transpose()?;
let mut client = bitwarden::Client::new(settings);
// Load session or return if no session exists
let _ = client
.access_token_login(&AccessTokenLoginRequest { access_token })
.await?;
let organization_id = match client.get_access_token_organization() {
Some(id) => id,
None => {
error!("Access token isn't associated to an organization.");
return Ok(());
}
};
// And finally we process all the commands which require authentication
match command {
Commands::Project {
cmd: ProjectCommand::List,
}
| Commands::List {
cmd: ListCommand::Projects,
} => {
let projects = client
.projects()
.list(&ProjectsListRequest { organization_id })
.await?
.data;
serialize_response(projects, cli.output, color);
}
Commands::Project {
cmd: ProjectCommand::Get { project_id },
}
| Commands::Get {
cmd: GetCommand::Project { project_id },
} => {
let project = client
.projects()
.get(&ProjectGetRequest { id: project_id })
.await?;
serialize_response(project, cli.output, color);
}
Commands::Project {
cmd: ProjectCommand::Create { name },
}
| Commands::Create {
cmd: CreateCommand::Project { name },
} => {
let project = client
.projects()
.create(&ProjectCreateRequest {
organization_id,
name,
})
.await?;
serialize_response(project, cli.output, color);
}
Commands::Project {
cmd: ProjectCommand::Edit { project_id, name },
}
| Commands::Edit {
cmd: EditCommand::Project { project_id, name },
} => {
let project = client
.projects()
.update(&ProjectPutRequest {
id: project_id,
organization_id,
name,
})
.await?;
serialize_response(project, cli.output, color);
}
Commands::Project {
cmd: ProjectCommand::Delete { project_ids },
}
| Commands::Delete {
cmd: DeleteCommand::Project { project_ids },
} => {
let count = project_ids.len();
let result = client
.projects()
.delete(ProjectsDeleteRequest { ids: project_ids })
.await?;
let projects_failed: Vec<(Uuid, String)> = result
.data
.into_iter()
.filter_map(|r| r.error.map(|e| (r.id, e)))
.collect();
let deleted_projects = count - projects_failed.len();
if deleted_projects > 1 {
println!("{} projects deleted successfully.", deleted_projects);
} else if deleted_projects == 1 {
println!("{} project deleted successfully.", deleted_projects);
}
if projects_failed.len() > 1 {
eprintln!("{} projects had errors:", projects_failed.len());
} else if projects_failed.len() == 1 {
eprintln!("{} project had an error:", projects_failed.len());
}
for project in &projects_failed {
eprintln!("{}: {}", project.0, project.1);
}
if !projects_failed.is_empty() {
process::exit(1);
}
}
Commands::Secret {
cmd: SecretCommand::List { project_id },
}
| Commands::List {
cmd: ListCommand::Secrets { project_id },
} => {
let res = if let Some(project_id) = project_id {
client
.secrets()
.list_by_project(&SecretIdentifiersByProjectRequest { project_id })
.await?
} else {
client
.secrets()
.list(&SecretIdentifiersRequest { organization_id })
.await?
};
let mut secrets = Vec::new();
for s in res.data {
let secret = client.secrets().get(&SecretGetRequest { id: s.id }).await?;
secrets.push(secret);
}
serialize_response(secrets, cli.output, color);
}
Commands::Secret {
cmd: SecretCommand::Get { secret_id },
}
| Commands::Get {
cmd: GetCommand::Secret { secret_id },
} => {
let secret = client
.secrets()
.get(&SecretGetRequest { id: secret_id })
.await?;
serialize_response(secret, cli.output, color);
}
Commands::Secret {
cmd:
SecretCommand::Create {
key,
value,
note,
project_id,
},
}
| Commands::Create {
cmd:
CreateCommand::Secret {
key,
value,
note,
project_id,
},
} => {
let secret = client
.secrets()
.create(&SecretCreateRequest {
organization_id,
key,
value,
note: note.unwrap_or_default(),
project_ids: Some(vec![project_id]),
})
.await?;
serialize_response(secret, cli.output, color);
}
Commands::Secret {
cmd:
SecretCommand::Edit {
secret_id,
key,
value,
note,
project_id,
},
}
| Commands::Edit {
cmd:
EditCommand::Secret {
secret_id,
key,
value,
note,
project_id,
},
} => {
let old_secret = client
.secrets()
.get(&SecretGetRequest { id: secret_id })
.await?;
let secret = client
.secrets()
.update(&SecretPutRequest {
id: secret_id,
organization_id,
key: key.unwrap_or(old_secret.key),
value: value.unwrap_or(old_secret.value),
note: note.unwrap_or(old_secret.note),
project_ids: match project_id {
Some(id) => Some(vec![id]),
None => match old_secret.project_id {
Some(id) => Some(vec![id]),
None => bail!("Editing a secret requires a project_id."),
},
},
})
.await?;
serialize_response(secret, cli.output, color);
}
Commands::Secret {
cmd: SecretCommand::Delete { secret_ids },
}
| Commands::Delete {
cmd: DeleteCommand::Secret { secret_ids },
} => {
let count = secret_ids.len();
let result = client
.secrets()
.delete(SecretsDeleteRequest { ids: secret_ids })
.await?;
let secrets_failed: Vec<(Uuid, String)> = result
.data
.into_iter()
.filter_map(|r| r.error.map(|e| (r.id, e)))
.collect();
let deleted_secrets = count - secrets_failed.len();
if deleted_secrets > 1 {
println!("{} secrets deleted successfully.", deleted_secrets);
} else if deleted_secrets == 1 {
println!("{} secret deleted successfully.", deleted_secrets);
}
if secrets_failed.len() > 1 {
eprintln!("{} secrets had errors:", secrets_failed.len());
} else if secrets_failed.len() == 1 {
eprintln!("{} secret had an error:", secrets_failed.len());
}
for secret in &secrets_failed {
eprintln!("{}: {}", secret.0, secret.1);
}
if !secrets_failed.is_empty() {
process::exit(1);
}
}
Commands::Config { .. } | Commands::Completions { .. } => {
unreachable!()
}
}
Ok(())
}
fn get_config_profile(
server_url: &Option<String>,
profile: &Option<String>,
config_file: &Option<PathBuf>,
access_token: &str,
) -> Result<Option<config::Profile>, color_eyre::Report> {
let profile = if let Some(server_url) = server_url {
Some(config::Profile::from_url(server_url)?)
} else {
let profile_defined = profile.is_some();
let profile_key = if let Some(profile) = profile {
profile.to_owned()
} else {
AccessToken::from_str(access_token)?
.service_account_id
.to_string()
};
let config = config::load_config(config_file.as_deref(), config_file.is_some())?;
config.select_profile(&profile_key, profile_defined)?
};
Ok(profile)
}