git-remote-object-store 0.2.4

Git remote helper backed by cloud object stores (S3, Azure Blob Storage)
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
//! `bundle-uri` command handler (issue #71, packchain-only).
//!
//! Git invokes `bundle-uri\n` after capability advertisement when the
//! helper has advertised the `bundle-uri` capability. The helper
//! responds with one entry per ref, each pointing at that ref's
//! baseline bundle on the bucket:
//!
//! ```text
//! bundle.<ref>.uri=<url>
//! bundle.<ref>.creationToken=<full_at>
//! <blank line>
//! ```
//!
//! `creationToken` lets the client cache the bundle across clones
//! until `full_at` advances (force push or [`crate::packchain::compact`]).
//!
//! ## Engine gating
//!
//! Only [`crate::url::StorageEngine::Packchain`] remotes ever reach
//! this handler — [`super::capabilities`] only advertises the
//! capability when both the engine resolves to packchain AND the
//! URL carries `?bundle_uri=1`. The bundle engine's bundle filenames
//! rotate per push, so a stable URL would race the next push; the
//! issue explicitly puts the bundle engine out of scope.
//!
//! ## URL generation
//!
//! This module emits either **canonical bucket URLs** (default,
//! works for public-read S3 buckets, S3-compatible CDNs, and Azure
//! blob containers with anonymous-read access) or **presigned
//! URLs** (S3 `SigV4` / Azure service-blob SAS) when the operator
//! sets [`BundleUriOpts::presign_ttl_seconds`] via the
//! `?bundle_uri_presign_ttl=<seconds>` URL flag. Presigning runs
//! through [`crate::object_store::ObjectStore::presigned_get_url`]
//! so the credential material lives in the per-backend store
//! impl, not here. (Issue #76.)
//!
//! ## Wire format
//!
//! Per `.claude/rules/protocol-stdout.md`, this handler emits only
//! protocol-formatted bytes on the writer. The trailing blank line
//! is part of the bundle-uri response per the gitprotocol-v2 spec
//! (`bundle list` framing).

use std::num::NonZeroU64;

use tokio::io::{AsyncWrite, AsyncWriteExt};
use tracing::warn;

use crate::keys;
use crate::object_store::{ObjectStore, ObjectStoreError};
use crate::packchain::PackchainError;
use crate::packchain::keys::is_chain_json_key;
use crate::packchain::schema::ChainManifest;
use crate::url::{AzureAddressing, RemoteUrl, S3Addressing};

/// Tunables for [`handle_bundle_uri`]. Mirrors the shape used by
/// other manage-style opts (Doctor, Gc, Compact).
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct BundleUriOpts {
    /// When `Some(N)`, presign emitted URLs with an `N`-second TTL
    /// using the backend's
    /// [`ObjectStore::presigned_get_url`](crate::object_store::ObjectStore::presigned_get_url)
    /// impl. `None` (default) emits canonical bucket URLs that
    /// only work against public-read buckets / CDN-fronted
    /// endpoints.
    ///
    /// `NonZeroU64` because a zero-second TTL is meaningless (the
    /// URL would expire before any client could observe it); the
    /// type-system check rejects the bad value at the boundary
    /// rather than letting it flow into the presigning code path.
    pub(crate) presign_ttl_seconds: Option<NonZeroU64>,
}

