grr-cli 2.2.0

Google tools from the terminal, at maximum performance: 401 methods across 14 Google APIs in one generated command tree, zero-config, over HTTP/3
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
//! `grr api` — the discovery-driven escape hatch.
//!
//! `grr api call <id>` reaches every method Google publishes across the
//! 14 APIs in the committed Discovery index — including anything released
//! after grr was built, with no code change and no new release. The
//! generated service tree
//! (`src/commands/generated.rs`, dispatched by `gen_dispatch.rs`) is the
//! same engine with a friendlier shape: both funnel through
//! [`call_method`], so a dry-run of the same method and parameters is
//! byte-identical either way.
//!
//! ```text
//! grr api list                                    # every method
//! grr api list gmail --filter list                # just Gmail listing methods
//! grr api describe gmail.users.messages.list      # params + scopes
//! grr api call gmail.users.messages.list --param userId=me --param 'q=is:unread'
//! grr api call drive.files.list --params '{"pageSize":10}'
//! grr gmail users messages list --user-id me      # the same call, generated
//! ```
//!
//! The login, not this command, decides the grant: `grr auth login` requests
//! a small 11-scope default, `--service <name>` adds one service's scopes and
//! `--all-scopes` the whole index — the sets and the reasoning behind them
//! live in `core::auth`. A method outside the current grant answers 403
//! naming the scope; widen the grant and retry.

use std::collections::BTreeMap;
use std::sync::{Mutex, MutexGuard};

use crate::commands::safety::SafetyProfile;
use crate::core::auth::GoogleAuth;
use crate::core::http::HttpCore;
use crate::discovery::{self, Method, Service};
use crate::output::{OutputFormat, print_output};
use anyhow::{Context, Result, bail};
use clap::{Args, Subcommand};
use serde_json::{Value, json};

#[derive(Subcommand, Debug)]
pub enum ApiCommands {
    /// List every method the Discovery index knows about
    List(ApiListArgs),
    /// Show one method's parameters, scopes and documentation
    Describe(ApiDescribeArgs),
    /// Invoke a method
    Call(ApiCallArgs),
    /// Fetch fresh Discovery documents into the local cache. The embedded
    /// index keeps working offline; this pulls it forward between releases.
    Refresh(ApiRefreshArgs),
}

#[derive(Args, Debug)]
pub struct ApiRefreshArgs {
    /// Refresh one service only (gmail, calendar, drive, people, chat,
    /// forms, tasks, docs, sheets, slides, script, analyticsadmin,
    /// analyticsdata, searchconsole)
    #[arg(long)]
    pub service: Option<String>,

    /// Output format
    #[arg(short, long, value_enum, default_value = "json")]
    pub format: OutputFormat,
}

#[derive(Args, Debug)]
pub struct ApiListArgs {
    /// Limit to one service (gmail, calendar, drive, people, chat, forms,
    /// tasks, docs, sheets, slides, script, analyticsadmin, analyticsdata,
    /// searchconsole)
    #[arg(long)]
    pub service: Option<String>,

    /// Case-insensitive substring filter over method ids and descriptions
    #[arg(long)]
    pub filter: Option<String>,

    /// Group output by service instead of one flat list
    #[arg(long)]
    pub grouped: bool,

    /// Output format
    #[arg(short, long, value_enum, default_value = "json")]
    pub format: OutputFormat,
}

#[derive(Args, Debug)]
pub struct ApiDescribeArgs {
    /// Method id, e.g. gmail.users.messages.list
    pub method: String,

    /// Output format
    #[arg(short, long, value_enum, default_value = "json")]
    pub format: OutputFormat,
}

#[derive(Args, Debug)]
pub struct ApiCallArgs {
    /// Method id, e.g. gmail.users.messages.list
    pub method: String,

    /// Parameters as a JSON object. Values for path placeholders are
    /// substituted into the URL; the rest become query parameters, or the
    /// request body for POST/PATCH/PUT.
    #[arg(long, value_name = "JSON")]
    pub params: Option<String>,

    /// A single parameter as key=value. Repeatable. Use for values that are
    /// awkward to quote in JSON.
    #[arg(long = "param", value_name = "KEY=VALUE")]
    pub param: Vec<String>,

    /// Read the request body from a file ("-" for stdin) instead of
    /// building one from --params. Sends the bytes verbatim.
    #[arg(long, value_name = "PATH")]
    pub body_file: Option<String>,

    /// Override the HTTP method from the Discovery document
    #[arg(long, value_name = "VERB")]
    pub method_override: Option<String>,

