[PATCH v2 07/11] kconfig-audit: Add support for policy overlays

From: Ahmed S. Darwish

Date: Thu Dec 03 2026 - 17:49:59 EST


A kconfig-audit policy overlay is a YAML file applied on top of an existing
policy file. Overlays are intended for distribution kernel packaging
scripts, CI environments, and board support packages; where the base rules
may need local adjustments. Overlays may override any rule's field. They
may also update the documentation URL or introduce totally new rules.

Add support for such an overlay mechanism at the kconfig-audit Python code.

Introduce a data model for rule overlays first, then extend the checker's
logic in terms of that.

Signed-off-by: Ahmed S. Darwish <darwi@xxxxxxxxxxxxx>
---
tools/kconfig-audit/audit.py | 210 ++++++++++++++++++++++++++++++++++-
1 file changed, 208 insertions(+), 2 deletions(-)

diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
index 94ff427715d1..ba6ba86f2791 100755
--- a/tools/kconfig-audit/audit.py
+++ b/tools/kconfig-audit/audit.py
@@ -9,7 +9,7 @@
# $ audit.py list-policies
# $ audit.py list-api-versions
#
-# $ audit.py check -c path/to/.config -p preempt_rt
+# $ audit.py check -c path/to/.config -p preempt_rt [-o path/to/overlay.yml]
#
# Development rules:
#
@@ -31,6 +31,9 @@
# Policy # internal model, typed policy rules repo
# PolicyFile # parser
#
+# PolicyOverlay # internal model, typed overlays repo
+# PolicyOverlayFile # parser
+#
# Schema # internal model, dictionary-like
# SchemaFile # parser
#
@@ -78,7 +81,9 @@ import textwrap
from dataclasses import dataclass, field
from enum import Enum, auto
from pathlib import Path
-from typing import Any, ClassVar, Final, Mapping, NoReturn, Optional, Protocol
+from typing import (
+ Any, ClassVar, Final, Mapping, NoReturn, Optional, Protocol, Union,
+)

#
# Initial sanity checks:
@@ -546,6 +551,195 @@ class PolicyFile(VersionedYamlFile):
# Schema should guard against this
Helpers.unreachable('YAML rule entry without `name` or `name_pattern`')

