forked from googleworkspace/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_commands.rs
More file actions
2187 lines (1981 loc) · 81.6 KB
/
Copy pathauth_commands.rs
File metadata and controls
2187 lines (1981 loc) · 81.6 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.
use std::collections::HashSet;
use std::path::PathBuf;
use serde_json::json;
use crate::credential_store;
use crate::error::GwsError;
/// Mask a secret string by showing only the first 4 and last 4 characters.
/// Strings with 8 or fewer characters are fully replaced with "***".
fn mask_secret(s: &str) -> String {
const MASK_PREFIX_LEN: usize = 4;
const MASK_SUFFIX_LEN: usize = 4;
const MIN_LEN_FOR_PARTIAL_MASK: usize = MASK_PREFIX_LEN + MASK_SUFFIX_LEN;
if s.len() > MIN_LEN_FOR_PARTIAL_MASK {
format!(
"{}...{}",
&s[..MASK_PREFIX_LEN],
&s[s.len() - MASK_SUFFIX_LEN..]
)
} else {
"***".to_string()
}
}
/// Minimal scopes for first-run login — only core Workspace APIs that never
/// trigger Google's `restricted_client` / unverified-app block.
///
/// These are the safest scopes for unverified OAuth apps and personal Cloud
/// projects. Users can request broader access with `--scopes` or `--full`.
pub const MINIMAL_SCOPES: &[&str] = &[
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/presentations",
"https://www.googleapis.com/auth/tasks",
];
/// Default scopes for login. Alias for [`MINIMAL_SCOPES`] — deliberately kept
/// narrow so first-run logins succeed even with an unverified OAuth app.
///
/// Previously this included `pubsub` and `cloud-platform`, which Google marks
/// as *restricted* and blocks for unverified apps, causing `Error 403:
/// restricted_client`. Use `--scopes` to add those scopes explicitly when you
/// have a verified app or a GCP project with the APIs enabled and approved.
pub const DEFAULT_SCOPES: &[&str] = MINIMAL_SCOPES;
/// Full scopes — all common Workspace APIs plus GCP platform access.
///
/// Use `gws auth login --full` to request these. Unverified OAuth apps will
/// receive a Google consent-screen warning, and some scopes (e.g. `pubsub`,
/// `cloud-platform`) require app verification or a Workspace domain admin to
/// grant access.
pub const FULL_SCOPES: &[&str] = &[
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/presentations",
"https://www.googleapis.com/auth/tasks",
"https://www.googleapis.com/auth/pubsub",
"https://www.googleapis.com/auth/cloud-platform",
];
/// Readonly scopes — read-only Workspace access.
const READONLY_SCOPES: &[&str] = &[
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/spreadsheets.readonly",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/calendar.readonly",
"https://www.googleapis.com/auth/documents.readonly",
"https://www.googleapis.com/auth/presentations.readonly",
"https://www.googleapis.com/auth/tasks.readonly",
];
pub fn config_dir() -> PathBuf {
if let Ok(dir) = std::env::var("GOOGLE_WORKSPACE_CLI_CONFIG_DIR") {
return PathBuf::from(dir);
}
// Use ~/.config/gws on all platforms for a consistent, user-friendly path.
let primary = dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".config")
.join("gws");
if primary.exists() {
return primary;
}
// Backward compat: fall back to OS-specific config dir for existing installs
// (e.g. ~/Library/Application Support/gws on macOS, %APPDATA%\gws on Windows).
let legacy = dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("gws");
if legacy.exists() {
return legacy;
}
primary
}
fn plain_credentials_path() -> PathBuf {
if let Ok(path) = std::env::var("GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE") {
return PathBuf::from(path);
}
config_dir().join("credentials.json")
}
fn token_cache_path() -> PathBuf {
config_dir().join("token_cache.json")
}
/// Handle `gws auth <subcommand>`.
pub async fn handle_auth_command(args: &[String]) -> Result<(), GwsError> {
const USAGE: &str = concat!(
"Usage: gws auth <login|setup|status|export|logout|list|default> [options]\n\n",
" login Authenticate via OAuth2 (opens browser)\n",
" --account EMAIL Associate credentials with a specific account\n",
" --readonly Request read-only scopes\n",
" --full Request all scopes incl. pubsub + cloud-platform\n",
" (may trigger restricted_client for unverified apps)\n",
" --scopes Comma-separated custom scopes\n",
" -s, --services Comma-separated service names to limit scope picker\n",
" (e.g. -s drive,gmail,sheets)\n",
" setup Configure GCP project + OAuth client (requires gcloud)\n",
" --project Use a specific GCP project\n",
" status Show current authentication state\n",
" export Print decrypted credentials to stdout\n",
" logout Clear saved credentials and token cache\n",
" --account EMAIL Logout a specific account (otherwise: all)\n",
" list List all registered accounts\n",
" default Set the default account\n",
" --account EMAIL Account to set as default",
);
// Honour --help / -h before treating the first arg as a subcommand.
if args.is_empty() || args[0] == "--help" || args[0] == "-h" {
println!("{USAGE}");
return Ok(());
}
match args[0].as_str() {
"login" => handle_login(&args[1..]).await,
"setup" => crate::setup::run_setup(&args[1..]).await,
"status" => handle_status().await,
"export" => {
let unmasked = args.len() > 1 && args[1] == "--unmasked";
handle_export(unmasked).await
}
"logout" => handle_logout(&args[1..]),
"list" => handle_list(),
"default" => handle_default(&args[1..]),
other => Err(GwsError::Validation(format!(
"Unknown auth subcommand: '{other}'. Use: login, setup, status, export, logout, list, default"
))),
}
}
/// Custom delegate that prints the OAuth URL on its own line for easy copying.
/// Optionally includes `login_hint` in the URL for account pre-selection.
struct CliFlowDelegate {
login_hint: Option<String>,
}
impl yup_oauth2::authenticator_delegate::InstalledFlowDelegate for CliFlowDelegate {
fn present_user_url<'a>(
&'a self,
url: &'a str,
_need_code: bool,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String, String>> + Send + 'a>>
{
Box::pin(async move {
// Inject login_hint into the OAuth URL if we have one
let display_url = if let Some(ref hint) = self.login_hint {
let encoded: String = percent_encoding::percent_encode(
hint.as_bytes(),
percent_encoding::NON_ALPHANUMERIC,
)
.to_string();
if url.contains('?') {
format!("{url}&login_hint={encoded}")
} else {
format!("{url}?login_hint={encoded}")
}
} else {
url.to_string()
};
eprintln!("Open this URL in your browser to authenticate:\n");
eprintln!(" {display_url}\n");
Ok(String::new())
})
}
}
async fn handle_login(args: &[String]) -> Result<(), GwsError> {
// Extract --account and -s/--services from args
let mut account_email: Option<String> = None;
let mut services_filter: Option<HashSet<String>> = None;
let mut filtered_args: Vec<String> = Vec::new();
let mut skip_next = false;
for i in 0..args.len() {
if skip_next {
skip_next = false;
continue;
}
if args[i] == "--account" && i + 1 < args.len() {
account_email = Some(args[i + 1].clone());
skip_next = true;
continue;
}
if let Some(value) = args[i].strip_prefix("--account=") {
account_email = Some(value.to_string());
continue;
}
let services_str = if (args[i] == "-s" || args[i] == "--services") && i + 1 < args.len() {
skip_next = true;
Some(args[i + 1].as_str())
} else {
args[i].strip_prefix("--services=")
};
if let Some(value) = services_str {
services_filter = Some(
value
.split(',')
.map(|s| s.trim().to_lowercase())
.filter(|s| !s.is_empty())
.collect(),
);
continue;
}
filtered_args.push(args[i].clone());
}
// Resolve client_id and client_secret:
// 1. Env vars (highest priority)
// 2. Saved client_secret.json from `gws auth setup` or manual download
let (client_id, client_secret, project_id) = resolve_client_credentials()?;
// Persist credentials to client_secret.json if not already saved,
// so they survive env var removal or shell session changes.
if !crate::oauth_config::client_config_path().exists() {
let _ = crate::oauth_config::save_client_config(
&client_id,
&client_secret,
project_id.as_deref().unwrap_or(""),
);
}
// Determine scopes: explicit flags > interactive TUI > defaults
let scopes = resolve_scopes(
&filtered_args,
project_id.as_deref(),
services_filter.as_ref(),
)
.await;
// Remove restrictive scopes when broader alternatives are present.
// gmail.metadata blocks query parameters like `q`, and is redundant
// when broader scopes (gmail.modify, gmail.readonly, mail.google.com)
// are already included.
let mut scopes = filter_redundant_restrictive_scopes(scopes);
let secret = yup_oauth2::ApplicationSecret {
client_id: client_id.clone(),
client_secret: client_secret.clone(),
auth_uri: "https://accounts.google.com/o/oauth2/auth".to_string(),
token_uri: "https://oauth2.googleapis.com/token".to_string(),
redirect_uris: vec!["http://localhost".to_string()],
..Default::default()
};
// Ensure openid + email scopes are always present so we can identify the user
// via the userinfo endpoint after login.
let identity_scopes = ["openid", "https://www.googleapis.com/auth/userinfo.email"];
for s in &identity_scopes {
if !scopes.iter().any(|existing| existing == s) {
scopes.push(s.to_string());
}
}
// Use a temp file for yup-oauth2's token persistence, then encrypt it
let temp_path = config_dir().join("credentials.tmp");
// Always start fresh — delete any stale temp cache from prior login attempts.
// Without this, yup-oauth2 finds a cached access token and skips the browser flow,
// which means no refresh_token is returned.
let _ = std::fs::remove_file(&temp_path);
// Ensure config directory exists
if let Some(parent) = temp_path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| GwsError::Validation(format!("Failed to create config directory: {e}")))?;
}
let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
secret,
yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
)
.with_storage(Box::new(crate::token_storage::EncryptedTokenStorage::new(
temp_path.clone(),
)))
.force_account_selection(true) // Adds prompt=consent so Google always returns a refresh_token
.flow_delegate(Box::new(CliFlowDelegate {
login_hint: account_email.clone(),
}))
.build()
.await
.map_err(|e| GwsError::Auth(format!("Failed to build authenticator: {e}")))?;
// Request a token — this triggers the browser OAuth flow
let scope_refs: Vec<&str> = scopes.iter().map(|s| s.as_str()).collect();
let token = auth
.token(&scope_refs)
.await
.map_err(|e| GwsError::Auth(format!("OAuth flow failed: {e}")))?;
if token.token().is_some() {
// Read yup-oauth2's token cache to extract the refresh_token.
// EncryptedTokenStorage stores data encrypted, so we must decrypt first.
let token_data = std::fs::read(&temp_path)
.ok()
.and_then(|bytes| crate::credential_store::decrypt(&bytes).ok())
.and_then(|decrypted| String::from_utf8(decrypted).ok())
.unwrap_or_default();
let refresh_token = extract_refresh_token(&token_data).ok_or_else(|| {
GwsError::Auth(
"OAuth flow completed but no refresh token was returned. \
Ensure the OAuth consent screen includes 'offline' access."
.to_string(),
)
})?;
// Build credentials in the standard authorized_user format
let creds_json = json!({
"type": "authorized_user",
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh_token,
});
let creds_str = serde_json::to_string_pretty(&creds_json)
.map_err(|e| GwsError::Validation(format!("Failed to serialize credentials: {e}")))?;
// Fetch the user's email from Google userinfo to validate and register
let access_token = token.token().unwrap_or_default();
let actual_email = fetch_userinfo_email(access_token).await;
// If --account was specified, validate the email matches
if let Some(ref requested) = account_email {
if let Some(ref actual) = actual_email {
let normalized_requested = crate::accounts::normalize_email(requested);
let normalized_actual = crate::accounts::normalize_email(actual);
if normalized_requested != normalized_actual {
// Clean up temp file
let _ = std::fs::remove_file(&temp_path);
return Err(GwsError::Auth(format!(
"Login account mismatch: requested '{}' but authenticated as '{}'. \
Please try again and select the correct account in the browser.",
requested, actual
)));
}
}
}
// Determine which email to use for the account
let resolved_email = account_email.or(actual_email);
// Save encrypted credentials
let enc_path = if let Some(ref email) = resolved_email {
// Per-account save
credential_store::save_encrypted_for(&creds_str, email)
.map_err(|e| GwsError::Auth(format!("Failed to encrypt credentials: {e}")))?;
// Register in accounts.json
let mut registry = crate::accounts::load_accounts()
.map_err(|e| GwsError::Auth(format!("Failed to load accounts: {e}")))?
.unwrap_or_default();
crate::accounts::add_account(&mut registry, email);
// If this is the first account, set it as default
if registry.default.is_none() || registry.accounts.len() == 1 {
crate::accounts::set_default(&mut registry, email)
.map_err(|e| GwsError::Auth(format!("Failed to set default: {e}")))?;
}
crate::accounts::save_accounts(®istry)
.map_err(|e| GwsError::Auth(format!("Failed to save accounts: {e}")))?;
credential_store::encrypted_credentials_path_for(email)
} else {
// Legacy single-account save (no email available)
credential_store::save_encrypted(&creds_str)
.map_err(|e| GwsError::Auth(format!("Failed to encrypt credentials: {e}")))?
};
// Clean up old legacy credentials.enc if we now have an account-keyed one
if resolved_email.is_some() {
let legacy = credential_store::encrypted_credentials_path();
if legacy.exists() && legacy != enc_path {
let _ = std::fs::remove_file(&legacy);
}
}
// Clean up temp file
let _ = std::fs::remove_file(&temp_path);
let output = json!({
"status": "success",
"message": "Authentication successful. Encrypted credentials saved.",
"account": resolved_email.as_deref().unwrap_or("(unknown)"),
"credentials_file": enc_path.display().to_string(),
"encryption": "AES-256-GCM (key secured by OS Keyring or local `.encryption_key`)",
"scopes": scopes,
});
println!(
"{}",
serde_json::to_string_pretty(&output).unwrap_or_default()
);
Ok(())
} else {
// Clean up temp file on failure
let _ = std::fs::remove_file(&temp_path);
Err(GwsError::Auth(
"OAuth flow completed but no token was returned.".to_string(),
))
}
}
/// Fetch the authenticated user's email from Google's userinfo endpoint.
async fn fetch_userinfo_email(access_token: &str) -> Option<String> {
let client = match crate::client::build_client() {
Ok(c) => c,
Err(_) => return None,
};
let resp = client
.get("https://www.googleapis.com/oauth2/v2/userinfo")
.bearer_auth(access_token)
.send()
.await
.ok()?;
if !resp.status().is_success() {
return None;
}
let body: serde_json::Value = resp.json().await.ok()?;
body.get("email")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
async fn handle_export(unmasked: bool) -> Result<(), GwsError> {
let enc_path = credential_store::encrypted_credentials_path();
if !enc_path.exists() {
return Err(GwsError::Auth(
"No encrypted credentials found. Run 'gws auth login' first.".to_string(),
));
}
match credential_store::load_encrypted() {
Ok(contents) => {
if unmasked {
println!("{contents}");
} else if let Ok(mut creds) = serde_json::from_str::<serde_json::Value>(&contents) {
if let Some(obj) = creds.as_object_mut() {
for key in ["client_secret", "refresh_token"] {
if let Some(val) = obj.get_mut(key) {
if let Some(s) = val.as_str() {
*val = json!(mask_secret(s));
}
}
}
}
println!("{}", serde_json::to_string_pretty(&creds).unwrap());
} else {
println!("{contents}");
}
Ok(())
}
Err(e) => Err(GwsError::Auth(format!(
"Failed to decrypt credentials: {e}. May have been created on a different machine.",
))),
}
}
/// Resolve OAuth client credentials from env vars or saved config file.
fn resolve_client_credentials() -> Result<(String, String, Option<String>), GwsError> {
// 1. Try env vars first
let env_id = std::env::var("GOOGLE_WORKSPACE_CLI_CLIENT_ID").ok();
let env_secret = std::env::var("GOOGLE_WORKSPACE_CLI_CLIENT_SECRET").ok();
if let (Some(id), Some(secret)) = (env_id, env_secret) {
// Still try to load project_id from config file for the scope picker
let project_id = crate::oauth_config::load_client_config()
.ok()
.map(|c| c.project_id);
return Ok((id, secret, project_id));
}
// 2. Try saved client_secret.json
match crate::oauth_config::load_client_config() {
Ok(config) => Ok((
config.client_id,
config.client_secret,
Some(config.project_id),
)),
Err(_) => Err(GwsError::Auth(
format!(
"No OAuth client configured.\n\n\
Either:\n \
1. Run `gws auth setup` to configure a GCP project and OAuth client\n \
2. Download client_secret.json from Google Cloud Console and save it to:\n \
{}\n \
3. Set env vars: GOOGLE_WORKSPACE_CLI_CLIENT_ID and GOOGLE_WORKSPACE_CLI_CLIENT_SECRET",
crate::oauth_config::client_config_path().display()
),
)),
}
}
/// Resolve OAuth scopes: explicit flags > interactive picker > defaults.
///
/// When `services_filter` is `Some`, only scopes belonging to the specified
/// services are shown in the picker (or returned in non-interactive mode).
async fn resolve_scopes(
args: &[String],
project_id: Option<&str>,
services_filter: Option<&HashSet<String>>,
) -> Vec<String> {
// Explicit --scopes flag takes priority (bypasses services filter)
for i in 0..args.len() {
if args[i] == "--scopes" && i + 1 < args.len() {
return args[i + 1]
.split(',')
.map(|s| s.trim().to_string())
.collect();
}
}
if args.iter().any(|a| a == "--readonly") {
let scopes: Vec<String> = READONLY_SCOPES.iter().map(|s| s.to_string()).collect();
return filter_scopes_by_services(scopes, services_filter);
}
if args.iter().any(|a| a == "--full") {
let scopes: Vec<String> = FULL_SCOPES.iter().map(|s| s.to_string()).collect();
return filter_scopes_by_services(scopes, services_filter);
}
// Interactive scope picker when running in a TTY
if !cfg!(test) && std::io::IsTerminal::is_terminal(&std::io::stdin()) {
// If we have a project_id, use discovery-based scope picker (rich templates)
if let Some(pid) = project_id {
let enabled_apis = crate::setup::get_enabled_apis(pid);
if !enabled_apis.is_empty() {
let api_ids: Vec<String> = enabled_apis;
let scopes = crate::setup::fetch_scopes_for_apis(&api_ids).await;
if !scopes.is_empty() {
if let Some(selected) = run_discovery_scope_picker(&scopes, services_filter) {
return selected;
}
}
}
}
// Fallback: simple scope picker using static SCOPE_ENTRIES
if let Some(selected) = run_simple_scope_picker(services_filter) {
return selected;
}
}
let defaults: Vec<String> = DEFAULT_SCOPES.iter().map(|s| s.to_string()).collect();
filter_scopes_by_services(defaults, services_filter)
}
/// Check if a scope URL belongs to one of the specified services.
///
/// Matching is done on the scope's short name (the part after
/// `https://www.googleapis.com/auth/`). A scope matches a service if its
/// short name equals the service or starts with `service.` (e.g. service
/// `drive` matches `drive`, `drive.readonly`, `drive.metadata.readonly`).
///
/// The `cloud-platform` scope always passes through since it's a
/// cross-service platform scope.
fn scope_matches_service(scope_url: &str, services: &HashSet<String>) -> bool {
let short = scope_url
.strip_prefix("https://www.googleapis.com/auth/")
.unwrap_or(scope_url);
// cloud-platform is a cross-service scope, always include
if short == "cloud-platform" {
return true;
}
let prefix = short.split('.').next().unwrap_or(short);
services.iter().any(|svc| {
// Map common user-friendly service names to their OAuth scope prefixes
let mapped_svc = match svc.as_str() {
"sheets" => "spreadsheets",
"slides" => "presentations",
"docs" => "documents",
s => s,
};
prefix == mapped_svc || short.starts_with(&format!("{mapped_svc}."))
})
}
/// Remove restrictive scopes that are redundant when broader alternatives
/// are present. For example, `gmail.metadata` restricts query parameters
/// and is unnecessary when `gmail.modify`, `gmail.readonly`, or the full
/// `https://mail.google.com/` scope is already included.
///
/// This prevents Google from enforcing the restrictive scope's limitations
/// on the access token even though broader access was granted.
fn filter_redundant_restrictive_scopes(scopes: Vec<String>) -> Vec<String> {
// Scopes that restrict API behavior when present in a token, even alongside
// broader scopes. Each entry maps a restrictive scope to the broader scopes
// that make it redundant. The restrictive scope is removed only if at least
// one of its broader alternatives is already in the list.
const RESTRICTIVE_SCOPES: &[(&str, &[&str])] = &[(
"https://www.googleapis.com/auth/gmail.metadata",
&[
"https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly",
],
)];
let scope_set: std::collections::HashSet<String> = scopes.iter().cloned().collect();
scopes
.into_iter()
.filter(|scope| {
!RESTRICTIVE_SCOPES.iter().any(|(restrictive, broader)| {
scope.as_str() == *restrictive && broader.iter().any(|b| scope_set.contains(*b))
})
})
.collect()
}
/// Filter a list of scope URLs to only those matching the given services.
/// If no filter is provided, returns all scopes unchanged.
fn filter_scopes_by_services(
scopes: Vec<String>,
services_filter: Option<&HashSet<String>>,
) -> Vec<String> {
match services_filter {
Some(services) if !services.is_empty() => scopes
.into_iter()
.filter(|s| scope_matches_service(s, services))
.collect(),
_ => scopes,
}
}
/// Check if a scope is subsumed by a broader scope in the list.
/// e.g. "drive.metadata" is subsumed by "drive", "calendar.events" by "calendar".
fn is_subsumed_scope(short: &str, all_shorts: &[&str]) -> bool {
all_shorts.iter().any(|&other| {
other != short
&& short.starts_with(other)
&& short.as_bytes().get(other.len()) == Some(&b'.')
})
}
/// Determine if a discovered scope should be included in the "Recommended" template.
///
/// When a services filter is active, recommends all top-level (non-subsumed) scopes.
/// Otherwise, recommends only the curated `MINIMAL_SCOPES` list to stay under
/// the 25-scope limit for unverified apps and @gmail.com accounts.
///
/// Always excludes admin-only and Workspace-admin scopes.
fn is_recommended_scope(
entry: &crate::setup::DiscoveredScope,
all_shorts: &[&str],
has_services_filter: bool,
) -> bool {
if entry.short.starts_with("admin.") || is_workspace_admin_scope(&entry.url) {
return false;
}
if has_services_filter {
!is_subsumed_scope(&entry.short, all_shorts)
} else {
MINIMAL_SCOPES.contains(&entry.url.as_str())
}
}
/// Run the rich discovery-based scope picker with templates.
fn run_discovery_scope_picker(
relevant_scopes: &[crate::setup::DiscoveredScope],
services_filter: Option<&HashSet<String>>,
) -> Option<Vec<String>> {
use crate::setup::{ScopeClassification, PLATFORM_SCOPE};
use crate::setup_tui::{PickerResult, SelectItem};
let mut recommended_scopes = vec![];
let mut readonly_scopes = vec![];
let mut all_scopes = vec![];
// Pre-filter scopes by services if a filter is specified
let filtered_scopes: Vec<&crate::setup::DiscoveredScope> = relevant_scopes
.iter()
.filter(|e| {
services_filter.is_none_or(|services| {
services.is_empty() || scope_matches_service(&e.url, services)
})
})
.collect();
// Collect all short names for hierarchical dedup of Full Access template
let all_shorts: Vec<&str> = filtered_scopes
.iter()
.filter(|e| !is_app_only_scope(&e.url))
.map(|e| e.short.as_str())
.collect();
for entry in &filtered_scopes {
// Skip app-only scopes that can't be used with user OAuth
if is_app_only_scope(&entry.url) {
continue;
}
if is_recommended_scope(entry, &all_shorts, services_filter.is_some()) {
recommended_scopes.push(entry.short.to_string());
}
if entry.is_readonly {
readonly_scopes.push(entry.short.to_string());
}
// For "Full Access": skip if a broader scope exists (hierarchical dedup)
// e.g. "drive.metadata" is subsumed by "drive", "calendar.events" by "calendar"
if !is_subsumed_scope(&entry.short, &all_shorts) {
all_scopes.push(entry.short.to_string());
}
}
let mut items: Vec<SelectItem> = vec![
SelectItem {
label: "✨ Recommended (Core Consumer Scopes)".to_string(),
description: "Selects Drive, Gmail, Calendar, Docs, Sheets, Slides, and Tasks"
.to_string(),
selected: true,
is_fixed: false,
is_template: true,
template_selects: recommended_scopes,
},
SelectItem {
label: "🔒 Read Only".to_string(),
description: "Selects only readonly scopes for enabled APIs".to_string(),
selected: false,
is_fixed: false,
is_template: true,
template_selects: readonly_scopes,
},
SelectItem {
label: "⚠️ Full Access (All Scopes)".to_string(),
description: "Selects ALL scopes, including restricted write scopes".to_string(),
selected: false,
is_fixed: false,
is_template: true,
template_selects: all_scopes,
},
];
let template_count = items.len();
let mut valid_scope_indices: Vec<usize> = Vec::new();
for (idx, entry) in filtered_scopes.iter().enumerate() {
// Skip app-only scopes from the picker entirely
if is_app_only_scope(&entry.url) {
continue;
}
let (prefix, emoji) = match entry.classification {
ScopeClassification::Restricted => ("RESTRICTED ", "⛔ "),
ScopeClassification::Sensitive => ("SENSITIVE ", "⚠️ "),
ScopeClassification::NonSensitive => ("", ""),
};
let desc_str = if entry.description.is_empty() {
entry.url.clone()
} else {
entry.description.clone()
};
let description = if prefix.is_empty() {
desc_str
} else {
format!("{}{}{}", emoji, prefix, desc_str)
};
let is_recommended = if entry.is_readonly {
let superset = entry.url.strip_suffix(".readonly").unwrap_or(&entry.url);
let superset_is_recommended = filtered_scopes
.iter()
.any(|s| s.url == superset && s.classification != ScopeClassification::Restricted);
!superset_is_recommended
} else {
entry.classification != ScopeClassification::Restricted
};
items.push(SelectItem {
label: entry.short.to_string(),
description,
selected: is_recommended,
is_fixed: false,
is_template: false,
template_selects: vec![],
});
valid_scope_indices.push(idx);
}
match crate::setup_tui::run_picker(
"Select OAuth scopes",
"Space to toggle, Enter to confirm",
items,
true,
) {
Ok(PickerResult::Confirmed(items)) => {
let recommended = items.first().is_some_and(|i| i.selected);
let readonly = items.get(1).is_some_and(|i| i.selected);
let full = items.get(2).is_some_and(|i| i.selected);
let mut selected: Vec<String> = Vec::new();
if full && !recommended && !readonly {
// Full Access: include all non-app-only scopes
// (hierarchical dedup is applied in post-processing below)
for entry in &filtered_scopes {
if is_app_only_scope(&entry.url) {
continue;
}
selected.push(entry.url.to_string());
}
} else if recommended && !full && !readonly {
// Recommended: consumer scopes only (or top-level scopes if filtered).
for entry in &filtered_scopes {
if is_app_only_scope(&entry.url) {
continue;
}
if is_recommended_scope(entry, &all_shorts, services_filter.is_some()) {
selected.push(entry.url.to_string());
}
}
} else if readonly && !full && !recommended {
for entry in &filtered_scopes {
if is_app_only_scope(&entry.url) {
continue;
}
if entry.is_readonly {
selected.push(entry.url.to_string());
}
}
} else {
for (i, item) in items.iter().enumerate().skip(template_count) {
if item.selected {
let picker_idx = i - template_count;
if let Some(&scope_idx) = valid_scope_indices.get(picker_idx) {
if let Some(entry) = filtered_scopes.get(scope_idx) {
selected.push(entry.url.to_string());
}
}
}
}
}
// Always include cloud-platform scope
if !selected.contains(&PLATFORM_SCOPE.to_string()) {
selected.push(PLATFORM_SCOPE.to_string());
}
// Hierarchical dedup: if we have both a broad scope (e.g. `.../auth/drive`)
// and a narrower scope (e.g. `.../auth/drive.metadata`, `.../auth/drive.readonly`),
// drop the narrower one since the broad scope subsumes it.
let prefix = "https://www.googleapis.com/auth/";
let shorts: Vec<&str> = selected
.iter()
.filter_map(|s| s.strip_prefix(prefix))
.collect();
let mut deduplicated: Vec<String> = Vec::new();
for scope in &selected {
if let Some(short) = scope.strip_prefix(prefix) {
// Check if any OTHER selected scope is a prefix of this one
// e.g. "drive" is a prefix of "drive.metadata" → drop "drive.metadata"
let is_subsumed = shorts.iter().any(|&other| {
other != short
&& short.starts_with(other)
&& short.as_bytes().get(other.len()) == Some(&b'.')
});
if is_subsumed {
continue;
}
}
deduplicated.push(scope.clone());
}
if deduplicated.len() > 30 {
eprintln!(
"⚠️ Warning: {} scopes selected. Unverified OAuth apps may fail with this many scopes.",
deduplicated.len()
);
}
if deduplicated.is_empty() {
None
} else {
Some(deduplicated)
}
}
_ => None, // GoBack, Cancelled, or error
}
}
/// Run the simple static scope picker (fallback when no project_id available).
fn run_simple_scope_picker(services_filter: Option<&HashSet<String>>) -> Option<Vec<String>> {
use crate::setup_tui::{PickerResult, SelectItem};
// Pre-filter SCOPE_ENTRIES by services if a filter is provided
let entries: Vec<&ScopeEntry> = SCOPE_ENTRIES
.iter()
.filter(|entry| {
services_filter.is_none_or(|services| {
services.is_empty() || scope_matches_service(entry.scope, services)
})
})
.collect();
let items: Vec<SelectItem> = entries
.iter()
.map(|entry| SelectItem {
label: entry.label.to_string(),
description: entry.scope.to_string(),
selected: true,
is_fixed: false,
is_template: false,
template_selects: vec![],
})
.collect();
match crate::setup_tui::run_picker(
"Select OAuth scopes",
"Space to toggle, 'a' to select all, Enter to confirm",
items,
true,
) {
Ok(PickerResult::Confirmed(items)) => {
let selected: Vec<String> = items
.iter()
.enumerate()
.filter(|(_, item)| item.selected)
.map(|(i, _)| entries[i].scope.to_string())
.collect();
if selected.is_empty() {
None
} else {
Some(selected)
}
}
_ => None,
}
}
async fn handle_status() -> Result<(), GwsError> {
let plain_path = plain_credentials_path();
let enc_path = credential_store::encrypted_credentials_path();
let token_cache = token_cache_path();
let has_encrypted = enc_path.exists();
let has_plain = plain_path.exists();
let has_token_cache = token_cache.exists();
let auth_method = if has_encrypted || has_plain {
"oauth2"
} else {
"none"
};
let storage = if has_encrypted {
"encrypted"
} else if has_plain {
"plaintext"
} else {
"none"
};
let mut output = json!({
"auth_method": auth_method,
"storage": storage,