verify-trust 0.7.0

CI verifier for VGI: checks that every commit in a git range is signed by a DID the community's Trust Registry currently authorizes.
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
//! The TRQP resource a run is checked under, and the form it is written in.
//!
//! Resources are moving from the bare `owner/repo` slug (`legacy`) to a
//! forge-qualified name (`qualified`):
//!
//! ```text
//! resource   = forge-host "/" owner [ "/" repo ]
//! forge-host = the forge's lowercased host: github.com, a GHES host,
//!              codeberg.org, git.example.org
//! ```
//!
//! `acme/widgets` alone names no forge, so it cannot tell `github.com/acme`
//! from `codeberg.org/acme` — which may belong to different people. The
//! qualified form makes the forge explicit, never assumed.
//!
//! The grammar itself is [`vgi_core::normalize_resource`], shared with the
//! VTC's registry projection and the forge adapters, so the resource this
//! run queries is byte-for-byte the one a grant was written under. This
//! module adds only what is verify-trust's own: the flag names in messages
//! and a fix suggested from the CI environment.
//!
//! The change is staged: `qualified` is the default (it was `legacy` until
//! 0.7.0); `legacy`, which takes `owner/repo` as given, remains for one more
//! release, and is then removed (#109). Registry grants must be written in the
//! form the run uses — the VTC's projection writes only the qualified form.
//!
//! [`CiEnv`] is the seam that knows how each CI system names the repository
//! under test. Anything it cannot detect falls back to an explicit
//! `--resource`.

use anyhow::{Context, Result, bail};
use vgi_core::{ResourceErrorKind, normalize_resource, resource_contains};

/// Which form the TRQP resource is written in.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum ResourceFormat {
    /// `owner/repo`, taken as given — the pre-qualification behaviour, kept
    /// for one release after the default moved to `qualified`.
    Legacy,
    /// `<forge-host>/owner/repo`, validated and lowercased. The default.
    #[default]
    Qualified,
}

/// What the CI environment says about the repository under test.
///
/// A snapshot of the variables rather than live reads, so the derivation can
/// be tested without touching the process environment.
#[derive(Debug, Clone, Default)]
pub struct CiEnv {
    /// `FORGEJO_SERVER_URL`: the instance's base URL on Forgejo Actions.
    pub forgejo_server_url: Option<String>,
    /// `FORGEJO_REPOSITORY`: `owner/repo` on Forgejo Actions.
    pub forgejo_repository: Option<String>,
    /// `GITHUB_SERVER_URL`: `https://github.com`, or a GHES host. Forgejo
    /// Actions sets it too, to the instance's URL.
    pub github_server_url: Option<String>,
    /// `GITHUB_REPOSITORY`: `owner/repo`.
    pub github_repository: Option<String>,
}

impl CiEnv {
    /// Read the variables from the process environment.
    pub fn from_env() -> Self {
        Self::from_lookup(|name| std::env::var(name).ok())
    }

    /// Read the variables through `lookup` (a name → value function).
    pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Self {
        Self {
            forgejo_server_url: lookup("FORGEJO_SERVER_URL"),
            forgejo_repository: lookup("FORGEJO_REPOSITORY"),
            github_server_url: lookup("GITHUB_SERVER_URL"),
            github_repository: lookup("GITHUB_REPOSITORY"),
        }
    }

    /// The server URL / repository pair to derive from: Forgejo's names when
    /// both are set, else GitHub's. A pair is never mixed across systems.
    fn detected(&self) -> Option<(&'static str, &str, &str)> {
        fn pair<'a>(
            url: &'a Option<String>,
            repo: &'a Option<String>,
        ) -> Option<(&'a str, &'a str)> {
            let url = url.as_deref().filter(|v| !v.is_empty())?;
            let repo = repo.as_deref().filter(|v| !v.is_empty())?;
            Some((url, repo))
        }
        pair(&self.forgejo_server_url, &self.forgejo_repository)
            .map(|(url, repo)| ("FORGEJO_SERVER_URL + FORGEJO_REPOSITORY", url, repo))
            .or_else(|| {
                pair(&self.github_server_url, &self.github_repository)
                    .map(|(url, repo)| ("GITHUB_SERVER_URL + GITHUB_REPOSITORY", url, repo))
            })
    }

    /// The forge host this run is on, when the environment names one. Used to
    /// suggest a fix for an unqualified `--resource`.
    pub fn forge_host(&self) -> Option<String> {
        [&self.forgejo_server_url, &self.github_server_url]
            .into_iter()
            .flatten()
            .find_map(|url| forge_host_of(url))
    }

    /// The qualified resource for the repository under test, or `None` when
    /// this is not a CI system we recognise.
    pub fn qualified_resource(&self) -> Result<Option<String>> {
        let Some((source, url, repo)) = self.detected() else {
            return Ok(None);
        };
        let host = forge_host_of(url)
            .with_context(|| format!("cannot read a forge host from {source} (`{url}`)"))?;
        normalize_qualified(
            &format!("resource derived from {source}"),
            &format!("{host}/{repo}"),
            self,
        )
        .map(Some)
    }
}

