Files
NODEDC_PLATFORM/infra/cms-deploy/test_build_base.py
T

172 lines
12 KiB
Python

import copy
from contextlib import redirect_stdout
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from test_runner import r, fixture
def images():
base={'Id':'sha256:'+'a'*64,'Os':'linux','Architecture':'amd64',
'RootFS':{'Type':'layers','Layers':['sha256:'+'1'*64,'sha256:'+'2'*64]},
'Config':{'Env':['PATH=/bin','NODE_VERSION=24.18.0','YARN_VERSION=1.22.22'],
'Cmd':['node'],'Entrypoint':['docker-entrypoint.sh'],'WorkingDir':'','User':''}}
old=copy.deepcopy(base);old['Id']='sha256:'+'b'*64
old['RootFS']['Layers']+=['sha256:'+'3'*64]
old['Config'].update(Cmd=['npm','run','admin'],WorkingDir='/app',ExposedPorts={'8090/tcp':{}})
old['Config']['Env']+=['HOST=0.0.0.0','PORT=8090']
return base,old
def proof(base,old):
return {'imageId':base['Id'],'acceptedImageId':old['Id'],
'layersSha256':r.cms_audit_digest(base['RootFS']['Layers']),
'configSha256':r.cms_audit_digest(base['Config'])}
class CmsBuildBaseTests(unittest.TestCase):
def test_proves_actual_ancestry_and_inherited_environment(self):
base,old=images();saved=copy.deepcopy(base)
self.assertTrue(r.cms_node_base_matches(base,old))
self.assertEqual(base,saved)
# A mutable tag's new image must fail even if it has the same version.
for field,value in [('Env',['PATH=/bin','NODE_VERSION=24.19.0','YARN_VERSION=1.22.22']),
('OnBuild',['RUN unauthorized']),('Volumes',{'/private':{}}),
('Labels',{'extra':'value'}),('User','1000'),('Entrypoint',['other']),
('WorkingDir','/app'),('Cmd',['npm','run','admin']),('ExposedPorts',{'80/tcp':{}})]:
changed=copy.deepcopy(base);changed['Config'][field]=value
self.assertFalse(r.cms_node_base_matches(changed,old),field)
for field,value in [('Architecture','arm64'),('Os','windows')]:
changed=copy.deepcopy(base);changed[field]=value
self.assertFalse(r.cms_node_base_matches(changed,old),field)
changed=copy.deepcopy(base);changed['RootFS']['Layers'][0]='sha256:'+'9'*64
self.assertFalse(r.cms_node_base_matches(changed,old))
self.assertFalse(r.cms_node_base_matches(old,old))
def test_duplicate_environment_and_secret_values_never_appear_in_errors(self):
for env in [None,{},['TOKEN=private-fixture','TOKEN=other'],['NO_SEPARATOR'],['=bad'],['A=bad\0']]:
with self.assertRaises(r.DeployError) as error:r.cms_image_env({'Env':env})
self.assertNotIn('private-fixture',str(error.exception))
def test_parent_chain_finds_untagged_base_without_global_inventory(self):
base,old=images();middle=copy.deepcopy(old);middle['Id']='sha256:'+'c'*64
old['Parent']=middle['Id'];middle['Parent']=base['Id']
inventory={i['Id']:i for i in (base,old,middle)}
with patch.object(r,'cms_inspect_image',side_effect=inventory.__getitem__) as inspect,patch.object(r,'cms_base_docker_json') as listing,redirect_stdout(io.StringIO()) as output:
self.assertEqual(r.cms_resolve_build_base({'imageId':old['Id']}),proof(base,old))
self.assertEqual(inspect.call_count,3);listing.assert_not_called()
self.assertIn('lookup=parent-chain',output.getvalue())
self.assertNotIn('PATH=',output.getvalue())
def test_parent_chain_rejects_cycles_invalid_edges_and_depth(self):
base,old=images()
for code,alter in [
('parent-invalid',lambda b,o:o.update(Parent='latest')),
('parent-cycle',lambda b,o:o.update(Parent=o['Id'])),
('parent-layers',lambda b,o:b['RootFS']['Layers'].reverse()),
('parent-platform',lambda b,o:b.update(Architecture='arm64')),
]:
b,o=copy.deepcopy(base),copy.deepcopy(old);o['Parent']=b['Id'];alter(b,o)
inventory={i['Id']:i for i in (b,o)}
with self.subTest(code=code),patch.object(r,'cms_inspect_image',side_effect=inventory.__getitem__),patch.object(r,'cms_base_docker_json') as listing:
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code):r.cms_resolve_build_base({'imageId':o['Id']})
listing.assert_not_called()
chain=[]
for i in range(130):
item=copy.deepcopy(old);item['Id']='sha256:'+format(i,'064x');item['Parent']='sha256:'+format(i+1,'064x');chain.append(item)
with patch.object(r,'cms_inspect_image',side_effect={i['Id']:i for i in chain}.__getitem__):
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-parent-depth'):r.cms_resolve_build_base({'imageId':chain[0]['Id']})
def test_node_cache_fallback_ignores_mutable_tag_and_rejects_missing_or_ambiguous_base(self):
base,old=images();latest=copy.deepcopy(base);latest['Id']='sha256:'+'c'*64
latest['Config']['Env'][1]='NODE_VERSION=24.19.0'
latest['RootFS']['Layers'][1]='sha256:'+'4'*64
latest['RepoTags']=['node:24-alpine']
for inventory,success in [([latest,base,old],True),([latest,old],False),([latest,base,old,{**base,'Id':'sha256:'+'d'*64}],False)]:
by_id={i['Id']:i for i in inventory}
with patch.object(r,'cms_inspect_image',side_effect=by_id.__getitem__),patch.object(r,'cms_base_docker_json',return_value=list(by_id)) as run,redirect_stdout(io.StringIO()) as output:
if success:self.assertEqual(r.cms_resolve_build_base({'imageId':old['Id']}),proof(base,old))
else:
with self.assertRaises(r.DeployError):r.cms_resolve_build_base({'imageId':old['Id']})
self.assertEqual(run.call_args.args[0],['image','ls','--all','--no-trunc','--filter','reference=node:*','--filter','reference=docker.io/library/node:*','--format','{{json .ID}}'])
self.assertEqual(run.call_args.kwargs,{'lines':True})
self.assertNotIn('PATH=',output.getvalue())
def test_inventory_rejects_short_ids_malformed_values_and_excess_before_inspect(self):
base,old=images()
for rows,code in [(['abcdef123456'],'format'),([{}],'format'),([None],'format'),([base['Id']]*257,'limit')]:
with self.subTest(code=code,rows=len(rows)),patch.object(r,'cms_inspect_image',return_value=old) as inspect,patch.object(r,'cms_base_docker_json',return_value=rows):
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-inventory-'+code):r.cms_resolve_build_base({'imageId':old['Id']})
inspect.assert_called_once_with(old['Id'])
def test_docker_reads_are_bounded_and_external_errors_are_redacted(self):
for error,code in [
(r.subprocess.TimeoutExpired(['docker','private-fixture'],30,stderr='secret-fixture'),'docker-timeout'),
(r.subprocess.CalledProcessError(1,['docker'],stderr='secret-fixture'),'docker-failed'),
(OSError('secret-fixture'),'docker-unavailable'),
]:
with patch.object(r.subprocess,'run',side_effect=error) as run:
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code) as caught:r.cms_base_docker_json(['image','inspect','fixture'])
self.assertNotIn('secret-fixture',str(caught.exception));self.assertEqual(run.call_args.kwargs['timeout'],30)
for value,lines,expected in [('[]',False,[]),('"sha256:abc"\n',True,['sha256:abc']),('',True,[])]:
with patch.object(r.subprocess,'run',return_value=type('Result',(),{'stdout':value})()):
self.assertEqual(r.cms_base_docker_json(['fixture'],lines=lines),expected)
for value,code in [('secret-fixture','json-invalid'),('x'*(8*1024*1024+1),'output-limit')]:
with patch.object(r.subprocess,'run',return_value=type('Result',(),{'stdout':value})()):
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code):r.cms_base_docker_json(['fixture'])
def test_image_inspection_requires_exact_immutable_identity(self):
base,old=images()
for rows in [[old],[],[base,base],[None],{}]:
with patch.object(r,'cms_base_docker_json',return_value=rows):
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-image-mismatch'):r.cms_inspect_image(base['Id'])
with patch.object(r,'cms_base_docker_json',return_value=[base]):self.assertEqual(r.cms_inspect_image(base['Id']),base)
def test_public_status_contains_only_allowlisted_base_codes(self):
error=r.CmsBuildBaseError('cms-base-missing');error.args=('secret-fixture',)
self.assertEqual(r.cms_autodeploy_error_status(error,())['reason'],'cms-base-missing')
error.code='secret-fixture'
self.assertNotIn('reason',r.cms_autodeploy_error_status(error,()))
for error in [r.DeployError('secret-fixture'),r.subprocess.TimeoutExpired(['private-fixture'],30)]:
result=r.cms_autodeploy_error_status(error,())
self.assertNotIn('reason',result);self.assertNotIn('fixture',json.dumps(result))
with self.assertRaises(ValueError):r.CmsBuildBaseError('secret-fixture')
def test_build_pins_only_clean_temporary_recipe_and_rejects_drift_before_recreation(self):
base,old=images()
for drift in [False,True]:
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);entries,_=fixture(root)
recipe=b'FROM node:24-alpine\nWORKDIR /app\n'
(root/'Dockerfile').write_bytes(recipe)
(root/'projects').mkdir();(root/'projects/password.json').write_text('private-fixture')
before={'entries':entries,'runtime':{'imageRef':'dc-cms-cms-app','imageId':old['Id']},'buildBase':proof(base,old)}
built=copy.deepcopy(old);built['Id']='sha256:'+'e'*64
if drift:built['Config']['Env'].append('TOKEN=private-fixture')
def build(cmd,**kwargs):
self.assertIn('--pull=false',cmd)
self.assertEqual(kwargs['env']['DOCKER_BUILDKIT'],'0')
context=Path(cmd[-1]);self.assertEqual(list((context/'projects').iterdir()),[])
self.assertEqual((context/'Dockerfile').read_bytes(),('FROM '+base['Id']+'\nWORKDIR /app\n').encode())
self.assertEqual(set(p.relative_to(context).as_posix() for p in context.rglob('*') if p.is_file()),set(entries)|{'Dockerfile'})
self.assertNotIn('private-fixture',str(cmd))
with patch.object(r,'CMS_ROOT',root),patch.object(r,'TMP_DIR',root),patch.dict(r.CMS_FOUNDATION,{'Dockerfile':r.hashlib.sha256(recipe).hexdigest()}),patch.object(r,'cms_inspect_image',side_effect=[base,old]),patch.object(r.subprocess,'run',side_effect=build),patch.object(r,'docker_json',return_value=[built]),redirect_stdout(io.StringIO()):
if drift:
with self.assertRaisesRegex(r.DeployError,'before recreation: Env') as error:r.build_cms_release(before)
self.assertNotIn('private-fixture',str(error.exception))
else:r.build_cms_release(before)
self.assertEqual((root/'Dockerfile').read_bytes(),recipe)
def test_changed_base_proof_rejected_before_build(self):
base,old=images();bad=proof(base,old);bad['configSha256']='0'*64
before={'runtime':{'imageId':old['Id']},'buildBase':bad}
with patch.object(r,'cms_inspect_image',side_effect=[base,old]),patch.object(r.subprocess,'run') as run:
with self.assertRaisesRegex(r.DeployError,'preflight proof'):r.build_cms_release(before)
run.assert_not_called()
if __name__=='__main__':unittest.main()