From bf3c2444ae4e7f3c58f4719e976745266c567de2 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Wed, 4 Nov 2026 23:49:06 +0300 Subject: [PATCH] Pin CMS build to accepted Node ancestor and verify image config before recreate --- infra/cms-deploy/R40_BUILD_BASE.md | 55 ++++++++++++ infra/cms-deploy/README.md | 6 +- infra/cms-deploy/release_runtime.py | 110 +++++++++++++++++++++++- infra/cms-deploy/test_build_base.py | 101 ++++++++++++++++++++++ infra/cms-deploy/test_reconciliation.py | 3 +- infra/cms-deploy/test_runner.py | 15 ---- infra/deploy-runner/nodedc-deploy | 110 +++++++++++++++++++++++- 7 files changed, 379 insertions(+), 21 deletions(-) create mode 100644 infra/cms-deploy/R40_BUILD_BASE.md create mode 100644 infra/cms-deploy/test_build_base.py diff --git a/infra/cms-deploy/R40_BUILD_BASE.md b/infra/cms-deploy/R40_BUILD_BASE.md new file mode 100644 index 0000000..2a728df --- /dev/null +++ b/infra/cms-deploy/R40_BUILD_BASE.md @@ -0,0 +1,55 @@ +# CMS r40: preserve the accepted Node base before recreation + +Run 40 qualified commit `02318ab6689298244a2ac8b4e7521ed1945600ee`. +Its artifact SHA-256 is `68b36de85f56ad5c003e89f8f4dfe9e0a70b8d01e65846111b18106f677a30e9`. +Canonical apply failed at `2026-11-04T20:37:58Z`, reporting only `config.Env`. +Rollback `ok:dc-cms-release` restored and verified the original image, source, +configuration, other services and project/site data. Backup: +`dc-cms-release-dc-cms-release-v1-r40-02318ab6689298244a2ac8b4e7521ed1945600ee-20261104-233622`. +The failed archive/receipt stay immutable. No reconciliation is required and +this artifact is never retried. + +The application builder used mutable `FROM node:24-alpine`. The source +Dockerfile, Compose and env-file were unchanged; rollback recreated the old +image with the same Compose and passed exact Env comparison. This locates the +drift in the new image's inherited environment. The discarded new container's +individual differing Env values were not recorded, so no exact Node version +transition is claimed. An application release must preserve its accepted base, +not silently update the Node image selected by a mutable local tag. + +The corrected read-only preflight inspects the accepted image by immutable ID +and a bounded local image inventory. It selects exactly one Node 24 base whose +complete root filesystem layers form a strict prefix of the accepted image, +and whose environment plus the registered HOST/PORT instructions exactly equals +the accepted image environment. Entrypoint, user, shell, labels, stop signal and +healthcheck must match. Base CMD is node, working directory is empty, and there +are no volumes, exposed ports or ONBUILD instructions. Duplicate Env keys, +missing or ambiguous ancestors and architecture changes fail before apply. +Proof stores image IDs and hashes only, never environment values. + +Build rechecks that proof and the registered source Dockerfile hash. In the +clean temporary context it replaces only FROM with the proved local image ID. +Docker 24 legacy builder is selected explicitly with DOCKER_BUILDKIT=0 and +--pull=false. BuildKit's FROM sha256: was tested locally and attempted +registry resolution; legacy builder resolved the local ID and completed. +This explicit selection avoids a backend-dependent pull or fallback. + +The base contains no prior application/project layers. projects is empty in +the build context, while the live registry, secrets, site workspaces and NAS +metadata stay outside it. The new image's full inherited configuration and +environment are compared before any service recreation. A difference reports +field/key names only and stops there. Runtime acceptance and rollback remain +unchanged and strict. There is no relaxed Env comparison, image pull, queue +reset, dependency change, production file edit or broader service selection. + +Validation: 87 CMS deployment tests, 95 Device Core regression tests, Python +3.8 AST and diff check. A separate local Docker integration creates isolated +fixture images without launching workload containers, invokes the actual +base resolver and builder, verifies exact environment/base ancestry, checks +all exported layers for the excluded private-project fixture and removes its +own image tags. It verifies the build mechanism, not NAS cache availability; +the production preflight remains authoritative for that. + +Promotion is the separate root-owned runner gate. After verify-install, +release a new CMS commit through the existing Git pipeline; no bootstrap, +reconciliation replay or manual container command is needed. diff --git a/infra/cms-deploy/README.md b/infra/cms-deploy/README.md index 0c34baf..443fb3b 100644 --- a/infra/cms-deploy/README.md +++ b/infra/cms-deploy/README.md @@ -6,7 +6,7 @@ The Device Core runner is scoped only to its own repository. CMS therefore regis `dc-cms-autodeploy` bootstraps exactly three source files under /volume1/docker/nodedc-cms-autodeploy, one build-runner service and two systemd units. Root-private queue state is /var/lib/nodedc-cms-autodeploy. Its read-only Gitea client uses the existing private Device Core read identity without copying it; preflight checks actual access to repository 33. The installed canonical receipt gates polling. Bootstrap preserves all preexisting containers and CMS data; rollback removes only the new runner/units/source partition, retaining private enrollment and queue for diagnosis. -`dc-cms-release` allows only flat admin/server application files and two exact dependency files. The initial predecessor is original CMS commit 4c6f133 with SMB-verified hashes in baseline.json. Foundation pins adm-zip 0.6.1 in foundation.json to fix known ZIP vulnerabilities. No later dependency, Dockerfile, Compose or Caddy change is admitted by this domain. Build uses the existing Dockerfile in an isolated temporary context with an empty projects directory. The canonical installer restarts only cms-app with no dependencies, no image pull and no rebuild during rollback. Acceptance verifies authentication, app hashes inside the running container, image generation, fixed ZIP dependency version, preserved env/mounts/networks/ports, other Compose services and site/project data. +`dc-cms-release` allows only flat admin/server application files and two exact dependency files. The initial predecessor is original CMS commit 4c6f133 with SMB-verified hashes in baseline.json. Foundation pins adm-zip 0.6.1 in foundation.json to fix known ZIP vulnerabilities. No later dependency, Dockerfile, Compose or Caddy change is admitted by this domain. Build uses the registered Dockerfile in an isolated temporary context with an empty projects directory. Only the temporary FROM line is replaced by the exact cached Node image ID proved against the accepted application's layer ancestry and inherited configuration; see [the build-base contract](R40_BUILD_BASE.md). The canonical installer restarts only cms-app with no dependencies, no image pull and no rebuild during rollback. Acceptance verifies authentication, app hashes inside the running container, image generation, fixed ZIP dependency version, preserved env/mounts/networks/ports, other Compose services and site/project data. ## Build and checks @@ -59,3 +59,7 @@ saved predecessor fingerprint: only bind-string order and three empty DNS list representations differ. See [the incident proof and recovery contract](R39_RUNTIME_RECONCILIATION.md). The separate `dc-cms-runtime-reconciliation` marker transition re-proves that exact legacy hash on NAS before releasing the r39 barrier. It never retries r39. +Reconciliation was accepted at 2026-11-04T20:28:35Z. The next qualified run r40 +failed only `config.Env`; its automatic rollback passed completely. r40 is also +terminal and must not be replayed. The build-base correction requires a new +runner promotion followed by a new CMS commit/run, without another bootstrap. diff --git a/infra/cms-deploy/release_runtime.py b/infra/cms-deploy/release_runtime.py index f680571..5fad5b0 100644 --- a/infra/cms-deploy/release_runtime.py +++ b/infra/cms-deploy/release_runtime.py @@ -162,6 +162,84 @@ def cms_healthchecks(): for check in COMPONENTS['dc-cms']['healthchecks']:healthcheck_url(check) +def cms_image_env(config): + # Values remain in process memory. Reject ambiguous duplicate keys. + values=config.get('Env') + if not isinstance(values,list):die('CMS image environment is missing') + result={} + for value in values: + if not isinstance(value,str) or '=' not in value or '\0' in value: + die('CMS image environment is malformed') + key,data=value.split('=',1) + if not re.fullmatch('[A-Za-z_][A-Za-z0-9_]*',key) or key in result: + die('CMS image environment has ambiguous keys') + result[key]=data + return result + + +def cms_inspect_image(identity): + if not re.fullmatch('sha256:[a-f0-9]{64}',str(identity)): + die('CMS immutable image identity is invalid') + rows=docker_json(['image','inspect',identity],'CMS immutable image') + if not isinstance(rows,list) or len(rows)!=1 or rows[0].get('Id')!=identity: + die('CMS immutable image inspection mismatch') + return rows[0] + + +def cms_node_base_matches(image, accepted): + # Prove filesystem ancestry AND the exact config inherited by the fixed + # Dockerfile. Neither a mutable tag nor a matching NODE_VERSION is proof. + layers=(image.get('RootFS') or {}).get('Layers') + original=(accepted.get('RootFS') or {}).get('Layers') + if ((image.get('RootFS') or {}).get('Type')!='layers' + or (accepted.get('RootFS') or {}).get('Type')!='layers' + or not isinstance(layers,list) or not isinstance(original,list) or not layers + or len(layers)>=len(original) or original[:len(layers)]!=layers + or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in layers)): + return False + if any(image.get(key)!=accepted.get(key) for key in ('Os','Architecture','Variant')): + return False + config=image.get('Config') or {};old=accepted.get('Config') or {} + if (image.get('Os')!='linux' or config.get('Cmd')!=['node'] + or config.get('WorkingDir') not in ('',None) + or config.get('OnBuild') not in (None,[]) or config.get('Volumes') not in (None,{}) + or config.get('ExposedPorts') not in (None,{})): + return False + for key in ('User','Entrypoint','Shell','StopSignal','Healthcheck','Labels'): + if config.get(key)!=old.get(key):return False + try: + env=cms_image_env(config);old_env=cms_image_env(old) + except DeployError: + return False + if not re.fullmatch(r'24\.[0-9]+\.[0-9]+',env.get('NODE_VERSION','')):return False + return {**env,'HOST':'0.0.0.0','PORT':'8090'}==old_env + + +def cms_resolve_build_base(runtime): + accepted=cms_inspect_image(runtime['imageId']) + proc=subprocess.run([str(DOCKER),'image','ls','--all','--quiet','--no-trunc'], + capture_output=True,text=True,check=True,timeout=30) + identities=sorted(set(proc.stdout.split())) + if not 1<=len(identities)<=2048 or any(not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in identities): + die('CMS local base image inventory is invalid or outside bounds') + matches=[] + for start in range(0,len(identities),64): + batch=identities[start:start+64] + images=docker_json(['image','inspect',*batch],'CMS local base inventory') + if not isinstance(images,list) or sorted(image.get('Id','') for image in images)!=batch: + die('CMS local base inventory changed during inspection') + for image in images: + if cms_node_base_matches(image,accepted):matches.append(image) + if len(matches)!=1: + die('CMS exact cached Node base is missing or ambiguous; no image pull or runtime change permitted') + base=matches[0] + proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'], + 'layersSha256':cms_audit_digest(base['RootFS']['Layers']), + 'configSha256':cms_audit_digest(base['Config'])} + print('cms_build_base=accepted-image-ancestor;immutable-id='+base['Id']+';pull=never') + return proof + + def preflight_cms_release(payload, entries, identity): require_root() d = validate_cms_release_payload(payload,entries,identity) @@ -172,12 +250,25 @@ def preflight_cms_release(payload, entries, identity): # v1 is additive: deleting an application file requires a reviewed transition. if not set(installed) <= set(entries):die('CMS v1 release cannot remove existing application files') cms_healthchecks() + runtime=cms_runtime_snapshot_v2() + base=cms_resolve_build_base(runtime) return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'], - 'runtimeFingerprintVersion':2,'runtime':cms_runtime_snapshot_v2(),'otherServices':cms_other_services(), + 'runtimeFingerprintVersion':2,'runtime':runtime,'buildBase':base,'otherServices':cms_other_services(), 'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed,'installedMetadata':metadata} def build_cms_release(before): + proof=before['buildBase'] + if proof.get('acceptedImageId')!=before['runtime']['imageId']: + die('CMS build base predecessor changed') + base=cms_inspect_image(proof['imageId']);accepted=cms_inspect_image(proof['acceptedImageId']) + if (not cms_node_base_matches(base,accepted) + or cms_audit_digest(base['RootFS']['Layers'])!=proof['layersSha256'] + or cms_audit_digest(base['Config'])!=proof['configSha256']): + die('CMS build base differs from its preflight proof') + dockerfile=(CMS_ROOT/'Dockerfile').read_bytes() + if hashlib.sha256(dockerfile).hexdigest()!=CMS_FOUNDATION['Dockerfile'] or not dockerfile.startswith(b'FROM node:24-alpine\n'): + die('CMS build recipe differs from the registered foundation') # Legacy Dockerfile COPYs projects. Supply an empty directory, never the NAS # project registry, encrypted passwords, uploaded ZIPs or site workspaces. with tempfile.TemporaryDirectory(prefix='cms-build-',dir=TMP_DIR) as temp: @@ -185,10 +276,25 @@ def build_cms_release(before): (context/'projects').mkdir() for rel in ('Dockerfile','package.json','package-lock.json',*before['entries']): target=context/rel;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(CMS_ROOT/rel,target) - subprocess.run([str(DOCKER),'build','--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)],check=True) + # Pin only the temporary recipe. The registered source Dockerfile is + # unchanged; no previous application/project layers enter this image. + (context/'Dockerfile').write_bytes(('FROM '+base['Id']+'\n').encode()+dockerfile.split(b'\n',1)[1]) + # Docker 24's legacy builder accepts a local image ID in FROM. BuildKit + # interprets sha256: as a registry repository and must not be used. + subprocess.run([str(DOCKER),'build','--pull=false','--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)], + check=True,env={**os.environ,'DOCKER_BUILDKIT':'0'}) image=docker_json(['image','inspect',before['runtime']['imageRef']],'CMS built image') if not isinstance(image,list) or len(image)!=1:die('CMS built image is ambiguous') before['builtImageId']=image[0]['Id'] + expected=accepted.get('Config') or {};actual=image[0].get('Config') or {} + changed=[key for key in ('User','Cmd','Entrypoint','WorkingDir','ExposedPorts','Shell','StopSignal','Healthcheck','Labels','Volumes','OnBuild') + if actual.get(key)!=expected.get(key)] + actual_env=cms_image_env(actual);expected_env=cms_image_env(expected) + if actual_env!=expected_env: + names=sorted(k for k in set(actual_env)|set(expected_env) if actual_env.get(k)!=expected_env.get(k)) + changed.append('Env['+','.join(names)+']') + if changed:die('CMS built image changes inherited configuration before recreation: '+','.join(changed)) + print('cms_build_accept=inherited-config-exact;runtime-not-recreated') def run_cms_release_compose(): diff --git a/infra/cms-deploy/test_build_base.py b/infra/cms-deploy/test_build_base.py new file mode 100644 index 0000000..0e00ae6 --- /dev/null +++ b/infra/cms-deploy/test_build_base.py @@ -0,0 +1,101 @@ +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_resolver_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)]: + listing=type('Result',(),{'stdout':'\n'.join(i['Id'] for i in inventory)})() + with patch.object(r,'cms_inspect_image',return_value=old),patch.object(r.subprocess,'run',return_value=listing) as run,patch.object(r,'docker_json',return_value=inventory),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],[str(r.DOCKER),'image','ls','--all','--quiet','--no-trunc']) + self.assertNotIn('PATH=',output.getvalue()) + + 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() diff --git a/infra/cms-deploy/test_reconciliation.py b/infra/cms-deploy/test_reconciliation.py index 57289d3..579112a 100644 --- a/infra/cms-deploy/test_reconciliation.py +++ b/infra/cms-deploy/test_reconciliation.py @@ -138,7 +138,8 @@ class ReconciliationTests(unittest.TestCase): ('cms_installed_release',{'sourceCommit':'old','runNumber':0}), ('cms_application_inventory',({'app':'sha'},{})),('cms_healthchecks',None), ('cms_foundation',{}),('cms_preserved_data',{}),('cms_other_services',{}), - ('cms_runtime_snapshot_v2',{'fieldSha256':{'config.Env':'sha'}})]: + ('cms_runtime_snapshot_v2',{'fieldSha256':{'config.Env':'sha'}}), + ('cms_resolve_build_base',{'imageId':'fixture-base'})]: stack.enter_context(patch.object(r,name,return_value=value)) legacy=stack.enter_context(patch.object(r,'cms_runtime_snapshot')) result=r.preflight_cms_release(self.payload,['app'],'new') diff --git a/infra/cms-deploy/test_runner.py b/infra/cms-deploy/test_runner.py index cf10507..d66a71a 100644 --- a/infra/cms-deploy/test_runner.py +++ b/infra/cms-deploy/test_runner.py @@ -55,21 +55,6 @@ class CmsRunnerTests(unittest.TestCase): self.assertIn('--dc-cms-autodeploy-tick',r.cms_autodeploy_units()[r.CMS_AUTODEPLOY_SERVICE]) self.assertEqual(r.CMS_AUTODEPLOY_DESCRIPTOR['publishedPorts'],[]) - def test_build_context_excludes_projects_and_credentials(self): - with tempfile.TemporaryDirectory() as tmp: - root=Path(tmp);entries,_=fixture(root) - for name in ('Dockerfile','package.json','package-lock.json'):(root/name).write_text('fixture') - (root/'projects/sites').mkdir(parents=True);(root/'projects/secret.json').write_text('never copy') - (root/'server/@eaDir').mkdir();(root/'server/@eaDir/admin-server.mjs@SynoEAStream').write_text('never copy metadata') - before={'entries':entries,'runtime':{'imageRef':'dc-cms-cms-app'}} - def build(cmd,**kwargs): - context=Path(cmd[-1]);self.assertEqual(list((context/'projects').iterdir()),[]) - self.assertEqual(set(p.relative_to(context).as_posix() for p in context.rglob('*') if p.is_file()),set(entries)|{'Dockerfile','package.json','package-lock.json'}) - self.assertEqual(cmd[:2],[str(r.DOCKER),'build']) - with patch.object(r,'CMS_ROOT',root),patch.object(r,'TMP_DIR',root),patch.object(r.subprocess,'run',side_effect=build),patch.object(r,'docker_json',return_value=[{'Id':'sha256:built'}]): - r.build_cms_release(before) - self.assertEqual(before['builtImageId'],'sha256:built') - def test_no_dependency_recreation_or_rollback_rebuild(self): with patch.object(r.subprocess,'run') as run: r.run_cms_release_compose() diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 78665cb..7286903 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -43121,6 +43121,84 @@ def cms_healthchecks(): for check in COMPONENTS['dc-cms']['healthchecks']:healthcheck_url(check) +def cms_image_env(config): + # Values remain in process memory. Reject ambiguous duplicate keys. + values=config.get('Env') + if not isinstance(values,list):die('CMS image environment is missing') + result={} + for value in values: + if not isinstance(value,str) or '=' not in value or '\0' in value: + die('CMS image environment is malformed') + key,data=value.split('=',1) + if not re.fullmatch('[A-Za-z_][A-Za-z0-9_]*',key) or key in result: + die('CMS image environment has ambiguous keys') + result[key]=data + return result + + +def cms_inspect_image(identity): + if not re.fullmatch('sha256:[a-f0-9]{64}',str(identity)): + die('CMS immutable image identity is invalid') + rows=docker_json(['image','inspect',identity],'CMS immutable image') + if not isinstance(rows,list) or len(rows)!=1 or rows[0].get('Id')!=identity: + die('CMS immutable image inspection mismatch') + return rows[0] + + +def cms_node_base_matches(image, accepted): + # Prove filesystem ancestry AND the exact config inherited by the fixed + # Dockerfile. Neither a mutable tag nor a matching NODE_VERSION is proof. + layers=(image.get('RootFS') or {}).get('Layers') + original=(accepted.get('RootFS') or {}).get('Layers') + if ((image.get('RootFS') or {}).get('Type')!='layers' + or (accepted.get('RootFS') or {}).get('Type')!='layers' + or not isinstance(layers,list) or not isinstance(original,list) or not layers + or len(layers)>=len(original) or original[:len(layers)]!=layers + or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in layers)): + return False + if any(image.get(key)!=accepted.get(key) for key in ('Os','Architecture','Variant')): + return False + config=image.get('Config') or {};old=accepted.get('Config') or {} + if (image.get('Os')!='linux' or config.get('Cmd')!=['node'] + or config.get('WorkingDir') not in ('',None) + or config.get('OnBuild') not in (None,[]) or config.get('Volumes') not in (None,{}) + or config.get('ExposedPorts') not in (None,{})): + return False + for key in ('User','Entrypoint','Shell','StopSignal','Healthcheck','Labels'): + if config.get(key)!=old.get(key):return False + try: + env=cms_image_env(config);old_env=cms_image_env(old) + except DeployError: + return False + if not re.fullmatch(r'24\.[0-9]+\.[0-9]+',env.get('NODE_VERSION','')):return False + return {**env,'HOST':'0.0.0.0','PORT':'8090'}==old_env + + +def cms_resolve_build_base(runtime): + accepted=cms_inspect_image(runtime['imageId']) + proc=subprocess.run([str(DOCKER),'image','ls','--all','--quiet','--no-trunc'], + capture_output=True,text=True,check=True,timeout=30) + identities=sorted(set(proc.stdout.split())) + if not 1<=len(identities)<=2048 or any(not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in identities): + die('CMS local base image inventory is invalid or outside bounds') + matches=[] + for start in range(0,len(identities),64): + batch=identities[start:start+64] + images=docker_json(['image','inspect',*batch],'CMS local base inventory') + if not isinstance(images,list) or sorted(image.get('Id','') for image in images)!=batch: + die('CMS local base inventory changed during inspection') + for image in images: + if cms_node_base_matches(image,accepted):matches.append(image) + if len(matches)!=1: + die('CMS exact cached Node base is missing or ambiguous; no image pull or runtime change permitted') + base=matches[0] + proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'], + 'layersSha256':cms_audit_digest(base['RootFS']['Layers']), + 'configSha256':cms_audit_digest(base['Config'])} + print('cms_build_base=accepted-image-ancestor;immutable-id='+base['Id']+';pull=never') + return proof + + def preflight_cms_release(payload, entries, identity): require_root() d = validate_cms_release_payload(payload,entries,identity) @@ -43131,12 +43209,25 @@ def preflight_cms_release(payload, entries, identity): # v1 is additive: deleting an application file requires a reviewed transition. if not set(installed) <= set(entries):die('CMS v1 release cannot remove existing application files') cms_healthchecks() + runtime=cms_runtime_snapshot_v2() + base=cms_resolve_build_base(runtime) return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'], - 'runtimeFingerprintVersion':2,'runtime':cms_runtime_snapshot_v2(),'otherServices':cms_other_services(), + 'runtimeFingerprintVersion':2,'runtime':runtime,'buildBase':base,'otherServices':cms_other_services(), 'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed,'installedMetadata':metadata} def build_cms_release(before): + proof=before['buildBase'] + if proof.get('acceptedImageId')!=before['runtime']['imageId']: + die('CMS build base predecessor changed') + base=cms_inspect_image(proof['imageId']);accepted=cms_inspect_image(proof['acceptedImageId']) + if (not cms_node_base_matches(base,accepted) + or cms_audit_digest(base['RootFS']['Layers'])!=proof['layersSha256'] + or cms_audit_digest(base['Config'])!=proof['configSha256']): + die('CMS build base differs from its preflight proof') + dockerfile=(CMS_ROOT/'Dockerfile').read_bytes() + if hashlib.sha256(dockerfile).hexdigest()!=CMS_FOUNDATION['Dockerfile'] or not dockerfile.startswith(b'FROM node:24-alpine\n'): + die('CMS build recipe differs from the registered foundation') # Legacy Dockerfile COPYs projects. Supply an empty directory, never the NAS # project registry, encrypted passwords, uploaded ZIPs or site workspaces. with tempfile.TemporaryDirectory(prefix='cms-build-',dir=TMP_DIR) as temp: @@ -43144,10 +43235,25 @@ def build_cms_release(before): (context/'projects').mkdir() for rel in ('Dockerfile','package.json','package-lock.json',*before['entries']): target=context/rel;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(CMS_ROOT/rel,target) - subprocess.run([str(DOCKER),'build','--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)],check=True) + # Pin only the temporary recipe. The registered source Dockerfile is + # unchanged; no previous application/project layers enter this image. + (context/'Dockerfile').write_bytes(('FROM '+base['Id']+'\n').encode()+dockerfile.split(b'\n',1)[1]) + # Docker 24's legacy builder accepts a local image ID in FROM. BuildKit + # interprets sha256: as a registry repository and must not be used. + subprocess.run([str(DOCKER),'build','--pull=false','--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)], + check=True,env={**os.environ,'DOCKER_BUILDKIT':'0'}) image=docker_json(['image','inspect',before['runtime']['imageRef']],'CMS built image') if not isinstance(image,list) or len(image)!=1:die('CMS built image is ambiguous') before['builtImageId']=image[0]['Id'] + expected=accepted.get('Config') or {};actual=image[0].get('Config') or {} + changed=[key for key in ('User','Cmd','Entrypoint','WorkingDir','ExposedPorts','Shell','StopSignal','Healthcheck','Labels','Volumes','OnBuild') + if actual.get(key)!=expected.get(key)] + actual_env=cms_image_env(actual);expected_env=cms_image_env(expected) + if actual_env!=expected_env: + names=sorted(k for k in set(actual_env)|set(expected_env) if actual_env.get(k)!=expected_env.get(k)) + changed.append('Env['+','.join(names)+']') + if changed:die('CMS built image changes inherited configuration before recreation: '+','.join(changed)) + print('cms_build_accept=inherited-config-exact;runtime-not-recreated') def run_cms_release_compose():