"""Exercise the real scanner: monitoring exceptions must be scoped and expire.""" import os from pathlib import Path import shutil import subprocess import tempfile import unittest ROOT = Path(__file__).resolve().parents[2] TRIVY = os.environ.get('TRIVY_BIN') or shutil.which('trivy') @unittest.skipUnless(TRIVY, 'Trivy is required for scanner policy integration checks') class TrivyPolicy(unittest.TestCase): def test_exception_does_not_cover_other_paths_or_survive_expiration(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) relative = Path('infra/prod/k8s/monitoring/04-node-exporter.yaml') approved = root / relative approved.parent.mkdir(parents=True) shutil.copyfile(ROOT / relative, approved) policy = root / '.trivyignore.yaml' policy.write_text((ROOT / '.trivyignore.yaml').read_text()) def scan(): result = subprocess.run( [TRIVY, 'config', '--skip-check-update', '--severity', 'HIGH,CRITICAL', '--ignorefile', str(policy), '--exit-code', '1', '--format', 'json', str(root)], capture_output=True, text=True, timeout=60) # A scanner crash or invalid report cannot count as a successful rejection. import json report = json.loads(result.stdout) self.assertIn('Results', report) return result.returncode self.assertEqual(scan(), 0, 'Approved monitoring policy should pass before expiry') other = root / 'unapproved.yaml' approved.rename(other) self.assertEqual(scan(), 1, 'The same access outside the approved path must fail') other.rename(approved) policy.write_text(policy.read_text().replace('2026-10-24', '2000-01-01')) self.assertEqual(scan(), 1, 'Expired exceptions must fail closed')