-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathauth_commands.rs
More file actions
2536 lines (2296 loc) · 91.9 KB
/
auth_commands.rs
File metadata and controls
2536 lines (2296 loc) · 91.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.
use std::collections::HashSet;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use serde::Deserialize;
use serde_json::json;
use crate::credential_store;
use crate::error::GwsError;
/// Response from Google's token endpoint
#[derive(Debug, Deserialize)]
struct OAuthTokenResponse {
access_token: String,
refresh_token: Option<String>,
#[allow(dead_code)]
expires_in: u64,
#[allow(dead_code)]
token_type: String,
}
/// Exchange authorization code for tokens using reqwest (supports HTTP proxy)
async fn exchange_code_with_reqwest(
client_id: &str,
client_secret: &str,
code: &str,
redirect_uri: &str,
) -> Result<OAuthTokenResponse, GwsError> {
let client = crate::client::shared_client()?;
let params = [
("client_id", client_id),
("client_secret", client_secret),
("code", code),
("redirect_uri", redirect_uri),
("grant_type", "authorization_code"),
];
let response = client
.post("https://oauth2.googleapis.com/token")
.form(¶ms)
.send()
.await
.map_err(|e| GwsError::Auth(format!("Failed to send token request: {e}")))?;
if !response.status().is_success() {
let status = response.status();
let body = crate::auth::response_text_or_placeholder(response.text().await);
return Err(GwsError::Auth(format!(
"Token exchange failed with status {}: {}",
status, body
)));
}
response
.json()
.await
.map_err(|e| GwsError::Auth(format!("Failed to parse token response: {e}")))
}
fn build_proxy_auth_url(client_id: &str, redirect_uri: &str, scopes: &[String]) -> String {
let scopes_str = scopes.join(" ");
format!(
"https://accounts.google.com/o/oauth2/auth?\
scope={}&\
access_type=offline&\
redirect_uri={}&\
response_type=code&\
client_id={}&\
prompt=select_account+consent",
urlencoding(&scopes_str),
urlencoding(redirect_uri),
urlencoding(client_id)
)
}
fn extract_authorization_code(request_line: &str) -> Result<String, GwsError> {
let path = request_line
.split_whitespace()
.nth(1)
.ok_or_else(|| GwsError::Auth("Invalid HTTP request".to_string()))?;
path.split('?')
.nth(1)
.and_then(|query| {
query.split('&').find_map(|pair| {
let mut parts = pair.split('=');
if parts.next() == Some("code") {
parts.next().map(|value| value.to_string())
} else {
None
}
})
})
.ok_or_else(|| GwsError::Auth("No authorization code in callback".to_string()))
}
/// Perform OAuth login flow with proxy support using reqwest for token exchange
async fn login_with_proxy_support(
client_id: &str,
client_secret: &str,
scopes: &[String],
) -> Result<(String, String), GwsError> {
// Start local server to receive OAuth callback
let listener = TcpListener::bind("127.0.0.1:0")
.map_err(|e| GwsError::Auth(format!("Failed to start local server: {e}")))?;
let port = listener
.local_addr()
.map_err(|e| GwsError::Auth(format!("Failed to inspect local server: {e}")))?
.port();
let redirect_uri = format!("http://localhost:{}", port);
let auth_url = build_proxy_auth_url(client_id, &redirect_uri, scopes);
println!("Open this URL in your browser to authenticate:\n");
println!(" {}\n", auth_url);
// Wait for OAuth callback
let (mut stream, _) = listener
.accept()
.map_err(|e| GwsError::Auth(format!("Failed to accept connection: {e}")))?;
let mut reader = BufReader::new(&stream);
let mut request_line = String::new();
reader
.read_line(&mut request_line)
.map_err(|e| GwsError::Auth(format!("Failed to read request: {e}")))?;
let code = extract_authorization_code(&request_line)?;
// Send success response to browser
let response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\
<html><body><h1>Success!</h1><p>You may now close this window.</p></body></html>";
let _ = stream.write_all(response.as_bytes());
// Exchange code for tokens using reqwest (proxy-aware)
let token_response =
exchange_code_with_reqwest(client_id, client_secret, &code, &redirect_uri).await?;
let refresh_token = token_response.refresh_token.ok_or_else(|| {
GwsError::Auth(
"OAuth flow completed but no refresh token was returned. \
Ensure the OAuth consent screen includes 'offline' access."
.to_string(),
)
})?;
Ok((token_response.access_token, refresh_token))
}
fn read_refresh_token_from_cache(temp_path: &Path) -> Result<String, GwsError> {
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();
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(),
)
})
}
async fn login_with_yup_oauth(
config_dir: &Path,
client_id: &str,
client_secret: &str,
scopes: &[String],
) -> Result<(String, String), GwsError> {
let secret = yup_oauth2::ApplicationSecret {
client_id: client_id.to_string(),
client_secret: client_secret.to_string(),
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()
};
let temp_path = config_dir.join("credentials.tmp");
let _ = std::fs::remove_file(&temp_path);
let result = async {
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)
.flow_delegate(Box::new(CliFlowDelegate { login_hint: None }))
.build()
.await
.map_err(|e| GwsError::Auth(format!("Failed to build authenticator: {e}")))?;
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}")))?;
let access_token = token
.token()
.ok_or_else(|| GwsError::Auth("No access token returned".to_string()))?
.to_string();
let refresh_token = read_refresh_token_from_cache(&temp_path)?;
Ok((access_token, refresh_token))
}
.await;
let _ = std::fs::remove_file(&temp_path);
result
}
/// Simple URL encoding
fn urlencoding(s: &str) -> String {
percent_encoding::utf8_percent_encode(s, percent_encoding::NON_ALPHANUMERIC).to_string()
}
/// Mask a secret string by showing only the first 4 and last 4 characters.
/// Strings with 8 or fewer characters are fully replaced with "***".
///
/// Uses char-based indexing (not byte offsets) so multi-byte UTF-8 secrets
/// never cause a panic.
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;
let char_count = s.chars().count();
if char_count > MIN_LEN_FOR_PARTIAL_MASK {
let prefix: String = s.chars().take(MASK_PREFIX_LEN).collect();
let suffix: String = s.chars().skip(char_count - MASK_SUFFIX_LEN).collect();
format!("{prefix}...{suffix}")
} 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")
}
/// Which scope set to use for login.
enum ScopeMode {
/// Use the default scopes (MINIMAL_SCOPES).
Default,
/// Use readonly scopes.
Readonly,
/// Use full scopes (incl. pubsub + cloud-platform).
Full,
/// Use explicitly provided custom scopes.
Custom(Vec<String>),
}
/// Build the clap Command for the `login` subcommand.
/// Used by both `auth_command()` and `login_command()` as single source of truth.
fn build_login_subcommand() -> clap::Command {
clap::Command::new("login")
.about("Authenticate via OAuth2 (opens browser)")
.arg(
clap::Arg::new("readonly")
.long("readonly")
.help("Request read-only scopes")
.action(clap::ArgAction::SetTrue)
.conflicts_with_all(["full", "scopes"]),
)
.arg(
clap::Arg::new("full")
.long("full")
.help("Request all scopes incl. pubsub + cloud-platform")
.action(clap::ArgAction::SetTrue)
.conflicts_with_all(["readonly", "scopes"]),
)
.arg(
clap::Arg::new("scopes")
.long("scopes")
.help("Comma-separated custom scopes")
.value_name("scopes")
.conflicts_with_all(["readonly", "full"]),
)
.arg(
clap::Arg::new("services")
.short('s')
.long("services")
.help(
"Comma-separated service names to limit scope picker (e.g. drive,gmail,sheets)",
)
.value_name("services"),
)
}
/// Build the clap Command for `gws auth`.
fn auth_command() -> clap::Command {
clap::Command::new("auth")
.about("Manage authentication for Google Workspace APIs")
.subcommand_required(false)
.subcommand(build_login_subcommand())
.subcommand(
clap::Command::new("setup")
.about("Configure GCP project + OAuth client (requires gcloud)")
.disable_help_flag(true)
// setup has its own clap-based arg parsing in setup.rs,
// so we pass remaining args through.
.arg(
clap::Arg::new("args")
.trailing_var_arg(true)
.allow_hyphen_values(true)
.num_args(0..)
.value_name("ARGS"),
),
)
.subcommand(clap::Command::new("status").about("Show current authentication state"))
.subcommand(
clap::Command::new("export")
.about("Print decrypted credentials to stdout")
.arg(
clap::Arg::new("unmasked")
.long("unmasked")
.help("Show secrets without masking")
.action(clap::ArgAction::SetTrue),
),
)
.subcommand(clap::Command::new("logout").about("Clear saved credentials and token cache"))
}
/// Handle `gws auth <subcommand>`.
pub async fn handle_auth_command(args: &[String]) -> Result<(), GwsError> {
let matches = match auth_command()
.try_get_matches_from(std::iter::once("auth".to_string()).chain(args.iter().cloned()))
{
Ok(m) => m,
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}"))
})?;
return Ok(());
}
Err(e) => return Err(GwsError::Validation(e.to_string())),
};
match matches.subcommand() {
Some(("login", sub_m)) => {
let (scope_mode, services_filter) = parse_login_args(sub_m);
handle_login_inner(scope_mode, services_filter).await
}
Some(("setup", sub_m)) => {
// Collect remaining args and delegate to setup's own clap parser.
let setup_args: Vec<String> = sub_m
.get_many::<String>("args")
.map(|vals| vals.cloned().collect())
.unwrap_or_default();
crate::setup::run_setup(&setup_args).await
}
Some(("status", _)) => handle_status().await,
Some(("export", sub_m)) => {
let unmasked = sub_m.get_flag("unmasked");
handle_export(unmasked).await
}
Some(("logout", _)) => handle_logout(),
_ => {
// No subcommand → print help
auth_command()
.print_help()
.map_err(|e| GwsError::Validation(format!("Failed to print help: {e}")))?;
Ok(())
}
}
}
/// Build the clap Command for `gws auth login` (used by `run_login` for
/// standalone parsing when called from setup.rs).
fn login_command() -> clap::Command {
build_login_subcommand()
}
/// Extract `ScopeMode` and optional services filter from parsed login args.
fn parse_login_args(matches: &clap::ArgMatches) -> (ScopeMode, Option<HashSet<String>>) {
let scope_mode = if let Some(scopes_str) = matches.get_one::<String>("scopes") {
ScopeMode::Custom(
scopes_str
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(String::from)
.collect(),
)
} else if matches.get_flag("readonly") {
ScopeMode::Readonly
} else if matches.get_flag("full") {
ScopeMode::Full
} else {
ScopeMode::Default
};
let services_filter: Option<HashSet<String>> = matches.get_one::<String>("services").map(|v| {
v.split(',')
.map(|s| s.trim().to_lowercase())
.filter(|s| !s.is_empty())
.collect()
});
(scope_mode, services_filter)
}
/// Run the `auth login` flow.
///
/// Exposed for internal orchestration (e.g. `auth setup --login`).
/// Accepts raw args for backward compat with setup.rs calling `run_login(&[])`.
pub async fn run_login(args: &[String]) -> Result<(), GwsError> {
let matches = match login_command()
.try_get_matches_from(std::iter::once("login".to_string()).chain(args.iter().cloned()))
{
Ok(m) => m,
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}"))
})?;
return Ok(());
}
Err(e) => return Err(GwsError::Validation(e.to_string())),
};
let (scope_mode, services_filter) = parse_login_args(&matches);
handle_login_inner(scope_mode, services_filter).await
}
/// 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())
})
}
}
/// Inner login implementation that takes already-parsed options.
async fn handle_login_inner(
scope_mode: ScopeMode,
services_filter: Option<HashSet<String>>,
) -> Result<(), GwsError> {
// 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(scope_mode, project_id.as_deref(), services_filter.as_ref()).await;
// Remove restrictive scopes when broader alternatives are present.
let mut scopes = filter_redundant_restrictive_scopes(scopes);
// Ensure openid + email + profile scopes are always present so we can
// identify the user via the userinfo endpoint after login, and so the
// Gmail helpers can fall back to the OAuth userinfo endpoint to populate
// the From display name when the send-as identity lacks one (Workspace
// accounts).
let identity_scopes = [
"openid",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
];
for s in &identity_scopes {
if !scopes.iter().any(|existing| existing == s) {
scopes.push(s.to_string());
}
}
// Ensure config directory exists
let config = config_dir();
std::fs::create_dir_all(&config)
.map_err(|e| GwsError::Validation(format!("Failed to create config directory: {e}")))?;
// If proxy env vars are set, use proxy-aware OAuth flow (reqwest)
// Otherwise use yup-oauth2 (faster, but doesn't support proxy)
let (access_token, refresh_token) = if crate::auth::has_proxy_env() {
login_with_proxy_support(&client_id, &client_secret, &scopes).await?
} else {
login_with_yup_oauth(&config, &client_id, &client_secret, &scopes).await?
};
// 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
let actual_email = fetch_userinfo_email(&access_token).await;
// Save encrypted credentials
let enc_path = credential_store::save_encrypted(&creds_str)
.map_err(|e| GwsError::Auth(format!("Failed to encrypt credentials: {e}")))?;
let output = json!({
"status": "success",
"message": "Authentication successful. Encrypted credentials saved.",
"account": actual_email.as_deref().unwrap_or("(unknown)"),
"credentials_file": enc_path.display().to_string(),
"encryption": "AES-256-GCM (key in OS keyring or local `.encryption_key`; set GOOGLE_WORKSPACE_CLI_KEYRING_BACKEND=file for headless)",
"scopes": scopes,
});
println!(
"{}",
serde_json::to_string_pretty(&output).unwrap_or_default()
);
Ok(())
}
/// 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(
scope_mode: ScopeMode,
project_id: Option<&str>,
services_filter: Option<&HashSet<String>>,
) -> Vec<String> {
match scope_mode {
ScopeMode::Custom(scopes) => return scopes,
ScopeMode::Readonly => {
let scopes: Vec<String> = READONLY_SCOPES.iter().map(|s| s.to_string()).collect();
let mut result = filter_scopes_by_services(scopes, services_filter);
augment_with_dynamic_scopes(&mut result, services_filter, true).await;
return result;
}
ScopeMode::Full => {
let scopes: Vec<String> = FULL_SCOPES.iter().map(|s| s.to_string()).collect();
let mut result = filter_scopes_by_services(scopes, services_filter);
augment_with_dynamic_scopes(&mut result, services_filter, false).await;
return result;
}
ScopeMode::Default => {} // fall through to interactive picker / defaults
}
// 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();
let mut result = filter_scopes_by_services(defaults, services_filter);
augment_with_dynamic_scopes(&mut result, services_filter, false).await;
result
}
/// 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| {
let prefixes = map_service_to_scope_prefixes(svc);
prefixes
.iter()
.any(|mapped| prefix == *mapped || short.starts_with(&format!("{mapped}.")))
})
}
/// Map user-friendly service names to their OAuth scope prefixes.
/// Some services map to multiple scope prefixes (e.g. People API uses
/// both `contacts` and `directory` scopes).
fn map_service_to_scope_prefixes(service: &str) -> Vec<&str> {
match service {
"sheets" => vec!["spreadsheets"],
"slides" => vec!["presentations"],
"docs" => vec!["documents"],
"people" => vec!["contacts", "directory"],
s => vec![s],
}
}
/// 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,