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
//! Integration tests for `git_remote_object_store::url::parse`.
//!
//! Covers every concrete URL example in the grammar plus negative
//! cases for the validation rules, the `?addressing=` override, and a
//! `proptest` round-trip on the legal grammar.

use git_remote_object_store::test_util::EnvGuard;
use git_remote_object_store::url::{
    AzureAddressing, ENV_ALLOW_HTTP, ParseError, RemoteFlags, RemoteUrl, S3Addressing, parse,
};
use proptest::prelude::*;

// Tests that mutate ENV_ALLOW_HTTP must serialize against each other.
// `EnvGuard` holds a per-key lock for the env var's lifetime and
// restores the prior value on drop — so an assertion panic inside the
// closure no longer leaks the env var to subsequent tests.
fn with_allow_http_env<R>(value: Option<&str>, f: impl FnOnce() -> R) -> R {
    let _env = match value {
        Some(v) => EnvGuard::set(ENV_ALLOW_HTTP, v),
        None => EnvGuard::unset(ENV_ALLOW_HTTP),
    };
    f()
}

// ---------------------------------------------------------------------------
// Positive cases — every concrete example in §3.1
// ---------------------------------------------------------------------------

#[test]
fn s3_virtual_hosted_aws() {
    let url = parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/my-repo").unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        flags,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "my-bucket");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
    assert_eq!(addressing, S3Addressing::VirtualHosted);
    assert_eq!(flags, RemoteFlags::default());
}

#[test]
fn s3_path_style_aws() {
    let url = parse("s3+https://s3.us-west-2.amazonaws.com/my-bucket/my-repo").unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "my-bucket");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
    assert_eq!(addressing, S3Addressing::PathStyle);
}

#[test]
fn s3_local_minio() {
    // No env override needed — loopback is always allowed.
    with_allow_http_env(None, || {
        let url = parse("s3+http://localhost:9000/my-bucket/my-repo").unwrap();
        let RemoteUrl::S3 {
            bucket,
            prefix,
            addressing,
            ..
        } = url
        else {
            panic!("expected S3");
        };
        assert_eq!(bucket, "my-bucket");
        assert_eq!(prefix.as_deref(), Some("my-repo"));
        assert_eq!(addressing, S3Addressing::PathStyle);
    });
}

#[test]
fn s3_cloudflare_r2() {
    let url = parse("s3+https://acc-id1234.r2.cloudflarestorage.com/my-bucket/my-repo").unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "my-bucket");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
    assert_eq!(addressing, S3Addressing::PathStyle);
}

#[test]
fn s3_backblaze_b2() {
    let url = parse("s3+https://s3.us-west-002.backblazeb2.com/my-bucket/my-repo").unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "my-bucket");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
    assert_eq!(addressing, S3Addressing::PathStyle);
}

#[test]
fn azure_public_cloud() {
    let url = parse("az+https://myaccount.blob.core.windows.net/my-container/my-repo").unwrap();
    let RemoteUrl::Azure {
        account,
        container,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected Azure");
    };
    assert_eq!(account, "myaccount");
    assert_eq!(container, "my-container");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
    assert_eq!(addressing, AzureAddressing::VirtualHosted);
}

#[test]
fn azure_us_gov_cloud() {
    let url =
        parse("az+https://myaccount.blob.core.usgovcloudapi.net/my-container/my-repo").unwrap();
    let RemoteUrl::Azure {
        account,
        container,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected Azure");
    };
    assert_eq!(account, "myaccount");
    assert_eq!(container, "my-container");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
    assert_eq!(addressing, AzureAddressing::VirtualHosted);
}

#[test]
fn azure_azurite_path_style() {
    with_allow_http_env(None, || {
        let url = parse("az+http://127.0.0.1:10000/devstoreaccount1/my-container/my-repo").unwrap();
        let RemoteUrl::Azure {
            account,
            container,
            prefix,
            addressing,
            ..
        } = url
        else {
            panic!("expected Azure");
        };
        assert_eq!(account, "devstoreaccount1");
        assert_eq!(container, "my-container");
        assert_eq!(prefix.as_deref(), Some("my-repo"));
        assert_eq!(addressing, AzureAddressing::PathStyle);
    });
}