/// Errors specific to the bundle-uri handler. Wrapped by
/// [`super::ProtocolError`] at the dispatch site; `pub` because it
/// is reachable through the public `ProtocolError::BundleUri`
/// variant.
#[derive(Debug, thiserror::Error)]
pub enum BundleUriError {
    /// Object-store transport / parse failure surfaced through the
    /// packchain engine (chain.json listing or fetch).
    #[error(transparent)]
    Packchain(#[from] PackchainError),
    /// Direct object-store error from
    /// [`ObjectStore::presigned_get_url`]. Distinct from
    /// `Packchain` so the per-entry `bundle_url_for_emission`
    /// failure path doesn't synthesise a fake `PackchainError::Store`
    /// wrapper just to nest the same `ObjectStoreError`.
    #[error(transparent)]
    Store(#[from] ObjectStoreError),
    /// I/O failure writing the response to the protocol writer.
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

/// Run the `bundle-uri` command.
///
/// `advertised` mirrors the capability gate: when `false` the
/// helper still responds (gitprotocol-v2 framing requires *some*
/// reply) but emits only the trailing blank-line terminator, no
/// entries. Centralising the gate here keeps the always-respond
/// contract in one place rather than splitting it between the
/// REPL dispatch and the handler.
///
/// On `advertised = true` the handler lists
/// `<prefix>/refs/heads/*/chain.json`, parses each, and emits
/// `bundle.<ref>.uri=<url>` + `bundle.<ref>.creationToken=<full_at>`
/// lines for every parsed chain. Per-entry parse failures
/// warn-and-skip; only transport failures on the initial list call
/// surface as errors. The trailing blank line ends the response.
pub(crate) async fn handle_bundle_uri<W>(
    store: &dyn ObjectStore,
    remote: &RemoteUrl,
    opts: BundleUriOpts,
    advertised: bool,
    writer: &mut W,
) -> Result<(), BundleUriError>
where
    W: AsyncWrite + Unpin,
{
    if !advertised {
        writer.write_all(b"\n").await?;
        writer.flush().await?;
        return Ok(());
    }

    let prefix = remote.prefix().unwrap_or_default();
    // Bundle-uri is best-effort hinting per gitprotocol-v2: on a
    // transport failure during the refs listing, log and emit an
    // empty response (terminator only) rather than aborting the
    // helper. The client falls back to the helper-protocol fetch
    // path. This matches the per-entry warn-and-skip policy
    // already applied to chain.json fetches inside
    // [`collect_entries`].
    let entries = match collect_entries(store, prefix).await {
        Ok(entries) => entries,
        Err(e) => {
            warn!(
                error = %e,
                "bundle-uri: refs listing failed; emitting empty response",
            );
            Vec::new()
        }
    };

    for entry in &entries {
        let url =
            match bundle_url_for_emission(store, remote, &entry.ref_path, &entry.full_at, &opts)
                .await
            {
                Ok(u) => u,
                Err(e) => {
                    // Per-entry warn-and-skip — an operator
                    // misconfiguration on one ref (e.g. SDK rejects
                    // a 7-day-plus TTL) must not blackhole the
                    // bundle-uri response for the rest of the refs.
                    // The terminator is still emitted at end of
                    // loop.
                    warn!(
                        ref_path = %entry.ref_path,
                        error = %e,
                        "bundle-uri: URL build failed; skipping entry",
                    );
                    continue;
                }
            };
        let ref_path = &entry.ref_path;
        let token = &entry.full_at;
        let line =
            format!("bundle.{ref_path}.uri={url}\nbundle.{ref_path}.creationToken={token}\n");
        writer.write_all(line.as_bytes()).await?;
    }
    // Blank-line terminator per gitprotocol-v2 bundle-uri framing.
    writer.write_all(b"\n").await?;
    writer.flush().await?;
    Ok(())
}

/// One parsed chain — the data the handler renders into a
/// `bundle.<ref>.*` block.
#[derive(Debug, Clone)]
struct BundleEntry {
    ref_path: String,
    full_at: String,
}

/// List `<prefix>/refs/heads/*/chain.json` and return the
/// `(ref_path, full_at)` pair for each parseable chain. Per-entry
/// parse failures warn-and-skip; only transport failures abort.
async fn collect_entries(
    store: &dyn ObjectStore,
    prefix: &str,
) -> Result<Vec<BundleEntry>, PackchainError> {
    let refs_prefix = keys::join(Some(prefix), "refs/heads/");
    let metas = store.list(&refs_prefix).await?;

    let prefix_opt = Some(prefix);
    // `metas.len()` is a tight upper bound: every kept entry is a
    // subset (chain.json keys after the `is_chain_json_key` filter).
    let mut out: Vec<BundleEntry> = Vec::with_capacity(metas.len());
    for meta in metas {
        if !is_chain_json_key(&meta.key) {
            continue;
        }
        let Some(ref_path) = crate::packchain::keys::ref_path_from_chain_key(prefix_opt, &meta.key)
        else {
            warn!(key = %meta.key, "bundle-uri: chain.json key has unexpected shape; skipping");
            continue;
        };
        // Validate the derived ref-path the same way `list_refs` and
        // the audit do: a maliciously-planted key such as
        // `<prefix>/refs/heads/../etc/passwd/chain.json` must not
        // emit a verbatim `bundle.refs/heads/../etc/passwd.uri=…`
        // line. `RefName::is_valid` rejects `..`, control chars, and
        // other gix-validate-rejected shapes without allocating a
        // wrapped `String` we'd immediately drop.
        if !crate::git::RefName::is_valid(&ref_path) {
            warn!(
                key = %meta.key,
                ref_path = %ref_path,
                "bundle-uri: derived ref path is not a valid ref name; skipping",
            );
            continue;
        }
        // Belt-and-suspenders against bundle-uri wire-format
        // *and* URL injection. The line shape is
        // `bundle.<id>.<key>=<value>\n`; git's parser splits each
        // line at the first `=`. `RefName::is_valid` (via
        // `gix_validate::reference::name`) already bans `\n`, `\r`,
        // ` `, `:`, and the rest of `\0-\x1F`, but it permits `=`
        // as well as RFC 3986 reserved bytes that would corrupt
        // the emitted URL (`#`, `%`, `&`, `;`, `,`, `?`). None of
        // these can relocate the URL host — the `:` ban forecloses
        // scheme injection — but each can either break wire framing
        // or produce a URL the bucket no longer resolves. Reject
        // defensively. See [`is_safe_for_bundle_uri_emission`] for
        // the per-byte rationale.
        if !is_safe_for_bundle_uri_emission(&ref_path) {
            warn!(
                key = %meta.key,
                ref_path = %ref_path,
                "bundle-uri: derived ref path contains framing-unsafe or URL-unsafe bytes; skipping",
            );
            continue;
        }
        // Fetch and parse chain.json. Per-ref transport failures
        // warn-and-skip rather than aborting — bundle-uri is
        // best-effort hinting; a missing entry just means the
        // client falls back to the helper-protocol fetch.
        let body = match store.get_bytes(&meta.key).await {
            Ok(b) => b,
            Err(e) => {
                warn!(
                    key = %meta.key,
                    error = %e,
                    "bundle-uri: chain.json fetch failed; skipping",
                );
                continue;
            }
        };
        match ChainManifest::from_json_bytes(&body) {
            Ok(chain) => out.push(BundleEntry {
                ref_path,
                full_at: chain.full_at.as_str().to_owned(),
            }),
            Err(e) => warn!(
                key = %meta.key,
                error = %e,
                "bundle-uri: chain.json failed to parse; skipping",
            ),
        }
    }
    // Stable order: sort by ref path so the wire output is
    // deterministic regardless of the listing's response order.
    out.sort_by(|a, b| a.ref_path.cmp(&b.ref_path));
    Ok(out)
}

/// Build the bundle URL to emit for `entry`. Dispatches on
/// [`BundleUriOpts::presign_ttl_seconds`]:
///
/// - `None` → [`canonical_bundle_url`] (unsigned, works for
///   public-read buckets and CDN-fronted endpoints).
/// - `Some(ttl)` → [`ObjectStore::presigned_get_url`] (signed,
///   required for private buckets — issue #76).
///
/// Per-entry errors propagate; the caller (`handle_bundle_uri`'s
/// emission loop) warn-and-skips rather than aborting the whole
/// helper.
async fn bundle_url_for_emission(
    store: &dyn ObjectStore,
    remote: &RemoteUrl,
    ref_path: &str,
    full_at: &str,
    opts: &BundleUriOpts,
) -> Result<String, BundleUriError> {
    let Some(ttl_seconds) = opts.presign_ttl_seconds else {
        return Ok(canonical_bundle_url(remote, ref_path, full_at));
    };
    let bundle_key = keys::bundle_key(remote.prefix(), ref_path, full_at);
    let ttl = std::time::Duration::from_secs(ttl_seconds.get());
    Ok(store.presigned_get_url(&bundle_key, ttl).await?)
}

/// Build a canonical (unsigned) bucket URL for the baseline bundle
/// at `<prefix>/<ref_path>/<full_at>.bundle`. Works for public-read
/// buckets and CDN-fronted endpoints. Private buckets use
/// [`bundle_url_for_emission`]'s presigning branch instead.
fn canonical_bundle_url(remote: &RemoteUrl, ref_path: &str, full_at: &str) -> String {
    let bundle_key = keys::bundle_key(remote.prefix(), ref_path, full_at);
    let endpoint = match remote {
        RemoteUrl::S3 { endpoint, .. } | RemoteUrl::Azure { endpoint, .. } => endpoint,
    };
    let authority = host_authority(endpoint);
    match remote {
        // Virtual-hosted S3: the parsed `endpoint.host_str()` already
        // includes the bucket as the leftmost label (e.g.
        // `my-bucket.s3.us-west-2.amazonaws.com`), so the URL is
        // `<scheme>://<host>[:port]/<key>` — the bucket name lives
        // in the host, not the path.
        RemoteUrl::S3 {
            addressing: S3Addressing::VirtualHosted,
            ..
        } => format!("{authority}/{bundle_key}"),
        // Path-style S3: the host has no bucket label; insert it as
        // the first path segment.
        RemoteUrl::S3 {
            bucket,
            addressing: S3Addressing::PathStyle,
            ..
        } => format!("{authority}/{bucket}/{bundle_key}"),
        // Virtual-hosted Azure: the host already includes the
        // account (`<account>.blob.<suffix>`); URL is
        // `<host>[:port]/<container>/<key>`.
        RemoteUrl::Azure {
            container,
            addressing: AzureAddressing::VirtualHosted,
            ..
        } => format!("{authority}/{container}/{bundle_key}"),
        // Path-style Azure (Azurite, custom endpoints):
        // `<host>[:port]/<account>/<container>/<key>`.
        RemoteUrl::Azure {
            account,
            container,
            addressing: AzureAddressing::PathStyle,
            ..
        } => format!("{authority}/{account}/{container}/{bundle_key}"),
    }
}

/// `true` if `ref_path` is safe to interpolate into the
/// `bundle.<id>.<key>=<value>\n` wire shape, *and* into the URL that
/// follows the `=`, after `RefName::is_valid` has already accepted it.
///
/// Rejected bytes and their reasons:
///
/// - `=` — bundle-uri wire framing: git's parser splits each line at
///   the first `=`, so a ref-name containing `=` corrupts the
///   `id`/`value` boundary.
/// - `#` — RFC 3986 fragment delimiter: a URL parser treats everything
///   after `#` as the fragment and discards it from the path. A
///   ref-name containing `#` would silently truncate the emitted URL.
/// - `%` — RFC 3986 percent-encoding sentinel: a literal `%` in the
///   path may be decoded as `%XX` by URL parsers or re-encoded by
///   intermediaries (CDNs, proxies), producing a URL the bucket no
///   longer recognises.
/// - `&` — RFC 3986 query separator: when the emission path appends a
///   query string (e.g. presigned URLs), a `&` mid-path is ambiguous
///   with the query separator and may shift the parsed boundary.
/// - `;` — RFC 3986 sub-delim historically used as a secondary query
///   separator by some clients (matrix-URI / cookie / form-encoded).
/// - `,` — RFC 3986 sub-delim used for matrix parameters; ambiguous
///   in some URL processors.
/// - `?` — RFC 3986 query delimiter: would truncate the path and
///   inject the rest of the ref-name into the query string.
///
/// All other framing-relevant bytes (`\n`, `\r`, ` `, `:`,
/// `\0`-`\x1F`, `\x7F`) are already rejected by gix-validate.
fn is_safe_for_bundle_uri_emission(ref_path: &str) -> bool {
    // Defense-in-depth: a ref-name containing any of these bytes
    // would corrupt either the bundle-uri wire framing (the `=`
    // split) or the emitted URL (RFC 3986 reserved characters).
    // Rather than percent-encode and risk a double-decode by an
    // intermediary, follow the existing warn-and-skip pattern.
    const FRAMING_AND_URL_UNSAFE: &[u8] = b"=#%&;,?";
    !ref_path
        .as_bytes()
        .iter()
        .any(|b| FRAMING_AND_URL_UNSAFE.contains(b))
}

/// Render `<scheme>://<host>[:port]` from a parsed [`url::Url`].
/// `RemoteUrl::parse` rejects URLs without a host, so `host_str()`
/// is provably `Some` here — the `expect` documents the invariant
/// rather than papering over an unreachable code path.
fn host_authority(endpoint: &url::Url) -> String {
    let scheme = endpoint.scheme();
    let host = endpoint
        .host_str()
        .expect("RemoteUrl invariant: parse() rejects URLs without a host");
    match endpoint.port() {
        Some(port) => format!("{scheme}://{host}:{port}"),
        None => format!("{scheme}://{host}"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::object_store::mock::MockStore;
    use crate::packchain::manifest::write_chain;
    use crate::packchain::schema::{ChainManifest, ChainSegment, Sha40};
    use crate::url::parse;
    use bytes::Bytes;

    const SHA_TIP: &str = "0000000000000000000000000000000000000001";
    const SHA_FULL: &str = "0000000000000000000000000000000000000002";
    const SHA_PACK: &str = "1111111111111111111111111111111111111111";

    fn sha40(s: &str) -> Sha40 {
        Sha40::try_new(s).unwrap()
    }

    fn ref_main() -> crate::git::RefName {
        crate::git::RefName::new("refs/heads/main").unwrap()
    }

    async fn write_test_chain(
        store: &MockStore,
        prefix: Option<&str>,
        ref_name: &crate::git::RefName,
        tip: &str,
        full_at: &str,
    ) {
        let chain = ChainManifest {
            v: 1,
            tip: sha40(tip),
            full_at: sha40(full_at),
            segments: vec![ChainSegment {
                sha: sha40(tip),
                parent_sha: None,
                pack: format!("packs/{SHA_PACK}.pack"),
                bytes: 1_024,
            }],
        };
        write_chain(store, prefix, ref_name, &chain).await.unwrap();
    }

    #[tokio::test]
    async fn empty_bucket_emits_just_terminator() {
        let store = MockStore::new();
        let remote =
            parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?bundle_uri=1").unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        assert_eq!(&buf, b"\n", "empty bucket must emit only the terminator");
    }

    #[tokio::test]
    async fn emits_one_entry_per_ref_with_canonical_s3_url() {
        let store = MockStore::new();
        write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;

        let remote = parse(
            "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        let text = std::str::from_utf8(&buf).unwrap();
        // Pin exact bytes — bundle-uri is a wire-format contract.
        assert_eq!(
            text,
            format!(
                "bundle.refs/heads/main.uri=https://my-bucket.s3.us-west-2.amazonaws.com/repo/refs/heads/main/{SHA_FULL}.bundle\n\
                 bundle.refs/heads/main.creationToken={SHA_FULL}\n\
                 \n"
            ),
        );
    }

    #[tokio::test]
    async fn s3_path_style_url_uses_bucket_in_path() {
        // `?addressing=path` → URL form is `<host>/<bucket>/<key>`.
        // For a path-style URL the bucket lives in the path, not
        // the hostname, so we use a bare regional endpoint here.
        let store = MockStore::new();
        write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;
        let remote = parse(
            "s3+https://s3.us-west-2.amazonaws.com/my-bucket/repo?addressing=path&engine=packchain&bundle_uri=1",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        let text = std::str::from_utf8(&buf).unwrap();
        assert!(
            text.contains(&format!(
                "uri=https://s3.us-west-2.amazonaws.com/my-bucket/repo/refs/heads/main/{SHA_FULL}.bundle\n",
            )),
            "{text}",
        );
    }

    #[tokio::test]
    async fn azure_virtual_hosted_url_uses_account_subdomain() {
        let store = MockStore::new();
        write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;
        let remote = parse(
            "az+https://myaccount.blob.core.windows.net/my-container/repo?engine=packchain&bundle_uri=1",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        let text = std::str::from_utf8(&buf).unwrap();
        assert!(
            text.contains(&format!(
                "uri=https://myaccount.blob.core.windows.net/my-container/repo/refs/heads/main/{SHA_FULL}.bundle\n",
            )),
            "{text}",
        );
    }

    #[tokio::test]
    async fn presign_ttl_emits_presigned_url_via_dispatch() {
        // With a backend that supports presigning, `bundle_url_for_emission`
        // routes through `ObjectStore::presigned_get_url` instead of
        // building a canonical URL. Arm `MockStore`'s presign stub
        // (test-only hook) to return a deterministic SigV4-shaped
        // URL and verify the dispatch path end-to-end.
        let store = MockStore::new();
        store.set_presign_stub(Some(|key: &str, ttl: std::time::Duration| {
            Ok(format!(
                "https://stub.example/{key}?X-Amz-Expires={}&X-Amz-Signature=DEADBEEF",
                ttl.as_secs(),
            ))
        }));
        write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;
        let remote = parse(
            "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo\
             ?engine=packchain&bundle_uri=1&bundle_uri_presign_ttl=3600",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(
            &store,
            &remote,
            BundleUriOpts {
                presign_ttl_seconds: Some(NonZeroU64::new(3_600).unwrap()),
            },
            true,
            &mut buf,
        )
        .await
        .expect("handler succeeds against a presign-capable backend");
        let text = std::str::from_utf8(&buf).unwrap();
        assert!(
            text.contains("uri=https://stub.example/"),
            "presigned URL must reach the wire output: {text}",
        );
        assert!(
            text.contains("X-Amz-Expires=3600"),
            "TTL must be honoured (3600s): {text}",
        );
        assert!(
            text.contains("X-Amz-Signature=DEADBEEF"),
            "signature query param must be present: {text}",
        );
    }

    #[tokio::test]
    async fn presign_ttl_against_unsupporting_backend_warn_skips_entries() {
        // `MockStore` inherits the `presigned_get_url` default impl
        // (returns `ObjectStoreError::Unsupported`). Per-entry errors
        // warn-and-skip — the bundle-uri response degrades to the
        // terminator-only shape rather than aborting the whole
        // helper invocation. (#76)
        let store = MockStore::new();
        write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;
        let remote = parse(
            "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo\
             ?engine=packchain&bundle_uri=1&bundle_uri_presign_ttl=3600",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(
            &store,
            &remote,
            BundleUriOpts {
                presign_ttl_seconds: Some(NonZeroU64::new(3_600).unwrap()),
            },
            true,
            &mut buf,
        )
        .await
        .expect("warn-and-skip never aborts the helper");
        assert_eq!(
            std::str::from_utf8(&buf).unwrap(),
            "\n",
            "presigning unsupported by backend → only the terminator reaches the wire",
        );
    }

    #[tokio::test]
    async fn skips_chain_json_with_equals_in_ref_name() {
        // Defense-in-depth against bundle-uri wire-format injection:
        // gix-validate permits `=` in ref names, but git's
        // `bundle-uri` parser splits each line at the first `=`. A
        // ref-path containing `=` would produce a malformed entry on
        // the wire. The host-relocation SSRF chain is foreclosed by
        // gix-validate's `:` ban (no scheme injection possible), but
        // we still skip rather than emit a corrupted line.
        //
        // Mutation-verified during /security-review: removing the
        // `is_safe_for_bundle_uri_emission` check at the call site
        // makes this test fail because `bundle.refs/heads/x=evil...`
        // reaches the wire output.
        let store = MockStore::new();
        write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;
        // Plant a chain.json under a ref name that gix-validate
        // accepts (`=` is not in its banned-bytes set) but that
        // would corrupt the bundle-uri wire framing.
        store.insert(
            "repo/refs/heads/x=evil/chain.json",
            Bytes::from(
                format!(r#"{{"v":1,"tip":"{SHA_TIP}","full_at":"{SHA_TIP}","segments":[]}}"#)
                    .into_bytes(),
            ),
        );
        let remote = parse(
            "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        let text = std::str::from_utf8(&buf).unwrap();
        // The malicious entry must not reach the wire output. We
        // anchor on the ref-name fragment `x=evil` rather than `=`
        // alone because legitimate `bundle.<ref>.uri=<url>` lines
        // also contain `=` as the id/value separator.
        assert!(
            !text.contains("x=evil"),
            "no entry containing `=` in the ref-name segment may reach the wire output: {text}",
        );
        // The good ref is still present.
        assert!(text.contains("bundle.refs/heads/main.uri="), "{text}");
    }

    #[test]
    fn is_safe_for_bundle_uri_emission_accepts_typical_ref_paths() {
        for path in &[
            "refs/heads/main",
            "refs/heads/feature/foo-bar.baz",
            "refs/heads/release-1.0.0",
            "refs/tags/v1",
        ] {
            assert!(
                is_safe_for_bundle_uri_emission(path),
                "expected `{path}` to be accepted",
            );
        }
    }

    #[test]
    fn is_safe_for_bundle_uri_emission_rejects_equals() {
        // `=` is the framing-relevant byte gix-validate permits.
        // Reject it everywhere it appears in the ref-path.
        for path in &[
            "refs/heads/x=y",
            "refs/heads/=",
            "=refs/heads/main",
            "refs/heads/main=",
            "refs/heads/main=evil.attacker",
        ] {
            assert!(
                !is_safe_for_bundle_uri_emission(path),
                "expected `{path}` to be rejected",
            );
        }
    }

    #[test]
    fn is_safe_for_bundle_uri_emission_rejects_url_reserved_bytes() {
        // gix-validate permits each of these in ref names, but each
        // breaks the emitted URL in a different way:
        //
        // - `#` → URL fragment delimiter; truncates the path.
        // - `%` → percent-encoding sentinel; may be re-encoded by
        //   intermediaries (CDN, proxy) into an unrecognised key.
        // - `&` → query separator; ambiguous when a query string is
        //   appended (presigned URLs).
        // - `;` → historical secondary query separator.
        // - `,` → matrix-parameter delimiter.
        // - `?` → query-string delimiter; truncates the path.
        //
        // Each byte is covered at three positions (mid-component,
        // leading, trailing) so a partial-fix that only checks one
        // position would visibly fail.
        for unsafe_byte in ['#', '%', '&', ';', ',', '?'] {
            for path in &[
                format!("refs/heads/x{unsafe_byte}y"),
                format!("{unsafe_byte}refs/heads/main"),
                format!("refs/heads/main{unsafe_byte}"),
            ] {
                assert!(
                    !is_safe_for_bundle_uri_emission(path),
                    "expected `{path}` to be rejected (byte = {unsafe_byte:?})",
                );
            }
        }
    }

    #[tokio::test]
    async fn skips_chain_json_with_url_reserved_bytes_in_ref_name() {
        // Per-byte end-to-end check that the warn-and-skip path
        // engages for each newly-rejected byte. gix-validate accepts
        // each of `#`, `%`, `&`, `;`, `,` in ref names but the
        // bundle-uri emission path must skip them so the resulting
        // URL stays well-formed.
        //
        // `?` is in `FRAMING_AND_URL_UNSAFE` for defense-in-depth but
        // gix-validate already rejects it (see `tag::name_inner`), so
        // it can't reach this code path through `RefName::is_valid`
        // and is therefore not exercisable end-to-end here. The
        // per-byte unit test below covers the `?` rejection at the
        // predicate level.
        //
        // Mutation-verified: shrinking `FRAMING_AND_URL_UNSAFE` back
        // to `b"="` makes this test fail because each malicious ref
        // reaches the wire output.
        for unsafe_byte in ['#', '%', '&', ';', ','] {
            let store = MockStore::new();
            // The good ref must still emit; it shares the listing
            // with the malicious entry so any over-broad rejection
            // would also drop it.
            write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;
            let bad_key = format!("repo/refs/heads/x{unsafe_byte}evil/chain.json");
            store.insert(
                &bad_key,
                Bytes::from(
                    format!(r#"{{"v":1,"tip":"{SHA_TIP}","full_at":"{SHA_TIP}","segments":[]}}"#)
                        .into_bytes(),
                ),
            );
            let remote = parse(
                "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1",
            )
            .unwrap();
            let mut buf: Vec<u8> = Vec::new();
            handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
                .await
                .unwrap();
            let text = std::str::from_utf8(&buf).unwrap();
            let needle = format!("x{unsafe_byte}evil");
            assert!(
                !text.contains(&needle),
                "no entry containing `{needle}` may reach the wire output: {text}",
            );
            // The good ref is still present — the rejection is
            // scoped to the offending entry.
            assert!(
                text.contains("bundle.refs/heads/main.uri="),
                "good ref dropped for byte {unsafe_byte:?}: {text}",
            );
        }
    }

    #[tokio::test]
    async fn skips_chain_json_with_path_traversal_in_ref_name() {
        // Defense-in-depth: a maliciously-planted
        // `<prefix>/refs/heads/../etc/passwd/chain.json` would
        // otherwise emit a verbatim
        // `bundle.refs/heads/../etc/passwd.uri=…` line.
        let store = MockStore::new();
        write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;
        store.insert(
            "repo/refs/heads/../etc/passwd/chain.json",
            Bytes::from(
                format!(r#"{{"v":1,"tip":"{SHA_TIP}","full_at":"{SHA_TIP}","segments":[]}}"#)
                    .into_bytes(),
            ),
        );
        let remote = parse(
            "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        let text = std::str::from_utf8(&buf).unwrap();
        assert!(
            !text.contains(".."),
            "no entry containing `..` may reach the wire output: {text}",
        );
        // The good ref is still present.
        assert!(text.contains("bundle.refs/heads/main.uri="), "{text}");
    }

    #[tokio::test]
    async fn corrupt_chain_json_is_skipped() {
        // A corrupt chain.json on one branch must not blackhole the
        // others — bundle-uri is best-effort.
        let store = MockStore::new();
        write_test_chain(&store, Some("repo"), &ref_main(), SHA_TIP, SHA_FULL).await;
        store.insert(
            "repo/refs/heads/broken/chain.json",
            Bytes::from_static(b"{not valid json"),
        );
        let remote = parse(
            "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        let text = std::str::from_utf8(&buf).unwrap();
        assert!(text.contains("bundle.refs/heads/main.uri="), "{text}");
        assert!(!text.contains("bundle.refs/heads/broken"), "{text}");
    }

    #[tokio::test]
    async fn entries_are_sorted_alphabetically_by_ref_path() {
        // The wire output must be deterministic regardless of the
        // listing's response order. Pin the lexical sort by writing
        // chains in reverse alphabetical order and asserting the
        // emitted entries come out in forward order.
        // Mutation-verified: replacing `out.sort_by(...)` with
        // `out.reverse()` makes this test fail.
        let store = MockStore::new();
        // Insert in reverse order so any test reliance on insertion
        // order would visibly fail.
        let zulu = crate::git::RefName::new("refs/heads/zulu").unwrap();
        let main = crate::git::RefName::new("refs/heads/main").unwrap();
        let alpha = crate::git::RefName::new("refs/heads/alpha").unwrap();
        write_test_chain(&store, Some("repo"), &zulu, SHA_TIP, SHA_FULL).await;
        write_test_chain(&store, Some("repo"), &main, SHA_TIP, SHA_FULL).await;
        write_test_chain(&store, Some("repo"), &alpha, SHA_TIP, SHA_FULL).await;

        let remote = parse(
            "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        let text = std::str::from_utf8(&buf).unwrap();

        let alpha_pos = text
            .find("bundle.refs/heads/alpha.uri=")
            .expect("alpha entry present");
        let main_pos = text
            .find("bundle.refs/heads/main.uri=")
            .expect("main entry present");
        let zulu_pos = text
            .find("bundle.refs/heads/zulu.uri=")
            .expect("zulu entry present");
        assert!(
            alpha_pos < main_pos && main_pos < zulu_pos,
            "entries must appear in lexical ref-path order; got\n{text}",
        );
    }

    #[tokio::test]
    async fn root_prefix_emits_bare_bundle_keys() {
        // Empty prefix (root-of-bucket) — the bundle key has no
        // leading prefix segment.
        let store = MockStore::new();
        write_test_chain(&store, None, &ref_main(), SHA_TIP, SHA_FULL).await;
        let remote =
            parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/?engine=packchain&bundle_uri=1")
                .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .unwrap();
        let text = std::str::from_utf8(&buf).unwrap();
        assert!(
            text.contains(&format!(
                "uri=https://my-bucket.s3.us-west-2.amazonaws.com/refs/heads/main/{SHA_FULL}.bundle\n",
            )),
            "{text}",
        );
    }

    /// Test-only `ObjectStore` decorator that fails on `list` and
    /// delegates everything else to an inner `MockStore`. Used to
    /// pin the "best-effort hinting" contract: a transport failure
    /// during `bundle-uri`'s refs listing must not abort the helper.
    /// Methods outside `list` are unreachable from the bundle-uri
    /// path, so they panic loudly if exercised.
    struct FailListStore;

    // Methods other than `list` are unreachable from the bundle-uri
    // path under test; the `unreachable!`s document that contract.
    // Project-level clippy denies `unreachable` by default, but these
    // are intentionally test-only stubs in a `#[cfg(test)]` module.
    #[allow(clippy::unreachable)]
    #[async_trait::async_trait]
    impl crate::object_store::ObjectStore for FailListStore {
        async fn list(
            &self,
            _prefix: &str,
        ) -> Result<Vec<crate::object_store::ObjectMeta>, crate::object_store::ObjectStoreError>
        {
            Err(crate::object_store::ObjectStoreError::Network(Box::new(
                std::io::Error::other("simulated transport failure"),
            )))
        }
        async fn get_to_file(
            &self,
            _key: &str,
            _dest: &std::path::Path,
            _opts: crate::object_store::GetOpts,
        ) -> Result<(), crate::object_store::ObjectStoreError> {
            unreachable!("bundle-uri does not call get_to_file")
        }
        async fn get_bytes(
            &self,
            _key: &str,
        ) -> Result<bytes::Bytes, crate::object_store::ObjectStoreError> {
            unreachable!("bundle-uri does not reach get_bytes when list fails")
        }
        async fn get_bytes_range(
            &self,
            _key: &str,
            _range: std::ops::Range<u64>,
        ) -> Result<bytes::Bytes, crate::object_store::ObjectStoreError> {
            unreachable!("bundle-uri does not call get_bytes_range")
        }
        async fn put_bytes(
            &self,
            _key: &str,
            _body: bytes::Bytes,
            _opts: crate::object_store::PutOpts,
        ) -> Result<(), crate::object_store::ObjectStoreError> {
            unreachable!("bundle-uri does not call put_bytes")
        }
        async fn put_if_absent(
            &self,
            _key: &str,
            _body: bytes::Bytes,
        ) -> Result<bool, crate::object_store::ObjectStoreError> {
            unreachable!("bundle-uri does not call put_if_absent")
        }
        async fn head(
            &self,
            _key: &str,
        ) -> Result<crate::object_store::ObjectMeta, crate::object_store::ObjectStoreError>
        {
            unreachable!("bundle-uri does not call head")
        }
        async fn copy(
            &self,
            _src: &str,
            _dst: &str,
        ) -> Result<(), crate::object_store::ObjectStoreError> {
            unreachable!("bundle-uri does not call copy")
        }
        async fn delete(&self, _key: &str) -> Result<(), crate::object_store::ObjectStoreError> {
            unreachable!("bundle-uri does not call delete")
        }
    }

    #[tokio::test]
    async fn list_failure_emits_empty_response_rather_than_aborting() {
        // Bundle-uri is best-effort hinting per gitprotocol-v2: a
        // transport failure on the refs listing should warn-and-emit-
        // empty so the helper keeps running and the client falls
        // back to the helper-protocol fetch. Mutation-verifiable:
        // changing the `match collect_entries(...)` to `?` makes
        // this test fail with a `BundleUriError::Packchain` error.
        let store = FailListStore;
        let remote = parse(
            "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1",
        )
        .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        handle_bundle_uri(&store, &remote, BundleUriOpts::default(), true, &mut buf)
            .await
            .expect("list failure must not surface as a hard error");
        assert_eq!(
            &buf, b"\n",
            "list failure must yield only the trailing terminator",
        );
    }
}