    /// Extra fields to merge into the query string, for endpoints whose
    /// parameters Discovery does not describe (alt=json, fields, key)
    #[arg(long = "query", value_name = "KEY=VALUE")]
    pub query: Vec<String>,

    /// Print the request that would be sent without sending it
    #[arg(long)]
    pub dry_run: bool,

    // NOTE: the safety flags (--readonly, --deny-service, --deny-verb) are
    // NOT redeclared here: they are global args on the root command
    // (cli.rs), and a second declaration with the same IDs would panic
    // clap's arg-matching. Global args propagate into this subcommand's
    // matches, so from_arg_matches still fills them.
    /// Output format
    #[arg(short, long, value_enum, default_value = "json")]
    pub format: OutputFormat,
}

pub async fn handle_api_cmd(
    auth: Option<&GoogleAuth>,
    cmd: ApiCommands,
    profile: &SafetyProfile,
) -> Result<()> {
    match cmd {
        // Introspection over the embedded index: no credential involved.
        ApiCommands::List(args) => handle_list(args)?,
        ApiCommands::Describe(args) => handle_describe(args)?,
        ApiCommands::Call(args) => {
            // The credential check lives in the call path (call_method),
            // not here: --dry-run is a plan-only operation that must work
            // with no OAuth client at all, while a real send reports the
            // actionable NO_CLIENT_HELP. Pass the Option straight through.
            handle_call(auth, args, profile).await?
        }
        // The refresh needs no credential: Discovery documents are public.
        ApiCommands::Refresh(args) => handle_refresh(args).await?,
    }
    Ok(())
}

async fn handle_refresh(args: ApiRefreshArgs) -> Result<()> {
    let reports = crate::discovery::refresh(args.service.as_deref())
        .await
        .map_err(anyhow::Error::msg)?;

    let refreshed = reports.iter().filter(|r| r.wrote_cache).count();
    let skipped = reports.iter().filter(|r| r.skipped_older).count();
    // stdout stays machine-readable; the summary goes to stderr.
    eprintln!("{refreshed} refreshed, {skipped} already current");
    print_output(
        &serde_json::json!({
            "refreshed": refreshed,
            "alreadyCurrent": skipped,
            "services": reports.iter().map(|r| serde_json::json!({
                "service": r.service,
                "from": r.from,
                "to": r.to,
                "methods": r.methods,
                "wroteCache": r.wrote_cache,
                "skippedOlder": r.skipped_older,
            })).collect::<Vec<_>>(),
            "nextStep": "restart grr (each invocation is a fresh process) to use the refreshed index",
        }),
        args.format,
    )?;
    Ok(())
}

fn matches_filter(method: &Method, needle: &str) -> bool {
    let needle = needle.to_ascii_lowercase();
    method.id.to_ascii_lowercase().contains(&needle)
        || method.description.to_ascii_lowercase().contains(&needle)
}

fn handle_list(args: ApiListArgs) -> Result<()> {
    let all = discovery::services();
    let selected: Vec<(&&str, &Service)> = match &args.service {
        Some(name) => {
            let service = all.get_key_value(name.as_str()).ok_or_else(|| {
                let known: Vec<&str> = all.keys().copied().collect();
                anyhow::anyhow!("unknown service `{name}`; known: {}", known.join(", "))
            })?;
            vec![service]
        }
        None => all.iter().collect(),
    };

    let filtered: Vec<(&&str, &Service, Vec<&Method>)> = selected
        .into_iter()
        .map(|(name, service)| {
            let methods: Vec<&Method> = match &args.filter {
                Some(needle) => service
                    .methods
                    .iter()
                    .filter(|m| matches_filter(m, needle))
                    .collect(),
                None => service.methods.iter().collect(),
            };
            (name, service, methods)
        })
        .filter(|(_, _, methods)| !methods.is_empty())
        .collect();

    if args.grouped {
        let payload: Vec<Value> = filtered
            .iter()
            .map(|(_, service, methods)| {
                json!({
                    "service": service.name,
                    "version": service.version,
                    "revision": service.revision,
                    "count": methods.len(),
                    "methods": methods.iter().map(|m| json!({
                        "id": format!("{}.{}", service.name, m.id),
                        "http": m.http_method,
                    })).collect::<Vec<_>>(),
                })
            })
            .collect();
        print_output(&Value::Array(payload), args.format)?;
        return Ok(());
    }

    let total: usize = filtered.iter().map(|(_, _, m)| m.len()).sum();
    let payload: Vec<Value> = filtered
        .iter()
        .flat_map(|(_, service, methods)| {
            methods.iter().map(move |m| {
                json!({
                    "id": format!("{}.{}", service.name, m.id),
                    "http": m.http_method,
                    "summary": first_sentence(&m.description),
                })
            })
        })
        .collect();

    // stderr keeps stdout pure JSON so `grr api list | jq` works.
    eprintln!("{total} methods");
    print_output(&Value::Array(payload), args.format)?;
    Ok(())
}

