forked from googleworkspace/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.rs
More file actions
2371 lines (2166 loc) · 82.9 KB
/
Copy pathsetup.rs
File metadata and controls
2371 lines (2166 loc) · 82.9 KB
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! GCP project setup and OAuth credential bootstrap.
//!
//! Automates the manual GCP setup steps: gcloud auth, project selection,
//! API enabling, consent screen configuration, and OAuth client creation.
//! Uses `gcloud` CLI for project ops and the OAuth2 REST API for credential creation.
use std::process::Command;
use serde_json::json;
use crate::error::GwsError;
use crate::output::sanitize_for_terminal;
use crate::setup_tui::{PickerResult, SelectItem, SetupWizard, StepStatus};
/// A Workspace API with its service ID, human-readable name, and discovery doc coordinates.
struct ApiEntry {
id: &'static str,
name: &'static str,
/// Discovery API name (e.g. "gmail", "drive").
discovery: &'static str,
/// Discovery API version (e.g. "v1", "v3").
version: &'static str,
}
/// All Google Workspace API service IDs that can be enabled.
const WORKSPACE_APIS: &[ApiEntry] = &[
ApiEntry {
id: "drive.googleapis.com",
name: "Google Drive",
discovery: "drive",
version: "v3",
},
ApiEntry {
id: "sheets.googleapis.com",
name: "Google Sheets",
discovery: "sheets",
version: "v4",
},
ApiEntry {
id: "gmail.googleapis.com",
name: "Gmail",
discovery: "gmail",
version: "v1",
},
ApiEntry {
id: "calendar-json.googleapis.com",
name: "Google Calendar",
discovery: "calendar",
version: "v3",
},
ApiEntry {
id: "docs.googleapis.com",
name: "Google Docs",
discovery: "docs",
version: "v1",
},
ApiEntry {
id: "slides.googleapis.com",
name: "Google Slides",
discovery: "slides",
version: "v1",
},
ApiEntry {
id: "tasks.googleapis.com",
name: "Google Tasks",
discovery: "tasks",
version: "v1",
},
ApiEntry {
id: "people.googleapis.com",
name: "People (Contacts)",
discovery: "people",
version: "v1",
},
ApiEntry {
id: "chat.googleapis.com",
name: "Google Chat",
discovery: "chat",
version: "v1",
},
ApiEntry {
id: "vault.googleapis.com",
name: "Google Vault",
discovery: "vault",
version: "v1",
},
ApiEntry {
id: "groupssettings.googleapis.com",
name: "Groups Settings",
discovery: "groupssettings",
version: "v1",
},
ApiEntry {
id: "reseller.googleapis.com",
name: "Reseller",
discovery: "reseller",
version: "v1",
},
ApiEntry {
id: "licensing.googleapis.com",
name: "Licensing",
discovery: "licensing",
version: "v1",
},
ApiEntry {
id: "script.googleapis.com",
name: "Apps Script",
discovery: "script",
version: "v1",
},
ApiEntry {
id: "admin.googleapis.com",
name: "Admin SDK",
discovery: "admin",
version: "directory_v1",
},
ApiEntry {
id: "classroom.googleapis.com",
name: "Classroom",
discovery: "classroom",
version: "v1",
},
ApiEntry {
id: "cloudidentity.googleapis.com",
name: "Cloud Identity",
discovery: "cloudidentity",
version: "v1",
},
ApiEntry {
id: "alertcenter.googleapis.com",
name: "Alert Center",
discovery: "alertcenter",
version: "v1beta1",
},
ApiEntry {
id: "forms.googleapis.com",
name: "Google Forms",
discovery: "forms",
version: "v1",
},
ApiEntry {
id: "keep.googleapis.com",
name: "Google Keep",
discovery: "keep",
version: "v1",
},
ApiEntry {
id: "meet.googleapis.com",
name: "Google Meet",
discovery: "meet",
version: "v2",
},
ApiEntry {
id: "pubsub.googleapis.com",
name: "Cloud Pub/Sub",
discovery: "pubsub",
version: "v1",
},
];
const RESTRICTED_SCOPES: &[&str] = &[
"https://www.googleapis.com/auth/chat.admin.delete",
"https://www.googleapis.com/auth/chat.delete",
"https://www.googleapis.com/auth/chat.messages",
"https://www.googleapis.com/auth/chat.messages.readonly",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.activity",
"https://www.googleapis.com/auth/drive.activity.readonly",
"https://www.googleapis.com/auth/drive.meet.readonly",
"https://www.googleapis.com/auth/drive.metadata",
"https://www.googleapis.com/auth/drive.metadata.readonly",
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/drive.scripts",
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/gmail.insert",
"https://www.googleapis.com/auth/gmail.metadata",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.settings.basic",
"https://www.googleapis.com/auth/gmail.settings.sharing",
];
const SENSITIVE_SCOPES: &[&str] = &[
"https://www.googleapis.com/auth/chat.admin.memberships",
"https://www.googleapis.com/auth/chat.admin.memberships.readonly",
"https://www.googleapis.com/auth/chat.admin.spaces",
"https://www.googleapis.com/auth/chat.admin.spaces.readonly",
"https://www.googleapis.com/auth/chat.customemojis",
"https://www.googleapis.com/auth/chat.customemojis.readonly",
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/documents.readonly",
"https://www.googleapis.com/auth/chat.memberships",
"https://www.googleapis.com/auth/chat.memberships.app",
"https://www.googleapis.com/auth/chat.memberships.readonly",
"https://www.googleapis.com/auth/chat.messages.create",
"https://www.googleapis.com/auth/chat.messages.reactions",
"https://www.googleapis.com/auth/chat.messages.reactions.create",
"https://www.googleapis.com/auth/chat.messages.reactions.readonly",
"https://www.googleapis.com/auth/chat.spaces",
"https://www.googleapis.com/auth/chat.spaces.create",
"https://www.googleapis.com/auth/chat.spaces.readonly",
"https://www.googleapis.com/auth/chat.users.readstate",
"https://www.googleapis.com/auth/chat.users.readstate.readonly",
"https://www.googleapis.com/auth/chat.users.spacesettings",
"https://www.googleapis.com/auth/drive.apps.readonly",
"https://www.googleapis.com/auth/gmail.addons.current.message.metadata",
"https://www.googleapis.com/auth/gmail.addons.current.message.readonly",
"https://www.googleapis.com/auth/gmail.send",
];
/// Helper to get just the API IDs (for tests and non-interactive mode).
fn all_api_ids() -> Vec<&'static str> {
WORKSPACE_APIS.iter().map(|a| a.id).collect()
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ScopeClassification {
NonSensitive,
Sensitive,
Restricted,
}
pub const PLATFORM_SCOPE: &str = "https://www.googleapis.com/auth/cloud-platform";
/// A scope discovered from a Discovery Document.
#[derive(Clone)]
pub struct DiscoveredScope {
/// Full scope URL, e.g. "https://www.googleapis.com/auth/drive"
pub url: String,
/// Short label, e.g. "drive"
pub short: String,
/// Human-readable description from the Discovery Document.
pub description: String,
/// Which API this scope came from, e.g. "Google Drive"
#[allow(dead_code)]
pub api_name: String,
/// Whether this is a ".readonly" variant.
pub is_readonly: bool,
/// Sensitivity classification.
pub classification: ScopeClassification,
}
/// Fetch scopes from discovery docs for the given enabled API IDs.
pub async fn fetch_scopes_for_apis(enabled_api_ids: &[String]) -> Vec<DiscoveredScope> {
let mut all_scopes: Vec<DiscoveredScope> = Vec::new();
for api_entry in WORKSPACE_APIS {
if !enabled_api_ids.iter().any(|id| id == api_entry.id) {
continue;
}
let doc = match crate::discovery::fetch_discovery_document(
api_entry.discovery,
api_entry.version,
)
.await
{
Ok(d) => d,
Err(_) => continue, // skip APIs we can't find a discovery doc for
};
if let Some(auth) = &doc.auth {
if let Some(oauth2) = &auth.oauth2 {
if let Some(scopes) = &oauth2.scopes {
for (url, desc) in scopes {
// Deduplicate (some APIs share scopes)
if all_scopes.iter().any(|s| s.url == *url) {
continue;
}
// Filter out legacy endpoints like m8/feeds or calendar/feeds
if !url.starts_with("https://www.googleapis.com/auth/") {
continue;
}
// Filter out scopes that can't be used with user OAuth consent
// (they require a Chat app or service account)
if url.contains("/auth/chat.app.")
|| url.contains("/auth/chat.bot")
|| url.contains("/auth/chat.import")
|| url.contains("/auth/keep")
|| url.contains("/auth/apps.alerts")
{
continue;
}
let short = url
.strip_prefix("https://www.googleapis.com/auth/")
.unwrap_or(url)
.to_string();
let is_readonly = short.contains("readonly");
let classification = if RESTRICTED_SCOPES.contains(&url.as_str()) {
ScopeClassification::Restricted
} else if SENSITIVE_SCOPES.contains(&url.as_str()) {
ScopeClassification::Sensitive
} else {
ScopeClassification::NonSensitive
};
let description = if let Some(desc) = &desc.description {
if !desc.is_empty() {
desc.clone()
} else {
// Generate a friendly name from the short URL
short
.split('.')
.map(|s| {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => {
f.to_uppercase().collect::<String>() + c.as_str()
}
}
})
.collect::<Vec<String>>()
.join(" ")
}
} else {
// Generate a friendly name from the short URL
short
.split('.')
.map(|s| {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => {
f.to_uppercase().collect::<String>() + c.as_str()
}
}
})
.collect::<Vec<String>>()
.join(" ")
};
all_scopes.push(DiscoveredScope {
url: url.clone(),
description,
short,
is_readonly,
api_name: api_entry.name.to_string(),
classification,
});
}
}
}
}
}
// Sort: restricted first, then sensitive, then non-sensitive, then alphabetically
all_scopes.sort_by(|a, b| {
b.classification
.cmp(&a.classification)
.then_with(|| a.short.cmp(&b.short))
});
all_scopes
}
/// Options for the setup command.
pub struct SetupOptions {
pub project: Option<String>,
pub dry_run: bool,
pub login: bool,
}
/// Build the clap Command for `gws auth setup`.
fn setup_command() -> clap::Command {
clap::Command::new("setup")
.about("Configure GCP project + OAuth client (requires gcloud)")
.arg(
clap::Arg::new("project")
.long("project")
.help("Use a specific GCP project")
.value_name("id"),
)
.arg(
clap::Arg::new("login")
.long("login")
.help("Run `gws auth login` after successful setup")
.action(clap::ArgAction::SetTrue),
)
.arg(
clap::Arg::new("dry-run")
.long("dry-run")
.help("Preview changes without making them")
.action(clap::ArgAction::SetTrue),
)
}
/// Parse setup flags from args using clap.
/// Returns `Ok(Some(opts))` on success, `Ok(None)` if clap handled
/// `--help`/`--version` (already printed), or `Err` for invalid args.
pub fn parse_setup_args(args: &[String]) -> Result<Option<SetupOptions>, GwsError> {
match setup_command()
.try_get_matches_from(std::iter::once("setup".to_string()).chain(args.iter().cloned()))
{
Ok(matches) => Ok(Some(SetupOptions {
project: matches.get_one::<String>("project").cloned(),
dry_run: matches.get_flag("dry-run"),
login: matches.get_flag("login"),
})),
Err(e)
if e.kind() == clap::error::ErrorKind::DisplayHelp
|| e.kind() == clap::error::ErrorKind::DisplayVersion =>
{
e.print().map_err(|io_err| {
GwsError::Validation(format!("Failed to print help: {io_err}"))
})?;
Ok(None)
}
Err(e) => Err(GwsError::Validation(e.to_string())),
}
}
// ── gcloud helpers ──────────────────────────────────────────────
/// Returns the gcloud executable name for the current platform.
/// On Windows, gcloud is installed as `gcloud.cmd` which Rust's
/// `Command` cannot find without the extension.
fn gcloud_bin() -> &'static str {
if cfg!(windows) {
"gcloud.cmd"
} else {
"gcloud"
}
}
/// Create a gcloud Command with interactive prompts disabled.
/// This prevents CBA proxy install prompts from blocking subprocess calls.
fn gcloud_cmd() -> Command {
let mut cmd = Command::new(gcloud_bin());
cmd.env("CLOUDSDK_CORE_DISABLE_PROMPTS", "1");
cmd
}
/// Check if gcloud CLI is installed.
pub fn is_gcloud_installed() -> bool {
Command::new(gcloud_bin())
.arg("version")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
/// Run `gcloud auth login` interactively.
fn gcloud_auth_login() -> Result<(), GwsError> {
let status = gcloud_cmd()
.args(["auth", "login"])
.status()
.map_err(|e| GwsError::Auth(format!("Failed to run gcloud auth login: {e}")))?;
if !status.success() {
return Err(GwsError::Auth("gcloud auth login failed".to_string()));
}
Ok(())
}
/// Get the active gcloud account email.
fn get_gcloud_account() -> Result<Option<String>, GwsError> {
let output = gcloud_cmd()
.args(["config", "get-value", "account"])
.output()
.map_err(|e| GwsError::Auth(format!("Failed to run gcloud: {e}")))?;
if !output.status.success() {
return Ok(None);
}
let val = String::from_utf8_lossy(&output.stdout).trim().to_string();
if val.is_empty() || val == "(unset)" {
return Ok(None);
}
Ok(Some(val))
}
/// List all authenticated gcloud accounts.
/// Returns (account_email, is_active) pairs.
fn list_gcloud_accounts() -> Vec<(String, bool)> {
let output = gcloud_cmd()
.args(["auth", "list", "--format=value(account,status)"])
.output();
match output {
Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout)
.lines()
.filter_map(|line| {
let parts: Vec<&str> = line.splitn(2, '\t').collect();
if parts.is_empty() || parts[0].is_empty() {
None
} else {
let account = parts[0].to_string();
let active = parts.get(1).is_some_and(|s| s.contains("ACTIVE"));
Some((account, active))
}
})
.collect(),
_ => Vec::new(),
}
}
/// Set the active gcloud account.
fn set_gcloud_account(account: &str) -> Result<(), GwsError> {
let status = gcloud_cmd()
.args(["config", "set", "account", account])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map_err(|e| GwsError::Auth(format!("Failed to set account: {e}")))?;
if !status.success() {
return Err(GwsError::Auth(format!(
"Failed to set account to '{account}'"
)));
}
Ok(())
}
/// Get the current gcloud project ID.
fn get_gcloud_project() -> Result<Option<String>, GwsError> {
let output = gcloud_cmd()
.args(["config", "get-value", "project"])
.output()
.map_err(|e| GwsError::Auth(format!("Failed to run gcloud: {e}")))?;
if !output.status.success() {
return Ok(None);
}
let val = String::from_utf8_lossy(&output.stdout).trim().to_string();
if val.is_empty() || val == "(unset)" {
return Ok(None);
}
Ok(Some(val))
}
/// Set the active gcloud project.
fn set_gcloud_project(project_id: &str) -> Result<(), GwsError> {
let status = gcloud_cmd()
.args(["config", "set", "project", project_id])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map_err(|e| GwsError::Validation(format!("Failed to set gcloud project: {e}")))?;
if !status.success() {
return Err(GwsError::Validation(format!(
"Failed to set project to '{project_id}'"
)));
}
Ok(())
}
/// List all GCP projects accessible to the current user.
/// Returns a list of (project_id, project_name) tuples, and an optional error message.
/// Times out after 10 seconds to avoid hanging on CBA-enrolled devices.
/// gcloud stderr flows through to the terminal so users see progress/error messages.
fn list_gcloud_projects() -> (Vec<(String, String)>, Option<String>) {
let child = gcloud_cmd()
.args([
"projects",
"list",
"--format=value(projectId,name)",
"--sort-by=projectId",
])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit()) // let user see gcloud messages
.spawn();
let mut child = match child {
Ok(c) => c,
Err(e) => return (Vec::new(), Some(format!("Failed to run gcloud: {e}"))),
};
// Drain stdout in a background thread to prevent pipe buffer deadlock.
// Without this, gcloud blocks once the OS pipe buffer (~64 KB) fills up,
// and the parent blocks waiting for gcloud to exit — a classic deadlock.
let stdout = child.stdout.take().expect("stdout was piped");
let reader_handle = std::thread::spawn(move || {
let mut buf = String::new();
std::io::Read::read_to_string(&mut { stdout }, &mut buf).ok();
buf
});
// Wait with timeout
let timeout = std::time::Duration::from_secs(10);
let start = std::time::Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) => {
if status.success() {
let stdout = reader_handle.join().unwrap_or_default();
let projects = stdout
.lines()
.filter_map(|line| {
let parts: Vec<&str> = line.splitn(2, '\t').collect();
if parts.is_empty() || parts[0].is_empty() {
None
} else {
let id = parts[0].to_string();
let name = parts.get(1).unwrap_or(&"").to_string();
Some((id, name))
}
})
.collect();
return (projects, None);
} else {
return (
Vec::new(),
Some("gcloud projects list failed (see above)".to_string()),
);
}
}
Ok(None) => {
if start.elapsed() > timeout {
let _ = child.kill();
return (
Vec::new(),
Some("Timed out listing projects (10s)".to_string()),
);
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
Err(e) => return (Vec::new(), Some(format!("Error waiting for gcloud: {e}"))),
}
}
}
/// Get a gcloud access token for REST API calls.
fn get_access_token() -> Result<String, GwsError> {
let output = gcloud_cmd()
.args(["auth", "print-access-token"])
.output()
.map_err(|e| GwsError::Auth(format!("Failed to get access token: {e}")))?;
if !output.status.success() {
return Err(GwsError::Auth(
"Failed to get gcloud access token. Run `gcloud auth login` first.".to_string(),
));
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
fn is_tos_precondition_error(gcloud_output: &str) -> bool {
let lower = gcloud_output.to_ascii_lowercase();
lower.contains("callers must accept terms of service")
|| (lower.contains("terms of service") && lower.contains("type: tos"))
|| (lower.contains("failed_precondition") && lower.contains("type: tos"))
}
fn is_invalid_project_id_error(gcloud_output: &str) -> bool {
let lower = gcloud_output.to_ascii_lowercase();
lower.contains("argument project_id: bad value")
|| lower.contains("project ids must be between 6 and 30 characters")
}
fn is_project_id_in_use_error(gcloud_output: &str) -> bool {
let lower = gcloud_output.to_ascii_lowercase();
lower.contains("already in use")
|| lower.contains("already exists")
|| lower.contains("already being used")
|| lower.contains("project ids are immutable")
}
fn primary_gcloud_error_line(gcloud_output: &str) -> Option<String> {
gcloud_output
.lines()
.map(str::trim)
.find(|line| line.starts_with("ERROR:"))
.map(ToString::to_string)
}
fn format_project_create_failure(project_id: &str, account: &str, gcloud_output: &str) -> String {
if is_tos_precondition_error(gcloud_output) {
let mut msg = format!(
concat!(
"Failed to create project '{project_id}' because the active gcloud account has not accepted Google Cloud Terms of Service.\n\n",
"Fix:\n",
"1. Verify the active account: `gcloud auth list` and `gcloud config get-value account`\n",
"2. Sign in to https://console.cloud.google.com/ with that same account and accept Terms of Service.\n",
"3. Retry `gws auth setup` (or `gcloud projects create {project_id}`).\n\n",
"If this is a Google Workspace-managed account, an org admin may need to enable Google Cloud for the domain first."
),
project_id = project_id
);
if !account.trim().is_empty() {
msg.push_str(&format!("\n\nActive account in this setup run: {account}"));
}
return msg;
}
if is_invalid_project_id_error(gcloud_output) {
return format!(
concat!(
"Failed to create project '{project_id}' because the project ID format is invalid.\n\n",
"Project IDs must:\n",
"- be 6 to 30 characters\n",
"- start with a lowercase letter\n",
"- use only lowercase letters, digits, or hyphens\n\n",
"Enter a new project ID and retry."
),
project_id = project_id
);
}
if is_project_id_in_use_error(gcloud_output) {
return format!(
"Failed to create project '{project_id}' because the ID is already in use. Enter a different unique project ID and retry."
);
}
if let Some(primary) = primary_gcloud_error_line(gcloud_output) {
return format!(
"Failed to create project '{project_id}'.\n\n{primary}\n\nEnter a different project ID and retry."
);
}
let details = gcloud_output.trim();
if details.is_empty() {
return format!(
"Failed to create project '{project_id}'. Enter a different project ID and retry."
);
}
format!("Failed to create project '{project_id}'.\n\ngcloud error:\n{details}")
}
// ── API enabling ────────────────────────────────────────────────
/// Enable selected Workspace APIs for a project.
/// Returns (enabled, skipped, failed) where failed includes the gcloud error message.
async fn enable_apis(
project_id: &str,
api_ids: &[String],
) -> (Vec<String>, Vec<String>, Vec<(String, String)>) {
// First, get already-enabled APIs
let already_enabled = get_enabled_apis(project_id);
let mut to_enable = Vec::new();
let mut skipped = Vec::new();
for api_id in api_ids {
if already_enabled.contains(api_id) {
skipped.push(api_id.clone());
} else {
to_enable.push(api_id.clone());
}
}
if to_enable.is_empty() {
return (Vec::new(), skipped, Vec::new());
}
// Enable each API individually and in parallel so one failure doesn't
// block the rest. Uses tokio::process to avoid blocking the executor.
use futures_util::stream::StreamExt;
let results = futures_util::stream::iter(to_enable)
.map(|api_id| {
let project_id = project_id.to_string();
async move {
let result = tokio::process::Command::new(gcloud_bin())
.env("CLOUDSDK_CORE_DISABLE_PROMPTS", "1")
.args(["services", "enable", &api_id, "--project", &project_id])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.output()
.await;
(api_id, result)
}
})
.buffer_unordered(5)
.collect::<Vec<_>>()
.await;
let mut enabled = Vec::new();
let mut failed = Vec::new();
for (api_id, result) in results {
match result {
Ok(output) if output.status.success() => {
enabled.push(api_id);
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let msg = if stderr.is_empty() {
format!(
"gcloud services enable failed (exit code {:?})",
output.status.code()
)
} else {
stderr
};
failed.push((api_id, msg));
}
Err(e) => {
failed.push((api_id, format!("Failed to run gcloud: {e}")));
}
}
}
(enabled, skipped, failed)
}
/// Get the list of already-enabled API service names for a project.
pub fn get_enabled_apis(project_id: &str) -> Vec<String> {
let output = gcloud_cmd()
.args([
"services",
"list",
"--enabled",
"--project",
project_id,
"--format=json",
])
.output();
match output {
Ok(out) if out.status.success() => {
let json_str = String::from_utf8_lossy(&out.stdout);
if let Ok(services) = serde_json::from_str::<Vec<serde_json::Value>>(&json_str) {
return services
.iter()
.filter_map(|s| {
s.get("config")
.and_then(|c| c.get("name"))
.and_then(|n| n.as_str())
.map(|s| s.to_string())
})
.collect();
}
Vec::new()
}
_ => Vec::new(),
}
}
// ── OAuth REST API ──────────────────────────────────────────────
/// Configure the OAuth consent screen via REST API.
async fn configure_consent_screen(
project_id: &str,
access_token: &str,
app_name: &str,
support_email: &str,
) -> Result<(), GwsError> {
let client = crate::client::build_client()?;
// Check if consent screen already exists
let check_url = format!(
"https://oauth2.googleapis.com/v1/projects/{}/brands",
project_id
);
let check_res = client
.get(&check_url)
.bearer_auth(access_token)
.send()
.await
.map_err(|e| GwsError::Auth(format!("Failed to check consent screen: {e}")))?;
if check_res.status().is_success() {
let data: serde_json::Value = check_res.json().await.unwrap_or_else(|_| json!({}));
if let Some(brands) = data.get("brands").and_then(|b| b.as_array()) {
if !brands.is_empty() {
return Ok(());
}
}
}
// Create the consent screen
let create_res = client
.post(&check_url)
.bearer_auth(access_token)
.json(&json!({
"applicationTitle": app_name,
"supportEmail": support_email,
}))
.send()
.await
.map_err(|e| GwsError::Auth(format!("Failed to create consent screen: {e}")))?;
if create_res.status().is_success() {
return Ok(());
}
let body = create_res.text().await.unwrap_or_default();
if body.contains("already exists") || body.contains("ALREADY_EXISTS") {
return Ok(());
}
// Fallback to manual instructions.
// We don't print anything here because the TUI / CLI orchestrator
// will guide the user to check/configure the consent screen.
Ok(())
}
// (create_oauth_client removed due to IAP Admin APIs deprecation)
// ── Main setup orchestrator ─────────────────────────────────────
const STEP_LABELS: [&str; 5] = [
"gcloud CLI",
"Authentication",
"GCP project",
"Workspace APIs",
"OAuth credentials",
];
enum SetupStage {
CheckGcloud,
Account,
Project,
EnableApis,
ConfigureOauth,
Finish,
}
/// Shared mutable state threaded through each setup stage.
struct SetupContext {
wizard: Option<SetupWizard>,
interactive: bool,
dry_run: bool,
opts: SetupOptions,
account: String,
project_id: String,
api_ids: Vec<String>,
client_id: String,
client_secret: String,
enabled: Vec<String>,
skipped: Vec<String>,
failed: Vec<(String, String)>,
}
impl SetupContext {
/// Helper to update wizard step if present.
fn wiz(&mut self, idx: usize, status: StepStatus) {
if let Some(ref mut w) = self.wizard {
let _ = w.update_step(idx, status);
}
}
/// Finish and consume the wizard.
fn finish_wizard(&mut self) {
if let Some(w) = self.wizard.take() {
let _ = w.finish();
}
}
}
/// Stage 1: Verify that gcloud CLI is installed.
fn stage_check_gcloud(ctx: &mut SetupContext) -> Result<SetupStage, GwsError> {
ctx.wiz(0, StepStatus::InProgress("Checking...".into()));
if !ctx.dry_run {
std::thread::sleep(std::time::Duration::from_millis(200));
}
if !is_gcloud_installed() {
ctx.wiz(0, StepStatus::Failed("not found".into()));
ctx.finish_wizard();
return Err(GwsError::Validation(
"gcloud CLI not found. Install it from https://cloud.google.com/sdk/docs/install"
.to_string(),
));
}
ctx.wiz(0, StepStatus::Done("found".into()));
if !ctx.interactive {
eprintln!("Step 1/6: Checking for gcloud CLI...\n ✓ gcloud CLI found");
}
Ok(SetupStage::Account)
}
/// Stage 2: Select or authenticate a Google account.
fn stage_account(ctx: &mut SetupContext) -> Result<SetupStage, GwsError> {
ctx.wiz(1, StepStatus::InProgress(String::new()));
if ctx.interactive {
let accounts = list_gcloud_accounts();
let current = get_gcloud_account()?.unwrap_or_default();
let mut items: Vec<SelectItem> = vec![SelectItem {
label: "➕ Login with new account".to_string(),
description: "Opens browser for gcloud auth login".to_string(),
selected: false,
is_fixed: false,
is_template: false,
template_selects: vec![],