omni-dev 0.41.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
//! Gmail REST API client.
//!
//! Thin `reqwest` wrapper that attaches a Bearer access token (refreshed by
//! an owned [`GmailSession`]) to every request, retries HTTP 429 via the
//! shared [`retry_429`](crate::utils::http::retry_429) driver, and retries
//! exactly once on HTTP 401 by forcing a session refresh. Modelled on
//! [`crate::datadog::client::DatadogClient`]; the difference is Bearer-token
//! auth with in-process refresh instead of two static API keys.

use anyhow::{Context, Result};
use reqwest::{Client, Response};
use url::Url;

use crate::gmail::auth::{GmailCredentials, GmailSession};
use crate::gmail::error::GmailError;
use crate::request_log;
use crate::utils::env::{EnvSource, SystemEnv};
use crate::utils::http::{connect_timeout, read_timeout, retry_if};

/// HTTP client for the Gmail v1 REST API.
pub struct GmailClient {
    client: Client,
    base_url: String,
    session: GmailSession,
}

impl std::fmt::Debug for GmailClient {
    // Hand-written, not derived: omits `session` entirely rather than
    // relying on every nested `Secret` staying wrapped — the safest
    // possible redaction is "not mentioned at all."
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GmailClient")
            .field("base_url", &self.base_url)
            .finish_non_exhaustive()
    }
}

impl GmailClient {
    /// The real Gmail API host. Unlike Datadog, there is no per-tenant
    /// site/region this is *derived* from — [`Self::DEFAULT_BASE_URL`] is
    /// the one real host, overridable wholesale via `GMAIL_API_URL`
    /// (`crate::gmail::auth::GMAIL_API_URL`; see
    /// [`Self::from_credentials_with`]) rather than site-substituted like
    /// Datadog's `DATADOG_API_URL`. [`Self::new`]'s `base_url` parameter is
    /// the lower-level seam both the override and tests go through.
    const DEFAULT_BASE_URL: &'static str = "https://gmail.googleapis.com";

    /// Builds a client against `base_url` with already-loaded credentials.
    ///
    /// For production use, construct via [`Self::from_credentials`]; tests
    /// pass a wiremock URL directly.
    pub fn new(base_url: &str, credentials: &GmailCredentials) -> Result<Self> {
        let client = Client::builder()
            .connect_timeout(connect_timeout())
            .read_timeout(read_timeout())
            .build()
            .context("Failed to build HTTP client")?;
        let session = GmailSession::new(client.clone(), credentials);
        Ok(Self {
            client,
            base_url: base_url.trim_end_matches('/').to_string(),
            session,
        })
    }

    /// Creates a client from stored credentials against the real Gmail API
    /// host.
    ///
    /// Respects `GMAIL_API_URL` as an optional override: when set (and
    /// non-empty) in the process environment it replaces
    /// [`Self::DEFAULT_BASE_URL`] wholesale. Added per PR #1466 review —
    /// without it, exercising the CLI's output shapes required a real
    /// Google Cloud project, and there was no way to route through a forced
    /// egress proxy.
    pub fn from_credentials(credentials: &GmailCredentials) -> Result<Self> {
        Self::from_credentials_with(&SystemEnv, credentials)
    }

