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
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
//! Drive REST API client.
//!
//! Thin `reqwest` wrapper that attaches a Bearer access token (refreshed by
//! an owned [`DriveSession`]) 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`] (and `crate::gmail::client::GmailClient`,
//! its closest sibling); 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::drive::auth::{DriveCredentials, DriveSession};
use crate::drive::error::DriveError;
use crate::request_log;
use crate::utils::env::{EnvSource, SystemEnv};
use crate::utils::http::{connect_timeout, read_timeout, retry_if};

/// HTTP client for the Drive v3 REST API.
pub struct DriveClient {
    client: Client,
    base_url: String,
    session: DriveSession,
}

impl std::fmt::Debug for DriveClient {
    // 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("DriveClient")
            .field("base_url", &self.base_url)
            .finish_non_exhaustive()
    }
}

impl DriveClient {
    /// The real Drive API host. Unlike Gmail, which lives on its own
    /// dedicated `gmail.googleapis.com` subdomain, Drive API v3 lives under
    /// the general `googleapis.com` host with a `/drive/v3/...` path prefix
    /// on each endpoint (see [ADR-0069](../../docs/adrs/adr-0069.md) §6).
    /// Overridable wholesale via `DRIVE_API_URL`
    /// (`crate::drive::auth::DRIVE_API_URL`; see
    /// [`Self::from_credentials_with`]). [`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://www.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: &DriveCredentials) -> Result<Self> {
        let client = Client::builder()
            .connect_timeout(connect_timeout())
            .read_timeout(read_timeout())
            .build()
            .context("Failed to build HTTP client")?;
        let session = DriveSession::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 Drive API
    /// host.
    ///
    /// Respects `DRIVE_API_URL` as an optional override: when set (and
    /// non-empty) in the process environment it replaces
    /// [`Self::DEFAULT_BASE_URL`] wholesale — mirrors Gmail's `GMAIL_API_URL`
    /// (PR #1466), used to exercise CLI output shapes without a real Google
    /// Cloud project or to route through a forced egress proxy.
    pub fn from_credentials(credentials: &DriveCredentials) -> Result<Self> {
        Self::from_credentials_with(&SystemEnv, credentials)
    }

    /// [`from_credentials`](Self::from_credentials) over an injected
    /// [`EnvSource`], so tests can exercise the `DRIVE_API_URL` override via
    /// `MapEnv` without mutating the process environment.
    pub(crate) fn from_credentials_with(
        env: &impl EnvSource,
        credentials: &DriveCredentials,
    ) -> Result<Self> {
        let base_url = env
            .var(crate::drive::auth::DRIVE_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 Drive 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 GET request without forcing an `Accept:
    /// application/json` header, for endpoints that return raw bytes rather
    /// than JSON (`files.export`, `files.get?alt=media`) — see
    /// [`Self::get_json`] for the JSON counterpart. Retries exactly once on
    /// HTTP 401, identically to `get_json`.
    pub async fn get_bytes(&self, url: &str) -> Result<Response> {
        self.send_authorized(url, "GET", |client, token| {
            client.get(url).bearer_auth(token)
        })
        .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 an authenticated PATCH request with a JSON body and returns the
    /// raw response. Drive's `files.update` (rename/move) is the only PATCH
    /// endpoint this client calls.
    pub async fn patch_json<T: serde::Serialize + Sync + ?Sized>(
        &self,
        url: &str,
        body: &T,
    ) -> Result<Response> {
        self.send_authorized(url, "PATCH", |client, token| {
            client
                .patch(url)
                .bearer_auth(token)
                .header("Content-Type", "application/json")
                .json(body)
        })
        .await
    }

    /// Sends a request built by `build`, retrying exactly once on HTTP 401.
    ///
    /// [`DriveSession::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 Drive 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 Drive 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("drive", method, url, started, result);
            },
            |status, body| status == 429 || is_drive_quota_exceeded(status, body),
        )
        .await
        .with_context(|| format!("Failed to send {method} request to Drive API"))
    }

    /// Consumes a non-success response into a [`DriveError`].
    ///
    /// Parses Drive's `{"error":{"message":...,"errors":[{"reason":...}]}}`
    /// envelope (the same shape every Google API error uses) into a human
    /// message when present (falls back to the raw body otherwise). Drive
    /// signals quota exhaustion as **403** `userRateLimitExceeded`, not
    /// `429` — unlike plain 429s, that shape now also drives a retry (see
    /// [`is_drive_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) -> DriveError {
        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(drive_error_reason);
        let body = value
            .as_ref()
            .and_then(drive_error_message)
            .map(|message| match &reason {
                Some(r) => format!("{message} (reason: {r})"),
                None => message,
            })
            .unwrap_or(raw);
        DriveError::ApiRequestFailed {
            status,
            body,
            reason,
        }
    }
}

/// Extracts the `error.errors[0].reason` field from Drive's already-parsed
/// JSON error envelope, if present.
fn drive_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 Drive's already-parsed JSON
/// error envelope, if present.
fn drive_error_message(value: &serde_json::Value) -> Option<String> {
    value
        .get("error")?
        .get("message")?
        .as_str()
        .map(str::to_string)
}

