Files
Heimdall/scripts/ci/test_ci.py
T
arnaud.dartois 7c0c8ecf46
Heimdall Gitea / Detect CI scope (push) Successful in 11s
Heimdall Gitea / Build and tests (push) Successful in 18m40s
Heimdall Gitea / Build and scan server image (push) Successful in 8m5s
Heimdall Gitea / Build and scan agent image (push) Successful in 12m52s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 28m19s
Heimdall Gitea / Publish versioned installer release (push) Successful in 4m43s
Heimdall Gitea / CI policy (push) Successful in 13s
[Install] Vérifier le checksum publié du bundle serveur (#328)
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 03:17:50 +01:00

331 lines
17 KiB
Python

"""Contract tests for security gates and versioned release uploads, without network."""
import contextlib
import io
import importlib.util
import json
import os
from pathlib import Path
import runpy
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent
REPO_ROOT = ROOT.parent.parent
def load_change_scope():
spec = importlib.util.spec_from_file_location('heimdall_change_scope', ROOT/'change_scope.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class ChangeScopeTests(unittest.TestCase):
def setUp(self):
self.scope = load_change_scope().scope_for
def test_documentation_does_not_build_or_validate_images(self):
self.assertEqual(self.scope(['docs/operations.md']), {
'run_validation': False, 'build_server': False,
'build_agent': False, 'build_agent_gpu': False,
})
def test_ci_script_changes_validate_without_building_container_images(self):
result = self.scope(['.gitea/workflows/build.yml', 'scripts/ci/change_scope.py'])
self.assertTrue(result['run_validation'])
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
(False, False, False))
def test_server_only_change_selects_only_server_image(self):
result = self.scope(['src/Heimdall.Web/Controllers/HealthController.cs'])
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
(True, False, False))
def test_agent_change_selects_cpu_and_gpu_images(self):
result = self.scope(['src/Heimdall.Agent/Program.cs'])
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
(False, True, True))
def test_shared_project_selects_all_dependent_images(self):
result = self.scope(['src/Heimdall.Application/Services/AgentService.cs'])
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
(True, True, True))
def test_version_tag_selects_every_image(self):
self.assertTrue(all(self.scope(['*']).values()))
def test_version_tag_must_be_semver_before_build_jobs_start(self):
with patch.dict(os.environ, {'EVENT_NAME': 'push', 'REF': 'refs/tags/not-a-version'}):
with self.assertRaises(SystemExit):
load_change_scope().changed_paths()
class PublicationWorkflowTests(unittest.TestCase):
def test_release_write_token_is_tag_only_and_not_a_long_lived_pat_secret(self):
workflow = (REPO_ROOT/'.gitea/workflows/build.yml').read_text()
self.assertNotIn('secrets.RELEASE_TOKEN', workflow)
self.assertEqual(workflow.count('secrets.GITEA_TOKEN'), 2)
publish = workflow.split(' publish:\n', 1)[1]
self.assertIn("startsWith(gitea.ref, 'refs/tags/')", publish)
self.assertIn(' contents: write', publish)
self.assertIn(' pull-requests: read', publish)
self.assertNotIn('secrets.GITEA_TOKEN', workflow.split(' publish:\n', 1)[0])
class PowerShellInstallerTests(unittest.TestCase):
@unittest.skipUnless(shutil.which('pwsh'), 'PowerShell is not installed')
def test_server_installer_has_valid_powershell_syntax(self):
parser = "$tokens=$null; $errors=$null; [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path 'install/install-server.ps1'), [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.Message }; exit 1 }"
result = subprocess.run([shutil.which('pwsh'), '-NoProfile', '-Command', parser],
cwd=REPO_ROOT, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
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)
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
def load_build_plan():
spec = importlib.util.spec_from_file_location('heimdall_build_plan', ROOT/'build-plan.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
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");'), [])
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):
plan = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])
suites = plan['suites']
self.assertIn('Heimdall.Agent.Tests', suites)
self.assertNotIn('Heimdall.Web.Tests', suites)
self.assertIn('tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj', plan['build_projects'])
self.assertFalse(any('Heimdall.Web' in target for target in plan['build_projects']))
def test_web_change_does_not_rebuild_agent(self):
plan = load_test_plan().plan(['src/Heimdall.Web/Components/App.razor'])
self.assertIn('Heimdall.Web.Tests', plan['suites'])
self.assertFalse(any('Heimdall.Agent' in target for target in plan['build_projects']))
self.assertFalse(any('Heimdall.slnx' == target for target in plan['build_projects']))
def test_solution_change_runs_all_and_docs_change_runs_none(self):
planner = load_test_plan()
solution = planner.plan(['global.json'])
self.assertEqual(len(solution['suites']), len(planner.TESTS))
self.assertEqual(solution['build_projects'], ['Heimdall.slnx'])
docs = planner.plan(['docs/README.md'])
self.assertEqual(docs['suites'], [])
self.assertEqual(docs['build_projects'], [])
def test_removed_backlog_file_does_not_skip_validation_as_docs_only(self):
planner = load_test_plan()
result = planner.plan(['todo.md'])
self.assertEqual(result['mode'], 'all')
self.assertEqual(len(result['suites']), len(planner.TESTS))
self.assertEqual(result['build_projects'], ['Heimdall.slnx'])
class BuildPlanTests(unittest.TestCase):
def test_builds_only_existing_targets_from_the_plan(self):
builder = load_build_plan()
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
target = 'tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj'
project = root/target
project.parent.mkdir(parents=True)
project.write_text('<Project />')
plan_path = root/'artifacts/tests/plan.json'
plan_path.parent.mkdir(parents=True)
plan_path.write_text(json.dumps({'build_projects':[target]}))
builder.ROOT = root
builder.PLAN = plan_path
with patch('subprocess.run') as run, contextlib.redirect_stdout(io.StringIO()):
builder.main()
run.assert_called_once_with(
['dotnet','build',target,'-c','Release','--no-restore','-m:2'],
cwd=root, check=True)
class GpuAgentImageTests(unittest.TestCase):
def test_cpu_default_stays_independent_of_nvidia_runtime(self):
dockerfile = (REPO_ROOT/'docker/Dockerfile.agent').read_text()
compose = (REPO_ROOT/'docker/docker-compose.agent.dev.yml').read_text()
self.assertNotIn('nvidia/cuda', dockerfile)
self.assertNotIn('Agent__InferenceExecutionProvider: CUDA', compose)
self.assertNotIn('driver: nvidia', compose)
def test_gpu_runtime_and_optional_overlay_pin_cuda_runtime_and_provider(self):
dockerfile = (REPO_ROOT/'docker/Dockerfile.agent.gpu').read_text()
compose = (REPO_ROOT/'docker/docker-compose.agent.dev.gpu-nvidia.yml').read_text()
self.assertIn('nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9', dockerfile)
self.assertIn('Microsoft.ML.OnnxRuntime.Gpu', (REPO_ROOT/'src/Heimdall.Agent/Heimdall.Agent.csproj').read_text())
self.assertIn('Agent__InferenceExecutionProvider: CUDA', compose)
self.assertIn('driver: nvidia', compose)
self.assertIn('capabilities: [gpu]', compose)
self.assertIn('image: heimdall-agent:gpu-local', compose)
state_init = compose.split(' agent-state-init:', 1)[1]
self.assertIn('dockerfile: docker/Dockerfile.agent.gpu', state_init)
class NativeAgentUpdateTests(unittest.TestCase):
def test_supervisor_rolls_back_failed_startup_to_previous_release(self):
with tempfile.TemporaryDirectory(prefix='hmd-supervisor-test-') as temporary:
root = Path(temporary)
old_release = root/'releases'/'v1.0.0'
new_release = root/'releases'/'v1.0.1'
old_release.mkdir(parents=True)
new_release.mkdir()
(old_release/'Heimdall.Agent.dll').write_bytes(b'old synthetic release')
(new_release/'Heimdall.Agent.dll').write_bytes(b'new synthetic release')
current = root/'current'
current.symlink_to(new_release, target_is_directory=True)
pending = root/'pending-update.json'
pending.write_text(json.dumps({'version': '1.0.1', 'previous': str(old_release)}))
dotnet = root/'fake-dotnet'
dotnet.write_text('#!/bin/sh\nexit 1\n')
dotnet.chmod(0o755)
environment = os.environ.copy()
environment['Agent__UpdateInstallRoot'] = str(root)
environment['HEIMDALL_DOTNET'] = str(dotnet)
result = subprocess.run(
[sys.executable, str(REPO_ROOT/'install/agent-supervisor.py')],
env=environment, capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 75, result.stderr)
self.assertEqual(current.resolve(), old_release.resolve())
self.assertFalse(pending.exists())
self.assertIn('previous release restored', result.stderr)
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):
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': False, 'tag_name': '1.2.3',
'html_url': 'https://example.test/releases/7'}).encode())
if req.method == 'GET':
names = ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']
return Response(json.dumps([{'id':index+8,'name':name} for index,name in enumerate(names)]).encode())
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','version':'1.2.3'}))
for name in ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']:
(directory/name).write_bytes(b'archive')
(directory/'agent-release-public.pem').write_bytes(b'key')
notes = Path(temp)/'release-notes.md'
notes.write_text('- Feature from PR #3.\n')
original = Path.cwd()
try:
os.chdir(temp)
with patch.dict(os.environ, {'BUILD_SERVER_URL':'https://example.test',
'BUILD_REPOSITORY':'owner/repo','RELEASE_TAG':'1.2.3','RELEASE_TOKEN':'dummy',
'RELEASE_NOTES_FILE':str(notes)}), \
patch('urllib.request.urlopen', fake_request), contextlib.redirect_stdout(io.StringIO()):
try:
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
except SystemExit as result:
if result.code != 0:
raise
finally:
os.chdir(original)
return calls
def test_complete_published_release_is_not_mutated_on_rerun(self):
calls = self.execute()
self.assertTrue(any('/releases/tags/1.2.3' in call.full_url for call in calls))
self.assertEqual([call.method for call in calls], ['GET', 'GET'])
class OfflineReleaseAcceptanceTests(unittest.TestCase):
def test_publish_signs_and_uploads_cpu_and_gpu_image_manifests(self):
result = subprocess.run(
[sys.executable, str(ROOT/'accept-release-offline.py')],
cwd=REPO_ROOT, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn('installer ZIP', result.stdout)
self.assertIn('selective Docker Hub tags', result.stdout)
if __name__ == '__main__':
unittest.main()