forked from googleworkspace/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.rs
More file actions
2566 lines (2308 loc) · 84 KB
/
executor.rs
File metadata and controls
2566 lines (2308 loc) · 84 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.
//! API Request Execution
//!
//! Handles building and dispatching HTTP requests to Google Workspace APIs.
//! Responsibilities include multipart file uploads, response pagination,
//! error mapping, and optionally running text content through Model Armor for sanitization.
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use anyhow::Context;
use base64::Engine as _;
use futures_util::stream::TryStreamExt;
use futures_util::StreamExt;
use serde_json::{json, Map, Value};
use tokio::io::AsyncWriteExt;
use crate::discovery::{RestDescription, RestMethod};
use crate::error::GwsError;
use crate::output::sanitize_for_terminal;
/// Tracks what authentication method was used for the request.
#[derive(Debug, Clone, PartialEq)]
pub enum AuthMethod {
/// OAuth2 bearer token from credentials file
OAuth,
/// No authentication was provided
None,
}
/// Source for media upload content.
///
/// Two mutually exclusive strategies: upload from a file on disk (for Drive,
/// Chat, etc.) or from in-memory bytes (for Gmail's constructed RFC 5322
/// messages). Using an enum makes illegal states (both set, or mismatched
/// content types) unrepresentable.
pub enum UploadSource<'a> {
/// Stream from a file on disk. Content type is inferred from the file
/// extension, overridden by metadata mimeType, or explicitly set.
File {
path: &'a str,
content_type: Option<&'a str>,
},
/// Upload from in-memory bytes with an explicit content type.
Bytes {
data: &'a [u8],
content_type: &'a str,
},
}
/// Configuration for auto-pagination.
#[derive(Debug, Clone)]
pub struct PaginationConfig {
/// Whether to auto-paginate through all pages.
pub page_all: bool,
/// Maximum number of pages to fetch (default: 10).
pub page_limit: u32,
/// Delay between page fetches in milliseconds (default: 100).
pub page_delay_ms: u64,
}
impl Default for PaginationConfig {
fn default() -> Self {
Self {
page_all: false,
page_limit: 10,
page_delay_ms: 100,
}
}
}
/// Parsed and validated inputs ready for request execution.
#[allow(dead_code)]
struct ExecutionInput {
params: Map<String, Value>,
body: Option<Value>,
full_url: String,
query_params: Vec<(String, String)>,
is_upload: bool,
}
/// Parse parameters and body JSON, validate against schema, check required params, and build the URL.
fn parse_and_validate_inputs(
doc: &RestDescription,
method: &RestMethod,
params_json: Option<&str>,
body_json: Option<&str>,
is_media_upload: bool,
) -> Result<ExecutionInput, GwsError> {
let params: Map<String, Value> = if let Some(p) = params_json {
serde_json::from_str(p)
.map_err(|e| GwsError::Validation(format!("Invalid --params JSON: {e}")))?
} else {
Map::new()
};
let body: Option<Value> = if let Some(b) = body_json {
let val: Value = serde_json::from_str(b)
.map_err(|e| GwsError::Validation(format!("Invalid --json body: {e}")))?;
if let Some(ref req_ref) = method.request {
if let Some(ref schema_name) = req_ref.schema_ref {
validate_body_against_schema(&val, schema_name, doc)?;
}
}
Some(val)
} else {
None
};
for param_name in &method.parameter_order {
if let Some(param_def) = method.parameters.get(param_name) {
if param_def.required
&& param_def.location.as_deref() == Some("path")
&& !params.contains_key(param_name)
{
return Err(GwsError::Validation(format!(
"Required path parameter {} is missing. Provide it via --params",
param_name
)));
}
}
}
for (param_name, param_def) in &method.parameters {
if param_def.required && !params.contains_key(param_name) {
return Err(GwsError::Validation(format!(
"Required parameter '{}' is missing. Provide it via --params",
param_name
)));
}
}
let (full_url, query_params) = build_url(doc, method, ¶ms, is_media_upload)?;
let is_upload = is_media_upload && method.supports_media_upload;
Ok(ExecutionInput {
params,
body,
full_url,
query_params,
is_upload,
})
}
/// Build an HTTP request with auth, query params, page token, and body/multipart attachment.
#[allow(clippy::too_many_arguments)]
async fn build_http_request(
client: &reqwest::Client,
method: &RestMethod,
input: &ExecutionInput,
token: Option<&str>,
auth_method: &AuthMethod,
page_token: Option<&str>,
pages_fetched: u32,
upload: &Option<UploadSource<'_>>,
) -> Result<reqwest::RequestBuilder, GwsError> {
let mut request = match method.http_method.as_str() {
"GET" => client.get(&input.full_url),
"POST" => client.post(&input.full_url),
"PUT" => client.put(&input.full_url),
"PATCH" => client.patch(&input.full_url),
"DELETE" => client.delete(&input.full_url),
other => {
return Err(GwsError::Other(anyhow::anyhow!(
"Unsupported HTTP method: {other}"
)))
}
};
if let Some(token) = token {
if *auth_method == AuthMethod::OAuth {
request = request.bearer_auth(token);
}
}
// Set quota project from ADC for billing/quota attribution
if let Some(quota_project) = crate::auth::get_quota_project() {
request = request.header("x-goog-user-project", quota_project);
}
let mut all_query_params = input.query_params.clone();
if let Some(pt) = page_token {
all_query_params.push(("pageToken".to_string(), pt.to_string()));
}
if !all_query_params.is_empty() {
request = request.query(&all_query_params);
}
if pages_fetched == 0 {
if let Some(upload_source) = upload {
request = request.query(&[("uploadType", "multipart")]);
let (body, content_type, content_length) = match upload_source {
UploadSource::Bytes { data, content_type } => {
if content_type.contains('\r') || content_type.contains('\n') {
return Err(GwsError::Validation(
"Upload content type must not contain CR or LF".to_string(),
));
}
build_multipart_bytes(&input.body, data, content_type)?
}
UploadSource::File { path, content_type } => {
let file_meta = tokio::fs::metadata(path).await.map_err(|e| {
GwsError::Validation(format!(
"Failed to get metadata for upload file '{}': {}",
path, e
))
})?;
let file_size = file_meta.len();
let media_mime = resolve_upload_mime(*content_type, Some(path), &input.body);
build_multipart_stream(&input.body, path, file_size, &media_mime)?
}
};
request = request.header("Content-Type", content_type);
request = request.header("Content-Length", content_length);
request = request.body(body);
} else if let Some(ref body_val) = input.body {
request = request.header("Content-Type", "application/json");
request = request.json(body_val);
} else if matches!(method.http_method.as_str(), "POST" | "PUT" | "PATCH") {
request = request.header("Content-Length", "0");
}
}
Ok(request)
}
/// Handle a JSON response: parse, sanitize via Model Armor, output, and check pagination.
/// Returns `Ok(true)` if the pagination loop should continue.
#[allow(clippy::too_many_arguments)]
async fn handle_json_response(
body_text: &str,
output_path: Option<&str>,
pagination: &PaginationConfig,
sanitize_template: Option<&str>,
sanitize_mode: &crate::helpers::modelarmor::SanitizeMode,
output_format: &crate::formatter::OutputFormat,
pages_fetched: &mut u32,
page_token: &mut Option<String>,
capture_output: bool,
captured: &mut Vec<Value>,
) -> Result<bool, GwsError> {
if let Ok(mut json_val) = serde_json::from_str::<Value>(body_text) {
*pages_fetched += 1;
// Run Model Armor sanitization if --sanitize is enabled
if let Some(template) = sanitize_template {
let text_to_check = serde_json::to_string(&json_val).unwrap_or_default();
match crate::helpers::modelarmor::sanitize_text(template, &text_to_check).await {
Ok(result) => {
let is_match = result.filter_match_state == "MATCH_FOUND";
if is_match {
eprintln!("⚠️ Model Armor: prompt injection detected (filterMatchState: MATCH_FOUND)");
}
if is_match && *sanitize_mode == crate::helpers::modelarmor::SanitizeMode::Block
{
let blocked = serde_json::json!({
"error": "Content blocked by Model Armor",
"sanitizationResult": serde_json::to_value(&result).unwrap_or_default(),
});
println!(
"{}",
serde_json::to_string_pretty(&blocked).unwrap_or_default()
);
return Err(GwsError::Other(anyhow::anyhow!(
"Content blocked by Model Armor"
)));
}
if let Some(obj) = json_val.as_object_mut() {
obj.insert(
"_sanitization".to_string(),
serde_json::to_value(&result).unwrap_or_default(),
);
}
}
Err(e) => {
eprintln!(
"⚠️ Model Armor sanitization failed: {}",
sanitize_for_terminal(&e.to_string())
);
}
}
}
if let Some(path) = output_path {
if pagination.page_all {
return Err(GwsError::Validation(
"--output cannot be used with --page-all for JSON responses".to_string(),
));
}
let data = extract_json_wrapped_binary(&json_val).ok_or_else(|| {
GwsError::Validation(
"--output is only supported for binary responses or JSON payloads with a base64url `data` field"
.to_string(),
)
})?;
let path = PathBuf::from(path);
tokio::fs::write(&path, &data)
.await
.context("Failed to write decoded JSON payload to output file")?;
let result = json!({
"status": "success",
"saved_file": path.display().to_string(),
"bytes": data.len(),
"decoded_from": "json.data(base64url)",
});
if capture_output {
captured.push(result);
} else {
println!("{}", crate::formatter::format_value(&result, output_format));
}
} else if capture_output {
captured.push(json_val.clone());
} else if pagination.page_all {
let is_first_page = *pages_fetched == 1;
println!(
"{}",
crate::formatter::format_value_paginated(&json_val, output_format, is_first_page)
);
} else {
println!(
"{}",
crate::formatter::format_value(&json_val, output_format)
);
}
// Check for nextPageToken to continue pagination
if pagination.page_all {
if let Some(next_token) = json_val.get("nextPageToken").and_then(|v| v.as_str()) {
if *pages_fetched < pagination.page_limit {
*page_token = Some(next_token.to_string());
if pagination.page_delay_ms > 0 {
tokio::time::sleep(std::time::Duration::from_millis(
pagination.page_delay_ms,
))
.await;
}
return Ok(true); // continue paginating
}
}
}
} else {
// Not valid JSON, output as-is
if !capture_output && !body_text.is_empty() {
println!("{body_text}");
}
}
Ok(false)
}
fn extract_json_wrapped_binary(json_val: &Value) -> Option<Vec<u8>> {
let data = json_val.get("data")?.as_str()?;
base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(data)
.ok()
.or_else(|| base64::engine::general_purpose::URL_SAFE.decode(data).ok())
}
/// Handle a binary response by streaming it to a file.
async fn handle_binary_response(
response: reqwest::Response,
content_type: &str,
output_path: Option<&str>,
output_format: &crate::formatter::OutputFormat,
capture_output: bool,
) -> Result<Option<Value>, GwsError> {
let file_path = if let Some(p) = output_path {
PathBuf::from(p)
} else {
let ext = mime_to_extension(content_type);
PathBuf::from(format!("download.{ext}"))
};
let mut file = tokio::fs::File::create(&file_path)
.await
.context("Failed to create output file")?;
let mut stream = response.bytes_stream();
let mut total_bytes: u64 = 0;
while let Some(chunk) = stream.next().await {
let chunk = chunk.context("Failed to read response chunk")?;
file.write_all(&chunk)
.await
.context("Failed to write to file")?;
total_bytes += chunk.len() as u64;
}
file.flush().await.context("Failed to flush file")?;
let result = json!({
"status": "success",
"saved_file": file_path.display().to_string(),
"mimeType": content_type,
"bytes": total_bytes,
});
if capture_output {
return Ok(Some(result));
}
println!("{}", crate::formatter::format_value(&result, output_format));
Ok(None)
}
/// Executes an API method call.
///
/// This is the core function of the CLI that handles:
/// 1. Parameter validation and URL construction.
/// 2. Request body validation against the Discovery Document schema.
/// 3. Authentication (OAuth or none).
/// 4. Sending the HTTP request (GET/POST/etc).
/// 5. Handling various response types (JSON, binary).
/// 6. Auto-pagination for list endpoints.
/// 7. Model Armor prompt injection scanning.
#[allow(clippy::too_many_arguments)]
pub async fn execute_method(
doc: &RestDescription,
method: &RestMethod,
params_json: Option<&str>,
body_json: Option<&str>,
token: Option<&str>,
auth_method: AuthMethod,
output_path: Option<&str>,
upload: Option<UploadSource<'_>>,
dry_run: bool,
pagination: &PaginationConfig,
sanitize_template: Option<&str>,
sanitize_mode: &crate::helpers::modelarmor::SanitizeMode,
output_format: &crate::formatter::OutputFormat,
capture_output: bool,
) -> Result<Option<Value>, GwsError> {
let input = parse_and_validate_inputs(doc, method, params_json, body_json, upload.is_some())?;
if dry_run {
let dry_run_info = json!({
"dry_run": true,
"url": input.full_url,
"method": method.http_method,
"query_params": input.query_params,
"body": input.body,
"is_multipart_upload": input.is_upload,
});
if capture_output {
return Ok(Some(dry_run_info));
}
println!(
"{}",
crate::formatter::format_value(&dry_run_info, output_format)
);
return Ok(None);
}
let mut page_token: Option<String> = None;
let mut pages_fetched: u32 = 0;
let mut captured_values = Vec::new();
loop {
let client = crate::client::build_client()?;
let request = build_http_request(
&client,
method,
&input,
token,
&auth_method,
page_token.as_deref(),
pages_fetched,
&upload,
)
.await?;
let method_id = method.id.as_deref().unwrap_or("unknown");
let start = std::time::Instant::now();
let response = request.send().await.context("HTTP request failed")?;
let latency_ms = start.elapsed().as_millis() as u64;
let status = response.status();
let content_type = response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
if !status.is_success() {
let error_body = response.text().await.unwrap_or_default();
tracing::warn!(
api_method = method_id,
http_method = %method.http_method,
status = status.as_u16(),
latency_ms = latency_ms,
"API error"
);
return handle_error_response(status, &error_body, &auth_method);
}
tracing::debug!(
api_method = method_id,
http_method = %method.http_method,
status = status.as_u16(),
latency_ms = latency_ms,
content_type = %content_type,
is_upload = input.is_upload,
page = pages_fetched,
"API request"
);
let is_json =
content_type.contains("application/json") || content_type.contains("text/json");
if is_json || content_type.is_empty() {
let body_text = response
.text()
.await
.context("Failed to read response body")?;
let should_continue = handle_json_response(
&body_text,
output_path,
pagination,
sanitize_template,
sanitize_mode,
output_format,
&mut pages_fetched,
&mut page_token,
capture_output,
&mut captured_values,
)
.await?;
if should_continue {
continue;
}
} else if let Some(res) = handle_binary_response(
response,
&content_type,
output_path,
output_format,
capture_output,
)
.await?
{
captured_values.push(res);
}
break;
}
if capture_output && !captured_values.is_empty() {
if captured_values.len() == 1 {
return Ok(Some(captured_values.pop().unwrap()));
} else {
return Ok(Some(Value::Array(captured_values)));
}
}
Ok(None)
}
fn build_url(
doc: &RestDescription,
method: &RestMethod,
params: &Map<String, Value>,
is_upload: bool,
) -> Result<(String, Vec<(String, String)>), GwsError> {
// Build URL base and path
// Actually we need to construct base URL properly if not present
let base_url = if let Some(b) = &doc.base_url {
b.clone()
} else {
format!("{}{}", doc.root_url, doc.service_path)
};
// Prefer flatPath when its placeholders match the method's path parameters.
// Some Discovery Documents (e.g., Slides presentations.get) have flatPath
// placeholders that don't match parameter names ({presentationsId} vs
// {presentationId}). In those cases, fall back to path which uses RFC 6570
// operators ({+var}) that this function already handles.
let path_template = match method.flat_path.as_deref() {
Some(fp) => {
let all_match = method
.parameters
.iter()
.filter(|(_, p)| p.location.as_deref() == Some("path"))
.all(|(name, _)| {
let plain = format!("{{{name}}}");
let plus = format!("{{+{name}}}");
fp.contains(&plain) || fp.contains(&plus)
});
if all_match {
fp
} else {
method.path.as_str()
}
}
None => method.path.as_str(),
};
// Substitute path parameters and separate query parameters
let path_parameters = extract_template_path_parameters(path_template);
let mut query_params: Vec<(String, String)> = Vec::new();
for (key, value) in params {
if path_parameters.contains(key.as_str()) {
continue;
}
let is_path_param = method
.parameters
.get(key)
.and_then(|p| p.location.as_deref())
== Some("path");
if is_path_param {
return Err(GwsError::Validation(format!(
"Path parameter '{}' was provided but is not present in URL template '{}'",
key, path_template
)));
}
// For repeated parameters, expand JSON arrays into multiple query entries
let is_repeated = method
.parameters
.get(key)
.map(|p| p.repeated)
.unwrap_or(false);
if is_repeated {
if let Value::Array(arr) = value {
for item in arr {
let val_str = match item {
Value::String(s) => s.clone(),
other => other.to_string(),
};
query_params.push((key.clone(), val_str));
}
continue;
}
}
if !is_repeated && value.is_array() {
eprintln!(
"Warning: parameter '{}' is not marked as repeated; array value will be stringified. \
Use `gws schema` to check which parameters accept arrays.",
key
);
}
let val_str = match value {
Value::String(s) => s.clone(),
other => other.to_string(),
};
query_params.push((key.clone(), val_str));
}
let url_path = render_path_template(path_template, params)?;
let full_url = if is_upload {
// Use the upload endpoint from the Discovery Document
let upload_endpoint = method
.media_upload
.as_ref()
.and_then(|mu| mu.protocols.as_ref())
.and_then(|p| p.simple.as_ref())
.map(|s| s.path.as_str())
.ok_or_else(|| {
GwsError::Validation(
"Method supports media upload but no upload path found in Discovery Document"
.to_string(),
)
})?;
let upload_path = render_path_template(upload_endpoint, params)?;
format!("{}{}", doc.root_url.trim_end_matches('/'), upload_path)
} else {
format!("{base_url}{url_path}")
};
Ok((full_url, query_params))
}
fn extract_template_path_parameters(path_template: &str) -> HashSet<&str> {
let mut found = HashSet::new();
let mut cursor = 0;
while let Some(open_idx) = path_template[cursor..].find('{') {
let token_start = cursor + open_idx;
let Some(close_idx) = path_template[token_start..].find('}') else {
break;
};
let token_end = token_start + close_idx;
let token = &path_template[token_start + 1..token_end];
if let Some(key) = token.strip_prefix('+') {
found.insert(key);
} else {
found.insert(token);
}
cursor = token_end + 1;
}
found
}
fn render_path_template(
path_template: &str,
params: &Map<String, Value>,
) -> Result<String, GwsError> {
let mut rendered = String::with_capacity(path_template.len());
let mut cursor = 0;
while let Some(open_idx) = path_template[cursor..].find('{') {
let token_start = cursor + open_idx;
rendered.push_str(&path_template[cursor..token_start]);
let Some(close_idx) = path_template[token_start..].find('}') else {
rendered.push_str(&path_template[token_start..]);
return Ok(rendered);
};
let token_end = token_start + close_idx;
let token = &path_template[token_start + 1..token_end];
let (is_plus, key) = if let Some(key) = token.strip_prefix('+') {
(true, key)
} else {
(false, token)
};
if let Some(value) = params.get(key) {
let val_str = match value {
Value::String(s) => s.clone(),
other => other.to_string(),
};
let encoded = if is_plus {
let validated = crate::validate::validate_resource_name(&val_str)?;
crate::validate::encode_path_preserving_slashes(validated)
} else {
crate::validate::encode_path_segment(&val_str)
};
rendered.push_str(&encoded);
} else {
rendered.push_str(&path_template[token_start..=token_end]);
}
cursor = token_end + 1;
}
rendered.push_str(&path_template[cursor..]);
Ok(rendered)
}
/// Attempts to extract a GCP console enable URL from a Google API `accessNotConfigured`
/// error message.
///
/// The message format is typically:
/// `"<API> has not been used in project <N> before or it is disabled. Enable it by visiting <URL> then retry."`
///
/// Returns the URL string if found, otherwise `None`.
pub fn extract_enable_url(message: &str) -> Option<String> {
// Look for "visiting <URL>" pattern
let after_visiting = message.split("visiting ").nth(1)?;
// URL ends at the next whitespace character
let url = after_visiting
.split_whitespace()
.next()
.map(|s| {
s.trim_end_matches(|c: char| ['.', ',', ';', ':', ')', ']', '"', '\''].contains(&c))
})
.filter(|s| s.starts_with("http"))?;
Some(url.to_string())
}
fn handle_error_response<T>(
status: reqwest::StatusCode,
error_body: &str,
auth_method: &AuthMethod,
) -> Result<T, GwsError> {
// If 401/403 and no auth was provided, give a helpful message
if (status.as_u16() == 401 || status.as_u16() == 403) && *auth_method == AuthMethod::None {
return Err(GwsError::Auth(
"Access denied. No credentials provided. Run `gws auth login` or set \
GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE to an OAuth credentials JSON file."
.to_string(),
));
}
// Try to parse as Google API error
if let Ok(error_json) = serde_json::from_str::<Value>(error_body) {
if let Some(err_obj) = error_json.get("error") {
let code = err_obj
.get("code")
.and_then(|c| c.as_u64())
.unwrap_or(status.as_u16() as u64) as u16;
let message = err_obj
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("Unknown error")
.to_string();
// Reason can appear in "errors[0].reason" or at the top-level "reason" field.
let reason = err_obj
.get("errors")
.and_then(|e| e.as_array())
.and_then(|arr| arr.first())
.and_then(|e| e.get("reason"))
.and_then(|r| r.as_str())
.or_else(|| err_obj.get("reason").and_then(|r| r.as_str()))
.unwrap_or("unknown")
.to_string();
// For accessNotConfigured, extract the GCP enable URL from the message.
let enable_url = if reason == "accessNotConfigured" {
extract_enable_url(&message)
} else {
None
};
return Err(GwsError::Api {
code,
message,
reason,
enable_url,
});
}
}
Err(GwsError::Api {
code: status.as_u16(),
message: error_body.to_string(),
reason: "httpError".to_string(),
enable_url: None,
})
}
/// Resolves the MIME type for the uploaded media content.
///
/// Priority:
/// 1. `--upload-content-type` flag (explicit override)
/// 2. File extension inference (best guess for what the bytes actually are)
/// 3. Metadata `mimeType` (fallback for backward compatibility)
/// 4. `application/octet-stream`
///
/// Extension inference ranks above metadata `mimeType` because in Google
/// Drive's multipart model, metadata `mimeType` represents the *target* type
/// (what the file should become in Drive), while the media `Content-Type`
/// represents the *source* type (what the bytes are). When a user uploads
/// `notes.md` with `"mimeType":"application/vnd.google-apps.document"`, the
/// media part should be `text/markdown`, not a Google Workspace MIME type.
/// All returned MIME types have control characters stripped to prevent
/// MIME header injection via user-controlled metadata.
fn resolve_upload_mime(
explicit: Option<&str>,
upload_path: Option<&str>,
metadata: &Option<Value>,
) -> String {
let raw = explicit
.map(|s| s.to_string())
.or_else(|| {
upload_path.and_then(|path| mime_guess2::from_path(path).first().map(|m| m.to_string()))
})
.or_else(|| {
metadata
.as_ref()
.and_then(|m| m.get("mimeType"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
})
.unwrap_or_else(|| "application/octet-stream".to_string());
// Strip CR/LF and other control characters to prevent MIME header injection.
let sanitized: String = raw.chars().filter(|c| !c.is_control()).collect();
if sanitized.is_empty() {
"application/octet-stream".to_string()
} else {
sanitized
}
}
/// Builds a streaming multipart/related body for media upload requests.
///
/// Instead of reading the entire file into memory, this streams the file in
/// chunks via `ReaderStream`, keeping memory usage at O(64 KB) regardless of
/// file size. The `Content-Length` is pre-computed from file metadata so Google
/// APIs still receive the correct header without buffering.
///
/// Returns `(body, content_type, content_length)`.
fn build_multipart_stream(
metadata: &Option<Value>,
file_path: &str,
file_size: u64,
media_mime: &str,
) -> Result<(reqwest::Body, String, u64), GwsError> {
let boundary = format!("gws_boundary_{:016x}", rand::random::<u64>());
let media_mime = media_mime.to_string();
let metadata_json = match metadata {
Some(m) => serde_json::to_string(m).map_err(|e| {
GwsError::Validation(format!("Failed to serialize upload metadata: {e}"))
})?,
None => "{}".to_string(),
};
let preamble = format!(
"--{boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{metadata_json}\r\n\
--{boundary}\r\nContent-Type: {media_mime}\r\n\r\n"
);
let postamble = format!("\r\n--{boundary}--\r\n");
let content_length = preamble.len() as u64 + file_size + postamble.len() as u64;
let content_type = format!("multipart/related; boundary={boundary}");
let preamble_bytes: bytes::Bytes = preamble.into_bytes().into();
let postamble_bytes: bytes::Bytes = postamble.into_bytes().into();
let file_path_owned = file_path.to_owned();
let file_stream = futures_util::stream::once(async move {
tokio::fs::File::open(&file_path_owned).await.map_err(|e| {
std::io::Error::new(
e.kind(),
format!("failed to open upload file '{}': {}", file_path_owned, e),
)
})
})
.map_ok(tokio_util::io::ReaderStream::new)
.try_flatten();
let stream = futures_util::stream::once(async { Ok::<_, std::io::Error>(preamble_bytes) })
.chain(file_stream)
.chain(futures_util::stream::once(async {
Ok::<_, std::io::Error>(postamble_bytes)
}));
Ok((
reqwest::Body::wrap_stream(stream),
content_type,
content_length,
))
}
/// Builds a multipart/related body from in-memory bytes.
///
/// Used when the upload content is constructed in memory (e.g., a Gmail RFC 5322
/// message with attachments) rather than read from a file on disk.
fn build_multipart_bytes(
metadata: &Option<Value>,
data: &[u8],
media_mime: &str,
) -> Result<(reqwest::Body, String, u64), GwsError> {
let boundary = format!("gws_boundary_{:016x}", rand::random::<u64>());
let metadata_json = match metadata {
Some(m) => serde_json::to_string(m).map_err(|e| {
GwsError::Validation(format!("Failed to serialize upload metadata: {e}"))
})?,
None => "{}".to_string(),
};
let preamble = format!(
"--{boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{metadata_json}\r\n\
--{boundary}\r\nContent-Type: {media_mime}\r\n\r\n"
);
let postamble = format!("\r\n--{boundary}--\r\n");
let mut body = Vec::with_capacity(preamble.len() + data.len() + postamble.len());
body.extend_from_slice(preamble.as_bytes());
body.extend_from_slice(data);
body.extend_from_slice(postamble.as_bytes());
let content_length = body.len() as u64;
let content_type = format!("multipart/related; boundary={boundary}");
Ok((reqwest::Body::from(body), content_type, content_length))
}
/// Builds a buffered multipart/related body for media upload requests.
///