2026-10-20 06:56:17 +02:00
|
|
|
"""Contract tests for security gates and draft release uploads, without network."""
|
|
|
|
|
import contextlib
|
|
|
|
|
import io
|
2026-10-23 22:23:11 +02:00
|
|
|
import importlib.util
|
2026-10-20 06:56:17 +02:00
|
|
|
import json
|
|
|
|
|
import os
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
import runpy
|
|
|
|
|
import subprocess
|
|
|
|
|
import sys
|
|
|
|
|
import tempfile
|
|
|
|
|
import unittest
|
|
|
|
|
from unittest.mock import patch
|
|
|
|
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parent
|
2026-10-25 17:08:13 +01:00
|
|
|
REPO_ROOT = ROOT.parent.parent
|
|
|
|
|
|
|
|
|
|
class PwaAssetTests(unittest.TestCase):
|
|
|
|
|
def test_manifest_raster_icons_exist_with_declared_dimensions(self):
|
|
|
|
|
manifest = json.loads((REPO_ROOT/'src/Heimdall.Web/wwwroot/manifest.webmanifest').read_text())
|
|
|
|
|
icons = {icon['sizes']: icon for icon in manifest['icons'] if icon['type'] == 'image/png'}
|
|
|
|
|
for size in (192, 512):
|
|
|
|
|
with self.subTest(size=size):
|
|
|
|
|
icon = icons[f'{size}x{size}']
|
|
|
|
|
self.assertTrue(icon['src'].startswith('/'))
|
|
|
|
|
image = REPO_ROOT/'src/Heimdall.Web/wwwroot'/icon['src'].lstrip('/')
|
|
|
|
|
data = image.read_bytes()
|
|
|
|
|
self.assertEqual(data[:8], b'\x89PNG\r\n\x1a\n')
|
|
|
|
|
self.assertEqual(int.from_bytes(data[16:20], 'big'), size)
|
|
|
|
|
self.assertEqual(int.from_bytes(data[20:24], 'big'), size)
|
|
|
|
|
|
|
|
|
|
def test_apple_touch_icon_exists_at_declared_size(self):
|
|
|
|
|
app = (REPO_ROOT/'src/Heimdall.Web/Components/App.razor').read_text()
|
|
|
|
|
self.assertIn('rel="apple-touch-icon" sizes="180x180" href="pwa-icon-180.png"', app)
|
|
|
|
|
data = (REPO_ROOT/'src/Heimdall.Web/wwwroot/pwa-icon-180.png').read_bytes()
|
|
|
|
|
self.assertEqual(data[:8], b'\x89PNG\r\n\x1a\n')
|
|
|
|
|
self.assertEqual(int.from_bytes(data[16:20], 'big'), 180)
|
|
|
|
|
self.assertEqual(int.from_bytes(data[20:24], 'big'), 180)
|
2026-10-20 06:56:17 +02:00
|
|
|
|
2026-10-23 22:23:11 +02:00
|
|
|
def load_test_plan():
|
|
|
|
|
spec = importlib.util.spec_from_file_location('heimdall_test_plan', ROOT/'test-plan.py')
|
|
|
|
|
module = importlib.util.module_from_spec(spec)
|
|
|
|
|
spec.loader.exec_module(module)
|
|
|
|
|
return module
|
|
|
|
|
|
2026-10-26 08:19:44 +01:00
|
|
|
def load_efcore_policy():
|
|
|
|
|
spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py')
|
|
|
|
|
module = importlib.util.module_from_spec(spec)
|
|
|
|
|
spec.loader.exec_module(module)
|
|
|
|
|
return module
|
|
|
|
|
|
|
|
|
|
class EfCorePolicyTests(unittest.TestCase):
|
|
|
|
|
def test_current_production_sources_follow_policy(self):
|
|
|
|
|
self.assertEqual(load_efcore_policy().check_tree(REPO_ROOT), [])
|
|
|
|
|
|
|
|
|
|
def test_agent_ado_net_is_rejected(self):
|
|
|
|
|
failures = load_efcore_policy().inspect_source(
|
|
|
|
|
'src/Heimdall.Agent/Services/Example.cs',
|
|
|
|
|
'using Microsoft.Data.Sqlite; var connection = new SqliteConnection();')
|
|
|
|
|
self.assertEqual(len(failures), 1)
|
|
|
|
|
|
|
|
|
|
def test_provider_specific_sql_requires_explicit_exception_marker(self):
|
|
|
|
|
policy = load_efcore_policy()
|
|
|
|
|
path = 'src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs'
|
|
|
|
|
self.assertEqual(policy.inspect_source(path, 'db.Database.ExecuteSqlRaw("VACUUM");'), [
|
|
|
|
|
f'{path}: direct database API is not allowed; use EF Core or document an approved provider-specific exception'])
|
|
|
|
|
self.assertEqual(policy.inspect_source(path, '// EF Core exception: PostgreSQL maintenance\ndb.Database.ExecuteSqlRaw("VACUUM");'), [])
|
|
|
|
|
|
2026-10-23 22:23:11 +02:00
|
|
|
class TestPlanTests(unittest.TestCase):
|
|
|
|
|
def test_domain_change_reaches_dependent_suites(self):
|
|
|
|
|
suites = load_test_plan().plan(['src/Heimdall.Domain/Camera.cs'])['suites']
|
|
|
|
|
self.assertIn('Heimdall.Domain.Tests', suites)
|
|
|
|
|
self.assertIn('Heimdall.IntegrationTests', suites)
|
|
|
|
|
self.assertIn('Heimdall.E2E.Tests', suites)
|
|
|
|
|
|
|
|
|
|
def test_agent_change_does_not_run_unrelated_web_tests(self):
|
|
|
|
|
suites = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])['suites']
|
|
|
|
|
self.assertIn('Heimdall.Agent.Tests', suites)
|
|
|
|
|
self.assertNotIn('Heimdall.Web.Tests', suites)
|
|
|
|
|
|
|
|
|
|
def test_solution_change_runs_all_and_docs_change_runs_none(self):
|
|
|
|
|
planner = load_test_plan()
|
|
|
|
|
self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS))
|
|
|
|
|
self.assertEqual(planner.plan(['docs/README.md'])['suites'], [])
|
|
|
|
|
|
2026-10-20 06:56:17 +02:00
|
|
|
class AdvisoryTests(unittest.TestCase):
|
|
|
|
|
def check(self, data):
|
|
|
|
|
with tempfile.TemporaryDirectory() as temp:
|
|
|
|
|
path = Path(temp)/'report.json'
|
|
|
|
|
path.write_text(json.dumps(data))
|
|
|
|
|
return subprocess.run([sys.executable, str(ROOT/'check-advisories.py'), str(path)],
|
|
|
|
|
capture_output=True, text=True).returncode
|
|
|
|
|
|
|
|
|
|
def test_high_and_critical_transitive_advisories_fail(self):
|
|
|
|
|
for severity in ('High', 'Critical'):
|
|
|
|
|
report = {'version': 1, 'projects': [{'frameworks': [{'transitivePackages': [{
|
|
|
|
|
'id': 'Example', 'vulnerabilities': [{'severity': severity, 'advisoryurl': 'https://example.test'}]
|
|
|
|
|
}]}]}]}
|
|
|
|
|
self.assertNotEqual(self.check(report), 0)
|
|
|
|
|
|
|
|
|
|
def test_clean_report_passes(self):
|
|
|
|
|
self.assertEqual(self.check({'version': 1, 'projects': [{'frameworks': []}]}), 0)
|
|
|
|
|
|
|
|
|
|
def test_failed_empty_and_invalid_reports_fail_closed(self):
|
|
|
|
|
for report in ({}, {'version': 1, 'projects': []},
|
|
|
|
|
{'version': 1, 'projects': [{}], 'problems': [{'message': 'offline'}]}):
|
|
|
|
|
self.assertNotEqual(self.check(report), 0)
|
|
|
|
|
|
|
|
|
|
class ReleaseTests(unittest.TestCase):
|
|
|
|
|
def execute(self, public=False):
|
|
|
|
|
calls = []
|
|
|
|
|
class Response(io.BytesIO):
|
|
|
|
|
def __enter__(self): return self
|
|
|
|
|
def __exit__(self, *args): self.close()
|
|
|
|
|
def fake_request(req, timeout):
|
|
|
|
|
calls.append(req)
|
|
|
|
|
if req.method == 'GET' and '/releases/tags/' in req.full_url:
|
|
|
|
|
return Response(json.dumps({'id': 7, 'draft': not public,
|
|
|
|
|
'html_url': 'https://example.test/releases/7'}).encode())
|
|
|
|
|
if req.method == 'GET':
|
|
|
|
|
return Response(b'[{"id":8}]')
|
|
|
|
|
if req.method == 'DELETE': return Response(b'')
|
|
|
|
|
return Response(b'{"id":9}')
|
|
|
|
|
with tempfile.TemporaryDirectory() as temp:
|
|
|
|
|
directory = Path(temp)/'artifacts/packages'
|
|
|
|
|
directory.mkdir(parents=True)
|
|
|
|
|
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42'}))
|
|
|
|
|
(directory/'package.tar.gz').write_bytes(b'archive')
|
|
|
|
|
original = Path.cwd()
|
|
|
|
|
try:
|
|
|
|
|
os.chdir(temp)
|
|
|
|
|
with patch.dict(os.environ, {'BUILD_SERVER_URL':'https://example.test',
|
|
|
|
|
'BUILD_REPOSITORY':'owner/repo','BUILD_REF':'refs/tags/v1.2.3','RELEASE_TOKEN':'dummy'}), \
|
|
|
|
|
patch('urllib.request.urlopen', fake_request), contextlib.redirect_stdout(io.StringIO()):
|
|
|
|
|
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
|
|
|
|
|
finally:
|
|
|
|
|
os.chdir(original)
|
|
|
|
|
return calls
|
|
|
|
|
|
|
|
|
|
def test_draft_assets_use_multipart_and_delete_accepts_204(self):
|
|
|
|
|
calls = self.execute()
|
|
|
|
|
uploads = [x for x in calls if x.method == 'POST']
|
|
|
|
|
self.assertEqual(len(uploads), 2)
|
|
|
|
|
for request in uploads:
|
|
|
|
|
self.assertTrue(request.get_header('Content-type').startswith('multipart/form-data; boundary='))
|
|
|
|
|
self.assertIn(b'name="attachment"', request.data)
|
|
|
|
|
self.assertEqual(sum(x.method == 'DELETE' for x in calls), 1)
|
|
|
|
|
|
|
|
|
|
def test_public_release_cannot_be_mutated(self):
|
|
|
|
|
with self.assertRaisesRegex(SystemExit, 'already public'):
|
|
|
|
|
self.execute(public=True)
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
unittest.main()
|