    /// [`from_credentials`](Self::from_credentials) over an injected
    /// [`EnvSource`], so tests can exercise the `GMAIL_API_URL` override via
    /// `MapEnv` without mutating the process environment.
    pub(crate) fn from_credentials_with(
        env: &impl EnvSource,
        credentials: &GmailCredentials,
    ) -> Result<Self> {
        let base_url = env
            .var(crate::gmail::auth::GMAIL_API_URL)
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| Self::DEFAULT_BASE_URL.to_string());
        Self::new(&base_url, credentials)
    }

    /// Returns the API base URL (without trailing slash).
    #[must_use]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Builds an absolute API URL by joining `path` onto `base_url`.
    ///
    /// Takes `base_url` (rather than `&self`) so the free `build_*_url`
    /// functions in the API façade modules — and their unit tests, which
    /// pass literal base URLs — can call it without an instance.
    pub(crate) fn api_url(base_url: &str, path: &str) -> Result<Url> {
        Url::parse(&format!("{base_url}{path}")).context("Invalid Gmail base URL")
    }

    /// Checks `response` for success and deserialises its JSON body into `T`.
    pub(crate) async fn parse_response<T: serde::de::DeserializeOwned>(
        &self,
        response: Response,
        context: &'static str,
    ) -> Result<T> {
        if !response.status().is_success() {
            return Err(Self::response_to_error(response).await.into());
        }
        response.json().await.context(context)
    }

    /// Sends an authenticated GET and deserialises the JSON body into `T`.
    pub(crate) async fn get_parsed<T: serde::de::DeserializeOwned>(
        &self,
        url: &str,
        context: &'static str,
    ) -> Result<T> {
        let response = self.get_json(url).await?;
        self.parse_response(response, context).await
    }

    /// Sends an authenticated GET request and returns the raw response.
    ///
    /// Retries exactly once on HTTP 401 by forcing a session refresh — see
    /// [`Self::send_authorized`] for why both a proactive and a reactive
    /// refresh path exist.
    pub async fn get_json(&self, url: &str) -> Result<Response> {
        self.send_authorized(url, "GET", |client, token| {
            client
                .get(url)
                .bearer_auth(token)
                .header("Accept", "application/json")
        })
        .await
    }

    /// Sends an authenticated POST request with a JSON body and returns the
    /// raw response.
    pub async fn post_json<T: serde::Serialize + Sync + ?Sized>(
        &self,
        url: &str,
        body: &T,
    ) -> Result<Response> {
        self.send_authorized(url, "POST", |client, token| {
            client
                .post(url)
                .bearer_auth(token)
                .header("Content-Type", "application/json")
                .json(body)
        })
        .await
    }

    /// Sends a request built by `build`, retrying exactly once on HTTP 401.
    ///
    /// [`GmailSession::access_token`] already refreshes proactively when the
    /// tracked expiry is near — this reactive path exists for what
    /// proactive tracking can't see: clock skew against Google's clock, or
    /// the token being invalidated server-side mid-run (revoked access). A
    /// second 401 after the retry is authoritative: either the refresh
    /// produced a token that was also rejected, or another caller's
    /// already-current token was reused and still rejected — either way the
    /// problem isn't staleness, so it surfaces as an ordinary
    /// `ApiRequestFailed` rather than retrying again.
    async fn send_authorized<F>(
        &self,
        url: &str,
        method: &'static str,
        build: F,
    ) -> Result<Response>
    where
        F: Fn(&Client, &str) -> reqwest::RequestBuilder + Send + Sync,
    {
        let token = self
            .session
            .access_token()
            .await
            .context("Failed to obtain a Gmail access token")?;
        let response = self
            .send_once(url, method, &build, token.expose_secret())
            .await?;
        if response.status().as_u16() != 401 {
            return Ok(response);
        }
        let refreshed = self
            .session
            .force_refresh(&token)
            .await
            .context("Failed to refresh the Gmail access token after a 401")?;
        self.send_once(url, method, &build, refreshed.expose_secret())
            .await
    }

    async fn send_once<F>(
        &self,
        url: &str,
        method: &'static str,
        build: &F,
        token: &str,
    ) -> Result<Response>
    where
        F: Fn(&Client, &str) -> reqwest::RequestBuilder + Send + Sync,
    {
        retry_if(
            || build(&self.client, token),
            |started, result| {
                request_log::record_http_result("gmail", method, url, started, result);
            },
            |status, body| status == 429 || is_gmail_quota_exceeded(status, body),
        )
        .await
        .with_context(|| format!("Failed to send {method} request to Gmail API"))
    }

    /// Consumes a non-success response into a [`GmailError`].
    ///
    /// Parses Gmail's `{"error":{"message":...,"errors":[{"reason":...}]}}`
    /// envelope into a human message when present (falls back to the raw
    /// body otherwise). Gmail signals quota exhaustion as **403**
    /// `rateLimitExceeded`/`userRateLimitExceeded`, not `429` — unlike plain
    /// 429s, that shape now also drives a retry (see [`is_gmail_quota_exceeded`]
    /// via [`retry_if`](crate::utils::http::retry_if)), so this only sees the
    /// error once retries are exhausted (or the reason didn't match).
    pub async fn response_to_error(response: Response) -> GmailError {
        let status = response.status().as_u16();
        let raw = response.text().await.unwrap_or_default();
        let value = serde_json::from_str::<serde_json::Value>(&raw).ok();
        let reason = value.as_ref().and_then(gmail_error_reason);
        let body = value
            .as_ref()
            .and_then(gmail_error_message)
            .map(|message| match &reason {
                Some(r) => format!("{message} (reason: {r})"),
                None => message,
            })
            .unwrap_or(raw);
        GmailError::ApiRequestFailed {
            status,
            body,
            reason,
        }
    }
}

