Skip to main content

interprex_github/
source_code_requirements.rs

1//! Requirements GitHub applies to an exact branch and head revision.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use async_trait::async_trait;
6use interprex::{
7    AppliedRequiredCheck, AppliedRequiredCheckState, AppliedSourceRequirements,
8    AppliedSourceRequirementsProvider, BranchUpdateRequirement, CheckConclusion, CheckRun,
9    CheckStatus, CommitRange, ProviderAppId, ProviderError, Repository, Result,
10};
11use octocrab::Page;
12use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
13use serde::Deserialize;
14use serde_json::Value;
15
16use crate::{
17    GithubProvider,
18    client::{authenticated_external, is_not_found, read_error},
19    code_reviews::checks::normalize_check_run,
20};
21
22const PAGE_SIZE: usize = 100;
23
24#[derive(Deserialize)]
25struct GithubBranch {
26    name: String,
27    commit: GithubBranchCommit,
28}
29
30#[derive(Deserialize)]
31struct GithubBranchCommit {
32    sha: String,
33}
34
35#[derive(Deserialize)]
36struct GithubAppliedRule {
37    #[serde(rename = "type")]
38    rule_type: String,
39    #[serde(default)]
40    parameters: Option<Value>,
41}
42
43#[derive(Deserialize)]
44struct GithubStatusCheckParameters {
45    strict_required_status_checks_policy: bool,
46    required_status_checks: Vec<GithubRequiredCheck>,
47}
48
49#[derive(Deserialize)]
50struct GithubRequiredCheck {
51    context: String,
52    #[serde(default)]
53    integration_id: Option<i64>,
54}
55
56#[derive(Deserialize)]
57struct GithubPullRequestParameters {
58    #[serde(default, rename = "allowed_merge_methods")]
59    _allowed_merge_methods: Vec<String>,
60    dismiss_stale_reviews_on_push: bool,
61    #[serde(default)]
62    dismissal_restriction: Option<GithubRulesetDismissalRestriction>,
63    require_code_owner_review: bool,
64    require_last_push_approval: bool,
65    required_approving_review_count: u32,
66    required_review_thread_resolution: bool,
67    #[serde(default)]
68    required_reviewers: Vec<Value>,
69    #[serde(flatten)]
70    additional: BTreeMap<String, Value>,
71}
72
73#[derive(Deserialize)]
74struct GithubRulesetDismissalRestriction {
75    enabled: bool,
76}
77
78#[derive(Deserialize)]
79struct GithubClassicProtection {
80    #[serde(default)]
81    required_status_checks: Option<GithubClassicStatusChecks>,
82    #[serde(default)]
83    required_pull_request_reviews: Option<GithubClassicReviews>,
84    #[serde(default)]
85    required_conversation_resolution: Option<GithubEnabledSetting>,
86}
87
88#[derive(Deserialize)]
89struct GithubEnabledSetting {
90    enabled: bool,
91}
92
93#[derive(Deserialize)]
94struct GithubClassicStatusChecks {
95    strict: bool,
96    contexts: Vec<String>,
97    checks: Vec<GithubClassicCheck>,
98}
99
100#[derive(Deserialize)]
101struct GithubClassicCheck {
102    context: String,
103    #[serde(default)]
104    app_id: Option<i64>,
105}
106
107#[derive(Deserialize)]
108struct GithubClassicReviews {
109    #[serde(default)]
110    dismiss_stale_reviews: bool,
111    #[serde(default)]
112    require_code_owner_reviews: bool,
113    #[serde(default)]
114    required_approving_review_count: u32,
115    #[serde(default)]
116    require_last_push_approval: bool,
117    #[serde(default)]
118    dismissal_restrictions: Option<GithubClassicDismissalRestrictions>,
119}
120
121#[derive(Deserialize)]
122struct GithubClassicDismissalRestrictions {
123    #[serde(default)]
124    users: Vec<Value>,
125    #[serde(default)]
126    teams: Vec<Value>,
127    #[serde(default)]
128    apps: Vec<Value>,
129}
130
131#[derive(Deserialize)]
132struct GithubCombinedStatusPage {
133    sha: String,
134    total_count: u64,
135    statuses: Vec<GithubCommitStatus>,
136}
137
138#[derive(Deserialize)]
139struct GithubCommitStatus {
140    context: String,
141    state: String,
142}
143
144#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
145struct RequiredCheckIdentity {
146    folded_name: String,
147    app_id: Option<u64>,
148}
149
150#[derive(Debug, Default)]
151struct Requirements {
152    approvals: u32,
153    branch_update: bool,
154    checks: BTreeMap<RequiredCheckIdentity, String>,
155}
156
157#[async_trait]
158impl AppliedSourceRequirementsProvider for GithubProvider {
159    #[tracing::instrument(
160        name = "interprex.provider.source_code_requirements.applied_requirements",
161        skip_all,
162        fields(interprex.provider.name = "github")
163    )]
164    async fn applied_requirements(
165        &self,
166        repository: &Repository,
167        target_branch: &str,
168        commit_range: &CommitRange,
169    ) -> Result<AppliedSourceRequirements> {
170        validate_request(target_branch, commit_range)?;
171        self.verify_branch_revision(repository, target_branch, &commit_range.base_sha)
172            .await?;
173
174        let rules = self.applied_branch_rules(repository, target_branch).await?;
175        let classic = self.classic_protection(repository, target_branch).await?;
176        let requirements = normalize_requirements(rules, classic)?;
177        let runs = self
178            .complete_github_check_runs(repository, &commit_range.head_sha)
179            .await?
180            .into_iter()
181            .map(normalize_check_run)
182            .collect::<Result<Vec<_>>>()?;
183        ensure_run_revisions(&runs, &commit_range.head_sha)?;
184        let statuses = self
185            .combined_statuses(repository, &commit_range.head_sha)
186            .await?;
187
188        // The target branch can advance while the independent policy and
189        // result collections are read. An answer for that mixed snapshot
190        // would not describe the caller's exact base revision.
191        self.verify_branch_revision(repository, target_branch, &commit_range.base_sha)
192            .await?;
193
194        let checks = requirements
195            .checks
196            .into_iter()
197            .map(|(identity, name)| {
198                let state = answer_requirement(&identity, &runs, &statuses)?;
199                let app = identity
200                    .app_id
201                    .map(|id| ProviderAppId::new(id.to_string()))
202                    .transpose()
203                    .map_err(unrepresentable_model)?;
204                AppliedRequiredCheck::new(name, app, state).map_err(unrepresentable_model)
205            })
206            .collect::<Result<Vec<_>>>()?;
207
208        AppliedSourceRequirements::new(
209            repository.clone(),
210            target_branch,
211            commit_range.clone(),
212            requirements.approvals,
213            if requirements.branch_update {
214                BranchUpdateRequirement::Required
215            } else {
216                BranchUpdateRequirement::NotRequired
217            },
218            checks,
219        )
220        .map_err(unrepresentable_model)
221    }
222}
223
224impl GithubProvider {
225    async fn verify_branch_revision(
226        &self,
227        repository: &Repository,
228        branch: &str,
229        expected_sha: &str,
230    ) -> Result<()> {
231        let segment = utf8_percent_encode(branch, NON_ALPHANUMERIC);
232        let observed: GithubBranch = self
233            .user()?
234            .get(
235                format!("/repos/{repository}/branches/{segment}"),
236                None::<&()>,
237            )
238            .await
239            .map_err(|error| {
240                read_error(
241                    "read target branch revision",
242                    format!("branch {branch} in {repository}"),
243                    error,
244                )
245            })?;
246        if observed.name != branch || observed.commit.sha != expected_sha {
247            return Err(ProviderError::NotFound {
248                entity: format!("branch {branch} at revision {expected_sha} in {repository}"),
249            });
250        }
251        Ok(())
252    }
253
254    async fn applied_branch_rules(
255        &self,
256        repository: &Repository,
257        branch: &str,
258    ) -> Result<Vec<GithubAppliedRule>> {
259        let segment = utf8_percent_encode(branch, NON_ALPHANUMERIC);
260        let first: Page<GithubAppliedRule> = self
261            .user()?
262            .get(
263                format!("/repos/{repository}/rules/branches/{segment}"),
264                Some(&[("per_page", PAGE_SIZE.to_string())]),
265            )
266            .await
267            .map_err(|error| {
268                read_error(
269                    "read applied branch rules",
270                    format!("rules applied to branch {branch} in {repository}"),
271                    error,
272                )
273            })?;
274        self.user()?.all_pages(first).await.map_err(|error| {
275            read_error(
276                "read applied branch rules",
277                format!("rules applied to branch {branch} in {repository}"),
278                error,
279            )
280        })
281    }
282
283    async fn classic_protection(
284        &self,
285        repository: &Repository,
286        branch: &str,
287    ) -> Result<Option<GithubClassicProtection>> {
288        let segment = utf8_percent_encode(branch, NON_ALPHANUMERIC);
289        let response = self
290            .user()?
291            .get(
292                format!("/repos/{repository}/branches/{segment}/protection"),
293                None::<&()>,
294            )
295            .await;
296        match response {
297            Ok(protection) => Ok(Some(protection)),
298            Err(error) if is_unprotected_branch(&error) => Ok(None),
299            Err(error) if is_not_found(&error) => Err(authenticated_external(
300                "read classic branch protection",
301                &error,
302            )),
303            Err(error) => Err(read_error(
304                "read classic branch protection",
305                format!("classic protection for branch {branch} in {repository}"),
306                error,
307            )),
308        }
309    }
310
311    async fn combined_statuses(
312        &self,
313        repository: &Repository,
314        head_sha: &str,
315    ) -> Result<Vec<GithubCommitStatus>> {
316        let mut statuses = Vec::new();
317        let mut page = 1_u32;
318        let mut expected_total = None;
319        loop {
320            let response: GithubCombinedStatusPage = self
321                .user()?
322                .get(
323                    format!("/repos/{repository}/commits/{head_sha}/status"),
324                    Some(&[
325                        ("per_page", PAGE_SIZE.to_string()),
326                        ("page", page.to_string()),
327                    ]),
328                )
329                .await
330                .map_err(|error| {
331                    read_error(
332                        "read combined commit status",
333                        format!("commit {head_sha} in {repository}"),
334                        error,
335                    )
336                })?;
337            if response.sha != head_sha {
338                return Err(unrepresentable(format!(
339                    "combined status names revision {} instead of {head_sha}",
340                    response.sha
341                )));
342            }
343            match expected_total {
344                Some(total) if total != response.total_count => {
345                    return Err(unrepresentable(format!(
346                        "combined-status total changed from {total} to {} while paging",
347                        response.total_count
348                    )));
349                }
350                None => expected_total = Some(response.total_count),
351                Some(_) => {}
352            }
353            let received = response.statuses.len();
354            statuses.extend(response.statuses);
355            let expected_total = expected_total.unwrap_or(response.total_count);
356            if statuses.len() as u64 > expected_total {
357                return Err(unrepresentable(format!(
358                    "combined status reported {expected_total} records but returned at least {}",
359                    statuses.len()
360                )));
361            }
362            if statuses.len() as u64 >= expected_total {
363                return Ok(statuses);
364            }
365            if received < PAGE_SIZE {
366                return Err(unrepresentable(format!(
367                    "combined status reported {} records but returned only {}",
368                    expected_total,
369                    statuses.len()
370                )));
371            }
372            page += 1;
373        }
374    }
375}
376
377fn validate_request(branch: &str, range: &CommitRange) -> Result<()> {
378    if branch.is_empty() {
379        return Err(invalid_input("target branch must not be empty"));
380    }
381    for (value, field) in [(&range.base_sha, "base sha"), (&range.head_sha, "head sha")] {
382        if value.len() != 40 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
383            return Err(invalid_input(format!(
384                "{field} must be a complete 40-character Git commit SHA"
385            )));
386        }
387    }
388    Ok(())
389}
390
391fn normalize_requirements(
392    rules: Vec<GithubAppliedRule>,
393    classic: Option<GithubClassicProtection>,
394) -> Result<Requirements> {
395    let mut result = Requirements::default();
396    for rule in rules {
397        match rule.rule_type.as_str() {
398            "required_status_checks" => {
399                let parameters: GithubStatusCheckParameters = parse_parameters(&rule)?;
400                result.branch_update |= parameters.strict_required_status_checks_policy;
401                for check in parameters.required_status_checks {
402                    insert_check(&mut result.checks, check.context, check.integration_id)?;
403                }
404            }
405            "pull_request" => {
406                let parameters: GithubPullRequestParameters = parse_parameters(&rule)?;
407                validate_ruleset_review_constraints(&parameters)?;
408                result.approvals = result
409                    .approvals
410                    .max(parameters.required_approving_review_count);
411            }
412            _ => {}
413        }
414    }
415
416    if let Some(classic) = classic {
417        if let Some(checks) = classic.required_status_checks {
418            result.branch_update |= checks.strict;
419            let checked_contexts = checks
420                .checks
421                .iter()
422                .map(|check| fold_context(&check.context))
423                .collect::<Result<BTreeSet<_>>>()?;
424            for check in checks.checks {
425                insert_check(&mut result.checks, check.context, check.app_id)?;
426            }
427            for context in checks.contexts {
428                if !checked_contexts.contains(&fold_context(&context)?) {
429                    insert_check(&mut result.checks, context, None)?;
430                }
431            }
432        }
433        if let Some(reviews) = classic.required_pull_request_reviews {
434            validate_classic_review_constraints(&reviews)?;
435            result.approvals = result
436                .approvals
437                .max(reviews.required_approving_review_count);
438        }
439        if classic
440            .required_conversation_resolution
441            .is_some_and(|setting| setting.enabled)
442        {
443            return Err(unrepresentable(
444                "classic protection requires review-thread resolution",
445            ));
446        }
447    }
448    Ok(result)
449}
450
451fn validate_ruleset_review_constraints(parameters: &GithubPullRequestParameters) -> Result<()> {
452    let active = if !parameters.required_reviewers.is_empty() {
453        Some("path-specific required reviewers")
454    } else if parameters.dismiss_stale_reviews_on_push {
455        Some("dismissal of stale reviews")
456    } else if parameters
457        .dismissal_restriction
458        .as_ref()
459        .is_some_and(|restriction| restriction.enabled)
460    {
461        Some("review-dismissal restrictions")
462    } else if parameters.require_code_owner_review {
463        Some("code-owner review")
464    } else if parameters.require_last_push_approval {
465        Some("approval by someone other than the last pusher")
466    } else if parameters.required_review_thread_resolution {
467        Some("review-thread resolution")
468    } else {
469        None
470    };
471    if let Some(constraint) = active {
472        return Err(unrepresentable(format!(
473            "an applied pull-request rule requires {constraint}, which cannot be represented as an approval count"
474        )));
475    }
476    if !parameters.additional.is_empty() {
477        return Err(unrepresentable(format!(
478            "an applied pull-request rule contains unsupported parameters: {}",
479            parameters
480                .additional
481                .keys()
482                .cloned()
483                .collect::<Vec<_>>()
484                .join(", ")
485        )));
486    }
487    Ok(())
488}
489
490fn validate_classic_review_constraints(reviews: &GithubClassicReviews) -> Result<()> {
491    let restricted_dismissal = reviews
492        .dismissal_restrictions
493        .as_ref()
494        .is_some_and(|value| {
495            !value.users.is_empty() || !value.teams.is_empty() || !value.apps.is_empty()
496        });
497    let active = if reviews.dismiss_stale_reviews {
498        Some("dismissal of stale reviews")
499    } else if reviews.require_code_owner_reviews {
500        Some("code-owner review")
501    } else if reviews.require_last_push_approval {
502        Some("approval by someone other than the last pusher")
503    } else if restricted_dismissal {
504        Some("review-dismissal restrictions")
505    } else {
506        None
507    };
508    if let Some(constraint) = active {
509        return Err(unrepresentable(format!(
510            "classic protection requires {constraint}, which cannot be represented as an approval count"
511        )));
512    }
513    Ok(())
514}
515
516fn parse_parameters<T: for<'de> Deserialize<'de>>(rule: &GithubAppliedRule) -> Result<T> {
517    let parameters = rule.parameters.clone().ok_or_else(|| {
518        unrepresentable(format!("applied {} rule has no parameters", rule.rule_type))
519    })?;
520    serde_json::from_value(parameters).map_err(|error| {
521        unrepresentable(format!(
522            "applied {} rule parameters are unreadable: {error}",
523            rule.rule_type
524        ))
525    })
526}
527
528fn insert_check(
529    checks: &mut BTreeMap<RequiredCheckIdentity, String>,
530    name: String,
531    app_id: Option<i64>,
532) -> Result<()> {
533    if name.is_empty() {
534        return Err(unrepresentable(
535            "an applied required check has an empty context",
536        ));
537    }
538    let folded_name = fold_context(&name)?;
539    let app_id = match app_id {
540        None | Some(-1) => None,
541        Some(value) if value > 0 => Some(value as u64),
542        Some(value) => {
543            return Err(unrepresentable(format!(
544                "required check {name} has invalid application id {value}"
545            )));
546        }
547    };
548    let identity = RequiredCheckIdentity {
549        folded_name,
550        app_id,
551    };
552    checks
553        .entry(identity)
554        .and_modify(|existing| {
555            if name < *existing {
556                existing.clone_from(&name);
557            }
558        })
559        .or_insert(name);
560    Ok(())
561}
562
563fn ensure_run_revisions(runs: &[CheckRun], expected: &str) -> Result<()> {
564    if let Some(run) = runs.iter().find(|run| run.head_sha != expected) {
565        return Err(unrepresentable(format!(
566            "check run {} names revision {} instead of {expected}",
567            run.name, run.head_sha
568        )));
569    }
570    Ok(())
571}
572
573fn answer_requirement(
574    identity: &RequiredCheckIdentity,
575    runs: &[CheckRun],
576    statuses: &[GithubCommitStatus],
577) -> Result<AppliedRequiredCheckState> {
578    let mut matching_runs = Vec::new();
579    for run in runs {
580        if fold_context(&run.name)? == identity.folded_name
581            && identity.app_id.is_none_or(|required| {
582                run.via_app
583                    .as_ref()
584                    .is_some_and(|app| app.id.as_str() == required.to_string())
585            })
586        {
587            matching_runs.push(check_run_state(run));
588        }
589    }
590    if identity.app_id.is_some() && matching_runs.is_empty() {
591        return Ok(AppliedRequiredCheckState::Missing);
592    }
593    let mut matching_statuses = Vec::new();
594    for status in statuses {
595        if fold_context(&status.context)? == identity.folded_name {
596            matching_statuses.push(commit_status_state(status)?);
597        }
598    }
599
600    let mut answers = matching_runs;
601    answers.extend(matching_statuses);
602    Ok(combine_states(&answers))
603}
604
605fn fold_context(context: &str) -> Result<String> {
606    if !context.is_ascii() {
607        return Err(unrepresentable(format!(
608            "check context {context:?} is non-ASCII; GitHub does not define a reproducible Unicode case-folding contract"
609        )));
610    }
611    Ok(context.to_ascii_lowercase())
612}
613
614fn check_run_state(run: &CheckRun) -> AppliedRequiredCheckState {
615    match &run.status {
616        CheckStatus::Completed { conclusion, .. } => match conclusion {
617            CheckConclusion::Success | CheckConclusion::Neutral | CheckConclusion::Skipped => {
618                AppliedRequiredCheckState::Satisfied
619            }
620            CheckConclusion::Failure
621            | CheckConclusion::Cancelled
622            | CheckConclusion::TimedOut
623            | CheckConclusion::ActionRequired
624            | CheckConclusion::Stale => AppliedRequiredCheckState::Failed,
625        },
626        CheckStatus::Requested
627        | CheckStatus::Queued
628        | CheckStatus::Pending
629        | CheckStatus::Waiting
630        | CheckStatus::InProgress => AppliedRequiredCheckState::Pending,
631    }
632}
633
634fn commit_status_state(status: &GithubCommitStatus) -> Result<AppliedRequiredCheckState> {
635    match status.state.as_str() {
636        "success" => Ok(AppliedRequiredCheckState::Satisfied),
637        "pending" => Ok(AppliedRequiredCheckState::Pending),
638        "failure" | "error" => Ok(AppliedRequiredCheckState::Failed),
639        other => Err(unrepresentable(format!(
640            "commit status {} has unknown state {other}",
641            status.context
642        ))),
643    }
644}
645
646fn combine_states(states: &[AppliedRequiredCheckState]) -> AppliedRequiredCheckState {
647    if states.contains(&AppliedRequiredCheckState::Failed) {
648        AppliedRequiredCheckState::Failed
649    } else if states.contains(&AppliedRequiredCheckState::Pending) {
650        AppliedRequiredCheckState::Pending
651    } else if states.contains(&AppliedRequiredCheckState::Satisfied) {
652        AppliedRequiredCheckState::Satisfied
653    } else {
654        AppliedRequiredCheckState::Missing
655    }
656}
657
658fn invalid_input(fact: impl Into<String>) -> ProviderError {
659    ProviderError::InvalidInput {
660        provider: "github",
661        fact: fact.into(),
662    }
663}
664
665fn is_unprotected_branch(error: &octocrab::Error) -> bool {
666    matches!(
667        error,
668        octocrab::Error::GitHub { source, .. }
669            if source.status_code.as_u16() == 404 && source.message == "Branch not protected"
670    )
671}
672
673fn unrepresentable(fact: impl Into<String>) -> ProviderError {
674    ProviderError::Unrepresentable {
675        provider: "github",
676        fact: fact.into(),
677    }
678}
679
680fn unrepresentable_model(error: impl std::fmt::Display) -> ProviderError {
681    unrepresentable(error.to_string())
682}
683
684#[cfg(test)]
685mod tests {
686    use chrono::TimeZone;
687    use interprex::{CheckStatus, ProviderApp};
688
689    use super::*;
690
691    fn run(name: &str, app: Option<&str>, status: CheckStatus) -> CheckRun {
692        CheckRun {
693            name: name.to_owned(),
694            head_sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned(),
695            via_app: app.map(|id| ProviderApp {
696                id: ProviderAppId::new(id).expect("app id"),
697                slug: "app".to_owned(),
698                name: "App".to_owned(),
699            }),
700            status,
701            summary: None,
702            html_url: None,
703        }
704    }
705
706    fn completed(conclusion: CheckConclusion) -> CheckStatus {
707        CheckStatus::Completed {
708            conclusion,
709            completed_at: chrono::Utc.timestamp_opt(1, 0).single().expect("time"),
710        }
711    }
712
713    fn complete_pull_request_parameters() -> Value {
714        serde_json::json!({
715            "allowed_merge_methods": ["merge", "squash", "rebase"],
716            "dismiss_stale_reviews_on_push": false,
717            "dismissal_restriction": {"enabled": false, "allowed_actors": []},
718            "require_code_owner_review": false,
719            "require_last_push_approval": false,
720            "required_approving_review_count": 1,
721            "required_review_thread_resolution": false,
722            "required_reviewers": []
723        })
724    }
725
726    #[test]
727    fn native_answers_use_failure_precedence_and_all_success_conclusions() {
728        for conclusion in [
729            CheckConclusion::Success,
730            CheckConclusion::Neutral,
731            CheckConclusion::Skipped,
732        ] {
733            assert_eq!(
734                check_run_state(&run("quality", None, completed(conclusion))),
735                AppliedRequiredCheckState::Satisfied
736            );
737        }
738        assert_eq!(
739            combine_states(&[
740                AppliedRequiredCheckState::Satisfied,
741                AppliedRequiredCheckState::Pending,
742                AppliedRequiredCheckState::Failed,
743            ]),
744            AppliedRequiredCheckState::Failed
745        );
746    }
747
748    #[test]
749    fn app_bound_requirement_needs_its_app_but_also_honors_an_existing_status() {
750        let identity = RequiredCheckIdentity {
751            folded_name: "quality".to_owned(),
752            app_id: Some(42),
753        };
754        let wrong_app = vec![run(
755            "QUALITY",
756            Some("41"),
757            completed(CheckConclusion::Success),
758        )];
759        let success_status = vec![GithubCommitStatus {
760            context: "Quality".to_owned(),
761            state: "success".to_owned(),
762        }];
763        assert_eq!(
764            answer_requirement(&identity, &wrong_app, &success_status).expect("answer"),
765            AppliedRequiredCheckState::Missing
766        );
767
768        let matching = vec![run(
769            "QUALITY",
770            Some("42"),
771            completed(CheckConclusion::Success),
772        )];
773        let failed_status = vec![GithubCommitStatus {
774            context: "quality".to_owned(),
775            state: "failure".to_owned(),
776        }];
777        assert_eq!(
778            answer_requirement(&identity, &matching, &failed_status).expect("answer"),
779            AppliedRequiredCheckState::Failed
780        );
781    }
782
783    #[test]
784    fn requirement_union_is_order_independent_and_classic_checks_supersede_context_aliases() {
785        let first = GithubAppliedRule {
786            rule_type: "required_status_checks".to_owned(),
787            parameters: Some(serde_json::json!({
788                "strict_required_status_checks_policy": false,
789                "required_status_checks": [{"context": "Zulu", "integration_id": null}]
790            })),
791        };
792        let second = GithubAppliedRule {
793            rule_type: "required_status_checks".to_owned(),
794            parameters: Some(serde_json::json!({
795                "strict_required_status_checks_policy": true,
796                "required_status_checks": [{"context": "alpha", "integration_id": 42}]
797            })),
798        };
799        let classic = || GithubClassicProtection {
800            required_status_checks: Some(GithubClassicStatusChecks {
801                strict: false,
802                contexts: vec!["ALPHA".to_owned()],
803                checks: vec![GithubClassicCheck {
804                    context: "alpha".to_owned(),
805                    app_id: Some(42),
806                }],
807            }),
808            required_pull_request_reviews: None,
809            required_conversation_resolution: None,
810        };
811
812        let left =
813            normalize_requirements(vec![first, second], Some(classic())).expect("first order");
814        let right = normalize_requirements(
815            vec![
816                GithubAppliedRule {
817                    rule_type: "required_status_checks".to_owned(),
818                    parameters: Some(serde_json::json!({
819                        "strict_required_status_checks_policy": true,
820                        "required_status_checks": [{"context": "alpha", "integration_id": 42}]
821                    })),
822                },
823                GithubAppliedRule {
824                    rule_type: "required_status_checks".to_owned(),
825                    parameters: Some(serde_json::json!({
826                        "strict_required_status_checks_policy": false,
827                        "required_status_checks": [{"context": "Zulu", "integration_id": null}]
828                    })),
829                },
830            ],
831            Some(classic()),
832        )
833        .expect("second order");
834        assert_eq!(left.checks, right.checks);
835        assert!(left.branch_update);
836        assert_eq!(
837            left.checks.len(),
838            2,
839            "classic contexts must not duplicate checks"
840        );
841    }
842
843    #[test]
844    fn nested_path_specific_required_reviewers_are_not_flattened_into_an_approval_count() {
845        let error = normalize_requirements(
846            vec![GithubAppliedRule {
847                rule_type: "pull_request".to_owned(),
848                parameters: Some(serde_json::json!({
849                    "allowed_merge_methods": ["squash", "merge", "rebase"],
850                    "dismiss_stale_reviews_on_push": false,
851                    "dismissal_restriction": {"enabled": false, "allowed_actors": []},
852                    "require_code_owner_review": false,
853                    "require_last_push_approval": false,
854                    "required_approving_review_count": 1,
855                    "required_review_thread_resolution": false,
856                    "required_reviewers": [{
857                        "file_patterns": ["src/**"],
858                        "minimum_approvals": 1,
859                        "reviewer": {"id": 9, "type": "Team"}
860                    }]
861                })),
862            }],
863            None,
864        )
865        .expect_err("path-specific reviewers are not a scalar");
866        assert!(matches!(
867            error,
868            ProviderError::Unrepresentable { fact, .. }
869                if fact.contains("path-specific required reviewers")
870        ));
871    }
872
873    #[test]
874    fn every_non_scalar_ruleset_review_constraint_is_rejected() {
875        for (field, value) in [
876            ("dismiss_stale_reviews_on_push", serde_json::json!(true)),
877            (
878                "dismissal_restriction",
879                serde_json::json!({"enabled": true, "allowed_actors": []}),
880            ),
881            ("require_code_owner_review", serde_json::json!(true)),
882            ("require_last_push_approval", serde_json::json!(true)),
883            ("required_review_thread_resolution", serde_json::json!(true)),
884        ] {
885            let mut parameters = serde_json::json!({
886                "allowed_merge_methods": ["squash"],
887                "dismiss_stale_reviews_on_push": false,
888                "dismissal_restriction": {"enabled": false, "allowed_actors": []},
889                "require_code_owner_review": false,
890                "require_last_push_approval": false,
891                "required_approving_review_count": 1,
892                "required_review_thread_resolution": false,
893                "required_reviewers": []
894            });
895            parameters[field] = value;
896            let error = normalize_requirements(
897                vec![GithubAppliedRule {
898                    rule_type: "pull_request".to_owned(),
899                    parameters: Some(parameters),
900                }],
901                None,
902            )
903            .expect_err("non-scalar review policy is not an approval count");
904            assert!(
905                matches!(error, ProviderError::Unrepresentable { .. }),
906                "field {field}"
907            );
908        }
909    }
910
911    #[test]
912    fn pull_request_rules_require_every_field_github_promises() {
913        for missing in [
914            "dismiss_stale_reviews_on_push",
915            "require_code_owner_review",
916            "require_last_push_approval",
917            "required_approving_review_count",
918            "required_review_thread_resolution",
919        ] {
920            let mut parameters = complete_pull_request_parameters();
921            parameters
922                .as_object_mut()
923                .expect("parameters object")
924                .remove(missing);
925            let error = normalize_requirements(
926                vec![GithubAppliedRule {
927                    rule_type: "pull_request".to_owned(),
928                    parameters: Some(parameters),
929                }],
930                None,
931            )
932            .expect_err("a promised field must not become a permissive default");
933            assert!(
934                matches!(error, ProviderError::Unrepresentable { .. }),
935                "missing field {missing}"
936            );
937        }
938
939        let mut parameters = complete_pull_request_parameters();
940        parameters["dismissal_restriction"] = serde_json::json!({"allowed_actors": []});
941        assert!(matches!(
942            normalize_requirements(
943                vec![GithubAppliedRule {
944                    rule_type: "pull_request".to_owned(),
945                    parameters: Some(parameters),
946                }],
947                None,
948            ),
949            Err(ProviderError::Unrepresentable { .. })
950        ));
951    }
952
953    #[test]
954    fn required_status_check_rules_do_not_default_required_fields() {
955        for parameters in [
956            serde_json::json!({"required_status_checks": []}),
957            serde_json::json!({"strict_required_status_checks_policy": false}),
958        ] {
959            assert!(matches!(
960                normalize_requirements(
961                    vec![GithubAppliedRule {
962                        rule_type: "required_status_checks".to_owned(),
963                        parameters: Some(parameters),
964                    }],
965                    None,
966                ),
967                Err(ProviderError::Unrepresentable { .. })
968            ));
969        }
970    }
971
972    #[test]
973    fn non_scalar_classic_review_constraints_are_not_flattened() {
974        let error = normalize_requirements(
975            Vec::new(),
976            Some(GithubClassicProtection {
977                required_status_checks: None,
978                required_pull_request_reviews: Some(GithubClassicReviews {
979                    dismiss_stale_reviews: false,
980                    require_code_owner_reviews: true,
981                    required_approving_review_count: 2,
982                    require_last_push_approval: false,
983                    dismissal_restrictions: Some(GithubClassicDismissalRestrictions {
984                        users: Vec::new(),
985                        teams: Vec::new(),
986                        apps: Vec::new(),
987                    }),
988                }),
989                required_conversation_resolution: None,
990            }),
991        )
992        .expect_err("code-owner identity is not a scalar approval count");
993        assert!(matches!(
994            error,
995            ProviderError::Unrepresentable { fact, .. }
996                if fact.contains("code-owner")
997        ));
998    }
999
1000    #[test]
1001    fn context_matching_rejects_undefined_non_ascii_case_folding() {
1002        let rule_error = insert_check(&mut BTreeMap::new(), "CAFÉ".to_owned(), None)
1003            .expect_err("ruleset context must be reproducibly comparable");
1004        assert!(matches!(
1005            rule_error,
1006            ProviderError::Unrepresentable { fact, .. } if fact.contains("non-ASCII")
1007        ));
1008
1009        let classic_error = normalize_requirements(
1010            Vec::new(),
1011            Some(GithubClassicProtection {
1012                required_status_checks: Some(GithubClassicStatusChecks {
1013                    strict: false,
1014                    contexts: vec!["CAFÉ".to_owned()],
1015                    checks: Vec::new(),
1016                }),
1017                required_pull_request_reviews: None,
1018                required_conversation_resolution: None,
1019            }),
1020        )
1021        .expect_err("classic aliases must be reproducibly comparable");
1022        assert!(matches!(
1023            classic_error,
1024            ProviderError::Unrepresentable { fact, .. } if fact.contains("non-ASCII")
1025        ));
1026
1027        let identity = RequiredCheckIdentity {
1028            folded_name: "quality".to_owned(),
1029            app_id: None,
1030        };
1031        for answer in [
1032            answer_requirement(
1033                &identity,
1034                &[run("qualité", None, completed(CheckConclusion::Success))],
1035                &[],
1036            ),
1037            answer_requirement(
1038                &identity,
1039                &[],
1040                &[GithubCommitStatus {
1041                    context: "qualité".to_owned(),
1042                    state: "success".to_owned(),
1043                }],
1044            ),
1045        ] {
1046            assert!(matches!(
1047                answer,
1048                Err(ProviderError::Unrepresentable { fact, .. }) if fact.contains("non-ASCII")
1049            ));
1050        }
1051    }
1052}