fn first_sentence(text: &str) -> String {
    match text.find(". ") {
        Some(idx) => text[..idx + 1].to_owned(),
        None => text.chars().take(120).collect(),
    }
}

fn handle_describe(args: ApiDescribeArgs) -> Result<()> {
    let (service, method) = discovery::resolve(&args.method).map_err(anyhow::Error::msg)?;
    print_output(
        &json!({
            "id": format!("{}.{}", service.name, method.id),
            "service": service.name,
            "apiVersion": service.version,
            "discoveryRevision": service.revision,
            "httpMethod": method.http_method,
            "path": method.path,
            // The raw template, not a rendered URL: placeholders are the
            // point, and the caller can see which values are required.
            "urlTemplate": format!(
                "{}{}{}",
                service.root_url.as_deref().unwrap_or_default(),
                service.base(),
                method.path
            ),
            "description": method.description,
            "scopes": method.scopes,
            "leastPrivilegeScope": method.least_privilege_scope(),
            "parameters": method.parameters.iter().map(|p| json!({
                "name": p.name,
                "type": p.kind,
                "required": p.required,
                "repeated": p.repeated,
                "description": p.description,
                "enum": p.enum_values,
            })).collect::<Vec<_>>(),
            "hint": format!(
                "grr api call {}.{} --params '{{\"{}\": \"...\"}}'",
                service.name, method.id,
                method.parameters.first().map(|p| p.name.as_str()).unwrap_or("userId")
            ),
        }),
        args.format,
    )?;
    Ok(())
}

async fn handle_call(
    auth: Option<&GoogleAuth>,
    args: ApiCallArgs,
    profile: &SafetyProfile,
) -> Result<()> {
    let (service, method) = discovery::resolve(&args.method).map_err(|message| {
        anyhow::anyhow!(
            "{message}\n\nRun `grr api list {}` to see what is available.",
            service_hint(&args.method)
        )
    })?;

    // The safety gate runs before anything is built or sent — the same
    // gate the `grr mcp` server honors (src/commands/safety.rs). The
    // profile comes from the global --readonly/--deny-service/--deny-verb
    // flags, parsed once in cli.rs.
    if let Err(message) = profile.check(&service.name, method) {
        bail!("{message}");
    }

    let params = parse_params(args.params.as_deref(), &args.param)?;
    let payload = call_method(
        auth,
        service,
        method,
        params,
        CallOptions {
            body_file: args.body_file,
            verb_override: args.method_override,
            query_extras: args.query,
            dry_run: args.dry_run,
        },
    )
    .await?;
    print_output(&payload, args.format)?;
    Ok(())
}

/// The caller-controlled request shaping beyond the parameter map. All
/// optional; `grr api call` fills everything, the generated tree leaves
/// `verb_override` at `None`, `auth status` leaves almost all of it.
#[derive(Debug, Default)]
pub(crate) struct CallOptions {
    /// Read the request body from this file ("-" = stdin) instead of
    /// synthesising one from the parameters.
    pub body_file: Option<String>,
    /// Override the HTTP method from the Discovery document
    /// (`grr api call --method-override`).
    pub verb_override: Option<String>,
    /// Extra KEY=VALUE query pairs for undocumented parameters.
    pub query_extras: Vec<String>,
    /// Print the request that would be sent without sending it.
    pub dry_run: bool,
}

/// Everything needed to issue (or dry-run) one Discovery method call.
/// The URL is fully built; the body is a parsed JSON value (or the raw
/// file/stdin bytes wrapped as a JSON string when they were not JSON).
#[derive(Debug)]
pub(crate) struct RequestPlan {
    pub verb: String,
    pub url: String,
    pub body: Option<Value>,
}