/// The lowercased host of a forge's base URL: scheme, credentials, port and
/// path dropped.
///
/// The port is dropped on purpose. A resource names a forge, not a socket, and
/// `:` has no place in the grammar; an instance served on a non-default port is
/// still identified by its host. Two forges on one host differing only by port
/// would share resources — an unusual deployment that should pass `--resource`
/// explicitly.
pub fn forge_host_of(url: &str) -> Option<String> {
    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
    let host_port = authority
        .rsplit_once('@')
        .map_or(authority, |(_, host)| host);
    let host = host_port.split(':').next().unwrap_or_default();
    (!host.is_empty()).then(|| host.to_ascii_lowercase())
}

/// Validate a qualified resource and return it normalised (lowercased).
///
/// `what` names the value in errors (`--resource`, `--fallback-resource`, or
/// where a derived one came from). Every rejection says how to fix it; an
/// unqualified `owner/repo` gets the forge host this run is on suggested.
pub fn normalize_qualified(what: &str, value: &str, ci: &CiEnv) -> Result<String> {
    match normalize_resource(value) {
        Ok(canonical) => Ok(canonical),
        Err(e) if *e.kind() == ResourceErrorKind::MissingForgeHost => {
            let bare = value.trim_matches('/').to_ascii_lowercase();
            let fix = match ci.forge_host() {
                Some(detected) => format!("did you mean `{detected}/{bare}`?"),
                None => format!("prefix the forge host, e.g. `github.com/{bare}`"),
            };
            bail!(
                "{what} `{value}` is not forge-qualified (--resource-format qualified expects \
                 `<forge-host>/<owner>[/<repo>]`); {fix}"
            )
        }
        Err(e) => bail!("{}", e.describe(what)),
    }
}

/// Check a legacy resource's shape: `owner` or `owner/repo`, each segment
/// ASCII letters, digits, `.`, `_` or `-` — the qualified grammar's character
/// set, with case kept, since legacy values are passed through untouched.
///
/// Before this the legacy arm took any string at all as the one input that
/// scopes the registry query: an empty `--resource`, a whitespace-padded one,
/// or one with a control character went to the registry verbatim (SEC-4045 /
/// VGI-03). Those failed closed, as no grant matches them — but they failed as
/// `unauthorized`, pointing the operator at the registry instead of the typo,
/// which is how a fallback gets widened to make a check go green.
fn check_legacy(what: &str, value: &str) -> Result<()> {
    if value.trim().is_empty() {
        bail!("{what} is empty; pass `owner/repo` (or the bare owner)");
    }
    if let Some(c) = value.chars().find(|c| c.is_whitespace() || c.is_control()) {
        bail!(
            "{what} `{}` contains {}; pass `owner/repo` (or the bare owner) with nothing \
             around it",
            value.escape_debug(),
            if c.is_whitespace() {
                "whitespace"
            } else {
                "a control character"
            }
        );
    }
    let segments: Vec<&str> = value.split('/').collect();
    if segments.len() > 2
        || segments
            .iter()
            .any(|s| s.is_empty() || *s == "." || *s == "..")
    {
        bail!("{what} `{value}` is not `owner/repo` or a bare owner");
    }
    if let Some(c) = value
        .chars()
        .find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-')))
    {
        bail!("{what} `{value}` contains `{c}`, which no owner or repository name can");
    }
    Ok(())
}