/// Extracts the `error.errors[0].reason` field from Gmail's already-parsed
/// JSON error envelope, if present.
fn gmail_error_reason(value: &serde_json::Value) -> Option<String> {
    value
        .get("error")
        .and_then(|e| e.get("errors"))
        .and_then(|e| e.as_array())
        .and_then(|a| a.first())
        .and_then(|e| e.get("reason"))
        .and_then(|r| r.as_str())
        .map(str::to_string)
}

/// Extracts the `error.message` field from Gmail's already-parsed JSON
/// error envelope, if present.
fn gmail_error_message(value: &serde_json::Value) -> Option<String> {
    value
        .get("error")?
        .get("message")?
        .as_str()
        .map(str::to_string)
}

/// Whether a response is Gmail's quota-exhaustion signal — **403** with
/// `reason` of `rateLimitExceeded` or `userRateLimitExceeded` specifically,
/// not any 403 with a `reason` field: e.g. `insufficientPermissions` is also
/// a 403 and must never be retried (retrying a scope/permission error just
/// wastes the backoff window before failing anyway).
fn is_gmail_quota_exceeded(status: u16, body: &[u8]) -> bool {
    if status != 403 {
        return false;
    }
    let Ok(text) = std::str::from_utf8(body) else {
        return false;
    };
    let Ok(value) = serde_json::from_str::<serde_json::Value>(text) else {
        return false;
    };
    matches!(
        gmail_error_reason(&value).as_deref(),
        Some("rateLimitExceeded" | "userRateLimitExceeded")
    )
}

/// Test-only seam letting sibling API-façade test modules (which can't
/// reach `GmailClient`'s private fields directly, unlike this module's own
/// `tests` submodule) bootstrap a deterministic access token via wiremock.
#[cfg(test)]
pub(crate) mod test_support {
    use super::GmailClient;
    use crate::gmail::auth::{GmailCredentials, GmailSession};

    /// Replaces `client`'s session with one pointed at an explicit token
    /// endpoint.
    pub(crate) fn replace_session(
        client: &mut GmailClient,
        credentials: &GmailCredentials,
        token_endpoint: &str,
    ) {
        client.session = GmailSession::new_with_token_endpoint(
            client.client.clone(),
            credentials,
            token_endpoint,
        );
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::gmail::auth::GmailScope;
    use crate::utils::secret::Secret;

    fn test_credentials() -> GmailCredentials {
        GmailCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: GmailScope::ReadOnly,
        }
    }

    #[test]
    fn new_client_strips_trailing_slash() {
        let client =
            GmailClient::new("https://gmail.googleapis.com/", &test_credentials()).unwrap();
        assert_eq!(client.base_url(), "https://gmail.googleapis.com");
    }

    #[test]
    fn new_client_preserves_clean_url() {
        let client = GmailClient::new("https://gmail.googleapis.com", &test_credentials()).unwrap();
        assert_eq!(client.base_url(), "https://gmail.googleapis.com");
    }