/// Validate parameters against the method and build the request. Pure:
/// no network, no credentials — which is what keeps the dry-run output
/// and the parity tests honest.
///
/// `query_extras` are appended after the Discovery-derived query pairs,
/// for endpoints whose parameters Discovery does not describe
/// (`alt=json`, `fields`, `key`).
pub(crate) fn plan_request(
    service: &Service,
    method: &Method,
    params: &serde_json::Map<String, Value>,
    body_raw: Option<&str>,
    verb_override: Option<&str>,
    query_extras: &[String],
) -> Result<RequestPlan> {
    // Warn loudly rather than letting Google return a confusing 400.
    for required in &method.required {
        if !params.contains_key(required) {
            let known: Vec<String> = method
                .parameters
                .iter()
                .filter(|p| p.required)
                .map(|p| format!("{} ({})", p.name, p.kind))
                .collect();
            bail!(
                "missing required parameter `{required}` for {}.{}\nRequired: {}",
                service.name,
                method.id,
                if known.is_empty() {
                    "none".to_owned()
                } else {
                    known.join(", ")
                }
            );
        }
    }

    let verb = verb_override
        .unwrap_or(&method.http_method)
        .to_ascii_uppercase();
    let path = discovery::build_path(service, method, params).map_err(anyhow::Error::msg)?;
    let mut query = discovery::build_query(method, params);
    for extra in query_extras {
        let Some((k, v)) = extra.split_once('=') else {
            bail!("--query expects KEY=VALUE, got `{extra}`");
        };
        if !query.is_empty() {
            query.push('&');
        }
        query.push_str(&urlencoding::encode(k));
        query.push('=');
        query.push_str(&urlencoding::encode(v));
    }
    let url = format!(
        "{}{}{}",
        service.root_url.as_deref().unwrap_or_default(),
        path,
        query
    );

    // With an already-read body, the caller's bytes win; otherwise synthesise
    // a body from the non-path, non-query parameters for verbs that take one.
    // No I/O happens here: the caller reads the source asynchronously (see
    // read_body_source), which keeps this planner pure and testable.
    let body: Option<Value> = match body_raw {
        Some(raw) => {
            Some(serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.to_owned())))
        }
        None => {
            let placeholders = method.path_placeholders();
            let is_write = matches!(verb.as_str(), "POST" | "PATCH" | "PUT");
            if !is_write {
                None
            } else {
                let mut rest = serde_json::Map::new();
                for (key, value) in params {
                    if placeholders.contains(&key.as_str()) {
                        continue;
                    }
                    if let Some(param) = method.parameter(key)
                        && param.location.as_deref() == Some("path")
                    {
                        continue;
                    }
                    rest.insert(key.clone(), value.clone());
                }
                (!rest.is_empty()).then_some(Value::Object(rest))
            }
        }
    };

    Ok(RequestPlan { verb, url, body })
}

/// The `--dry-run` payload for a planned request. Shared by `grr api call`
/// and the generated tree so both print byte-identical output.
pub(crate) fn dry_run_payload(method: &Method, plan: &RequestPlan) -> Value {
    json!({
        "method": plan.verb,
        "url": plan.url,
        "body": plan.body,
        "scopesRequested": method.scopes,
        "leastPrivilegeScope": method.least_privilege_scope(),
        "dryRun": true,
    })
}

/// Read a `--body-file` source into memory; `-` means stdin.
///
/// Async on purpose: this runs on the shared call path (`grr api call`, the
/// generated tree, `grr ask --run`, every MCP tools/call). A blocking read
/// would stall an executor worker, and the MCP server is a strictly
/// sequential stdio loop — a slow pipe on `--body-file -` would stall the
/// whole server. `plan_request` stays pure; this is the one I/O step before
/// it.
async fn read_body_source(source: &str) -> Result<String> {
    if source == "-" {
        let mut buf = String::new();
        tokio::io::AsyncReadExt::read_to_string(&mut tokio::io::stdin(), &mut buf)
            .await
            .with_context(|| "reading body from stdin")?;
        Ok(buf)
    } else {
        tokio::fs::read_to_string(source)
            .await
            .with_context(|| format!("reading body from {source}"))
    }
}

/// One request engine per service base URL, for the process lifetime.
///
/// [`HttpCore::connect`] probes the transport with an authenticated round
/// trip, so the probe is paid once per host per process rather than once per
/// call: `grr ask --run` and the `grr mcp` server issue many calls in one
/// process. `--dry-run` returns before this is ever touched, so planning
/// stays network-free. The cache is a const-constructible
/// `Mutex<BTreeMap>`, and a process carries one credential handle (the
/// `--account` rebind happens before any call), so keying on the base URL
/// alone cannot mix accounts. The index covers 14 services, so a handful of
/// origins is the whole population.
static CORES: Mutex<BTreeMap<String, HttpCore>> = Mutex::new(BTreeMap::new());

/// Probe path for the data plane: the service root. Any HTTP response — even
/// a 404 — proves the transport negotiated, and no cheaper path is shared by
/// every API in the index.
const PROBE_PATH: &str = "";