/// The primary and fallback resources a run queries, in the chosen form.
///
/// `legacy` is the pre-qualification behaviour: values pass through
/// untouched, and the primary defaults to `$GITHUB_REPOSITORY`. Both must be
/// shaped as an owner or `owner/repo` ([`check_legacy`]); a forge-qualified
/// fallback is refused, since it would mix the two forms in one run, and so is
/// a fallback that is neither the primary's owner nor the primary itself —
/// the legacy counterpart of the containment rule below. `qualified` validates and lowercases explicit values, derives the
/// default from [`CiEnv`], and requires the fallback to **contain** the
/// primary — the namespace it sits in (`github.com/acme` for
/// `github.com/acme/widgets`), or the primary itself. A fallback naming
/// another owner or another forge is refused, so a grant there can never
/// authorize this repository.
pub fn select_resources(
    format: ResourceFormat,
    resource: Option<String>,
    fallback_resource: Option<String>,
    ci: &CiEnv,
) -> Result<(String, Option<String>)> {
    // One form per run, never both. Querying `github.com/acme/widgets` and
    // then `acme/widgets` would accept a grant under either, so during the
    // migration window — when the VTC writes both — a stale or hand-issued
    // legacy grant would silently widen who may sign.
    match format {
        ResourceFormat::Legacy => {
            let resource = resource
                .or_else(|| ci.github_repository.clone())
                .context("--resource is required (or set GITHUB_REPOSITORY)")?;
            check_legacy("--resource", &resource)?;
            if let Some(fallback) = &fallback_resource {
                if let Ok(qualified) = normalize_resource(fallback) {
                    bail!(
                        "--fallback-resource `{fallback}` is forge-qualified (`{qualified}`) but \
                         --resource-format is legacy; one run uses one form: pass \
                         --resource-format qualified, or the bare owner"
                    );
                }
                check_legacy("--fallback-resource", fallback)?;
                // Owners and repositories are case-insensitive on the forges,
                // so containment is too; the values themselves stay untouched.
                let owner = resource.split('/').next().unwrap_or_default();
                if !fallback.eq_ignore_ascii_case(owner)
                    && !fallback.eq_ignore_ascii_case(&resource)
                {
                    bail!(
                        "--fallback-resource `{fallback}` is not the owner of --resource \
                         `{resource}`: the fallback must be the namespace the repository sits \
                         in (`{owner}`), never another owner's"
                    );
                }
            }
            Ok((resource, fallback_resource))
        }
        ResourceFormat::Qualified => {
            let resource = match resource {
                Some(value) => normalize_qualified("--resource", &value, ci)?,
                None => ci.qualified_resource()?.context(
                    "--resource is required: no CI environment detected to derive it from \
                     (FORGEJO_SERVER_URL + FORGEJO_REPOSITORY, or GITHUB_SERVER_URL + \
                     GITHUB_REPOSITORY); pass e.g. `--resource github.com/acme/widgets`",
                )?,
            };
            let fallback = fallback_resource
                .map(|value| normalize_qualified("--fallback-resource", &value, ci))
                .transpose()?;
            if let Some(fallback) = &fallback
                && !resource_contains(fallback, &resource)
            {
                bail!(
                    "--fallback-resource `{fallback}` does not contain --resource `{resource}`: \
                     the fallback must be the namespace the repository sits in (e.g. `{}`), \
                     never another owner's or another forge's",
                    namespace_of(&resource)
                );
            }
            Ok((resource, fallback))
        }
    }
}

