🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: linux.kernel
Article #58

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

#58
From: Ahmed S. Darwish
Date: Thu, 03 Dec 2026 23:10
274 lines
11390 bytes
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@linutronix.de>
---
 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
Technical Details
Message-ID: <O6o65-fPfD-21@gated-at.bofh.it>
Path: mbox-mo1.pugleaf.net!feed-eu-txt.newsdeef.eu!feed-eu-nl.newsdeef.eu!feed-eu-ch.newsdeef.eu!srl.newsdeef.eu!news.samoylyk.net!gothmog.csi.it!bofh.it!news.nic.it!robomod
References: <O6o65-fPfD-3@gated-at.bofh.it>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!feed-eu-txt.newsdeef.eu!feed-eu-nl.newsdeef.eu!feed-eu-ch.newsdeef.eu!srl.newsdeef.eu!news.samoylyk.net!gothmog.csi.it!bofh.it!news.nic.it!robomod
From: "Ahmed S. Darwish" <darwi@linutronix.de>
Newsgroups: linux.debian.kernel,linux.kernel
Subject: [PATCH v2 07/11] kconfig-audit: Add support for policy overlays
Date: Fri, 04 Dec 2026 00:10:01 +0100
Message-ID: <O6o65-fPfD-21@gated-at.bofh.it>
References: <O6o65-fPfD-3@gated-at.bofh.it>
X-Original-To: Nathan Chancellor <nathan@kernel.org>,
	Nicolas Schier <nsc@kernel.org>,
	Julian Braha <julianbraha@gmail.com>,
	Emanuele Rocca <ema@debian.org>,
	Clark Williams <clrkwllms@kernel.org>,
	Steven Rostedt <rostedt@goodmis.org>,
	Ingo Molnar <mingo@redhat.com>
X-Mailbox-Line: From debian-kernel-request@lists.debian.org  Thu Dec  3 23:07:32 2026
Old-Return-Path: <darwi@linutronix.de>
X-Amavis-Spam-Status: No, score=-4.4 tagged_above=-10000 required=5.3
 tests=[BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1,
 DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_MED=-2.3] autolearn=ham autolearn_force=no
X-Policyd-Weight: using cached result; rate: -4.6
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
X-Mailing-List: <debian-kernel@lists.debian.org> archive/latest/158718
List-ID: <debian-kernel.lists.debian.org>
List-URL: <https://lists.debian.org/debian-kernel/>
List-Archive: https://lists.debian.org/msgid-search/20261203224916.118064-8-darwi@linutronix.de
Approved: robomod@news.nic.it
Lines: 274
Organization: linux.* mail to news gateway
Sender: robomod@news.nic.it
X-Original-Cc: Sebastian Andrzej Siewior <bigeasy@linutronix.de>,
	Frederic Weisbecker <frederic@kernel.org>,
	John Ogness <john.ogness@linutronix.de>,
	Derek Barbosa <debarbos@redhat.com>,
	Zbigniew Jędrzejewski-Szmek <zbyszek@amutable.com>,
	Daan De Meyer <daan.j.demeyer@gmail.com>,
	Luca Boccassi <luca.boccassi@gmail.com>,
	linux-rt-devel@lists.linux.dev,
	debian-kernel@lists.debian.org,
	linux-kbuild@vger.kernel.org,
	linux-doc@vger.kernel.org,
	linux-kernel@vger.kernel.org,
	"Ahmed S. Darwish" <darwi@linutronix.de>
X-Original-Date: Thu,  3 Dec 2026 23:49:08 +0100
X-Original-Message-ID: <20261203224916.118064-8-darwi@linutronix.de>
X-Original-References: <20261203224916.118064-1-darwi@linutronix.de>