/// The engine for one service origin, probed on first use, reused after.
///
/// Two concurrent misses probe twice and the last one wins: both probes are
/// one extra GET to the same host, which beats serialising every call of a
/// burst behind this lock. A failed connect evicts any cached engine for
/// that origin first, so a transport change (network switch, QUIC blocked
/// mid-session) rebuilds instead of pinning the dead engine forever.
async fn engine_for(auth: &GoogleAuth, base: &url::Url) -> Result<HttpCore> {
    let key = base.as_str().to_owned();
    if let Some(engine) = cores().get(&key) {
        return Ok(engine.clone());
    }
    match HttpCore::connect(auth.clone(), base, PROBE_PATH).await {
        Ok(engine) => {
            cores().insert(key, engine.clone());
            Ok(engine)
        }
        Err(error) => {
            cores().remove(&key);
            Err(error.into())
        }
    }
}

/// The engine cache. Poisoning is ignored on purpose: an engine that
/// panicked mid-request must not wedge every later call in the process.
fn cores() -> MutexGuard<'static, BTreeMap<String, HttpCore>> {
    CORES
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// THE shared call path: `grr api call`, the generated service tree and
/// `grr auth status` all issue Discovery methods through this function.
///
/// Returns the payload for the caller to print with its chosen format: a
/// dry-run returns its plan payload, a live call the parsed response body.
pub(crate) async fn call_method(
    auth: Option<&GoogleAuth>,
    service: &Service,
    method: &Method,
    params: serde_json::Map<String, Value>,
    options: CallOptions,
) -> Result<Value> {
    let body_raw = match options.body_file.as_deref() {
        Some(source) => Some(read_body_source(source).await?),
        None => None,
    };
    let plan = plan_request(
        service,
        method,
        &params,
        body_raw.as_deref(),
        options.verb_override.as_deref(),
        &options.query_extras,
    )?;

    if options.dry_run {
        // The plan is the whole answer: no credential is consulted, so a
        // fresh CI runner (or a first-time user exploring with --dry-run)
        // sees the exact request without any OAuth client configured.
        return Ok(dry_run_payload(method, &plan));
    }

    // Sending is the first moment a credential exists at all.
    let auth = auth.ok_or_else(|| anyhow::anyhow!("{}", crate::core::config::NO_CLIENT_HELP))?;

    let parsed_url = url::Url::parse(&plan.url).with_context(|| {
        format!(
            "`{}` is not a valid URL (Discovery path + parameters)",
            plan.url
        )
    })?;

    // The data plane rides `HttpCore`, the engine `grr transport` reports on:
    // bearer auth, the HTTP/3 transport (HTTP/2 prior knowledge on the
    // fallback path), the in-flight valve and the retry policy — 429 with
    // `Retry-After`, 401 with the `grr auth login` hint. The engine is probed
    // once per origin and cached for the rest of the process.
    let engine = engine_for(auth, &parsed_url.join("/")?).await?;

    let mut request = engine.http_client().request(
        reqwest::Method::from_bytes(plan.verb.as_bytes()).unwrap_or(reqwest::Method::GET),
        parsed_url,
    );
    if let Some(payload) = &plan.body {
        request = request.json(payload);
    }
    let response = engine.execute(request).await?;

    let status = response.status();
    let text = response.text().await.unwrap_or_default();
    let parsed: Value = serde_json::from_str(&text).unwrap_or_else(|_| Value::String(text.clone()));

    if !status.is_success() {
        bail!(
            "{}",
            api_failure_message(&plan, status.as_u16(), &parsed, &text, method)
        );
    }

    Ok(parsed)
}

/// The error message for a non-success response on the shared call path.
///
/// 403 with insufficient_scope is the common case when a method needs a
/// scope this build did not request, so it names the scope; Google's own
/// message tells the three real causes apart ("Request had insufficient
/// authentication scopes" vs "… API has not been used in project … or it is
/// disabled"), so it is quoted rather than replaced. Everything else keeps
/// the long-standing `VERB url -> HTTP <status>` shape with Google's body
/// pretty-printed — scripts grep for it.
pub(crate) fn api_failure_message(
    plan: &RequestPlan,
    status: u16,
    parsed: &Value,
    text: &str,
    method: &Method,
) -> String {
    if status == 403
        && let Some(scope) = method.least_privilege_scope()
    {
        let detail = parsed["error"]["message"].as_str().unwrap_or("");
        let google_said = if detail.is_empty() {
            String::new()
        } else {
            format!("\nGoogle said: {detail}")
        };
        return format!(
            "{} {} -> HTTP 403: this method needs the `{scope}` scope.\n\
             This build requests every scope the embedded index names, so the grant is what \
             to check: a token that predates the current set (re-run `grr auth login`), a \
             scope the project's consent screen never declared (Google Auth Platform → Data \
             access — undeclared scopes are dropped silently at consent), or an API that is \
             disabled on the Cloud project.{google_said}",
            plan.verb, plan.url
        );
    }
    format!(
        "{} {} -> HTTP {}\n{}",
        plan.verb,
        plan.url,
        status,
        serde_json::to_string_pretty(parsed).unwrap_or_else(|_| text.to_owned())
    )
}