    #[test]
    fn from_credentials_uses_gmail_api_host() {
        // Via a fresh MapEnv, not from_credentials()'s real SystemEnv — a
        // stray GMAIL_API_URL in the actual process environment must not
        // make this test flaky (mirrors the Datadog precedent,
        // from_credentials_builds_base_url_from_site).
        let env = crate::test_support::env::MapEnv::new();
        let client = GmailClient::from_credentials_with(&env, &test_credentials()).unwrap();
        assert_eq!(client.base_url(), "https://gmail.googleapis.com");
    }

    #[test]
    fn from_credentials_honours_api_url_override() {
        let env = crate::test_support::env::MapEnv::new().with(
            crate::gmail::auth::GMAIL_API_URL,
            "http://proxy.example:8080",
        );
        let client = GmailClient::from_credentials_with(&env, &test_credentials()).unwrap();
        assert_eq!(client.base_url(), "http://proxy.example:8080");
    }

    #[test]
    fn from_credentials_ignores_empty_api_url_override() {
        let env =
            crate::test_support::env::MapEnv::new().with(crate::gmail::auth::GMAIL_API_URL, "");
        let client = GmailClient::from_credentials_with(&env, &test_credentials()).unwrap();
        assert_eq!(client.base_url(), "https://gmail.googleapis.com");
    }

    #[test]
    fn client_debug_never_mentions_session_field() {
        let client = GmailClient::new("https://gmail.googleapis.com", &test_credentials()).unwrap();
        let debug = format!("{client:?}");
        assert!(!debug.contains("secret-1"));
        assert!(!debug.contains("refresh-1"));
        assert!(!debug.contains("session"));
        assert!(debug.contains("GmailClient"));
    }

