202 lines
12 KiB
Python
202 lines
12 KiB
Python
"""Additive B2 foundation: exact scope and fail-closed preservation proofs."""
|
|
import copy
|
|
import importlib.machinery
|
|
import importlib.util
|
|
import json
|
|
from pathlib import Path
|
|
import tempfile
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
loader=importlib.machinery.SourceFileLoader('b2_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)
|
|
|
|
|
|
def baseline():
|
|
return {'services':{'device-control-core':{'image':'same','environment':{'EXISTING':'preserved'},
|
|
'volumes':[{'type':'bind','source':'/private/current','target':'/run/current','read_only':True}],
|
|
'ports':[]},'device-postgres':{'image':'postgres:existing','volumes':['unchanged']}}}
|
|
|
|
|
|
def candidate():
|
|
v=baseline();c=v['services']['device-control-core']
|
|
c['environment']['DEVICE_B2_SECRET_ROOT']=R.DEVICE_B2_DESTINATION
|
|
c['volumes'].append({'type':'bind','source':str(R.DEVICE_B2_SECRET_ROOT),'target':R.DEVICE_B2_DESTINATION,
|
|
'read_only':False,'bind':{'create_host_path':False}})
|
|
return v
|
|
|
|
|
|
FIXTURE = Path(__file__).with_name('fixtures') / 'device-b2-foundation-compose220'
|
|
|
|
|
|
def compose_fixture():
|
|
return tuple(json.loads((FIXTURE / (name + '.json')).read_text()) for name in ('base', 'candidate'))
|
|
|
|
|
|
class Foundation(unittest.TestCase):
|
|
def test_source_yaml_and_new_identity_remain_exact(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
(root / 'deployment').mkdir()
|
|
(root / R.DEVICE_B2_DESCRIPTOR).write_text(json.dumps(R.device_b2_descriptor()))
|
|
yaml = root / R.DEVICE_B2_OVERRIDE
|
|
yaml.write_text(R.DEVICE_B2_YAML)
|
|
# Isolate the YAML/identity guard; no database or SQL execution.
|
|
with mock.patch.object(R, 'sha256_file', return_value=R.DEVICE_B2_SQL_SHA):
|
|
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
|
|
with self.assertRaises(R.DeployError):
|
|
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, 'device-b2-foundation-v1-20260930-001')
|
|
for replacement in ('true', 'null', '0'):
|
|
yaml.write_text(R.DEVICE_B2_YAML.replace('create_host_path: false', 'create_host_path: ' + replacement))
|
|
with self.subTest(replacement=replacement), self.assertRaises(R.DeployError):
|
|
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
|
|
yaml.write_text(R.DEVICE_B2_YAML.replace(' create_host_path: false\n', ''))
|
|
with self.assertRaises(R.DeployError):
|
|
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
|
|
|
|
def test_real_compose_2201_output_preserves_raw_inputs_and_digest(self):
|
|
base, actual = compose_fixture()
|
|
saved = copy.deepcopy((base, actual))
|
|
mount = next(v for v in actual['services']['device-control-core']['volumes']
|
|
if v['target'] == R.DEVICE_B2_DESTINATION)
|
|
self.assertEqual(mount['bind'], {})
|
|
self.assertNotIn('read_only', mount)
|
|
self.assertEqual(R.device_b2_config_proof(base, actual), R.device_release_drift_digest(actual))
|
|
self.assertEqual((base, actual), saved)
|
|
self.assertEqual((FIXTURE / 'override.yml').read_text(), R.DEVICE_B2_YAML)
|
|
|
|
def test_real_compose_new_mount_accepts_only_false_or_omitted_booleans(self):
|
|
base, actual = compose_fixture()
|
|
for read_only in ('omitted', False):
|
|
for create in ('omitted', False):
|
|
v = copy.deepcopy(actual)
|
|
mount = next(m for m in v['services']['device-control-core']['volumes']
|
|
if m['target'] == R.DEVICE_B2_DESTINATION)
|
|
if read_only != 'omitted': mount['read_only'] = read_only
|
|
if create != 'omitted': mount['bind']['create_host_path'] = create
|
|
with self.subTest(read_only=read_only, create=create):
|
|
R.device_b2_config_proof(base, v)
|
|
for key in ('read_only', 'create_host_path'):
|
|
for value in (True, None, 0, 1, 0.0, 'false', {}, []):
|
|
v = copy.deepcopy(actual)
|
|
mount = next(m for m in v['services']['device-control-core']['volumes']
|
|
if m['target'] == R.DEVICE_B2_DESTINATION)
|
|
target = mount if key == 'read_only' else mount['bind']
|
|
target[key] = value
|
|
with self.subTest(key=key, value=value), self.assertRaises(R.DeployError):
|
|
R.device_b2_config_proof(base, v)
|
|
|
|
def test_real_compose_rejects_other_mount_options_and_unrelated_changes(self):
|
|
base, actual = compose_fixture()
|
|
for mutation in ('source', 'type', 'bind-null', 'bind-absent', 'propagation',
|
|
'existing-bind', 'existing-readonly', 'duplicate', 'env', 'network', 'database'):
|
|
v = copy.deepcopy(actual)
|
|
core = v['services']['device-control-core']
|
|
mount = next(m for m in core['volumes'] if m['target'] == R.DEVICE_B2_DESTINATION)
|
|
existing = next(m for m in core['volumes'] if m['target'] != R.DEVICE_B2_DESTINATION)
|
|
if mutation == 'source': mount['source'] = '/other'
|
|
if mutation == 'type': mount['type'] = 'volume'
|
|
if mutation == 'bind-null': mount['bind'] = None
|
|
if mutation == 'bind-absent': mount.pop('bind')
|
|
if mutation == 'propagation': mount['bind']['propagation'] = 'rshared'
|
|
if mutation == 'existing-bind': existing['bind']['create_host_path'] = False
|
|
if mutation == 'existing-readonly': existing['read_only'] = False
|
|
if mutation == 'duplicate': core['volumes'].append(copy.deepcopy(mount))
|
|
if mutation == 'env': core['environment']['EXISTING'] = 'changed'
|
|
if mutation == 'network': core['networks']['private']['priority'] = 0
|
|
if mutation == 'database': v['services']['device-postgres']['image'] = 'changed'
|
|
with self.subTest(mutation=mutation), self.assertRaises(R.DeployError):
|
|
R.device_b2_config_proof(base, v)
|
|
|
|
def test_scope_has_only_core_and_no_build(self):
|
|
self.assertEqual(R.component_services('device-b2-foundation',R.DEVICE_B2_ENTRIES),('device-control-core',))
|
|
self.assertFalse(R.component_builds('device-b2-foundation',R.DEVICE_B2_ENTRIES))
|
|
self.assertTrue(R.component_compose_no_deps('device-b2-foundation',R.DEVICE_B2_ENTRIES))
|
|
for entries in [[],R.DEVICE_B2_ENTRIES[:-1],(*R.DEVICE_B2_ENTRIES,'services/device-postgres')]:
|
|
with self.assertRaises(R.DeployError):R.component_services('device-b2-foundation',entries)
|
|
for p in ['.env','secrets/key','deployment/other.sql','services/device-control-core/src/server.mjs','../escape','hooks.sh']:
|
|
with self.assertRaises(R.DeployError):R.allowed_payload_path('device-b2-foundation',p)
|
|
|
|
def test_config_delta_keeps_ports_database_and_other_environment(self):
|
|
R.device_b2_config_proof(baseline(),candidate())
|
|
for mutation in ['ports','database','environment','mount','readonly']:
|
|
v=candidate();c=v['services']['device-control-core']
|
|
if mutation=='ports':c['ports']=[{'target':42,'published':'42'}]
|
|
if mutation=='database':v['services']['device-postgres']['image']='different'
|
|
if mutation=='environment':c['environment']['EXISTING']='changed'
|
|
if mutation=='mount':c['volumes'][0]['read_only']=False
|
|
if mutation=='readonly':c['volumes'][-1]['read_only']=True
|
|
with self.subTest(mutation=mutation),self.assertRaises(R.DeployError):R.device_b2_config_proof(baseline(),v)
|
|
|
|
def test_runtime_strip_accepts_only_private_mount_and_env(self):
|
|
field={'HostConfig':{'Mounts':[{'Type':'bind','Source':str(R.DEVICE_B2_SECRET_ROOT),
|
|
'Target':R.DEVICE_B2_DESTINATION,'ReadOnly':False}]},
|
|
'Config':{'Env':['OTHER=one','DEVICE_B2_SECRET_ROOT='+R.DEVICE_B2_DESTINATION]},
|
|
'Mounts':[{'Type':'bind','Source':str(R.DEVICE_B2_SECRET_ROOT),'Destination':R.DEVICE_B2_DESTINATION,
|
|
'RW':True,'Propagation':'rprivate'}],'networks':['same']}
|
|
result=R.device_b2_strip_runtime(field)
|
|
self.assertEqual(result,{'HostConfig':{'Mounts':[]},'Config':{'Env':['OTHER=one']},'Mounts':[],'networks':['same']})
|
|
for part,key,value in [('Mounts','RW',False),('Mounts','Propagation','rshared'),('HostConfig','Source','/elsewhere')]:
|
|
wrong=copy.deepcopy(field)
|
|
target=wrong[part][0] if part=='Mounts' else wrong[part]['Mounts'][0]
|
|
target[key]=value
|
|
with self.assertRaises(R.DeployError):R.device_b2_strip_runtime(wrong)
|
|
|
|
def test_recreate_never_pulls_builds_or_selects_dependencies(self):
|
|
with mock.patch.object(R,'device_b2_base',return_value=['docker','compose']),mock.patch.object(R.subprocess,'run') as run:
|
|
R.device_b2_recreate(True)
|
|
cmd=run.call_args.args[0]
|
|
self.assertEqual(cmd[-1],'device-control-core')
|
|
self.assertIn('--no-build',cmd);self.assertIn('--no-deps',cmd)
|
|
self.assertEqual(cmd[cmd.index('--pull')+1],'never')
|
|
self.assertNotIn('device-postgres',cmd)
|
|
|
|
def test_schema_collision_and_unvalidated_constraints_fail(self):
|
|
with self.assertRaises(R.DeployError):R.validate_device_b2_schema([])
|
|
rows=copy.deepcopy(R.DEVICE_B2_EXPECTED_SCHEMA)
|
|
R.validate_device_b2_schema(rows)
|
|
rows[0]['validated']=False
|
|
with self.assertRaises(R.DeployError):R.validate_device_b2_schema(rows)
|
|
|
|
def test_failed_rollback_prevents_activation(self):
|
|
with mock.patch.object(R,'load_state',return_value=[{'component':'device-b2-foundation','started_apply':True,'rollback_status':'failed:DeployError'}]):
|
|
with self.assertRaises(R.DeployError):R.device_b2_failed_barrier()
|
|
|
|
def test_schema_failure_does_not_mark_or_restart_runtime(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root=Path(tmp); (root/'deployment').mkdir()
|
|
(root/R.DEVICE_B2_SQL).write_text('synthetic migration')
|
|
mark=mock.Mock()
|
|
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root),mock.patch.object(R,'device_b2_private_directory'),\
|
|
mock.patch.object(R,'device_b2_database',side_effect=R.DeployError('schema failed')),\
|
|
mock.patch.object(R,'device_b2_recreate') as recreate:
|
|
with self.assertRaises(R.DeployError):R.apply_device_b2({},root,mark)
|
|
mark.assert_not_called();recreate.assert_not_called()
|
|
|
|
def test_normal_releases_check_installed_schema_mount_and_vault(self):
|
|
with mock.patch.object(R,'device_b2_compose_files',return_value=('accepted-foundation',)),\
|
|
mock.patch.object(R,'device_b2_private_directory') as directory,\
|
|
mock.patch.object(R,'device_b2_schema',return_value=R.DEVICE_B2_EXPECTED_SCHEMA),\
|
|
mock.patch.object(R,'device_release_drift_sample',return_value={'device-control-core':{'fields':{}}}),\
|
|
mock.patch.object(R,'device_b2_strip_runtime',side_effect=R.DeployError('lost mount')):
|
|
with self.assertRaises(R.DeployError):R.validate_installed_device_b2()
|
|
directory.assert_called_once_with()
|
|
|
|
def test_marker_without_ledger_cannot_activate_compose(self):
|
|
with tempfile.TemporaryDirectory() as tmp,mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)),mock.patch.object(R,'load_state',return_value=[]):
|
|
(Path(tmp)/R.DEVICE_B2_OVERRIDE).write_text(R.DEVICE_B2_YAML)
|
|
with self.assertRaises(R.DeployError):R.device_b2_compose_files(())
|
|
|
|
def test_rollback_retains_nonempty_private_storage(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root=Path(tmp);vault=root/'vault';vault.mkdir();(vault/'credential').write_text('synthetic')
|
|
with mock.patch.object(R,'DEVICE_B2_SECRET_ROOT',vault),mock.patch.object(R,'restore_platform_overlay'),\
|
|
mock.patch.object(R,'device_b2_schema',return_value=[]),mock.patch.object(R,'device_b2_private_directory'),\
|
|
mock.patch.object(R,'device_b2_recreate'),mock.patch.object(R,'accept_device_b2') as accept:
|
|
with self.assertRaises(OSError):R.rollback_device_b2(root,root,(),'',{},True)
|
|
accept.assert_not_called()
|
|
self.assertEqual((vault/'credential').read_text(),'synthetic')
|
|
|
|
|
|
if __name__=='__main__':unittest.main()
|