Skip to main content

interprex_github/
source_code_configuration.rs

1//! Complete GitHub ruleset values and source-configuration capabilities.
2
3use std::collections::BTreeMap;
4
5use async_trait::async_trait;
6use interprex::{ModelError, ProviderError, Repository, Result, SourceCodeConfigurationProvider};
7use octocrab::Page;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11use crate::{
12    GithubProvider,
13    client::{authenticated_external, read_error},
14};
15
16const WRITABLE_RULE_TYPES: &[&str] = &[
17    "creation",
18    "update",
19    "deletion",
20    "required_linear_history",
21    "merge_queue",
22    "required_deployments",
23    "required_signatures",
24    "pull_request",
25    "required_status_checks",
26    "non_fast_forward",
27    "commit_message_pattern",
28    "commit_author_email_pattern",
29    "committer_email_pattern",
30    "branch_name_pattern",
31    "tag_name_pattern",
32    "workflows",
33    "code_scanning",
34    "copilot_code_review",
35    "license_compliance_scanning",
36    "file_path_restriction",
37    "max_file_path_length",
38    "file_extension_restriction",
39    "max_file_size",
40];
41
42const READ_ONLY_RULESET_FIELDS: &[&str] = &[
43    "node_id",
44    "_links",
45    "current_user_can_bypass",
46    "created_at",
47    "updated_at",
48];
49
50#[derive(Deserialize)]
51struct GithubRulesetSummary {
52    id: u64,
53    name: String,
54    #[serde(default)]
55    target: Option<String>,
56    source_type: String,
57    source: String,
58    enforcement: String,
59}
60
61#[derive(Serialize)]
62struct RulesetListQuery {
63    per_page: u8,
64    includes_parents: bool,
65}
66
67#[derive(Serialize)]
68struct IncludesParents {
69    includes_parents: bool,
70}
71
72#[derive(Deserialize)]
73struct RulesetWriteReceipt {
74    id: u64,
75}
76
77#[derive(Serialize)]
78struct GithubRulesetWrite<'a> {
79    name: &'a str,
80    target: &'a str,
81    enforcement: &'a str,
82    bypass_actors: &'a [GithubRulesetBypassActor],
83    #[serde(skip_serializing_if = "Option::is_none")]
84    conditions: Option<&'a GithubRulesetConditions>,
85    rules: &'a [GithubRulesetRule],
86}
87
88/// One GitHub repository ruleset, including read-only source identity and
89/// every writable configuration field.
90///
91/// Optional fields remain absent rather than acquiring GitHub's documented
92/// defaults. `additional` retains response fields added by GitHub. Rule
93/// parameters and unrecognized rule forms are retained by [`GithubRulesetRule`]
94/// without provider-neutral normalization. Applying a value rejects unknown
95/// writable forms instead of omitting them from the GitHub request.
96#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
97pub struct GithubRuleset {
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub id: Option<u64>,
100    pub name: String,
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub target: Option<String>,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub source_type: Option<String>,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub source: Option<String>,
107    pub enforcement: String,
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub bypass_actors: Option<Vec<GithubRulesetBypassActor>>,
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub conditions: Option<GithubRulesetConditions>,
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub rules: Option<Vec<GithubRulesetRule>>,
114    #[serde(flatten)]
115    pub additional: BTreeMap<String, Value>,
116}
117
118impl GithubRuleset {
119    /// Checks local invariants without interpreting unknown GitHub values.
120    ///
121    /// This rejects empty identities and zero numeric identifiers. It does not
122    /// replace provider validation of whether a retained rule, target, or
123    /// parameter is writable in the repository that receives it.
124    pub fn validate(&self) -> std::result::Result<(), ModelError> {
125        non_empty(&self.name, "GitHub ruleset name")?;
126        non_empty(&self.enforcement, "GitHub ruleset enforcement")?;
127        if self.id == Some(0) {
128            return Err(ModelError::InvalidNumber);
129        }
130        for (value, field) in [
131            (self.target.as_deref(), "GitHub ruleset target"),
132            (self.source_type.as_deref(), "GitHub ruleset source type"),
133            (self.source.as_deref(), "GitHub ruleset source"),
134        ] {
135            if let Some(value) = value {
136                non_empty(value, field)?;
137            }
138        }
139        if let Some(actors) = &self.bypass_actors {
140            for actor in actors {
141                actor.validate()?;
142            }
143        }
144        if let Some(rules) = &self.rules {
145            for rule in rules {
146                rule.validate()?;
147            }
148        }
149        Ok(())
150    }
151}
152
153/// GitHub ruleset conditions.
154///
155/// `ref_name` exposes include and exclusion patterns. Conditions used by
156/// organization or future rulesets remain in `additional` and round-trip
157/// unchanged.
158#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
159pub struct GithubRulesetConditions {
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub ref_name: Option<GithubRefNameCondition>,
162    #[serde(flatten)]
163    pub additional: BTreeMap<String, Value>,
164}
165
166/// Include and exclusion patterns for a GitHub ref-name condition.
167///
168/// Absence is distinct from an explicitly empty collection, so Interprex does
169/// not invent a target pattern or exclusion list.
170#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
171pub struct GithubRefNameCondition {
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub include: Option<Vec<String>>,
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub exclude: Option<Vec<String>>,
176    #[serde(flatten)]
177    pub additional: BTreeMap<String, Value>,
178}
179
180/// A GitHub actor allowed to bypass a ruleset.
181///
182/// Provider strings are retained verbatim so a newer actor type or bypass
183/// mode is visible to configuration tools rather than discarded. A missing
184/// mode remains missing instead of being changed to GitHub's default.
185#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
186pub struct GithubRulesetBypassActor {
187    pub actor_type: String,
188    #[serde(flatten)]
189    pub fields: BTreeMap<String, Value>,
190}
191
192impl GithubRulesetBypassActor {
193    fn validate(&self) -> std::result::Result<(), ModelError> {
194        non_empty(&self.actor_type, "GitHub bypass actor type")?;
195        if self.fields.get("actor_id").and_then(Value::as_u64) == Some(0) {
196            return Err(ModelError::InvalidNumber);
197        }
198        if let Some(mode) = self.fields.get("bypass_mode").and_then(Value::as_str) {
199            non_empty(mode, "GitHub bypass mode")?;
200        }
201        Ok(())
202    }
203
204    /// The actor ID exactly as GitHub represented it, including explicit null.
205    #[must_use]
206    pub fn actor_id(&self) -> Option<&Value> {
207        self.fields.get("actor_id")
208    }
209
210    /// The bypass mode exactly as GitHub represented it.
211    #[must_use]
212    pub fn bypass_mode(&self) -> Option<&Value> {
213        self.fields.get("bypass_mode")
214    }
215}
216
217/// One GitHub ruleset rule in its complete native shape.
218///
219/// `rule_type` identifies the documented or future rule. `fields` retains all
220/// remaining fields, including the complete `parameters` object for rules that
221/// have one. Parameterless and unknown rules therefore round-trip without a
222/// fabricated empty parameters object.
223#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
224pub struct GithubRulesetRule {
225    #[serde(rename = "type")]
226    pub rule_type: String,
227    #[serde(flatten)]
228    pub fields: BTreeMap<String, Value>,
229}
230
231impl GithubRulesetRule {
232    fn validate(&self) -> std::result::Result<(), ModelError> {
233        non_empty(&self.rule_type, "GitHub rule type")
234    }
235
236    /// The complete GitHub parameters value when this rule carries one.
237    #[must_use]
238    pub fn parameters(&self) -> Option<&Value> {
239        self.fields.get("parameters")
240    }
241}
242
243#[async_trait]
244impl SourceCodeConfigurationProvider for GithubProvider {
245    type Ruleset = GithubRuleset;
246
247    /// Returns rulesets ordered by source type, source identity, and numeric
248    /// GitHub ruleset ID. This order makes repeated inventory reads stable; it
249    /// does not describe GitHub's ruleset evaluation priority.
250    async fn read_rulesets(&self, repository: &Repository) -> Result<Vec<Self::Ruleset>> {
251        let page: Page<Value> = self
252            .user()?
253            .get(
254                format!("/repos/{repository}/rulesets"),
255                Some(&RulesetListQuery {
256                    per_page: 100,
257                    includes_parents: true,
258                }),
259            )
260            .await
261            .map_err(|error| {
262                read_error(
263                    "list source rulesets",
264                    format!("source rulesets for {repository}"),
265                    error,
266                )
267            })?;
268        let mut summaries = self
269            .user()?
270            .all_pages(page)
271            .await
272            .map_err(|error| {
273                read_error(
274                    "list source rulesets",
275                    format!("source rulesets for {repository}"),
276                    error,
277                )
278            })?
279            .into_iter()
280            .map(parse_summary)
281            .collect::<Result<Vec<_>>>()?;
282        summaries.sort_by(|left, right| {
283            (&left.source_type, &left.source, left.id).cmp(&(
284                &right.source_type,
285                &right.source,
286                right.id,
287            ))
288        });
289
290        let mut rulesets = Vec::with_capacity(summaries.len());
291        for summary in summaries {
292            rulesets.push(self.read_ruleset_detail(repository, &summary).await?);
293        }
294        Ok(rulesets)
295    }
296
297    async fn apply_ruleset(
298        &self,
299        repository: &Repository,
300        ruleset: &Self::Ruleset,
301    ) -> Result<Self::Ruleset> {
302        let desired = writable_ruleset(repository, ruleset)?;
303        let desired_value = serde_json::to_value(&desired).map_err(|error| {
304            invalid_input(format!("ruleset cannot be serialized for GitHub: {error}"))
305        })?;
306        let id = match ruleset.id {
307            Some(id) => {
308                let _: Value = self
309                    .streaming_user()?
310                    .put(
311                        format!("/repos/{repository}/rulesets/{id}"),
312                        Some(&desired_value),
313                    )
314                    .await
315                    .map_err(|error| write_error("update source ruleset", Some(id), error))?;
316                id
317            }
318            None => {
319                let response: Value = self
320                    .streaming_user()?
321                    .post(
322                        format!("/repos/{repository}/rulesets"),
323                        Some(&desired_value),
324                    )
325                    .await
326                    .map_err(|error| write_error("create source ruleset", None, error))?;
327                parse_receipt(response)?
328            }
329        };
330
331        let summary = GithubRulesetSummary {
332            id,
333            name: desired.name.to_owned(),
334            target: Some(desired.target.to_owned()),
335            source_type: "Repository".to_owned(),
336            source: repository.to_string(),
337            enforcement: desired.enforcement.to_owned(),
338        };
339        let observed = self.read_ruleset_detail(repository, &summary).await?;
340        let observed_value = serde_json::to_value(writable_ruleset(repository, &observed)?)
341            .map_err(|error| {
342                unrepresentable(format!("accepted ruleset cannot be read: {error}"))
343            })?;
344        if observed_value != desired_value {
345            return Err(unrepresentable(format!(
346                "ruleset {id} writable configuration changed between apply and verification"
347            )));
348        }
349        Ok(observed)
350    }
351}
352
353impl GithubProvider {
354    async fn read_ruleset_detail(
355        &self,
356        repository: &Repository,
357        summary: &GithubRulesetSummary,
358    ) -> Result<GithubRuleset> {
359        let response: Value = self
360            .user()?
361            .get(
362                format!("/repos/{repository}/rulesets/{}", summary.id),
363                Some(&IncludesParents {
364                    includes_parents: true,
365                }),
366            )
367            .await
368            .map_err(|error| {
369                read_error(
370                    "read source ruleset detail",
371                    format!("source ruleset {} for {repository}", summary.id),
372                    error,
373                )
374            })?;
375        let ruleset: GithubRuleset = serde_json::from_value(response).map_err(|error| {
376            unrepresentable(format!(
377                "source ruleset {} detail is unreadable: {error}",
378                summary.id
379            ))
380        })?;
381        validate_detail(repository, summary, &ruleset)?;
382        Ok(ruleset)
383    }
384}
385
386fn parse_summary(value: Value) -> Result<GithubRulesetSummary> {
387    let summary: GithubRulesetSummary = serde_json::from_value(value).map_err(|error| {
388        unrepresentable(format!("source ruleset summary is unreadable: {error}"))
389    })?;
390    if summary.id == 0 {
391        return Err(unrepresentable("source ruleset summary has a zero id"));
392    }
393    for (value, fact) in [
394        (&summary.name, "name"),
395        (&summary.source_type, "source type"),
396        (&summary.source, "source"),
397        (&summary.enforcement, "enforcement"),
398    ] {
399        if value.is_empty() {
400            return Err(unrepresentable(format!(
401                "source ruleset {} summary has an empty {fact}",
402                summary.id
403            )));
404        }
405    }
406    if summary.target.as_deref() == Some("") {
407        return Err(unrepresentable(format!(
408            "source ruleset {} summary has an empty target",
409            summary.id
410        )));
411    }
412    Ok(summary)
413}
414
415fn validate_detail(
416    repository: &Repository,
417    summary: &GithubRulesetSummary,
418    ruleset: &GithubRuleset,
419) -> Result<()> {
420    ruleset.validate().map_err(|error| {
421        unrepresentable(format!(
422            "source ruleset {} detail is invalid: {error}",
423            summary.id
424        ))
425    })?;
426    if ruleset.id != Some(summary.id) {
427        return Err(unrepresentable(format!(
428            "source ruleset {} detail identifies {:?}",
429            summary.id, ruleset.id
430        )));
431    }
432    let target = ruleset
433        .target
434        .as_deref()
435        .ok_or_else(|| unrepresentable(format!("source ruleset {} has no target", summary.id)))?;
436    if !matches!(target, "branch" | "tag" | "push" | "repository") {
437        return Err(unsupported("read an unknown ruleset target"));
438    }
439    let source_type = ruleset.source_type.as_deref().ok_or_else(|| {
440        unrepresentable(format!("source ruleset {} has no source type", summary.id))
441    })?;
442    if !matches!(source_type, "Repository" | "Organization" | "Enterprise") {
443        return Err(unsupported("read an unknown ruleset source type"));
444    }
445    let source = ruleset
446        .source
447        .as_deref()
448        .ok_or_else(|| unrepresentable(format!("source ruleset {} has no source", summary.id)))?;
449    if ruleset.source_type.as_deref() != Some(summary.source_type.as_str())
450        || ruleset.source.as_deref() != Some(summary.source.as_str())
451    {
452        return Err(unrepresentable(format!(
453            "source ruleset {} detail has a different source identity",
454            summary.id
455        )));
456    }
457    if source_type == "Repository" && source != repository.to_string() {
458        return Err(unrepresentable(format!(
459            "source ruleset {} belongs to repository {source}, not {repository}",
460            summary.id
461        )));
462    }
463    if ruleset.bypass_actors.is_none() {
464        return Err(unsupported(
465            "read complete rulesets without bypass-actor access",
466        ));
467    }
468    if ruleset.rules.is_none() {
469        return Err(unrepresentable(format!(
470            "source ruleset {} detail has no rules",
471            summary.id
472        )));
473    }
474    Ok(())
475}
476
477fn writable_ruleset<'a>(
478    repository: &Repository,
479    ruleset: &'a GithubRuleset,
480) -> Result<GithubRulesetWrite<'a>> {
481    ruleset
482        .validate()
483        .map_err(|error| invalid_input(error.to_string()))?;
484    let target = ruleset
485        .target
486        .as_deref()
487        .ok_or_else(|| invalid_input("ruleset target must be explicit"))?;
488    if target == "repository" {
489        return Err(unsupported(
490            "apply repository-target rulesets through a repository endpoint",
491        ));
492    }
493    if !matches!(target, "branch" | "tag" | "push") {
494        return Err(unsupported("apply an unknown ruleset target"));
495    }
496    if !matches!(
497        ruleset.enforcement.as_str(),
498        "disabled" | "active" | "evaluate"
499    ) {
500        return Err(unsupported("apply an unknown ruleset enforcement value"));
501    }
502    validate_write_source(repository, ruleset)?;
503    validate_write_fields(ruleset)?;
504    let bypass_actors = ruleset
505        .bypass_actors
506        .as_deref()
507        .ok_or_else(|| invalid_input("complete ruleset requires bypass_actors, including empty"))?;
508    let rules = ruleset
509        .rules
510        .as_deref()
511        .ok_or_else(|| invalid_input("complete ruleset requires rules, including empty"))?;
512    Ok(GithubRulesetWrite {
513        name: &ruleset.name,
514        target,
515        enforcement: &ruleset.enforcement,
516        bypass_actors,
517        conditions: ruleset.conditions.as_ref(),
518        rules,
519    })
520}
521
522fn validate_write_source(repository: &Repository, ruleset: &GithubRuleset) -> Result<()> {
523    match ruleset.id {
524        Some(_) => match (ruleset.source_type.as_deref(), ruleset.source.as_deref()) {
525            (Some("Repository"), Some(source)) if source == repository.to_string() => Ok(()),
526            (Some("Repository"), Some(_)) => Err(invalid_input(
527                "ruleset repository source does not match the destination repository",
528            )),
529            (Some("Organization"), Some(_)) | (Some("Enterprise"), Some(_)) => Err(unsupported(
530                "apply an inherited ruleset through a repository endpoint",
531            )),
532            (Some(_), Some(_)) => Err(unsupported("apply an unknown ruleset source type")),
533            _ => Err(invalid_input(
534                "existing ruleset requires its repository source identity",
535            )),
536        },
537        None if ruleset.source_type.is_some() || ruleset.source.is_some() => Err(invalid_input(
538            "new ruleset must not carry read-only source identity",
539        )),
540        None => Ok(()),
541    }
542}
543
544fn validate_write_fields(ruleset: &GithubRuleset) -> Result<()> {
545    if ruleset
546        .additional
547        .keys()
548        .any(|field| !READ_ONLY_RULESET_FIELDS.contains(&field.as_str()))
549    {
550        return Err(unsupported(
551            "apply a ruleset with an unknown top-level field",
552        ));
553    }
554    if ruleset.id.is_none() && !ruleset.additional.is_empty() {
555        return Err(invalid_input(
556            "new ruleset must not carry read-only provider metadata",
557        ));
558    }
559    if let Some(conditions) = &ruleset.conditions
560        && (!conditions.additional.is_empty()
561            || conditions
562                .ref_name
563                .as_ref()
564                .is_some_and(|condition| !condition.additional.is_empty()))
565    {
566        return Err(unsupported("apply a ruleset with an unknown condition"));
567    }
568    if let Some(ref_name) = ruleset
569        .conditions
570        .as_ref()
571        .and_then(|conditions| conditions.ref_name.as_ref())
572        && (ref_name.include.is_none() || ref_name.exclude.is_none())
573    {
574        return Err(invalid_input(
575            "a ref-name condition requires explicit include and exclude collections",
576        ));
577    }
578    if let Some(actors) = &ruleset.bypass_actors {
579        for actor in actors {
580            if actor
581                .fields
582                .keys()
583                .any(|field| !matches!(field.as_str(), "actor_id" | "bypass_mode"))
584            {
585                return Err(unsupported("apply a ruleset with an unknown bypass field"));
586            }
587            if !matches!(
588                actor.actor_type.as_str(),
589                "Integration"
590                    | "OrganizationAdmin"
591                    | "RepositoryRole"
592                    | "Team"
593                    | "DeployKey"
594                    | "User"
595            ) {
596                return Err(unsupported(
597                    "apply a ruleset with an unknown bypass actor type",
598                ));
599            }
600            match actor.actor_id() {
601                Some(Value::Null) => {}
602                Some(Value::Number(id)) if id.as_u64().is_some_and(|id| id > 0) => {}
603                _ => {
604                    return Err(invalid_input(
605                        "a bypass actor requires an explicit null or positive integer actor_id",
606                    ));
607                }
608            }
609            let mode = actor
610                .bypass_mode()
611                .and_then(Value::as_str)
612                .ok_or_else(|| invalid_input("a bypass actor requires a string bypass_mode"))?;
613            if !matches!(mode, "always" | "pull_request" | "exempt") {
614                return Err(unsupported("apply a ruleset with an unknown bypass mode"));
615            }
616        }
617    }
618    if let Some(rules) = &ruleset.rules {
619        for rule in rules {
620            if !WRITABLE_RULE_TYPES.contains(&rule.rule_type.as_str()) {
621                return Err(unsupported("apply an unknown ruleset rule"));
622            }
623            if rule
624                .fields
625                .keys()
626                .any(|field| field.as_str() != "parameters")
627            {
628                return Err(unsupported("apply a ruleset rule with an unknown field"));
629            }
630        }
631    }
632    Ok(())
633}
634
635fn parse_receipt(value: Value) -> Result<u64> {
636    let receipt: RulesetWriteReceipt = serde_json::from_value(value)
637        .map_err(|error| unrepresentable(format!("created ruleset has no readable id: {error}")))?;
638    if receipt.id == 0 {
639        Err(unrepresentable("created ruleset has a zero id"))
640    } else {
641        Ok(receipt.id)
642    }
643}
644
645fn write_error(
646    operation: &'static str,
647    ruleset_id: Option<u64>,
648    error: octocrab::Error,
649) -> ProviderError {
650    if matches!(
651        &error,
652        octocrab::Error::GitHub { source, .. } if source.status_code.as_u16() == 404
653    ) {
654        return ProviderError::NotFound {
655            entity: ruleset_id.map_or_else(
656                || "repository rulesets".to_owned(),
657                |id| format!("source ruleset {id}"),
658            ),
659        };
660    }
661    if let octocrab::Error::GitHub { source, .. } = &error
662        && source.status_code.as_u16() == 422
663        && let Some(errors) = source.errors.as_deref()
664        && !errors.is_empty()
665        && let Some(mut fields) = errors
666            .iter()
667            .map(ruleset_validation_field)
668            .collect::<Option<Vec<_>>>()
669    {
670        fields.sort_unstable();
671        fields.dedup();
672        return invalid_input(format!(
673            "GitHub rejected these ruleset fields: {}",
674            fields.join(", ")
675        ));
676    }
677    authenticated_external(operation, &error)
678}
679
680fn ruleset_validation_field(error: &Value) -> Option<&'static str> {
681    let field = error.get("field")?.as_str()?;
682    let code = error.get("code")?.as_str()?;
683    if !matches!(
684        code,
685        "custom" | "invalid" | "missing" | "missing_field" | "unprocessable"
686    ) {
687        return None;
688    }
689    match field {
690        "name" => Some("name"),
691        "target" => Some("target"),
692        "enforcement" => Some("enforcement"),
693        "bypass_actors" => Some("bypass_actors"),
694        "conditions" => Some("conditions"),
695        "rules" => Some("rules"),
696        _ => None,
697    }
698}
699
700fn invalid_input(fact: impl Into<String>) -> ProviderError {
701    ProviderError::InvalidInput {
702        provider: "github",
703        fact: fact.into(),
704    }
705}
706
707fn unrepresentable(fact: impl Into<String>) -> ProviderError {
708    ProviderError::Unrepresentable {
709        provider: "github",
710        fact: fact.into(),
711    }
712}
713
714fn unsupported(operation: &'static str) -> ProviderError {
715    ProviderError::Unsupported {
716        provider: "github",
717        operation,
718    }
719}
720
721fn non_empty(value: &str, field: &'static str) -> std::result::Result<(), ModelError> {
722    if value.is_empty() {
723        Err(ModelError::Empty { field })
724    } else {
725        Ok(())
726    }
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732
733    #[test]
734    fn complete_ruleset_round_trips_known_and_unknown_native_fields() {
735        let fixture = serde_json::json!({
736            "id": 7,
737            "name": "pull requests",
738            "target": "branch",
739            "source_type": "Repository",
740            "source": "civitas-forge/interprex",
741            "enforcement": "evaluate",
742            "bypass_actors": [
743                {"actor_id": 15368, "actor_type": "Integration", "bypass_mode": "pull_request"},
744                {"actor_id": null, "actor_type": "FutureActor", "bypass_mode": "future_mode", "future": true}
745            ],
746            "conditions": {
747                "ref_name": {"include": ["~DEFAULT_BRANCH"], "exclude": ["refs/heads/release/*"]},
748                "repository_name": {"include": ["important-*"], "exclude": ["archive-*"], "protected": true}
749            },
750            "rules": [
751                {"type": "required_status_checks", "parameters": {
752                    "strict_required_status_checks_policy": true,
753                    "do_not_enforce_on_create": false,
754                    "required_status_checks": [{"context": "quality", "integration_id": 15368}]
755                }},
756                {"type": "required_signatures"},
757                {"type": "future_rule", "parameters": {"new_option": true}, "future": "retained"}
758            ],
759            "current_user_can_bypass": "never",
760            "future_top_level": {"retained": true}
761        });
762
763        let ruleset: GithubRuleset =
764            serde_json::from_value(fixture.clone()).expect("deserialize complete ruleset");
765        ruleset.validate().expect("valid ruleset");
766        assert_eq!(
767            ruleset
768                .conditions
769                .as_ref()
770                .and_then(|conditions| conditions.ref_name.as_ref())
771                .and_then(|condition| condition.exclude.as_ref()),
772            Some(&vec!["refs/heads/release/*".to_owned()])
773        );
774        assert_eq!(
775            ruleset.rules.as_ref().expect("rules")[0].parameters(),
776            Some(&fixture["rules"][0]["parameters"])
777        );
778        assert_eq!(
779            serde_json::to_value(ruleset).expect("serialize complete ruleset"),
780            fixture
781        );
782    }
783
784    #[test]
785    fn ruleset_validation_rejects_empty_native_identities() {
786        let ruleset: GithubRuleset = serde_json::from_value(serde_json::json!({
787            "id": 7,
788            "name": "pull requests",
789            "enforcement": "active",
790            "rules": [{"type": ""}]
791        }))
792        .expect("deserialize ruleset");
793        assert_eq!(
794            ruleset.validate(),
795            Err(ModelError::Empty {
796                field: "GitHub rule type"
797            })
798        );
799    }
800
801    #[test]
802    fn every_current_writable_rule_kind_retains_its_complete_fields() {
803        let kinds = [
804            "creation",
805            "update",
806            "deletion",
807            "required_linear_history",
808            "merge_queue",
809            "required_deployments",
810            "required_signatures",
811            "pull_request",
812            "required_status_checks",
813            "non_fast_forward",
814            "commit_message_pattern",
815            "commit_author_email_pattern",
816            "committer_email_pattern",
817            "branch_name_pattern",
818            "tag_name_pattern",
819            "workflows",
820            "code_scanning",
821            "copilot_code_review",
822            "license_compliance_scanning",
823            "file_path_restriction",
824            "max_file_path_length",
825            "file_extension_restriction",
826            "max_file_size",
827        ];
828        for kind in kinds {
829            let fixture = serde_json::json!({
830                "type": kind,
831                "parameters": {"provider_owned": [true, 7, "value"]},
832                "future_field": {"retained": true}
833            });
834            let rule: GithubRulesetRule =
835                serde_json::from_value(fixture.clone()).expect("deserialize rule");
836            assert_eq!(serde_json::to_value(rule).expect("serialize rule"), fixture);
837        }
838    }
839}