    /// Mounts a bootstrap token-endpoint mock at the same base URL as the
    /// Gmail API mock — `GmailSession` doesn't distinguish the two hosts in
    /// these tests, so pointing the token endpoint at the wiremock server
    /// too keeps the setup to one server per test.
    async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> GmailClient {
        // `up_to_n_times(1)` + `with_priority(1)` so a test's own follow-up
        // POST /token mock (registered at `with_priority(2)`, matched only
        // once this one is exhausted) can simulate a second, distinct
        // refresh without either mock racing the other for every request.
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "bootstrap-token",
                    "expires_in": 3600,
                })),
            )
            .up_to_n_times(1)
            .with_priority(1)
            .mount(server)
            .await;

        let mut client = GmailClient::new(&server.uri(), &test_credentials()).unwrap();
        client.session = GmailSession::new_with_token_endpoint(
            client.client.clone(),
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        client
    }

    #[tokio::test]
    async fn get_json_sends_bearer_auth_header() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .and(wiremock::matchers::header(
                "Authorization",
                "Bearer bootstrap-token",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok": true})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        assert!(resp.status().is_success());
    }

    #[tokio::test]
    async fn post_json_sends_body_and_bearer_auth() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/test"))
            .and(wiremock::matchers::header(
                "Authorization",
                "Bearer bootstrap-token",
            ))
            .and(wiremock::matchers::body_json(serde_json::json!({"k": "v"})))
            .respond_with(wiremock::ResponseTemplate::new(200))
            .expect(1)
            .mount(&server)
            .await;

        let resp = client
            .post_json(
                &format!("{}/test", server.uri()),
                &serde_json::json!({"k": "v"}),
            )
            .await
            .unwrap();
        assert!(resp.status().is_success());
    }

    #[tokio::test]
    async fn get_json_retries_on_429() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(wiremock::ResponseTemplate::new(429).append_header("Retry-After", "0"))
            .up_to_n_times(1)
            .with_priority(1)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(wiremock::ResponseTemplate::new(200))
            .with_priority(2)
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 200);
    }

    #[tokio::test]
    async fn get_json_retries_403_rate_limit_exceeded_then_succeeds() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(
                wiremock::ResponseTemplate::new(403)
                    .append_header("Retry-After", "0")
                    .set_body_json(serde_json::json!({
                        "error": {"message": "Rate Limit Exceeded", "errors": [{"reason": "rateLimitExceeded"}]}
                    })),
            )
            .up_to_n_times(1)
            .with_priority(1)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(wiremock::ResponseTemplate::new(200))
            .with_priority(2)
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 200);
    }

    #[tokio::test]
    async fn get_json_does_not_retry_insufficient_permissions_403() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(
                wiremock::ResponseTemplate::new(403).set_body_json(serde_json::json!({
                    "error": {"message": "Insufficient Permission", "errors": [{"reason": "insufficientPermissions"}]}
                })),
            )
            .expect(1)
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 403);
    }

    #[tokio::test]
    async fn get_json_refreshes_and_retries_once_on_401() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        // The refresh endpoint issues a second, distinct token.
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "refreshed-token",
                    "expires_in": 3600,
                })),
            )
            .up_to_n_times(1)
            .with_priority(2)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .and(wiremock::matchers::header(
                "Authorization",
                "Bearer bootstrap-token",
            ))
            .respond_with(wiremock::ResponseTemplate::new(401))
            .expect(1)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .and(wiremock::matchers::header(
                "Authorization",
                "Bearer refreshed-token",
            ))
            .respond_with(wiremock::ResponseTemplate::new(200))
            .expect(1)
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 200);
    }

    #[tokio::test]
    async fn get_json_does_not_retry_a_second_time_on_persistent_401() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "still-rejected-token",
                    "expires_in": 3600,
                })),
            )
            .up_to_n_times(1)
            .with_priority(2)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(
                wiremock::ResponseTemplate::new(401).set_body_string("still unauthorized"),
            )
            .expect(2)
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 401);
    }

    #[tokio::test]
    async fn response_to_error_extracts_gmail_message_and_reason() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        // `userRateLimitExceeded` is now retryable (`is_gmail_quota_exceeded`),
        // so without a zero-delay `Retry-After` this test would wait through
        // the real exponential backoff before giving up.
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(
                wiremock::ResponseTemplate::new(403)
                    .append_header("Retry-After", "0")
                    .set_body_json(serde_json::json!({
                        "error": {
                            "message": "User Rate Limit Exceeded",
                            "errors": [{"reason": "userRateLimitExceeded"}],
                        }
                    })),
            )
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        let err = GmailClient::response_to_error(resp).await;
        let msg = err.to_string();
        assert!(msg.contains("User Rate Limit Exceeded"));
        assert!(msg.contains("userRateLimitExceeded"));
        assert_eq!(err.reason(), Some("userRateLimitExceeded"));
    }

    #[tokio::test]
    async fn response_to_error_omits_reason_suffix_when_absent() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(
                wiremock::ResponseTemplate::new(400).set_body_json(serde_json::json!({
                    "error": {
                        "message": "Invalid request",
                    }
                })),
            )
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        let err = GmailClient::response_to_error(resp).await;
        let msg = err.to_string();
        assert!(msg.contains("Invalid request"));
        assert!(!msg.contains("reason:"));
        assert_eq!(err.reason(), None);
    }

    #[tokio::test]
    async fn response_to_error_falls_back_to_raw_body_when_not_gmail_shaped() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("internal error"))
            .mount(&server)
            .await;

        let resp = client
            .get_json(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        let err = GmailClient::response_to_error(resp).await;
        assert!(err.to_string().contains("internal error"));
    }

    #[tokio::test]
    async fn get_json_propagates_network_errors() {
        let client = GmailClient::new("http://127.0.0.1:1", &test_credentials()).unwrap();
        let result = client.get_json("http://127.0.0.1:1/test").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn get_parsed_errors_on_malformed_json_response() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/test"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("not json"))
            .mount(&server)
            .await;

        let result: Result<serde_json::Value> = client
            .get_parsed(&format!("{}/test", server.uri()), "test context")
            .await;
        assert!(result.is_err());
    }
}