/// Whether a response is Drive's quota-exhaustion signal — **403** with
/// `reason` of `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).
///
/// Unlike Gmail's `is_gmail_quota_exceeded`, this does **not** also match
/// the bare `rateLimitExceeded` reason — that string is confirmed for
/// Gmail but not confirmed for Drive against
/// [Drive's error-handling guide](https://developers.google.com/workspace/drive/api/guides/handle-errors);
/// widen this match only once testing surfaces it. Plain `429` responses
/// (Drive's other documented rate-limit signal) are already covered by the
/// literal `status == 429` branch in [`DriveClient::send_once`], independent
/// of this function.
fn is_drive_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!(
        drive_error_reason(&value).as_deref(),
        Some("userRateLimitExceeded")
    )
}

/// Test-only seam letting sibling API-façade test modules (which can't
/// reach `DriveClient`'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::DriveClient;
    use crate::drive::auth::{DriveCredentials, DriveSession};

    /// Replaces `client`'s session with one pointed at an explicit token
    /// endpoint.
    pub(crate) fn replace_session(
        client: &mut DriveClient,
        credentials: &DriveCredentials,
        token_endpoint: &str,
    ) {
        client.session = DriveSession::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::drive::auth::DriveScope;
    use crate::utils::secret::Secret;

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

    #[test]
    fn is_drive_quota_exceeded_false_on_non_utf8_body() {
        assert!(!is_drive_quota_exceeded(403, &[0xff, 0xfe]));
    }

    #[test]
    fn is_drive_quota_exceeded_false_on_non_403_status() {
        assert!(!is_drive_quota_exceeded(
            429,
            br#"{"error":{"errors":[{"reason":"userRateLimitExceeded"}]}}"#
        ));
    }

    #[test]
    fn is_drive_quota_exceeded_true_on_matching_403_reason() {
        assert!(is_drive_quota_exceeded(
            403,
            br#"{"error":{"errors":[{"reason":"userRateLimitExceeded"}]}}"#
        ));
    }

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

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

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

    #[test]
    fn from_credentials_honours_api_url_override() {
        let env = crate::test_support::env::MapEnv::new().with(
            crate::drive::auth::DRIVE_API_URL,
            "http://proxy.example:8080",
        );
        let client = DriveClient::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::drive::auth::DRIVE_API_URL, "");
        let client = DriveClient::from_credentials_with(&env, &test_credentials()).unwrap();
        assert_eq!(client.base_url(), "https://www.googleapis.com");
    }

    #[test]
    fn client_debug_never_mentions_session_field() {
        let client = DriveClient::new("https://www.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("DriveClient"));
    }

    /// Mounts a bootstrap token-endpoint mock at the same base URL as the
    /// Drive API mock — `DriveSession` 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) -> DriveClient {
        // `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 = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
        client.session = DriveSession::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 get_bytes_sends_bearer_auth_header_without_json_accept_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_bytes(b"raw bytes".to_vec()),
            )
            .expect(1)
            .mount(&server)
            .await;

        let resp = client
            .get_bytes(&format!("{}/test", server.uri()))
            .await
            .unwrap();
        assert!(resp.status().is_success());
        let bytes = resp.bytes().await.unwrap();
        assert_eq!(bytes.as_ref(), b"raw bytes");
    }

    #[tokio::test]
    async fn get_bytes_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).set_body_bytes(b"ok".to_vec()))
            .with_priority(2)
            .mount(&server)
            .await;

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

    #[tokio::test]
    async fn get_bytes_refreshes_and_retries_once_on_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": "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).set_body_bytes(b"ok".to_vec()))
            .expect(1)
            .mount(&server)
            .await;

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

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

    #[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 patch_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("PATCH"))
            .and(wiremock::matchers::path("/test"))
            .and(wiremock::matchers::header(
                "Authorization",
                "Bearer bootstrap-token",
            ))
            .and(wiremock::matchers::body_json(
                serde_json::json!({"name": "new-name"}),
            ))
            .respond_with(wiremock::ResponseTemplate::new(200))
            .expect(1)
            .mount(&server)
            .await;

        let resp = client
            .patch_json(
                &format!("{}/test", server.uri()),
                &serde_json::json!({"name": "new-name"}),
            )
            .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_user_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": "User Rate Limit Exceeded", "errors": [{"reason": "userRateLimitExceeded"}]}
                    })),
            )
            .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_drive_message_and_reason() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        // `userRateLimitExceeded` is now retryable (`is_drive_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 = DriveClient::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 = DriveClient::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_drive_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 = DriveClient::response_to_error(resp).await;
        assert!(err.to_string().contains("internal error"));
    }

    #[tokio::test]
    async fn get_json_propagates_network_errors() {
        let client = DriveClient::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());
    }

    #[tokio::test]
    async fn get_parsed_errors_on_non_success_status_without_parsing_the_body() {
        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(404).set_body_json(serde_json::json!({
                    "error": {"message": "File not found"}
                })),
            )
            .mount(&server)
            .await;

        let result: Result<serde_json::Value> = client
            .get_parsed(&format!("{}/test", server.uri()), "test context")
            .await;
        let err = result.unwrap_err();
        assert!(err.to_string().contains("File not found"));
    }
}