/// `host/owner` of a normalised qualified resource (itself when it is one).
fn namespace_of(resource: &str) -> String {
    resource
        .splitn(3, '/')
        .take(2)
        .collect::<Vec<_>>()
        .join("/")
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;

    fn ci(vars: &[(&str, &str)]) -> CiEnv {
        CiEnv::from_lookup(|name| {
            vars.iter()
                .find(|(k, _)| *k == name)
                .map(|(_, v)| (*v).to_string())
        })
    }

    fn github() -> CiEnv {
        ci(&[
            ("GITHUB_SERVER_URL", "https://github.com"),
            ("GITHUB_REPOSITORY", "Acme/Widgets"),
        ])
    }

    fn err(what: &str, value: &str, ci: &CiEnv) -> String {
        normalize_qualified(what, value, ci)
            .unwrap_err()
            .to_string()
    }

    // --- CiEnv derivation ----------------------------------------------------

    #[test]
    fn github_actions_yields_the_lowercased_github_resource() {
        assert_eq!(
            github().qualified_resource().unwrap().as_deref(),
            Some("github.com/acme/widgets")
        );
    }

    #[test]
    fn an_enterprise_server_gets_its_own_host() {
        let env = ci(&[
            ("GITHUB_SERVER_URL", "https://GHE.Example.com/"),
            ("GITHUB_REPOSITORY", "acme/widgets"),
        ]);
        assert_eq!(
            env.qualified_resource().unwrap().as_deref(),
            Some("ghe.example.com/acme/widgets")
        );
    }

    #[test]
    fn forgejo_names_take_precedence_over_the_github_ones() {
        let env = ci(&[
            ("FORGEJO_SERVER_URL", "https://codeberg.org"),
            ("FORGEJO_REPOSITORY", "acme/widgets"),
            ("GITHUB_SERVER_URL", "https://github.com"),
            ("GITHUB_REPOSITORY", "other/thing"),
        ]);
        assert_eq!(
            env.qualified_resource().unwrap().as_deref(),
            Some("codeberg.org/acme/widgets")
        );
    }

    #[test]
    fn a_half_set_forgejo_pair_falls_back_to_github_names() {
        let env = ci(&[
            ("FORGEJO_SERVER_URL", "https://git.example.org"),
            ("GITHUB_SERVER_URL", "https://git.example.org"),
            ("GITHUB_REPOSITORY", "acme/widgets"),
        ]);
        assert_eq!(
            env.qualified_resource().unwrap().as_deref(),
            Some("git.example.org/acme/widgets")
        );
    }

    #[test]
    fn a_port_is_not_part_of_the_forge_host() {
        let env = ci(&[
            (
                "FORGEJO_SERVER_URL",
                "http://user@git.example.org:3000/forgejo",
            ),
            ("FORGEJO_REPOSITORY", "acme/widgets"),
        ]);
        assert_eq!(
            env.qualified_resource().unwrap().as_deref(),
            Some("git.example.org/acme/widgets")
        );
        assert_eq!(
            forge_host_of("http://localhost:3000").as_deref(),
            Some("localhost")
        );
    }

    #[test]
    fn no_ci_environment_derives_nothing() {
        assert_eq!(CiEnv::default().qualified_resource().unwrap(), None);
        // A repository with no server URL is not enough to name the forge.
        let env = ci(&[("GITHUB_REPOSITORY", "acme/widgets")]);
        assert_eq!(env.qualified_resource().unwrap(), None);
        let env = ci(&[
            ("GITHUB_SERVER_URL", ""),
            ("GITHUB_REPOSITORY", "acme/widgets"),
        ]);
        assert_eq!(env.qualified_resource().unwrap(), None);
    }

    // --- validation and normalisation ----------------------------------------

    #[test]
    fn qualified_values_are_accepted_and_lowercased() {
        let none = CiEnv::default();
        for (value, expected) in [
            ("GitHub.com/Acme/Widgets", "github.com/acme/widgets"),
            ("github.com/acme", "github.com/acme"),
            ("codeberg.org/acme/widgets", "codeberg.org/acme/widgets"),
            ("localhost/acme/widgets", "localhost/acme/widgets"),
            (
                "gitlab.example.org/group/sub/project",
                "gitlab.example.org/group/sub/project",
            ),
        ] {
            assert_eq!(
                normalize_qualified("--resource", value, &none).unwrap(),
                expected
            );
        }
    }

    #[test]
    fn an_unqualified_value_suggests_the_detected_forge() {
        let message = err("--resource", "Acme/Widgets", &github());
        assert!(message.contains("not forge-qualified"), "{message}");
        assert!(
            message.contains("did you mean `github.com/acme/widgets`?"),
            "{message}"
        );

        let message = err("--fallback-resource", "acme", &github());
        assert!(
            message.starts_with("--fallback-resource `acme`"),
            "{message}"
        );
        assert!(
            message.contains("did you mean `github.com/acme`?"),
            "{message}"
        );
    }

    #[test]
    fn an_unqualified_value_outside_ci_suggests_a_prefix() {
        let message = err("--resource", "acme/widgets", &CiEnv::default());
        assert!(
            message.contains("prefix the forge host, e.g. `github.com/acme/widgets`"),
            "{message}"
        );
    }

    #[test]
    fn malformed_values_are_rejected_with_a_fix() {
        let none = CiEnv::default();
        let cases = [
            ("", "is empty"),
            ("github.com/acme widgets", "whitespace"),
            (
                "https://github.com/acme/widgets.git",
                "did you mean `github.com/acme/widgets`?",
            ),
            (
                "/github.com/acme/widgets",
                "did you mean `github.com/acme/widgets`?",
            ),
            (
                "github.com/acme/widgets/",
                "did you mean `github.com/acme/widgets`?",
            ),
            ("github.com//widgets", "empty path segment"),
            ("github.com/acme/../other", "`.` or `..` segment"),
            ("github.com/./acme", "`.` or `..` segment"),
            (
                "git.example.org:3000/acme",
                "did you mean `git.example.org/acme`?",
            ),
            ("github.com", "names a forge but no owner"),
            ("github..com/acme", "invalid forge host"),
            ("github.com/acme@x", "may only contain"),
        ];
        for (value, expected) in cases {
            let message = err("--resource", value, &none);
            assert!(message.contains(expected), "{value:?}: {message}");
        }
    }

    // --- mode selection --------------------------------------------------------

    /// #109: the default is the forge-qualified form, derived from the CI
    /// environment — the form the VTC writes grants in.
    #[test]
    fn qualified_is_the_default() {
        assert_eq!(ResourceFormat::default(), ResourceFormat::Qualified);
        assert_eq!(
            select_resources(ResourceFormat::default(), None, None, &github()).unwrap(),
            ("github.com/acme/widgets".to_string(), None)
        );
    }

    #[test]
    fn legacy_still_passes_values_through_untouched() {
        // Derived: $GITHUB_REPOSITORY verbatim — no host, no lowercasing.
        assert_eq!(
            select_resources(ResourceFormat::Legacy, None, None, &github()).unwrap(),
            ("Acme/Widgets".to_string(), None)
        );
        // Explicit: whatever was given, qualified-looking or not.
        assert_eq!(
            select_resources(
                ResourceFormat::Legacy,
                Some("Acme/Widgets".into()),
                Some("Acme".into()),
                &github()
            )
            .unwrap(),
            ("Acme/Widgets".to_string(), Some("Acme".to_string()))
        );
        // Forgejo's names are not consulted in legacy mode.
        let env = ci(&[
            ("FORGEJO_SERVER_URL", "https://codeberg.org"),
            ("FORGEJO_REPOSITORY", "acme/widgets"),
        ]);
        let message = select_resources(ResourceFormat::Legacy, None, None, &env)
            .unwrap_err()
            .to_string();
        assert_eq!(message, "--resource is required (or set GITHUB_REPOSITORY)");
    }

    #[test]
    fn qualified_mode_derives_and_validates_both_resources() {
        assert_eq!(
            select_resources(
                ResourceFormat::Qualified,
                None,
                Some("GitHub.com/Acme".into()),
                &github()
            )
            .unwrap(),
            (
                "github.com/acme/widgets".to_string(),
                Some("github.com/acme".to_string())
            )
        );
        let message = select_resources(
            ResourceFormat::Qualified,
            None,
            Some("acme".into()),
            &github(),
        )
        .unwrap_err()
        .to_string();
        assert!(
            message.contains("did you mean `github.com/acme`?"),
            "{message}"
        );
    }

    #[test]
    fn a_qualified_fallback_must_be_the_repositorys_own_namespace() {
        let select = |fallback: &str| {
            select_resources(
                ResourceFormat::Qualified,
                None,
                Some(fallback.into()),
                &github(),
            )
        };
        // The namespace, however it is cased, and the repository itself.
        for ok in [
            "github.com/acme",
            "GitHub.com/Acme",
            "github.com/acme/widgets",
        ] {
            assert!(select(ok).is_ok(), "{ok}");
        }
        // Another owner, a byte-prefix owner, another forge, a sibling
        // repository, a deeper path: never.
        for other in [
            "github.com/other",
            "github.com/acm",
            "github.com/acme-labs",
            "codeberg.org/acme",
            "ghe.example.com/acme",
            "github.com/acme/other",
            "github.com/acme/widgets/sub",
        ] {
            let message = select(other).unwrap_err().to_string();
            assert!(
                message.contains("does not contain --resource `github.com/acme/widgets`")
                    && message.contains("`github.com/acme`"),
                "{other}: {message}"
            );
        }
        // The same holds for an explicit primary.
        let message = select_resources(
            ResourceFormat::Qualified,
            Some("github.com/acme/widgets".into()),
            Some("github.com/evil".into()),
            &CiEnv::default(),
        )
        .unwrap_err()
        .to_string();
        assert!(message.contains("does not contain"), "{message}");
    }

    #[test]
    fn legacy_mode_refuses_a_qualified_fallback() {
        let message = select_resources(
            ResourceFormat::Legacy,
            None,
            Some("github.com/acme".into()),
            &github(),
        )
        .unwrap_err()
        .to_string();
        assert!(
            message.contains("is forge-qualified") && message.contains("legacy"),
            "{message}"
        );
        // A dotted first segment reads as a host: `john.doe/repo` is refused
        // too, while the bare dotted owner `john.doe` (no owner segment
        // after it, so not qualified) still passes.
        assert!(
            select_resources(
                ResourceFormat::Legacy,
                None,
                Some("john.doe/repo".into()),
                &github()
            )
            .is_err()
        );
        assert!(
            select_resources(
                ResourceFormat::Legacy,
                Some("john.doe/widgets".into()),
                Some("john.doe".into()),
                &github()
            )
            .is_ok()
        );
        // A bare owner is still passed through untouched.
        assert_eq!(
            select_resources(ResourceFormat::Legacy, None, Some("Acme".into()), &github())
                .unwrap()
                .1
                .as_deref(),
            Some("Acme")
        );
    }

    /// VGI-03: the legacy arm used to send any string to the registry.
    #[test]
    fn legacy_mode_refuses_a_malformed_resource() {
        for (resource, expected) in [
            ("", "is empty"),
            ("   ", "is empty"),
            (" Acme/Widgets", "whitespace"),
            ("Acme/Widgets\n", "whitespace"),
            ("Acme/Wid\u{7}gets", "control character"),
            ("Acme/Widgets/extra", "not `owner/repo`"),
            ("Acme//Widgets", "not `owner/repo`"),
            ("/Widgets", "not `owner/repo`"),
            ("Acme/..", "not `owner/repo`"),
            ("Acme/Wid*gets", "contains `*`"),
        ] {
            let message = select_resources(
                ResourceFormat::Legacy,
                Some(resource.into()),
                None,
                &github(),
            )
            .unwrap_err()
            .to_string();
            assert!(message.contains(expected), "{resource:?}: {message}");
        }
        // $GITHUB_REPOSITORY is held to the same shape.
        let env = ci(&[("GITHUB_REPOSITORY", "")]);
        assert!(select_resources(ResourceFormat::Legacy, None, None, &env).is_err());
        // What legacy has always accepted still passes, untouched.
        for resource in ["Acme/Widgets", "acme", "john.doe/my_repo-2"] {
            assert_eq!(
                select_resources(
                    ResourceFormat::Legacy,
                    Some(resource.into()),
                    None,
                    &github()
                )
                .unwrap()
                .0,
                resource
            );
        }
    }

    /// VGI-03: a legacy fallback may widen a run to the repository's own
    /// owner, never to someone else's.
    #[test]
    fn legacy_mode_refuses_a_fallback_naming_another_owner() {
        let message =
            select_resources(ResourceFormat::Legacy, None, Some("Evil".into()), &github())
                .unwrap_err()
                .to_string();
        assert!(message.contains("is not the owner of"), "{message}");
        assert!(message.contains("`Acme`"), "{message}");
        for fallback in [" Acme", ""] {
            assert!(
                select_resources(
                    ResourceFormat::Legacy,
                    None,
                    Some(fallback.into()),
                    &github()
                )
                .is_err(),
                "{fallback:?}"
            );
        }
        // Its own owner, in any case, or the repository itself, pass untouched.
        for fallback in ["Acme", "acme", "Acme/Widgets"] {
            assert_eq!(
                select_resources(
                    ResourceFormat::Legacy,
                    None,
                    Some(fallback.into()),
                    &github()
                )
                .unwrap()
                .1
                .as_deref(),
                Some(fallback)
            );
        }
    }

    #[test]
    fn qualified_mode_outside_ci_requires_an_explicit_resource() {
        let message = select_resources(ResourceFormat::Qualified, None, None, &CiEnv::default())
            .unwrap_err()
            .to_string();
        assert!(message.contains("--resource is required"), "{message}");
        assert!(message.contains("github.com/acme/widgets"), "{message}");
    }
}