fn service_hint(method_id: &str) -> &str {
    method_id.split('.').next().unwrap_or("gmail")
}

/// Merge `--params` JSON with KEY=VALUE pairs (and, in the generated tree,
/// with the typed flags). Shared with the generated tree's dispatch: the
/// later, more specific source always wins, and values that parse as JSON
/// keep their real type so `--param pageSize=10` is a number.
pub(crate) fn parse_params(
    json_blob: Option<&str>,
    pairs: &[String],
) -> Result<serde_json::Map<String, Value>> {
    let mut map = serde_json::Map::new();

    if let Some(blob) = json_blob {
        let parsed: Value = serde_json::from_str(blob)
            .with_context(|| "--params must be a JSON object, e.g. '{\"userId\":\"me\"}'")?;
        let Value::Object(object) = parsed else {
            bail!("--params must be a JSON object, got {}", type_name(&parsed));
        };
        map.extend(object);
    }

    for pair in pairs {
        let Some((key, value)) = pair.split_once('=') else {
            bail!("--param expects KEY=VALUE, got `{pair}`");
        };
        // Bare `true`/`123`/`[...]` become real JSON values, so `--param
        // pageSize=10` is a number and not the string "10" — otherwise
        // every numeric parameter would need quoting.
        let coerced = serde_json::from_str::<Value>(value)
            .unwrap_or_else(|_| Value::String(value.to_owned()));
        map.insert(key.to_owned(), coerced);
    }

    Ok(map)
}

