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