Files
NODEDC_PLATFORM/infra/deploy-runner/test_device_b2_shared_contours.py
T

187 lines
13 KiB
Python

"""Exact schema transition, receipt boundary and data-preserving rollback."""
import copy
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import shutil
import tarfile
import tempfile
import unittest
from unittest import mock
loader = importlib.machinery.SourceFileLoader('shared_runner_test', str(Path(__file__).with_name('nodedc-deploy')))
spec = importlib.util.spec_from_loader(loader.name, loader)
R = importlib.util.module_from_spec(spec); loader.exec_module(R)
FIXTURE = Path(__file__).with_name('fixtures')/'device-b2-shared-contours'
def archive(path, extra=None):
files = {'manifest.env': f'id={R.DEVICE_B2_SHARED_ID}\ncomponent=device-b2-shared-contours\ntype=app-overlay\n'.encode(),
'files.txt': ('\n'.join(R.DEVICE_B2_SHARED_ENTRIES)+'\n').encode(),
**{'payload/'+p: (FIXTURE/p).read_bytes() for p in R.DEVICE_B2_SHARED_ENTRIES}}
files.update(extra or {})
with tarfile.open(path, 'w:gz') as target:
for name, data in files.items():
entry=tarfile.TarInfo(name); entry.size=len(data); entry.mode=0o644
target.addfile(entry, io.BytesIO(data))
class SharedContours(unittest.TestCase):
def test_exact_archive_load_and_empty_runtime_scope(self):
with tempfile.TemporaryDirectory() as tmp:
path=Path(tmp)/'a.tgz'; archive(path)
_, entries, payload=R.load_artifact(path, Path(tmp)/'unpack')
R.validate_device_b2_shared_payload(payload, entries, R.DEVICE_B2_SHARED_ID)
self.assertEqual(R.component_services('device-b2-shared-contours', entries), ())
self.assertEqual(R.component_builds('device-b2-shared-contours', entries), ())
self.assertTrue(R.component_artifact_only('device-b2-shared-contours'))
self.assertEqual(R.component_root('device-b2-shared-contours'), R.DEVICE_PLANE_ROOT)
def test_extra_sql_env_hook_runtime_or_traversal_rejected(self):
for name in ('.env', 'hooks.sh', 'deployment/other.sql', 'secrets/admin.json', '../escape',
'services/device-control-core/src/server.mjs', 'runtime/db.dump'):
with self.subTest(name=name), self.assertRaises(R.DeployError):
R.allowed_payload_path('device-b2-shared-contours', name)
for entries in ((), R.DEVICE_B2_SHARED_ENTRIES[:-1], tuple(reversed(R.DEVICE_B2_SHARED_ENTRIES))):
with self.assertRaises(R.DeployError): R.component_services('device-b2-shared-contours', entries)
def test_modified_sql_descriptor_and_identity_rejected(self):
for rel in R.DEVICE_B2_SHARED_ENTRIES:
with self.subTest(rel=rel), tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); shutil.copytree(FIXTURE, root, dirs_exist_ok=True)
path=root/rel
if rel == R.DEVICE_B2_SHARED_DESCRIPTOR:
v=json.loads(path.read_text()); v['services']=['device-postgres']; path.write_text(json.dumps(v))
else: path.write_text('drop table device_b2_hosts;')
with self.assertRaises(R.DeployError):
R.validate_device_b2_shared_payload(root, R.DEVICE_B2_SHARED_ENTRIES, R.DEVICE_B2_SHARED_ID)
with self.assertRaises(R.DeployError):
R.validate_device_b2_shared_payload(FIXTURE, R.DEVICE_B2_SHARED_ENTRIES, 'unreviewed')
def test_forward_schema_is_exact_and_old_contract_is_unchanged(self):
old=copy.deepcopy(R.DEVICE_B2_EXPECTED_SCHEMA); new=R.device_b2_shared_schema()
R.validate_device_b2_schema(old)
with self.assertRaises(R.DeployError): R.validate_device_b2_schema(new)
R.validate_device_b2_schema(new, expected=R.device_b2_shared_schema())
self.assertEqual(R.DEVICE_B2_EXPECTED_SCHEMA, old)
self.assertEqual(old[1:], new[1:])
for key in ('constraints', 'fields', 'validated', 'columns'):
self.assertEqual(old[0][key], new[0][key])
for mutation in ('missing-fk', 'wrong-marker', 'extra-field', 'wrong-pk'):
value=copy.deepcopy(new)
if mutation=='missing-fk': value[0]['definitions'].pop(1)
if mutation=='wrong-marker': value[0]['marker']='other'
if mutation=='extra-field': value[0]['fields'].append(['unsafe','text',False])
if mutation=='wrong-pk': value[0]['definitions'][-1]='PRIMARY KEY (contour_id)'
with self.subTest(mutation=mutation), self.assertRaises(R.DeployError):
R.validate_device_b2_schema(value, expected=new)
def test_failed_mutation_blocks_normal_compose_even_without_overlay(self):
row={'component':'device-b2-shared-contours','started_apply':True,'rollback_status':'failed:DeployError'}
with mock.patch.object(R, 'load_state', return_value=[row]), self.assertRaises(R.DeployError):
R.device_b2_compose_files(())
for r in ({**row,'started_apply':False}, {**row,'rollback_status':'ok:device-b2-shared-contours'}):
with mock.patch.object(R,'load_state',return_value=[r]): R.device_b2_shared_failed_barrier()
def test_receipt_requires_all_files_unique_success_and_verified_archive(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp)/'live'; root.mkdir()
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root), mock.patch.object(R,'TMP_DIR',Path(tmp)), \
mock.patch.object(R,'load_state',return_value=[]):
self.assertFalse(R.device_b2_shared_receipt())
shutil.copytree(FIXTURE,root,dirs_exist_ok=True)
with self.assertRaises(R.DeployError): R.device_b2_shared_receipt()
row={'component':'device-b2-shared-contours','id':R.DEVICE_B2_SHARED_ID,'status':'ok'}
good=Path(tmp)/'good.tgz'; archive(good)
state=lambda path: [row] if path==R.STATE_FILE else []
with mock.patch.object(R,'load_state',side_effect=state), \
mock.patch.object(R,'device_release_applied_archive',return_value=good) as checked:
self.assertTrue(R.device_b2_shared_receipt()); checked.assert_called_once_with(row)
for rows in ([row,row],[{**row,'id':'other'}],[{**row,'status':'failed'}]):
with mock.patch.object(R,'load_state',side_effect=lambda p:rows if p==R.STATE_FILE else []), self.assertRaises(R.DeployError):
R.device_b2_shared_receipt()
with mock.patch.object(R,'load_state',side_effect=state), \
mock.patch.object(R,'device_release_applied_archive',side_effect=R.DeployError('archive mismatch')), \
self.assertRaises(R.DeployError): R.device_b2_shared_receipt()
def test_preflight_rejects_wrong_live_release_before_database_mutation(self):
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)), \
mock.patch.object(R,'load_state',return_value=[]), mock.patch.object(R,'device_b2_database') as db:
with self.assertRaisesRegex(R.DeployError,'r37'):
R.preflight_device_b2_shared(FIXTURE,R.DEVICE_B2_SHARED_ENTRIES,R.DEVICE_B2_SHARED_ID)
db.assert_not_called()
def test_preflight_rejects_missing_foundation_and_wrong_source(self):
row={'component':'device-core-release','id':R.DEVICE_B2_SHARED_BASELINE,'sha256':R.DEVICE_B2_SHARED_BASELINE_SHA}
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)), \
mock.patch.object(R,'TMP_DIR',Path(tmp)), \
mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.STATE_FILE else []), \
mock.patch.object(R,'device_release_applied_archive',return_value=Path(tmp)/'release.tgz'), \
mock.patch.object(R,'load_artifact',return_value=({'component':'device-core-release'}, R.DEVICE_RELEASE_ENTRIES,Path(tmp))), \
mock.patch.object(R,'collect_exact_files',side_effect=[{'a':'one'},{'a':'two'}]), \
self.assertRaisesRegex(R.DeployError,'source drift'):
R.preflight_device_b2_shared(FIXTURE,R.DEVICE_B2_SHARED_ENTRIES,R.DEVICE_B2_SHARED_ID)
def test_rollback_never_restores_old_data_over_new_links(self):
with mock.patch.object(R,'device_b2_schema',return_value=R.device_b2_shared_schema()), \
mock.patch.object(R,'device_b2_database',side_effect=R.DeployError('would_lose_links')) as db, \
mock.patch.object(R,'restore_platform_overlay') as restore, \
mock.patch.object(R,'accept_device_b2_shared') as accept:
with self.assertRaisesRegex(R.DeployError,'would_lose_links'):
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
self.assertIn('rollback_would_lose_links',db.call_args.args[0])
restore.assert_not_called(); accept.assert_not_called()
def test_rollback_after_failed_transaction_restores_only_new_files(self):
with mock.patch.object(R,'device_b2_schema',return_value=R.DEVICE_B2_EXPECTED_SCHEMA), \
mock.patch.object(R,'device_b2_database') as db, \
mock.patch.object(R,'restore_platform_overlay') as restore, \
mock.patch.object(R,'accept_device_b2_shared') as accept:
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
db.assert_not_called(); restore.assert_called_once(); accept.assert_called_once_with({},Path('/unused'),rollback=True)
def test_unknown_schema_retained_without_destructive_attempt(self):
with mock.patch.object(R,'device_b2_schema',return_value=[]), mock.patch.object(R,'device_b2_database') as db, \
mock.patch.object(R,'restore_platform_overlay') as restore, self.assertRaises(R.DeployError):
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
db.assert_not_called(); restore.assert_not_called()
def test_private_table_backup_fixed_scope_and_failure_precedes_sql(self):
def dump(argv, **kwargs):
self.assertEqual(argv[-3:], ['--strict-names', '-t', 'public.device_b2_contour_links'])
kwargs['stdout'].write(b'PGDMP-synthetic-fixture')
return mock.Mock(returncode=0, stderr=b'')
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'device_plane_service_container_ids',return_value=['postgres-existing']), \
mock.patch.object(R.subprocess,'run',side_effect=dump), mock.patch.object(R,'device_b2_database') as sql:
root=Path(tmp)
R.backup_device_b2_shared(root,{'runtime':{}})
self.assertEqual((root/'device-b2-contour-links.dump').stat().st_mode & 0o777,0o600)
self.assertEqual((root/'device-b2-contour-links.dump.sha256').read_text().strip(),R.sha256_file(root/'device-b2-contour-links.dump'))
sql.assert_not_called()
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'device_plane_service_container_ids',return_value=['postgres-existing']), \
mock.patch.object(R.subprocess,'run',return_value=mock.Mock(returncode=1,stderr=b'failed')), self.assertRaises(R.DeployError):
R.backup_device_b2_shared(Path(tmp),{})
def test_acceptance_checks_schema_backup_and_preserved_runtime_before_success(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); shutil.copytree(FIXTURE,root,dirs_exist_ok=True)
dump=root/'device-b2-contour-links.dump'; dump.write_bytes(b'PGDMP-fixture'); dump.chmod(0o600)
(root/'device-b2-contour-links.dump.sha256').write_text(R.sha256_file(dump)+'\n')
before={'runtime':{'postgres':'same','core':'same'},'otherComposeServices':{},'compose':{},'installedFiles':{}}
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root), mock.patch.object(R,'device_b2_schema',return_value=R.device_b2_shared_schema()), \
mock.patch.object(R,'device_b2_private_directory'), mock.patch.object(R,'run_healthchecks') as health, \
mock.patch.object(R,'device_release_runtime_snapshot_v2',return_value=before['runtime']) as runtime, \
mock.patch.object(R,'device_release_other_compose_services',return_value={}), \
mock.patch.object(R,'collect_exact_files',return_value={}):
R.accept_device_b2_shared(before,root)
health.assert_called_once_with('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)
runtime.return_value={'postgres':'recreated','core':'same'}
with self.assertRaisesRegex(R.DeployError,'preserved service'): R.accept_device_b2_shared(before,root)
runtime.return_value=before['runtime']; dump.write_bytes(b'changed')
with self.assertRaisesRegex(R.DeployError,'backup changed'): R.accept_device_b2_shared(before,root)
if __name__ == '__main__': unittest.main()