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 observed_sha = self.target_branch_revision(repository, branch).await?;
232        if observed_sha != expected_sha {
233            return Err(ProviderError::BranchRevisionChanged {
234                repository: Box::new(repository.clone()),
235                branch: branch.to_owned(),
236                expected_sha: expected_sha.to_owned(),
237                observed_sha,
238            });
239        }
240        Ok(())
241    }
242
243    pub(crate) async fn target_branch_revision(
244        &self,
245        repository: &Repository,
246        branch: &str,
247    ) -> Result<String> {
248        let segment = utf8_percent_encode(branch, NON_ALPHANUMERIC);
249        let observed: GithubBranch = self
250            .user()?
251            .get(
252                format!("/repos/{repository}/branches/{segment}"),
253                None::<&()>,
254            )
255            .await
256            .map_err(|error| {
257                read_error(
258                    "read target branch revision",
259                    format!("branch {branch} in {repository}"),
260                    error,
261                )
262            })?;
263        if observed.name != branch
264            || !(observed.commit.sha.len() == 40
265                && observed
266                    .commit
267                    .sha
268                    .bytes()
269                    .all(|byte| byte.is_ascii_hexdigit()))
270        {
271            return Err(ProviderError::Unrepresentable {
272                provider: "github",
273                fact: format!(
274                    "target branch response does not identify {branch} with a full commit SHA"
275                ),
276            });
277        }
278        Ok(observed.commit.sha)
279    }
280
281    async fn applied_branch_rules(
282        &self,
283        repository: &Repository,
284        branch: &str,
285    ) -> Result<Vec<GithubAppliedRule>> {
286        let segment = utf8_percent_encode(branch, NON_ALPHANUMERIC);
287        let first: Page<GithubAppliedRule> = self
288            .user()?
289            .get(
290                format!("/repos/{repository}/rules/branches/{segment}"),
291                Some(&[("per_page", PAGE_SIZE.to_string())]),
292            )
293            .await
294            .map_err(|error| {
295                read_error(
296                    "read applied branch rules",
297                    format!("rules applied to branch {branch} in {repository}"),
298                    error,
299                )
300            })?;
301        self.user()?.all_pages(first).await.map_err(|error| {
302            read_error(
303                "read applied branch rules",
304                format!("rules applied to branch {branch} in {repository}"),
305                error,
306            )
307        })
308    }
309
310    async fn classic_protection(
311        &self,
312        repository: &Repository,
313        branch: &str,
314    ) -> Result<Option<GithubClassicProtection>> {
315        let segment = utf8_percent_encode(branch, NON_ALPHANUMERIC);
316        let response = self
317            .user()?
318            .get(
319                format!("/repos/{repository}/branches/{segment}/protection"),
320                None::<&()>,
321            )
322            .await;
323        match response {
324            Ok(protection) => Ok(Some(protection)),
325            Err(error) if is_unprotected_branch(&error) => Ok(None),
326            Err(error) if is_not_found(&error) => Err(authenticated_external(
327                "read classic branch protection",
328                &error,
329            )),
330            Err(error) => Err(read_error(
331                "read classic branch protection",
332                format!("classic protection for branch {branch} in {repository}"),
333                error,
334            )),
335        }
336    }
337
338    async fn combined_statuses(
339        &self,
340        repository: &Repository,
341        head_sha: &str,
342    ) -> Result<Vec<GithubCommitStatus>> {
343        let mut statuses = Vec::new();
344        let mut page = 1_u32;
345        let mut expected_total = None;
346        loop {
347            let response: GithubCombinedStatusPage = self
348                .user()?
349                .get(
350                    format!("/repos/{repository}/commits/{head_sha}/status"),
351                    Some(&[
352                        ("per_page", PAGE_SIZE.to_string()),
353                        ("page", page.to_string()),
354                    ]),
355                )
356                .await
357                .map_err(|error| {
358                    read_error(
359                        "read combined commit status",
360                        format!("commit {head_sha} in {repository}"),
361                        error,
362                    )
363                })?;
364            if response.sha != head_sha {
365                return Err(unrepresentable(format!(
366                    "combined status names revision {} instead of {head_sha}",
367                    response.sha
368                )));
369            }
370            match expected_total {
371                Some(total) if total != response.total_count => {
372                    return Err(unrepresentable(format!(
373                        "combined-status total changed from {total} to {} while paging",
374                        response.total_count
375                    )));
376                }
377                None => expected_total = Some(response.total_count),
378                Some(_) => {}
379            }
380            let received = response.statuses.len();
381            statuses.extend(response.statuses);
382            let expected_total = expected_total.unwrap_or(response.total_count);
383            if statuses.len() as u64 > expected_total {
384                return Err(unrepresentable(format!(
385                    "combined status reported {expected_total} records but returned at least {}",
386                    statuses.len()
387                )));
388            }
389            if statuses.len() as u64 >= expected_total {
390                return Ok(statuses);
391            }
392            if received < PAGE_SIZE {
393                return Err(unrepresentable(format!(
394                    "combined status reported {} records but returned only {}",
395                    expected_total,
396                    statuses.len()
397                )));
398            }
399            page += 1;
400        }
401    }
402}
403
404fn validate_request(branch: &str, range: &CommitRange) -> Result<()> {
405    if branch.is_empty() {
406        return Err(invalid_input("target branch must not be empty"));
407    }
408    for (value, field) in [(&range.base_sha, "base sha"), (&range.head_sha, "head sha")] {
409        if value.len() != 40 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
410            return Err(invalid_input(format!(
411                "{field} must be a complete 40-character Git commit SHA"
412            )));
413        }
414    }
415    Ok(())
416}
417
418fn normalize_requirements(
419    rules: Vec<GithubAppliedRule>,
420    classic: Option<GithubClassicProtection>,
421) -> Result<Requirements> {
422    let mut result = Requirements::default();
423    for rule in rules {
424        match rule.rule_type.as_str() {
425            "required_status_checks" => {
426                let parameters: GithubStatusCheckParameters = parse_parameters(&rule)?;
427                result.branch_update |= parameters.strict_required_status_checks_policy;
428                for check in parameters.required_status_checks {
429                    insert_check(&mut result.checks, check.context, check.integration_id)?;
430                }
431            }
432            "pull_request" => {
433                let parameters: GithubPullRequestParameters = parse_parameters(&rule)?;
434                validate_ruleset_review_constraints(&parameters)?;
435                result.approvals = result
436                    .approvals
437                    .max(parameters.required_approving_review_count);
438            }
439            _ => {}
440        }
441    }
442
443    if let Some(classic) = classic {
444        if let Some(checks) = classic.required_status_checks {
445            result.branch_update |= checks.strict;
446            let checked_contexts = checks
447                .checks
448                .iter()
449                .map(|check| fold_context(&check.context))
450                .collect::<Result<BTreeSet<_>>>()?;
451            for check in checks.checks {
452                insert_check(&mut result.checks, check.context, check.app_id)?;
453            }
454            for context in checks.contexts {
455                if !checked_contexts.contains(&fold_context(&context)?) {
456                    insert_check(&mut result.checks, context, None)?;
457                }
458            }
459        }
460        if let Some(reviews) = classic.required_pull_request_reviews {
461            validate_classic_review_constraints(&reviews)?;
462            result.approvals = result
463                .approvals
464                .max(reviews.required_approving_review_count);
465        }
466        if classic
467            .required_conversation_resolution
468            .is_some_and(|setting| setting.enabled)
469        {
470            return Err(unrepresentable(
471                "classic protection requires review-thread resolution",
472            ));
473        }
474    }
475    Ok(result)
476}
477
478fn validate_ruleset_review_constraints(parameters: &GithubPullRequestParameters) -> Result<()> {
479    let active = if !parameters.required_reviewers.is_empty() {
480        Some("path-specific required reviewers")
481    } else if parameters.dismiss_stale_reviews_on_push {
482        Some("dismissal of stale reviews")
483    } else if parameters
484        .dismissal_restriction
485        .as_ref()
486        .is_some_and(|restriction| restriction.enabled)
487    {
488        Some("review-dismissal restrictions")
489    } else if parameters.require_code_owner_review {
490        Some("code-owner review")
491    } else if parameters.require_last_push_approval {
492        Some("approval by someone other than the last pusher")
493    } else if parameters.required_review_thread_resolution {
494        Some("review-thread resolution")
495    } else {
496        None
497    };
498    if let Some(constraint) = active {
499        return Err(unrepresentable(format!(
500            "an applied pull-request rule requires {constraint}, which cannot be represented as an approval count"
501        )));
502    }
503    if !parameters.additional.is_empty() {
504        return Err(unrepresentable(format!(
505            "an applied pull-request rule contains unsupported parameters: {}",
506            parameters
507                .additional
508                .keys()
509                .cloned()
510                .collect::<Vec<_>>()
511                .join(", ")
512        )));
513    }
514    Ok(())
515}
516
517fn validate_classic_review_constraints(reviews: &GithubClassicReviews) -> Result<()> {
518    let restricted_dismissal = reviews
519        .dismissal_restrictions
520        .as_ref()
521        .is_some_and(|value| {
522            !value.users.is_empty() || !value.teams.is_empty() || !value.apps.is_empty()
523        });
524    let active = if reviews.dismiss_stale_reviews {
525        Some("dismissal of stale reviews")
526    } else if reviews.require_code_owner_reviews {
527        Some("code-owner review")
528    } else if reviews.require_last_push_approval {
529        Some("approval by someone other than the last pusher")
530    } else if restricted_dismissal {
531        Some("review-dismissal restrictions")
532    } else {
533        None
534    };
535    if let Some(constraint) = active {
536        return Err(unrepresentable(format!(
537            "classic protection requires {constraint}, which cannot be represented as an approval count"
538        )));
539    }
540    Ok(())
541}
542
543fn parse_parameters<T: for<'de> Deserialize<'de>>(rule: &GithubAppliedRule) -> Result<T> {
544    let parameters = rule.parameters.clone().ok_or_else(|| {
545        unrepresentable(format!("applied {} rule has no parameters", rule.rule_type))
546    })?;
547    serde_json::from_value(parameters).map_err(|error| {
548        unrepresentable(format!(
549            "applied {} rule parameters are unreadable: {error}",
550            rule.rule_type
551        ))
552    })
553}
554
555fn insert_check(
556    checks: &mut BTreeMap<RequiredCheckIdentity, String>,
557    name: String,
558    app_id: Option<i64>,
559) -> Result<()> {
560    if name.is_empty() {
561        return Err(unrepresentable(
562            "an applied required check has an empty context",
563        ));
564    }
565    let folded_name = fold_context(&name)?;
566    let app_id = match app_id {
567        None | Some(-1) => None,
568        Some(value) if value > 0 => Some(value as u64),
569        Some(value) => {
570            return Err(unrepresentable(format!(
571                "required check {name} has invalid application id {value}"
572            )));
573        }
574    };
575    let identity = RequiredCheckIdentity {
576        folded_name,
577        app_id,
578    };
579    checks
580        .entry(identity)
581        .and_modify(|existing| {
582            if name < *existing {
583                existing.clone_from(&name);
584            }
585        })
586        .or_insert(name);
587    Ok(())
588}
589
590fn ensure_run_revisions(runs: &[CheckRun], expected: &str) -> Result<()> {
591    if let Some(run) = runs.iter().find(|run| run.head_sha != expected) {
592        return Err(unrepresentable(format!(
593            "check run {} names revision {} instead of {expected}",
594            run.name, run.head_sha
595        )));
596    }
597    Ok(())
598}
599
600fn answer_requirement(
601    identity: &RequiredCheckIdentity,
602    runs: &[CheckRun],
603    statuses: &[GithubCommitStatus],
604) -> Result<AppliedRequiredCheckState> {
605    let mut matching_runs = Vec::new();
606    for run in runs {
607        if fold_context(&run.name)? == identity.folded_name
608            && identity.app_id.is_none_or(|required| {
609                run.via_app
610                    .as_ref()
611                    .is_some_and(|app| app.id.as_str() == required.to_string())
612            })
613        {
614            matching_runs.push(check_run_state(run));
615        }
616    }
617    if identity.app_id.is_some() && matching_runs.is_empty() {
618        return Ok(AppliedRequiredCheckState::Missing);
619    }
620    let mut matching_statuses = Vec::new();
621    for status in statuses {
622        if fold_context(&status.context)? == identity.folded_name {
623            matching_statuses.push(commit_status_state(status)?);
624        }
625    }
626
627    let mut answers = matching_runs;
628    answers.extend(matching_statuses);
629    Ok(combine_states(&answers))
630}
631
632fn fold_context(context: &str) -> Result<String> {
633    if !context.is_ascii() {
634        return Err(unrepresentable(format!(
635            "check context {context:?} is non-ASCII; GitHub does not define a reproducible Unicode case-folding contract"
636        )));
637    }
638    Ok(context.to_ascii_lowercase())
639}
640
641fn check_run_state(run: &CheckRun) -> AppliedRequiredCheckState {
642    match &run.status {
643        CheckStatus::Completed { conclusion, .. } => match conclusion {
644            CheckConclusion::Success | CheckConclusion::Neutral | CheckConclusion::Skipped => {
645                AppliedRequiredCheckState::Satisfied
646            }
647            CheckConclusion::Failure
648            | CheckConclusion::Cancelled
649            | CheckConclusion::TimedOut
650            | CheckConclusion::ActionRequired
651            | CheckConclusion::Stale => AppliedRequiredCheckState::Failed,
652        },
653        CheckStatus::Requested
654        | CheckStatus::Queued
655        | CheckStatus::Pending
656        | CheckStatus::Waiting
657        | CheckStatus::InProgress => AppliedRequiredCheckState::Pending,
658    }
659}
660
661fn commit_status_state(status: &GithubCommitStatus) -> Result<AppliedRequiredCheckState> {
662    match status.state.as_str() {
663        "success" => Ok(AppliedRequiredCheckState::Satisfied),
664        "pending" => Ok(AppliedRequiredCheckState::Pending),
665        "failure" | "error" => Ok(AppliedRequiredCheckState::Failed),
666        other => Err(unrepresentable(format!(
667            "commit status {} has unknown state {other}",
668            status.context
669        ))),
670    }
671}
672
673fn combine_states(states: &[AppliedRequiredCheckState]) -> AppliedRequiredCheckState {
674    if states.contains(&AppliedRequiredCheckState::Failed) {
675        AppliedRequiredCheckState::Failed
676    } else if states.contains(&AppliedRequiredCheckState::Pending) {
677        AppliedRequiredCheckState::Pending
678    } else if states.contains(&AppliedRequiredCheckState::Satisfied) {
679        AppliedRequiredCheckState::Satisfied
680    } else {
681        AppliedRequiredCheckState::Missing
682    }
683}
684
685fn invalid_input(fact: impl Into<String>) -> ProviderError {
686    ProviderError::InvalidInput {
687        provider: "github",
688        fact: fact.into(),
689    }
690}
691
692fn is_unprotected_branch(error: &octocrab::Error) -> bool {
693    matches!(
694        error,
695        octocrab::Error::GitHub { source, .. }
696            if source.status_code.as_u16() == 404 && source.message == "Branch not protected"
697    )
698}
699
700fn unrepresentable(fact: impl Into<String>) -> ProviderError {
701    ProviderError::Unrepresentable {
702        provider: "github",
703        fact: fact.into(),
704    }
705}
706
707fn unrepresentable_model(error: impl std::fmt::Display) -> ProviderError {
708    unrepresentable(error.to_string())
709}
710
711#[cfg(test)]
712mod tests {
713    use chrono::TimeZone;
714    use interprex::{CheckStatus, ProviderApp};
715
716    use super::*;
717
718    fn run(name: &str, app: Option<&str>, status: CheckStatus) -> CheckRun {
719        CheckRun {
720            name: name.to_owned(),
721            head_sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned(),
722            via_app: app.map(|id| ProviderApp {
723                id: ProviderAppId::new(id).expect("app id"),
724                slug: "app".to_owned(),
725                name: "App".to_owned(),
726            }),
727            status,
728            summary: None,
729            html_url: None,
730        }
731    }
732
733    fn completed(conclusion: CheckConclusion) -> CheckStatus {
734        CheckStatus::Completed {
735            conclusion,
736            completed_at: chrono::Utc.timestamp_opt(1, 0).single().expect("time"),
737        }
738    }
739
740    fn complete_pull_request_parameters() -> Value {
741        serde_json::json!({
742            "allowed_merge_methods": ["merge", "squash", "rebase"],
743            "dismiss_stale_reviews_on_push": false,
744            "dismissal_restriction": {"enabled": false, "allowed_actors": []},
745            "require_code_owner_review": false,
746            "require_last_push_approval": false,
747            "required_approving_review_count": 1,
748            "required_review_thread_resolution": false,
749            "required_reviewers": []
750        })
751    }
752
753    #[test]
754    fn native_answers_use_failure_precedence_and_all_success_conclusions() {
755        for conclusion in [
756            CheckConclusion::Success,
757            CheckConclusion::Neutral,
758            CheckConclusion::Skipped,
759        ] {
760            assert_eq!(
761                check_run_state(&run("quality", None, completed(conclusion))),
762                AppliedRequiredCheckState::Satisfied
763            );
764        }
765        assert_eq!(
766            combine_states(&[
767                AppliedRequiredCheckState::Satisfied,
768                AppliedRequiredCheckState::Pending,
769                AppliedRequiredCheckState::Failed,
770            ]),
771            AppliedRequiredCheckState::Failed
772        );
773    }
774
775    #[test]
776    fn app_bound_requirement_needs_its_app_but_also_honors_an_existing_status() {
777        let identity = RequiredCheckIdentity {
778            folded_name: "quality".to_owned(),
779            app_id: Some(42),
780        };
781        let wrong_app = vec![run(
782            "QUALITY",
783            Some("41"),
784            completed(CheckConclusion::Success),
785        )];
786        let success_status = vec![GithubCommitStatus {
787            context: "Quality".to_owned(),
788            state: "success".to_owned(),
789        }];
790        assert_eq!(
791            answer_requirement(&identity, &wrong_app, &success_status).expect("answer"),
792            AppliedRequiredCheckState::Missing
793        );
794
795        let matching = vec![run(
796            "QUALITY",
797            Some("42"),
798            completed(CheckConclusion::Success),
799        )];
800        let failed_status = vec![GithubCommitStatus {
801            context: "quality".to_owned(),
802            state: "failure".to_owned(),
803        }];
804        assert_eq!(
805            answer_requirement(&identity, &matching, &failed_status).expect("answer"),
806            AppliedRequiredCheckState::Failed
807        );
808    }
809
810    #[test]
811    fn requirement_union_is_order_independent_and_classic_checks_supersede_context_aliases() {
812        let first = GithubAppliedRule {
813            rule_type: "required_status_checks".to_owned(),
814            parameters: Some(serde_json::json!({
815                "strict_required_status_checks_policy": false,
816                "required_status_checks": [{"context": "Zulu", "integration_id": null}]
817            })),
818        };
819        let second = GithubAppliedRule {
820            rule_type: "required_status_checks".to_owned(),
821            parameters: Some(serde_json::json!({
822                "strict_required_status_checks_policy": true,
823                "required_status_checks": [{"context": "alpha", "integration_id": 42}]
824            })),
825        };
826        let classic = || GithubClassicProtection {
827            required_status_checks: Some(GithubClassicStatusChecks {
828                strict: false,
829                contexts: vec!["ALPHA".to_owned()],
830                checks: vec![GithubClassicCheck {
831                    context: "alpha".to_owned(),
832                    app_id: Some(42),
833                }],
834            }),
835            required_pull_request_reviews: None,
836            required_conversation_resolution: None,
837        };
838
839        let left =
840            normalize_requirements(vec![first, second], Some(classic())).expect("first order");
841        let right = normalize_requirements(
842            vec![
843                GithubAppliedRule {
844                    rule_type: "required_status_checks".to_owned(),
845                    parameters: Some(serde_json::json!({
846                        "strict_required_status_checks_policy": true,
847                        "required_status_checks": [{"context": "alpha", "integration_id": 42}]
848                    })),
849                },
850                GithubAppliedRule {
851                    rule_type: "required_status_checks".to_owned(),
852                    parameters: Some(serde_json::json!({
853                        "strict_required_status_checks_policy": false,
854                        "required_status_checks": [{"context": "Zulu", "integration_id": null}]
855                    })),
856                },
857            ],
858            Some(classic()),
859        )
860        .expect("second order");
861        assert_eq!(left.checks, right.checks);
862        assert!(left.branch_update);
863        assert_eq!(
864            left.checks.len(),
865            2,
866            "classic contexts must not duplicate checks"
867        );
868    }
869
870    #[test]
871    fn nested_path_specific_required_reviewers_are_not_flattened_into_an_approval_count() {
872        let error = normalize_requirements(
873            vec![GithubAppliedRule {
874                rule_type: "pull_request".to_owned(),
875                parameters: Some(serde_json::json!({
876                    "allowed_merge_methods": ["squash", "merge", "rebase"],
877                    "dismiss_stale_reviews_on_push": false,
878                    "dismissal_restriction": {"enabled": false, "allowed_actors": []},
879                    "require_code_owner_review": false,
880                    "require_last_push_approval": false,
881                    "required_approving_review_count": 1,
882                    "required_review_thread_resolution": false,
883                    "required_reviewers": [{
884                        "file_patterns": ["src/**"],
885                        "minimum_approvals": 1,
886                        "reviewer": {"id": 9, "type": "Team"}
887                    }]
888                })),
889            }],
890            None,
891        )
892        .expect_err("path-specific reviewers are not a scalar");
893        assert!(matches!(
894            error,
895            ProviderError::Unrepresentable { fact, .. }
896                if fact.contains("path-specific required reviewers")
897        ));
898    }
899
900    #[test]
901    fn every_non_scalar_ruleset_review_constraint_is_rejected() {
902        for (field, value) in [
903            ("dismiss_stale_reviews_on_push", serde_json::json!(true)),
904            (
905                "dismissal_restriction",
906                serde_json::json!({"enabled": true, "allowed_actors": []}),
907            ),
908            ("require_code_owner_review", serde_json::json!(true)),
909            ("require_last_push_approval", serde_json::json!(true)),
910            ("required_review_thread_resolution", serde_json::json!(true)),
911        ] {
912            let mut parameters = serde_json::json!({
913                "allowed_merge_methods": ["squash"],
914                "dismiss_stale_reviews_on_push": false,
915                "dismissal_restriction": {"enabled": false, "allowed_actors": []},
916                "require_code_owner_review": false,
917                "require_last_push_approval": false,
918                "required_approving_review_count": 1,
919                "required_review_thread_resolution": false,
920                "required_reviewers": []
921            });
922            parameters[field] = value;
923            let error = normalize_requirements(
924                vec![GithubAppliedRule {
925                    rule_type: "pull_request".to_owned(),
926                    parameters: Some(parameters),
927                }],
928                None,
929            )
930            .expect_err("non-scalar review policy is not an approval count");
931            assert!(
932                matches!(error, ProviderError::Unrepresentable { .. }),
933                "field {field}"
934            );
935        }
936    }
937
938    #[test]
939    fn pull_request_rules_require_every_field_github_promises() {
940        for missing in [
941            "dismiss_stale_reviews_on_push",
942            "require_code_owner_review",
943            "require_last_push_approval",
944            "required_approving_review_count",
945            "required_review_thread_resolution",
946        ] {
947            let mut parameters = complete_pull_request_parameters();
948            parameters
949                .as_object_mut()
950                .expect("parameters object")
951                .remove(missing);
952            let error = normalize_requirements(
953                vec![GithubAppliedRule {
954                    rule_type: "pull_request".to_owned(),
955                    parameters: Some(parameters),
956                }],
957                None,
958            )
959            .expect_err("a promised field must not become a permissive default");
960            assert!(
961                matches!(error, ProviderError::Unrepresentable { .. }),
962                "missing field {missing}"
963            );
964        }
965
966        let mut parameters = complete_pull_request_parameters();
967        parameters["dismissal_restriction"] = serde_json::json!({"allowed_actors": []});
968        assert!(matches!(
969            normalize_requirements(
970                vec![GithubAppliedRule {
971                    rule_type: "pull_request".to_owned(),
972                    parameters: Some(parameters),
973                }],
974                None,
975            ),
976            Err(ProviderError::Unrepresentable { .. })
977        ));
978    }
979
980    #[test]
981    fn required_status_check_rules_do_not_default_required_fields() {
982        for parameters in [
983            serde_json::json!({"required_status_checks": []}),
984            serde_json::json!({"strict_required_status_checks_policy": false}),
985        ] {
986            assert!(matches!(
987                normalize_requirements(
988                    vec![GithubAppliedRule {
989                        rule_type: "required_status_checks".to_owned(),
990                        parameters: Some(parameters),
991                    }],
992                    None,
993                ),
994                Err(ProviderError::Unrepresentable { .. })
995            ));
996        }
997    }
998
999    #[test]
1000    fn non_scalar_classic_review_constraints_are_not_flattened() {
1001        let error = normalize_requirements(
1002            Vec::new(),
1003            Some(GithubClassicProtection {
1004                required_status_checks: None,
1005                required_pull_request_reviews: Some(GithubClassicReviews {
1006                    dismiss_stale_reviews: false,
1007                    require_code_owner_reviews: true,
1008                    required_approving_review_count: 2,
1009                    require_last_push_approval: false,
1010                    dismissal_restrictions: Some(GithubClassicDismissalRestrictions {
1011                        users: Vec::new(),
1012                        teams: Vec::new(),
1013                        apps: Vec::new(),
1014                    }),
1015                }),
1016                required_conversation_resolution: None,
1017            }),
1018        )
1019        .expect_err("code-owner identity is not a scalar approval count");
1020        assert!(matches!(
1021            error,
1022            ProviderError::Unrepresentable { fact, .. }
1023                if fact.contains("code-owner")
1024        ));
1025    }
1026
1027    #[test]
1028    fn context_matching_rejects_undefined_non_ascii_case_folding() {
1029        let rule_error = insert_check(&mut BTreeMap::new(), "CAFÉ".to_owned(), None)
1030            .expect_err("ruleset context must be reproducibly comparable");
1031        assert!(matches!(
1032            rule_error,
1033            ProviderError::Unrepresentable { fact, .. } if fact.contains("non-ASCII")
1034        ));
1035
1036        let classic_error = normalize_requirements(
1037            Vec::new(),
1038            Some(GithubClassicProtection {
1039                required_status_checks: Some(GithubClassicStatusChecks {
1040                    strict: false,
1041                    contexts: vec!["CAFÉ".to_owned()],
1042                    checks: Vec::new(),
1043                }),
1044                required_pull_request_reviews: None,
1045                required_conversation_resolution: None,
1046            }),
1047        )
1048        .expect_err("classic aliases must be reproducibly comparable");
1049        assert!(matches!(
1050            classic_error,
1051            ProviderError::Unrepresentable { fact, .. } if fact.contains("non-ASCII")
1052        ));
1053
1054        let identity = RequiredCheckIdentity {
1055            folded_name: "quality".to_owned(),
1056            app_id: None,
1057        };
1058        for answer in [
1059            answer_requirement(
1060                &identity,
1061                &[run("qualité", None, completed(CheckConclusion::Success))],
1062                &[],
1063            ),
1064            answer_requirement(
1065                &identity,
1066                &[],
1067                &[GithubCommitStatus {
1068                    context: "qualité".to_owned(),
1069                    state: "success".to_owned(),
1070                }],
1071            ),
1072        ] {
1073            assert!(matches!(
1074                answer,
1075                Err(ProviderError::Unrepresentable { fact, .. }) if fact.contains("non-ASCII")
1076            ));
1077        }
1078    }
1079}