+#
+# Policy overlays model:
+#
+
+@dataclass(frozen=True)
+class SymbolOverlay:
+ """Overlay for a .config symbol rule"""
+
+ symbol: str
+
+ @property
+ def rule_id(self) -> str:
+ return self.symbol
+
+@dataclass(frozen=True)
+class PatternOverlay:
+ """Overlay for a .config regex pattern rule"""
+
+ symbol_regex: str
+
+ @property
+ def rule_id(self) -> str:
+ return self.symbol_regex
+
+OverlayTarget = Union[SymbolOverlay, PatternOverlay]
+
+@dataclass
+class RuleOverlay:
+ """Typed overlay for a (symbol or regex) .config rule"""
+
+ target: OverlayTarget
+ expected: Optional[ExpectedValue]
+ severity: Optional[Severity]
+ rationale: Optional[str]
+ docs_hint: Optional[str]
+
+ @property
+ def rule_id(self) -> str:
+ return self.target.rule_id
+
+@dataclass
+class PolicyOverlay:
+ """Policy overlays repository / data model"""
+
+ docs_url: Optional[str]
+
+ # Store rule overlays in a dictionary to easily detect duplicates
+ rules: dict[OverlayTarget, RuleOverlay]
+
+ def add_rule(self, rule: RuleOverlay) -> None:
+ """Add the given rule overly to the overlays repository"""
+ target = rule.target
+
+ if target in self.rules:
+ if isinstance(target, SymbolOverlay):
+ error(
+ f'Duplicate overlay rule: {rule.rule_id}',
+ os.EX_DATAERR,
+ )
+ if isinstance(target, PatternOverlay):
+ error(
+ f'Duplicate overlay pattern: {rule.rule_id}',
+ os.EX_DATAERR,
+ )
+ raise TypeError(f'Unsupported target type: {type(target).__name__}')
+
+ self.rules[target] = rule
+
+class PolicyOverlayFile(VersionedYamlFile):
+ """YAML overlay files parser (to PolicyOverlay)"""
+
+ SCHEMAS = {
+ VersionedYamlFile.AUDIT_API_V1: 'policy-overlay-v1.yml',
+ }
+
+ def parse(self) -> PolicyOverlay:
+ """Parse the YAML overlay file into a typed PolicyOverlay"""
+ docs_url = self.yaml.get('docs_url')
+ overlay = PolicyOverlay(docs_url, {})
+
+ for rule_mapping in self.yaml.get('rules', []):
+ overlay.add_rule(self._parse_rule(rule_mapping))
+
+ return overlay
+
+ def _parse_rule(self, rule: YamlDict) -> RuleOverlay:
+ """Parse passed single YAML overlay rule (to RuleOverlay)"""
+ if 'name' in rule:
+ symbol = rule['name']
+ target: OverlayTarget = SymbolOverlay(symbol)
+ elif 'name_pattern' in rule:
+ regex = rule['name_pattern']
+ target = PatternOverlay(regex)
+ else:
+ Helpers.unreachable('Overlay rule without `name` or `name_pattern`')
+
+ expected = (
+ ExpectedValue[rule['expected']]
+ if 'expected' in rule else None
+ )
+ severity = (
+ Severity[rule['severity']]
+ if 'severity' in rule else None
+ )
+
+ return RuleOverlay(
+ target,
+ expected,
+ severity,
+ rule.get('rationale'),
+ rule.get('docs_hint'),
+ )
+
+class Overlayer:
+ """Apply a parsed policy overlay to a policy"""
+
+ @staticmethod
+ def apply(overlay: PolicyOverlay, policy: Policy) -> Policy:
+ """Apply passed overlay to policy and return the updated policy"""
+ if overlay.docs_url:
+ policy.docs_url = overlay.docs_url
+
+ for rule_overlay in overlay.rules.values():
+ rule = Overlayer._find_rule(rule_overlay, policy)
+ if rule:
+ Overlayer._update_rule(rule_overlay, rule)
+ else:
+ new_rule = Overlayer._new_rule(rule_overlay)
+ policy.add_rule(new_rule)
+
+ return policy
+
+ @staticmethod
+ def _find_rule(overlay: RuleOverlay, policy: Policy) -> Optional[Rule]:
+ """Find the actual policy rule targeted by passed rule overlay"""
+ if isinstance(overlay.target, SymbolOverlay):
+ return policy.get_symbol_rule(overlay.rule_id)
+
+ if isinstance(overlay.target, PatternOverlay):
+ return policy.get_pattern_rule(overlay.rule_id)
+
+ Helpers.unreachable('Unknown overlay target type')
+
+ @staticmethod
+ def _update_rule(overlay: RuleOverlay, rule: Rule) -> None:
+ """Apply an overlay's specified fields to an existing rule"""
+ if overlay.expected:
+ rule.expected = overlay.expected
+
+ if overlay.severity:
+ rule.severity = overlay.severity
+
+ if overlay.rationale:
+ rule.rationale = overlay.rationale
+
+ if overlay.docs_hint:
+ rule.docs_hint = overlay.docs_hint
+ rule._normalize_docs_hint()
+
+ @staticmethod
+ def _new_rule(overlay: RuleOverlay) -> Rule:
+ """Create a new policy rule from an overlay that has no matching rule"""
+
+ # A policy overlay over a base rule has all required fields
+ # provided by its parent. New rules have no parent, and thus all
+ # required fields must be manually checked.
+ if not overlay.expected:
+ error(
+ f'`expected` is missing from {overlay.rule_id}',
+ os.EX_DATAERR,
+ )
+ if not overlay.severity:
+ error(
+ f'`severity` is missing from {overlay.rule_id}',
+ os.EX_DATAERR,
+ )
+
+ args = (
+ overlay.expected,
+ overlay.severity,
+ overlay.rationale,
+ overlay.docs_hint,
+ )
+
+ if isinstance(overlay.target, SymbolOverlay):
+ return SymbolRule(*args, overlay.rule_id)
+
+ return PatternRule(*args, re.compile(overlay.rule_id))
+
#
# Error reporting model:
#
@@ -904,6 +1098,14 @@ def parse_args(policies: list[str]) -> argparse.Namespace:
help='policy file to check against',
)

+ check_parser.add_argument(
+ '-o',
+ '--overlay',
+ metavar='OVERLAY_FILE',
+ type=Path,
+ help='policy overlay file to apply after the selected policy',
+ )
+
return parser.parse_args()

def main() -> None:
@@ -932,6 +1134,10 @@ def main() -> None:
policy_f = policy_dir / f'{args.policy}.yml'
policy = PolicyFile(policy_f, schema_dir).parse()

+ if args.overlay:
+ overlay = PolicyOverlayFile(args.overlay, schema_dir).parse()
+ policy = Overlayer.apply(overlay, policy)
+
checker = Checker(kconfig, policy)
report = checker.make_report()

--
2.56.0