#[test]
fn s3_virtual_hosted_dotted_bucket_auto_detect() {
    // Pre-2018 AWS allowed `.` in bucket names. Auto-detection must
    // recognise the virtual-hosted shape and capture the full prefix —
    // not just the leftmost label — as the bucket.
    let url = parse("s3+https://bucketname.com.s3.us-west-2.amazonaws.com/repo").unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "bucketname.com");
    assert_eq!(prefix.as_deref(), Some("repo"));
    assert_eq!(addressing, S3Addressing::VirtualHosted);
}

#[test]
fn s3_virtual_hosted_dotted_bucket_explicit_flag() {
    // Same URL with `?addressing=virtual` set: the explicit flag must
    // not regress to the leftmost-label parse that silently dropped
    // bucket segments before the fix.
    let url = parse("s3+https://bucketname.com.s3.us-west-2.amazonaws.com/repo?addressing=virtual")
        .unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "bucketname.com");
    assert_eq!(prefix.as_deref(), Some("repo"));
    assert_eq!(addressing, S3Addressing::VirtualHosted);
}

#[test]
fn s3_legacy_hyphenated_with_dotted_bucket() {
    // Legacy `s3-<region>` hyphenated form combined with a dotted
    // bucket name.
    let url = parse("s3+https://bucketname.com.s3-us-west-2.amazonaws.com/repo").unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "bucketname.com");
    assert_eq!(prefix.as_deref(), Some("repo"));
    assert_eq!(addressing, S3Addressing::VirtualHosted);
}

#[test]
fn s3_virtual_hosted_short_dotted_bucket_no_longer_invalid() {
    // Before the fix, `my.dotted.s3.<region>.amazonaws.com` parsed as
    // the bucket "my" (length 2, fails `is_valid_bucket`). The full
    // prefix is now recovered.
    let url = parse("s3+https://my.dotted.s3.us-west-2.amazonaws.com/repo").unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "my.dotted");
    assert_eq!(prefix.as_deref(), Some("repo"));
    assert_eq!(addressing, S3Addressing::VirtualHosted);
}

#[test]
fn s3_path_style_dotted_bucket_still_works() {
    // Path-style URL pointing at a dotted bucket: bucket comes from
    // the path, not the host, and the existing extraction is
    // unaffected by the virtual-hosted change.
    let url = parse("s3+https://s3.us-west-2.amazonaws.com/my.dotted.bucket/repo").unwrap();
    let RemoteUrl::S3 {
        bucket,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "my.dotted.bucket");
    assert_eq!(prefix.as_deref(), Some("repo"));
    assert_eq!(addressing, S3Addressing::PathStyle);
}

#[test]
fn s3_zip_flag() {
    let url = parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/my-repo?zip=1").unwrap();
    assert!(url.flags().zip);
    assert_eq!(url.flags().profile, None);
}

#[test]
fn s3_all_flags() {
    let url = parse(
        "s3+https://my-bucket.s3.us-west-2.amazonaws.com/my-repo\
         ?zip=true&profile=prod&region=us-east-1",
    )
    .unwrap();
    assert!(url.flags().zip);
    assert_eq!(url.flags().profile.as_deref(), Some("prod"));
    assert_eq!(url.flags().region.as_deref(), Some("us-east-1"));
}

#[test]
fn azure_credential_flag() {
    let url = parse(
        "az+https://myaccount.blob.core.windows.net/my-container/repo\
         ?credential=ci-cd",
    )
    .unwrap();
    assert_eq!(url.flags().credential.as_deref(), Some("ci-cd"));
}