fn type_name(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "a string",
        Value::Array(_) => "an array",
        Value::Object(_) => "an object",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn json_params_are_merged() {
        let params = parse_params(Some(r#"{"userId":"me","q":"is:unread"}"#), &[]).unwrap();
        assert_eq!(params.get("userId").unwrap(), "me");
        assert_eq!(params.get("q").unwrap(), "is:unread");
    }

    #[test]
    fn param_flags_win_over_json_params() {
        // The later, more specific source should win so a caller can
        // override one field of a large --params blob.
        let params =
            parse_params(Some(r#"{"userId":"me"}"#), &["userId=someone-else".into()]).unwrap();
        assert_eq!(params.get("userId").unwrap(), "someone-else");
    }

    #[test]
    fn param_values_are_coerced_to_json_types() {
        let params =
            parse_params(None, &["a=10".into(), "b=true".into(), "c=text".into()]).unwrap();
        assert_eq!(params.get("a").unwrap(), 10);
        assert_eq!(params.get("b").unwrap(), true);
        assert_eq!(params.get("c").unwrap(), "text");
    }

    #[test]
    fn values_containing_equals_are_preserved() {
        // Drive queries and Gmail searches contain '='; only split once.
        let params = parse_params(None, &["q=name=a.pdf".into()]).unwrap();
        assert_eq!(params.get("q").unwrap(), "name=a.pdf");
    }

    #[test]
    fn malformed_input_is_rejected_with_guidance() {
        assert!(parse_params(Some("not json"), &[]).is_err());
        assert!(parse_params(Some("[1,2]"), &[]).is_err());
        assert!(parse_params(None, &["novalue".into()]).is_err());
    }

    fn plan(id: &str, params: &[(&str, Value)]) -> (super::RequestPlan, &'static Method) {
        let (service, method) = crate::discovery::resolve(id).unwrap();
        let map: serde_json::Map<String, Value> = params
            .iter()
            .map(|(k, v)| ((*k).to_owned(), v.clone()))
            .collect();
        (
            super::plan_request(service, method, &map, None, None, &[]).unwrap(),
            method,
        )
    }

    #[test]
    fn plan_builds_the_url_from_discovery() {
        let (plan, method) = plan(
            "gmail.users.messages.list",
            &[("userId", json!("me")), ("q", json!("is:unread"))],
        );
        assert_eq!(plan.verb, "GET");
        assert_eq!(
            plan.url,
            "https://gmail.googleapis.com/gmail/v1/users/me/messages?q=is%3Aunread"
        );
        assert_eq!(plan.body, None);
        assert_eq!(method.id, "users.messages.list");
    }

    #[test]
    fn plan_rejects_a_missing_required_parameter_by_name() {
        let (service, method) = crate::discovery::resolve("gmail.users.messages.list").unwrap();
        let err = super::plan_request(service, method, &serde_json::Map::new(), None, None, &[])
            .unwrap_err()
            .to_string();
        assert!(err.contains("missing required parameter `userId`"), "{err}");
    }

    #[test]
    fn plan_appends_query_extras_after_discovery_pairs() {
        let (service, method) = crate::discovery::resolve("gmail.users.messages.list").unwrap();
        let mut params = serde_json::Map::new();
        params.insert("userId".into(), json!("me"));
        params.insert("q".into(), json!("is:unread"));
        let plan = super::plan_request(
            service,
            method,
            &params,
            None,
            None,
            &["alt=json".to_owned()],
        )
        .unwrap();
        assert!(plan.url.ends_with("q=is%3Aunread&alt=json"), "{}", plan.url);
    }

    #[test]
    fn plan_rejects_malformed_query_extras() {
        let (service, method) = crate::discovery::resolve("gmail.users.messages.list").unwrap();
        let mut params = serde_json::Map::new();
        params.insert("userId".into(), json!("me"));
        let err = super::plan_request(
            service,
            method,
            &params,
            None,
            None,
            &["no-equals-sign".to_owned()],
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("KEY=VALUE"), "{err}");
    }

    #[test]
    fn plan_uppercases_a_verb_override() {
        let (service, method) = crate::discovery::resolve("gmail.users.messages.list").unwrap();
        let mut params = serde_json::Map::new();
        params.insert("userId".into(), json!("me"));
        let plan = super::plan_request(service, method, &params, None, Some("post"), &[]).unwrap();
        assert_eq!(plan.verb, "POST");
    }

    #[test]
    fn plan_synthesizes_a_body_for_write_verbs_only() {
        // drive.files.create is a POST: leftover (non-path) params become
        // the request body, exactly as `grr api call` always did.
        let (service, method) = crate::discovery::resolve("drive.files.create").unwrap();
        let mut params = serde_json::Map::new();
        params.insert("name".into(), json!("quarterly.pdf"));
        let plan = super::plan_request(service, method, &params, None, None, &[]).unwrap();
        assert_eq!(plan.body, Some(json!({"name": "quarterly.pdf"})));

        // A GET never gets a body, even with leftover params — they ride
        // in the query string instead.
        let (service, method) = crate::discovery::resolve("gmail.users.messages.list").unwrap();
        let mut params = serde_json::Map::new();
        params.insert("userId".into(), json!("me"));
        params.insert("q".into(), json!("is:unread"));
        let plan = super::plan_request(service, method, &params, None, None, &[]).unwrap();
        assert_eq!(plan.body, None);
        assert!(plan.url.contains("q=is%3Aunread"));
    }

    #[test]
    fn plan_parses_json_bodies_and_wraps_the_rest() {
        // The planner receives already-read bytes (read_body_source owns the
        // I/O): JSON parses, anything else is wrapped as a string, never
        // rejected.
        let (service, method) = crate::discovery::resolve("drive.files.create").unwrap();
        let plan = super::plan_request(
            service,
            method,
            &serde_json::Map::new(),
            Some(r#"{"name":"uploaded.pdf"}"#),
            None,
            &[],
        )
        .unwrap();
        assert_eq!(plan.body, Some(json!({"name": "uploaded.pdf"})));

        let plan = super::plan_request(
            service,
            method,
            &serde_json::Map::new(),
            Some("not json at all"),
            None,
            &[],
        )
        .unwrap();
        assert_eq!(plan.body, Some(json!("not json at all")));
    }

    #[tokio::test]
    async fn read_body_source_reads_a_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("body.json");
        tokio::fs::write(&path, r#"{"a":1}"#).await.unwrap();
        let raw = super::read_body_source(path.to_str().unwrap())
            .await
            .unwrap();
        assert_eq!(raw, r#"{"a":1}"#);
    }

    #[test]
    fn dry_run_payload_is_a_pure_function_of_the_plan() {
        let (plan, method) = plan("gmail.users.messages.list", &[("userId", json!("me"))]);
        let payload = super::dry_run_payload(method, &plan);
        assert_eq!(payload["method"], "GET");
        assert_eq!(
            payload["url"],
            "https://gmail.googleapis.com/gmail/v1/users/me/messages"
        );
        assert_eq!(payload["dryRun"], true);
        assert!(
            payload["leastPrivilegeScope"]
                .as_str()
                .unwrap()
                .ends_with("gmail.readonly")
        );
    }

    fn a_get_plan() -> super::RequestPlan {
        super::RequestPlan {
            verb: "GET".into(),
            url: "https://gmail.googleapis.com/gmail/v1/users/me/messages".into(),
            body: None,
        }
    }

    #[test]
    fn a_403_names_the_missing_scope_and_keeps_googles_message() {
        // The scope guidance is the whole point of the 403 branch: without
        // it a user sees only "HTTP 403" and starts re-running commands
        // instead of re-running `grr auth login`.
        let (_, method) = crate::discovery::resolve("gmail.users.messages.list").unwrap();
        let parsed = json!({
            "error": {"code": 403, "message": "Request had insufficient authentication scopes."}
        });
        let message = super::api_failure_message(&a_get_plan(), 403, &parsed, "", method);
        assert!(message.contains("HTTP 403"), "{message}");
        assert!(
            message.contains("gmail.readonly"),
            "the method's least-privilege scope must be named: {message}"
        );
        assert!(
            message.contains("re-run `grr auth login`"),
            "the remediation must be named: {message}"
        );
        assert!(
            message.contains("insufficient authentication scopes"),
            "Google's own message must be quoted, not replaced: {message}"
        );
    }

    #[test]
    fn other_statuses_keep_the_verb_url_body_shape() {
        // The long-standing `VERB url -> HTTP <status>` shape with the
        // pretty-printed body is an output contract: scripts grep for it.
        // It also covers the 403-with-no-scope case (API disabled): the
        // generic body quote is the fallback, never a scope name.
        let (_, method) = crate::discovery::resolve("gmail.users.messages.list").unwrap();
        let parsed = json!({"error": {"code": 404, "message": "Requested entity was not found."}});
        let message = super::api_failure_message(&a_get_plan(), 404, &parsed, "", method);
        assert!(
            message.contains(
                "GET https://gmail.googleapis.com/gmail/v1/users/me/messages -> HTTP 404"
            ),
            "{message}"
        );
        assert!(
            message.contains("Requested entity was not found."),
            "{message}"
        );
    }

    async fn test_auth() -> GoogleAuth {
        let config = crate::core::config::OAuthConfig {
            client_id: "test-id.apps.googleusercontent.com".into(),
            client_secret: None,
            ..Default::default()
        };
        let storage = crate::core::auth::TokenStorage {
            access_token: "test-token".into(),
            refresh_token: None,
            expires_at: u64::MAX,
            token_type: "Bearer".into(),
            scope: String::new(),
        };
        GoogleAuth::with_token(config, storage).await.unwrap()
    }

    #[tokio::test]
    async fn handle_call_refuses_a_write_under_readonly() {
        // The gate fires before anything is built or sent, so the dummy
        // auth handle is never used.
        let auth = test_auth().await;
        let args = ApiCallArgs {
            method: "gmail.users.messages.send".into(),
            params: None,
            param: vec![],
            body_file: None,
            method_override: None,
            query: vec![],
            dry_run: true,
            format: OutputFormat::Json,
        };
        let err = handle_call(Some(&auth), args, &SafetyProfile::new(true, [], []))
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("POST"), "{err}");
        assert!(err.contains("--readonly"), "{err}");
        assert!(err.contains("Rerun without --readonly"), "{err}");
    }

    #[tokio::test]
    async fn handle_call_refuses_a_denied_service_and_a_denied_verb() {
        let auth = test_auth().await;
        let args = ApiCallArgs {
            method: "gmail.users.messages.list".into(),
            params: None,
            param: vec![],
            body_file: None,
            method_override: None,
            query: vec![],
            dry_run: true,
            format: OutputFormat::Json,
        };
        let profile = SafetyProfile::new(false, vec!["gmail".to_owned()], vec![]);
        let err = handle_call(Some(&auth), args, &profile)
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("--deny-service gmail"), "{err}");

        let args = ApiCallArgs {
            method: "gmail.users.messages.list".into(),
            params: None,
            param: vec![],
            body_file: None,
            method_override: None,
            query: vec![],
            dry_run: true,
            format: OutputFormat::Json,
        };
        let profile = SafetyProfile::new(false, vec![], vec!["get".to_owned()]);
        let err = handle_call(Some(&auth), args, &profile)
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("--deny-verb GET"), "{err}");
    }

    #[tokio::test]
    async fn handle_call_runs_a_read_under_readonly() {
        let auth = test_auth().await;
        let args = ApiCallArgs {
            method: "gmail.users.messages.list".into(),
            params: None,
            param: vec!["userId=me".into()],
            body_file: None,
            method_override: None,
            query: vec![],
            dry_run: true,
            format: OutputFormat::Json,
        };
        // A GET is not a write: the dry-run returns instead of refusing.
        assert!(
            handle_call(Some(&auth), args, &SafetyProfile::new(true, [], []))
                .await
                .is_ok()
        );
    }
}