#[test]
fn missing_prefix_is_allowed_virtual() {
    let url = parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com").unwrap();
    let RemoteUrl::S3 { bucket, prefix, .. } = url else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "my-bucket");
    assert_eq!(prefix, None);
}

#[test]
fn missing_prefix_is_allowed_path_style() {
    let url = parse("s3+https://s3.us-west-2.amazonaws.com/my-bucket").unwrap();
    let RemoteUrl::S3 { bucket, prefix, .. } = url else {
        panic!("expected S3");
    };
    assert_eq!(bucket, "my-bucket");
    assert_eq!(prefix, None);
}

#[test]
fn trailing_slash_on_prefix_is_stripped() {
    let url = parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/my-repo/").unwrap();
    assert_eq!(url.prefix(), Some("my-repo"));
}

#[test]
fn nested_prefix_is_joined() {
    let url = parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/team/repo").unwrap();
    assert_eq!(url.prefix(), Some("team/repo"));
}

// ---------------------------------------------------------------------------
// Addressing override (§3.4)
// ---------------------------------------------------------------------------

#[test]
fn addressing_override_forces_path_on_virtual_host() {
    // Hostname looks virtual-hosted (`<bucket>.s3.…`) but we override
    // to path-style; the first hostname label is no longer treated as
    // a bucket and the first path segment becomes the bucket.
    let url =
        parse("s3+https://example.s3.us-west-2.amazonaws.com/my-bucket/my-repo?addressing=path")
            .unwrap();
    let RemoteUrl::S3 {
        bucket,
        addressing,
        prefix,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(addressing, S3Addressing::PathStyle);
    assert_eq!(bucket, "my-bucket");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
}

#[test]
fn addressing_override_forces_virtual_on_path_host() {
    // Use a hostname that doesn't match the `s3` heuristic but the
    // user knows the endpoint follows a virtual-hosted convention.
    let url = parse("s3+https://my-bucket.minio.example.com/my-repo?addressing=virtual").unwrap();
    let RemoteUrl::S3 {
        bucket,
        addressing,
        prefix,
        ..
    } = url
    else {
        panic!("expected S3");
    };
    assert_eq!(addressing, S3Addressing::VirtualHosted);
    assert_eq!(bucket, "my-bucket");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
}

#[test]
fn azure_addressing_override_path() {
    let url = parse(
        "az+https://myaccount.blob.core.windows.net/myacct1/my-container/my-repo\
         ?addressing=path",
    )
    .unwrap();
    let RemoteUrl::Azure {
        account,
        container,
        prefix,
        addressing,
        ..
    } = url
    else {
        panic!("expected Azure");
    };
    assert_eq!(addressing, AzureAddressing::PathStyle);
    assert_eq!(account, "myacct1");
    assert_eq!(container, "my-container");
    assert_eq!(prefix.as_deref(), Some("my-repo"));
}

// ---------------------------------------------------------------------------
// Negative cases — §3.5
// ---------------------------------------------------------------------------

#[test]
fn rejects_https_without_backend_prefix() {
    let err = parse("https://my-bucket.s3.us-west-2.amazonaws.com/my-repo").unwrap_err();
    assert!(matches!(err, ParseError::UnsupportedScheme(s) if s == "https"));
}

#[test]
fn rejects_ftp() {
    let err = parse("ftp://example.com/").unwrap_err();
    assert!(matches!(err, ParseError::UnsupportedScheme(s) if s == "ftp"));
}

#[test]
fn rejects_cleartext_http_to_non_loopback_without_env() {
    with_allow_http_env(None, || {
        let err = parse("s3+http://example.com/my-bucket/my-repo").unwrap_err();
        assert!(matches!(err, ParseError::CleartextHttpForbidden { .. }));
    });
}

#[test]
fn allows_cleartext_http_to_non_loopback_with_env() {
    with_allow_http_env(Some("1"), || {
        let url = parse("s3+http://example.com/my-bucket/my-repo").unwrap();
        let RemoteUrl::S3 { bucket, .. } = url else {
            panic!("expected S3");
        };
        assert_eq!(bucket, "my-bucket");
    });
}

/// Per-value matrix for the boolean vocabulary on `ENV_ALLOW_HTTP`.
/// Issue #187: the env-var read shares its parser with `parse_bool_flag`
/// so `ALLOW_HTTP=true`, `ALLOW_HTTP=yes`, `ALLOW_HTTP=ON`, … all open
/// the gate just like `?zip=true` accepts the same vocabulary on the
/// URL surface.
#[test]
fn env_allow_http_accepts_every_truthy_token() {
    for value in [
        "1", "true", "TRUE", "True", "yes", "Yes", "YES", "on", "On", "ON",
    ] {
        with_allow_http_env(Some(value), || {
            let url = parse("s3+http://example.com/my-bucket/my-repo")
                .unwrap_or_else(|err| panic!("expected `{value}` to open the gate, got {err:?}"));
            let RemoteUrl::S3 { bucket, .. } = url else {
                panic!("expected S3");
            };
            assert_eq!(bucket, "my-bucket");
        });
    }
}

/// Per-value matrix for falsy / unrecognised env-var values. These
/// must leave the gate closed — fail-safe is "no cleartext".
#[test]
fn env_allow_http_rejects_falsy_and_unknown_tokens() {
    // Falsy tokens recognised by the helper, plus arbitrary junk
    // (`maybe`, ` `, `2`) and the empty string. Every case must
    // continue to refuse cleartext against a non-loopback host.
    for value in [
        "0", "false", "FALSE", "False", "no", "No", "NO", "off", "Off", "OFF", "", " ", "maybe",
        "2", "-1",
    ] {
        with_allow_http_env(Some(value), || {
            let err = parse("s3+http://example.com/my-bucket/my-repo")
                .err()
                .unwrap_or_else(|| panic!("expected `{value}` to keep the gate closed"));
            assert!(
                matches!(err, ParseError::CleartextHttpForbidden { .. }),
                "expected CleartextHttpForbidden for `{value}`, got {err:?}",
            );
        });
    }
}

#[test]
fn ipv6_loopback_allows_cleartext() {
    with_allow_http_env(None, || {
        let url = parse("s3+http://[::1]:9000/my-bucket/my-repo").unwrap();
        let RemoteUrl::S3 { bucket, .. } = url else {
            panic!("expected S3");
        };
        assert_eq!(bucket, "my-bucket");
    });
}

#[test]
fn rejects_uppercase_bucket() {
    let err = parse("s3+https://s3.us-west-2.amazonaws.com/MyBucket/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidBucket(s) if s == "MyBucket"));
}

#[test]
fn rejects_too_short_bucket() {
    let err = parse("s3+https://s3.us-west-2.amazonaws.com/ab/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidBucket(s) if s == "ab"));
}

#[test]
fn rejects_bucket_starting_with_dash() {
    let err = parse("s3+https://s3.us-west-2.amazonaws.com/-bucket/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidBucket(s) if s == "-bucket"));
}

#[test]
fn rejects_missing_bucket() {
    let err = parse("s3+https://s3.us-west-2.amazonaws.com/").unwrap_err();
    assert!(matches!(err, ParseError::MissingBucket));
}

#[test]
fn rejects_missing_container() {
    let url = "az+https://myaccount.blob.core.windows.net/";
    let err = parse(url).unwrap_err();
    assert!(matches!(err, ParseError::MissingContainer));
}

#[test]
fn rejects_missing_account_path_style() {
    with_allow_http_env(None, || {
        let err = parse("az+http://127.0.0.1:10000/").unwrap_err();
        assert!(matches!(err, ParseError::MissingAccount));
    });
}

#[test]
fn rejects_invalid_account_charset() {
    let err = parse("az+https://has-hyphen.blob.core.windows.net/my-container/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidAccount(s) if s == "has-hyphen"));
}

#[test]
fn rejects_invalid_container_charset() {
    let err = parse("az+https://myaccount.blob.core.windows.net/UPPER/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidContainer(s) if s == "UPPER"));
}

#[test]
fn rejects_forbidden_bucket_prefixes_path_style() {
    for bad in ["xn--abcdef", "sthree-foo", "amzn-s3-demo-bucket"] {
        let url = format!("s3+https://s3.us-west-2.amazonaws.com/{bad}/repo");
        let err = parse(&url).unwrap_err();
        assert!(
            matches!(&err, ParseError::InvalidBucket(s) if s == bad),
            "expected InvalidBucket({bad}), got {err:?}"
        );
    }
}

#[test]
fn rejects_forbidden_bucket_suffixes_path_style() {
    for bad in [
        "my-bucket-s3alias",
        "my-bucket--ol-s3",
        "my-bucket--x-s3",
        "my-bucket--table-s3",
        "ab.mrap",
    ] {
        let url = format!("s3+https://s3.us-west-2.amazonaws.com/{bad}/repo");
        let err = parse(&url).unwrap_err();
        assert!(
            matches!(&err, ParseError::InvalidBucket(s) if s == bad),
            "expected InvalidBucket({bad}), got {err:?}"
        );
    }
}

#[test]
fn rejects_bucket_formatted_as_ipv4() {
    let err = parse("s3+https://s3.us-west-2.amazonaws.com/192.168.1.1/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidBucket(s) if s == "192.168.1.1"));
}

#[test]
fn rejects_bucket_with_consecutive_periods() {
    let err = parse("s3+https://s3.us-west-2.amazonaws.com/ab..cd/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidBucket(s) if s == "ab..cd"));
}

#[test]
fn rejects_bucket_ending_with_dash() {
    let err = parse("s3+https://s3.us-west-2.amazonaws.com/bucket-/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidBucket(s) if s == "bucket-"));
}

#[test]
fn rejects_container_with_leading_dash() {
    let err = parse("az+https://myaccount.blob.core.windows.net/-leading/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidContainer(s) if s == "-leading"));
}

#[test]
fn rejects_container_with_trailing_dash() {
    let err = parse("az+https://myaccount.blob.core.windows.net/trailing-/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidContainer(s) if s == "trailing-"));
}

#[test]
fn rejects_container_with_consecutive_dashes() {
    let err = parse("az+https://myaccount.blob.core.windows.net/foo--bar/repo").unwrap_err();
    assert!(matches!(err, ParseError::InvalidContainer(s) if s == "foo--bar"));
}

#[test]
fn rejects_unknown_flag() {
    let err = parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?bogus=1").unwrap_err();
    assert!(matches!(err, ParseError::UnknownFlag(s) if s == "bogus"));
}

#[test]
fn rejects_invalid_zip_value() {
    // `?zip=maybe` is outside the accepted boolean vocabulary
    // (`1|true|yes|on` / `0|false|no|off`, case-insensitive); the URL
    // surface must surface `InvalidFlagValue` so typos are caught at
    // parse time rather than silently treated as "off".
    let err = parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?zip=maybe").unwrap_err();
    assert!(matches!(
        err,
        ParseError::InvalidFlagValue { name, value } if name == "zip" && value == "maybe"
    ));
}

#[test]
fn rejects_unknown_addressing() {
    let err =
        parse("s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?addressing=weird").unwrap_err();
    assert!(matches!(err, ParseError::UnknownAddressing(s) if s == "weird"));
}

#[test]
fn rejects_empty_input() {
    assert_eq!(parse(""), Err(ParseError::Empty));
    assert_eq!(parse("   "), Err(ParseError::Empty));
}

// ---------------------------------------------------------------------------
// Display round-trip
// ---------------------------------------------------------------------------

#[test]
fn display_round_trip_concrete() {
    let inputs = [
        "s3+https://my-bucket.s3.us-west-2.amazonaws.com/my-repo",
        "s3+https://s3.us-west-2.amazonaws.com/my-bucket/my-repo",
        "s3+https://my-bucket.s3.us-west-2.amazonaws.com/my-repo?zip=1",
        "az+https://myaccount.blob.core.windows.net/my-container/my-repo",
    ];
    for input in inputs {
        let parsed = parse(input).expect(input);
        let displayed = parsed.to_string();
        let reparsed = parse(&displayed).expect(&displayed);
        assert_eq!(parsed, reparsed, "round-trip mismatch for `{input}`");
    }
}

// ---------------------------------------------------------------------------
// Property-based round-trip
// ---------------------------------------------------------------------------

/// AWS-reserved bucket-name prefixes mirrored from `src/url.rs` so the
/// proptest generator can avoid emitting them. Kept independent of the
/// production constants on purpose: the proptest is meant to exercise
/// the production validator, not borrow its definitions.
const FORBIDDEN_BUCKET_PREFIXES: &[&str] = &["xn--", "sthree-", "amzn-s3-demo-"];

/// AWS-reserved bucket-name suffixes (see comment above).
const FORBIDDEN_BUCKET_SUFFIXES: &[&str] = &["-s3alias", "--ol-s3", "--x-s3", "--table-s3"];

/// S3 bucket strategy that excludes `.` so the bucket is a single
/// hostname label, requires the first and last bytes to be alphanumeric
/// per AWS rules, and filters out the AWS reserved prefixes/suffixes so
/// every generated value is a valid AWS bucket name.
fn arb_bucket() -> impl Strategy<Value = String> {
    proptest::string::string_regex("[a-z0-9][a-z0-9-]{1,28}[a-z0-9]")
        .expect("valid bucket regex")
        .prop_filter("excludes AWS reserved prefix/suffix", |s| {
            !FORBIDDEN_BUCKET_PREFIXES.iter().any(|p| s.starts_with(p))
                && !FORBIDDEN_BUCKET_SUFFIXES.iter().any(|p| s.ends_with(p))
        })
}

/// True iff `s` looks like a dotted-quad IPv4 address — four
/// numeric-only segments separated by `.`. AWS rejects bucket names
/// with this shape; the proptest generator filters them out so every
/// generated value is a valid bucket.
fn looks_like_ipv4(s: &str) -> bool {
    let mut parts = s.split('.');
    let segs = [parts.next(), parts.next(), parts.next(), parts.next()];
    parts.next().is_none()
        && segs
            .iter()
            .all(|p| matches!(p, Some(seg) if !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit())))
}

/// Dotted-bucket strategy: two or more dot-separated segments, each
/// alphanumeric only (so the bucket cannot start/end with a dash or
/// produce consecutive periods). The full string must satisfy
/// `is_valid_bucket`'s 3..=63 length, charset, IPv4-shape, and
/// reserved-prefix/suffix rules.
fn arb_dotted_bucket() -> impl Strategy<Value = String> {
    proptest::collection::vec(
        proptest::string::string_regex("[a-z0-9]{1,8}").expect("dotted-bucket segment regex"),
        2..=4,
    )
    .prop_map(|parts| parts.join("."))
    .prop_filter("valid AWS bucket name", |s| {
        (3..=63).contains(&s.len())
            && !FORBIDDEN_BUCKET_PREFIXES.iter().any(|p| s.starts_with(p))
            && !FORBIDDEN_BUCKET_SUFFIXES.iter().any(|p| s.ends_with(p))
            && !looks_like_ipv4(s)
    })
}

fn arb_account() -> impl Strategy<Value = String> {
    proptest::string::string_regex("[a-z0-9]{3,24}").expect("valid account regex")
}

/// Azure container strategy: alphanumeric bookends, no consecutive
/// hyphens, lowercase only.
fn arb_container() -> impl Strategy<Value = String> {
    proptest::string::string_regex("[a-z0-9][a-z0-9-]{1,28}[a-z0-9]")
        .expect("valid container regex")
        .prop_filter("no consecutive hyphens", |s| !s.contains("--"))
}

fn arb_prefix() -> impl Strategy<Value = Option<String>> {
    prop_oneof![
        Just(None),
        proptest::string::string_regex("[a-z0-9][a-z0-9_-]{0,16}")
            .expect("prefix regex")
            .prop_map(Some),
        (
            proptest::string::string_regex("[a-z0-9]{1,8}").expect("seg regex"),
            proptest::string::string_regex("[a-z0-9]{1,8}").expect("seg regex"),
        )
            .prop_map(|(a, b)| Some(format!("{a}/{b}"))),
    ]
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(256))]

    #[test]
    fn s3_virtual_hosted_round_trip(
        bucket in arb_bucket(),
        prefix in arb_prefix(),
        zip in any::<bool>(),
    ) {
        let prefix_part = prefix.as_deref().map_or(String::new(), |p| format!("/{p}"));
        let zip_part = if zip { "?zip=1" } else { "" };
        let input = format!(
            "s3+https://{bucket}.s3.us-west-2.amazonaws.com{prefix_part}{zip_part}"
        );
        let parsed = parse(&input).expect("valid input");
        let displayed = parsed.to_string();
        let reparsed = parse(&displayed).expect("display output should re-parse");
        prop_assert_eq!(parsed, reparsed);
    }

    #[test]
    fn s3_path_style_round_trip(
        bucket in arb_bucket(),
        prefix in arb_prefix(),
    ) {
        let prefix_part = prefix.as_deref().map_or(String::new(), |p| format!("/{p}"));
        let input = format!("s3+https://s3.us-west-2.amazonaws.com/{bucket}{prefix_part}");
        let parsed = parse(&input).expect("valid input");
        let reparsed = parse(&parsed.to_string()).expect("display output should re-parse");
        prop_assert_eq!(parsed, reparsed);
    }

    #[test]
    fn s3_virtual_hosted_dotted_bucket_round_trip(
        bucket in arb_dotted_bucket(),
        prefix in arb_prefix(),
    ) {
        let prefix_part = prefix.as_deref().map_or(String::new(), |p| format!("/{p}"));
        let input = format!(
            "s3+https://{bucket}.s3.us-west-2.amazonaws.com{prefix_part}"
        );
        let parsed = parse(&input).expect("valid input");
        let RemoteUrl::S3 { bucket: parsed_bucket, addressing, .. } = &parsed else {
            panic!("expected S3");
        };
        prop_assert_eq!(parsed_bucket, &bucket);
        prop_assert_eq!(*addressing, S3Addressing::VirtualHosted);
        let reparsed = parse(&parsed.to_string()).expect("display output should re-parse");
        prop_assert_eq!(parsed, reparsed);
    }

    #[test]
    fn azure_virtual_hosted_round_trip(
        account in arb_account(),
        container in arb_container(),
        prefix in arb_prefix(),
    ) {
        let prefix_part = prefix.as_deref().map_or(String::new(), |p| format!("/{p}"));
        let input = format!(
            "az+https://{account}.blob.core.windows.net/{container}{prefix_part}"
        );
        let parsed = parse(&input).expect("valid input");
        let reparsed = parse(&parsed.to_string()).expect("display output should re-parse");
        prop_assert_eq!(parsed, reparsed);
    }

    #[test]
    fn azure_path_style_round_trip(
        account in arb_account(),
        container in arb_container(),
        prefix in arb_prefix(),
    ) {
        // Azurite-style: loopback host, path-style addressing. No env
        // mutation needed because 127.0.0.1 is always allowed.
        let prefix_part = prefix.as_deref().map_or(String::new(), |p| format!("/{p}"));
        let input = format!(
            "az+http://127.0.0.1:10000/{account}/{container}{prefix_part}"
        );
        let parsed = parse(&input).expect("valid input");
        let reparsed = parse(&parsed.to_string()).expect("display output should re-parse");
        prop_assert_eq!(parsed, reparsed);
    }
}