diff --git a/infra/cms-deploy/README.md b/infra/cms-deploy/README.md index 1e904e5..8118a9c 100644 --- a/infra/cms-deploy/README.md +++ b/infra/cms-deploy/README.md @@ -17,3 +17,14 @@ The Device Core runner is scoped only to its own repository. CMS therefore regis `python3 infra/cms-deploy/build_autodeploy.py --output-dir ` Before production: SHA-pinned root runner promotion and verify-install; then fresh canonical plan/apply of the bootstrap artifact. Ordinary CMS pushes afterward need no operator NAS commands. A queued or green Actions run alone is not deployment evidence; require canonical receipt and product acceptance. + +Bootstrap 002 corrects the initial POSIX inventory: the NAS contains a Synology +`server/@eaDir/admin-server.mjs@SynoEAStream` file hidden from SMB. The original +application and foundation hashes were confirmed unchanged through both paths. +Only flat `admin|server/@eaDir/@SynoEAStream` regular +files are classified as metadata. Orphaned streams, unknown paths and symlinks +remain errors. Metadata is excluded from application identity and clean image +build inputs, and preserved byte-for-byte across application release/rollback. +The same partition handles old images containing these non-code streams; all +application hashes are still exact. Bootstrap 001 failed during read-only plan, +never entered apply, and is superseded rather than retried or overwritten. diff --git a/infra/cms-deploy/autodeploy-v1.json b/infra/cms-deploy/autodeploy-v1.json index d30bb6c..88e4f4f 100644 --- a/infra/cms-deploy/autodeploy-v1.json +++ b/infra/cms-deploy/autodeploy-v1.json @@ -8,7 +8,7 @@ "intervalAfterCompletionSeconds": 30, "publishedPorts": [], "releaseComponent": "dc-cms-release", - "releaseId": "dc-cms-autodeploy-v1-20261104-001", + "releaseId": "dc-cms-autodeploy-v1-20261104-002", "repository": "SILVER/DC_CMS", "repositoryId": 33, "scheduler": "native-systemd-timer", diff --git a/infra/cms-deploy/autodeploy_runtime.py b/infra/cms-deploy/autodeploy_runtime.py index ee073ba..e950f93 100644 --- a/infra/cms-deploy/autodeploy_runtime.py +++ b/infra/cms-deploy/autodeploy_runtime.py @@ -1,5 +1,5 @@ # DC CMS outbound automatic deployment. All authority stays in this file. -CMS_AUTODEPLOY_ID = 'dc-cms-autodeploy-v1-20261104-001' +CMS_AUTODEPLOY_ID = 'dc-cms-autodeploy-v1-20261104-002' CMS_AUTODEPLOY_ENTRY = 'deployment/dc-cms-autodeploy-v1.json' CMS_AUTODEPLOY_ENTRIES = CMS_CI_V4_ENTRIES CMS_AUTODEPLOY_ROOT = Path('/volume1/docker/nodedc-cms-autodeploy') diff --git a/infra/cms-deploy/release_runtime.py b/infra/cms-deploy/release_runtime.py index ab48868..02d0c1a 100644 --- a/infra/cms-deploy/release_runtime.py +++ b/infra/cms-deploy/release_runtime.py @@ -61,6 +61,35 @@ def cms_foundation(): return {**expected, 'infra/.env.synology':sha256_file(env)} +def cms_without_synology_metadata(files, label): + """Partition only NAS EA streams attached to a present application file. + + Synology exposes these files to POSIX but hides them from SMB. They are + never application payload or build input. Unknown paths remain rejected. + """ + application = {} + metadata = {} + for rel, digest in files.items(): + parts = PurePosixPath(rel).parts + if '@eaDir' not in parts: + application[rel] = digest + continue + if (len(parts) != 3 or parts[0] not in ('admin', 'server') + or parts[1] != '@eaDir' or not parts[2].endswith('@SynoEAStream')): + die(label + ' has an unrecognized Synology metadata path: ' + rel) + sibling = parts[0] + '/' + parts[2][:-len('@SynoEAStream')] + cms_release_path(sibling) + if sibling not in files: + die(label + ' has orphaned Synology metadata: ' + rel) + metadata[rel] = digest + return application, metadata + + +def cms_application_inventory(): + files = collect_exact_files(CMS_ROOT, ('admin', 'server', *CMS_DEPENDENCY_FILES), 'CMS installed app') + return cms_without_synology_metadata(files, 'CMS installed app') + + def cms_installed_release(): for row in load_state(FAILED_STATE_FILE): if row.get('component') in ('dc-cms-release','dc-cms-autodeploy') and row.get('started_apply') and not str(row.get('rollback_status','')).startswith('ok:'): @@ -78,8 +107,11 @@ def cms_installed_release(): # Initial transition is independently anchored in the exact live CMS source. descriptor = {'sourceCommit':CMS_BASELINE['sourceCommit'],'runNumber':0,'releaseId':'dc-cms-4c6f133'} expected = {**CMS_BASELINE['filesSha256'], **{p:CMS_BASELINE['foundationSha256'][p] for p in CMS_DEPENDENCY_FILES}} - if collect_exact_files(CMS_ROOT, ('admin','server',*CMS_DEPENDENCY_FILES), 'CMS installed app') != expected: - die('CMS installed application differs from its canonical predecessor') + actual, _ = cms_application_inventory() + if actual != expected: + delta = {'missing':sorted(set(expected)-set(actual)), 'unexpected':sorted(set(actual)-set(expected)), + 'changed':sorted(p for p in set(actual)&set(expected) if actual[p]!=expected[p])} + die('CMS installed application differs from its canonical predecessor: ' + json.dumps(delta, sort_keys=True)) cms_foundation() return descriptor @@ -135,13 +167,13 @@ def preflight_cms_release(payload, entries, identity): previous = cms_installed_release() if d['runNumber'] <= previous['runNumber'] or d['sourceCommit'] == previous['sourceCommit']: die('CMS release is stale or already installed') - installed = collect_exact_files(CMS_ROOT,('admin','server',*CMS_DEPENDENCY_FILES),'CMS rollback source') + installed, metadata = cms_application_inventory() # 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() return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'], 'runtime':cms_runtime_snapshot(),'otherServices':cms_other_services(), - 'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed} + 'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed,'installedMetadata':metadata} def build_cms_release(before): @@ -164,9 +196,17 @@ def run_cms_release_compose(): def cms_image_files(identity): - script="const fs=require('fs'),p=require('path'),c=require('crypto'),r={};for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){const f='/app/'+d+'/'+n;if(!fs.lstatSync(f).isFile())throw Error('unexpected runtime path');r[d+'/'+n]=c.createHash('sha256').update(fs.readFileSync(f)).digest('hex')}process.stdout.write(JSON.stringify(r))" + script="""const fs=require('fs'),c=require('crypto'),r={}; +for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){ + const rel=d+'/'+n,f='/app/'+rel,s=fs.lstatSync(f); + if(s.isFile())r[rel]=c.createHash('sha256').update(fs.readFileSync(f)).digest('hex'); + else if(n==='@eaDir'&&s.isDirectory())for(const m of fs.readdirSync(f)){ + const q=f+'/'+m;if(!fs.lstatSync(q).isFile())throw Error('unexpected runtime metadata path'); + r[rel+'/'+m]=c.createHash('sha256').update(fs.readFileSync(q)).digest('hex'); + }else throw Error('unexpected runtime path'); +}process.stdout.write(JSON.stringify(r))""" proc=subprocess.run([str(DOCKER),'exec',identity,'node','-e',script],capture_output=True,text=True,check=True,timeout=30) - return json.loads(proc.stdout) + return cms_without_synology_metadata(json.loads(proc.stdout), 'CMS running image')[0] def accept_cms_release(before, *, rollback=False): @@ -180,7 +220,8 @@ def accept_cms_release(before, *, rollback=False): expected_foundation=before['foundation'] if rollback else {**CMS_FOUNDATION,'infra/.env.synology':before['foundation']['infra/.env.synology']} if cms_other_services()!=before['otherServices'] or cms_foundation()!=expected_foundation or cms_preserved_data()!=before['data']: die('CMS release changed preserved applications or project data') - actual=collect_exact_files(CMS_ROOT,('admin','server',*CMS_DEPENDENCY_FILES),'CMS installed app') + actual, metadata=cms_application_inventory() + if metadata != before['installedMetadata']:die('CMS release changed preserved Synology metadata') if rollback: if actual!=before['installedFiles']:die('CMS rollback source mismatch') else: diff --git a/infra/cms-deploy/test_runner.py b/infra/cms-deploy/test_runner.py index cbcee9f..cf10507 100644 --- a/infra/cms-deploy/test_runner.py +++ b/infra/cms-deploy/test_runner.py @@ -60,6 +60,7 @@ class CmsRunnerTests(unittest.TestCase): 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()),[]) diff --git a/infra/cms-deploy/test_synology_metadata.py b/infra/cms-deploy/test_synology_metadata.py new file mode 100644 index 0000000..b72f98c --- /dev/null +++ b/infra/cms-deploy/test_synology_metadata.py @@ -0,0 +1,112 @@ +"""Regression for POSIX-only @eaDir files observed on the production NAS.""" +from contextlib import ExitStack +import hashlib +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +from unittest.mock import patch +from test_runner import r + + +class SynologyMetadataTests(unittest.TestCase): + def initial(self, root): + for rel in r.CMS_BASELINE['filesSha256']: + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text('predecessor: ' + rel) + for rel in r.CMS_BASELINE['foundationSha256']: + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text('foundation: ' + rel) + (root / 'infra/.env.synology').write_text('TEST_ONLY=1\n') + baseline = {'sourceCommit':r.CMS_BASELINE['sourceCommit']} + for key in ('filesSha256', 'foundationSha256'): + baseline[key] = {rel:hashlib.sha256((root/rel).read_bytes()).hexdigest() + for rel in r.CMS_BASELINE[key]} + stream = root / 'server/@eaDir/admin-server.mjs@SynoEAStream' + stream.parent.mkdir(mode=0o777) + stream.write_bytes(b'NAS extended attribute fixture') + stream.chmod(0o777) + return baseline, stream + + def initial_check(self, root, baseline): + with patch.object(r, 'CMS_ROOT', root), patch.object(r, 'CMS_BASELINE', baseline), patch.object(r, 'load_state', return_value=[]): + return r.cms_installed_release() + + def test_initial_predecessor_with_posix_only_metadata(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + baseline, stream = self.initial(root) + self.assertEqual(self.initial_check(root, baseline)['sourceCommit'], baseline['sourceCommit']) + with patch.object(r, 'CMS_ROOT', root): + app, metadata = r.cms_application_inventory() + self.assertNotIn(stream.relative_to(root).as_posix(), app) + self.assertEqual(metadata, {stream.relative_to(root).as_posix():hashlib.sha256(stream.read_bytes()).hexdigest()}) + + def test_actual_source_drift_still_fails_with_actionable_paths(self): + for mutation, expected in [('change','changed'), ('extra','unexpected'), ('remove','missing')]: + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as d: + root = Path(d) + baseline, _ = self.initial(root) + if mutation == 'change': (root/'admin/admin.js').write_text('unauthorized') + elif mutation == 'extra': (root/'server/unexpected.mjs').write_text('unauthorized') + else: (root/'admin/index.html').unlink() + with self.assertRaisesRegex(r.DeployError, expected): + self.initial_check(root, baseline) + + def test_unknown_or_orphaned_metadata_is_rejected(self): + for rel in ('server/@eaDir/code.mjs', 'server/@eaDir/missing.mjs@SynoEAStream', + 'server/@eaDir/nested/admin-server.mjs@SynoEAStream', 'admin/@eaDir/.env@SynoEAStream'): + with self.subTest(rel=rel), tempfile.TemporaryDirectory() as d: + root = Path(d) + baseline, _ = self.initial(root) + extra = root/rel + extra.parent.mkdir(parents=True, exist_ok=True) + extra.write_text('unexpected') + with self.assertRaises(r.DeployError): self.initial_check(root, baseline) + + def test_metadata_symlinks_still_fail(self): + for whole_directory in (False, True): + with self.subTest(directory=whole_directory), tempfile.TemporaryDirectory() as d: + root = Path(d) + baseline, stream = self.initial(root) + stream.unlink() + if whole_directory: + stream.parent.rmdir() + stream.parent.symlink_to(root/'admin', target_is_directory=True) + else: + stream.symlink_to(root/'server/admin-server.mjs') + with self.assertRaisesRegex(r.DeployError, 'unsafe'): + self.initial_check(root, baseline) + + def test_runtime_inventory_executes_with_and_without_old_metadata(self): + node = shutil.which('node') + self.assertIsNotNone(node, 'node is required to verify the in-container inventory program') + run = subprocess.run + for with_metadata in (False, True): + with self.subTest(metadata=with_metadata), tempfile.TemporaryDirectory() as d: + root = Path(d) + baseline, stream = self.initial(root) + if not with_metadata: + stream.unlink();stream.parent.rmdir() + def execute(cmd, **kwargs): + self.assertEqual(cmd[:5], [str(r.DOCKER),'exec','fixture-container','node','-e']) + return run([node,'-e',cmd[5].replace('/app/', str(root)+'/')], **kwargs) + with patch.object(r.subprocess, 'run', side_effect=execute): + self.assertEqual(r.cms_image_files('fixture-container'), baseline['filesSha256']) + + def test_runtime_metadata_symlink_is_rejected(self): + node = shutil.which('node');run = subprocess.run + with tempfile.TemporaryDirectory() as d: + root = Path(d) + _, stream = self.initial(root) + stream.unlink();stream.symlink_to(root/'server/admin-server.mjs') + def execute(cmd, **kwargs): + return run([node,'-e',cmd[5].replace('/app/', str(root)+'/')], **kwargs) + with patch.object(r.subprocess, 'run', side_effect=execute), self.assertRaises(subprocess.CalledProcessError): + r.cms_image_files('fixture-container') + + +if __name__ == '__main__': unittest.main() diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 5f5e6ec..bf307dc 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -42975,6 +42975,35 @@ def cms_foundation(): return {**expected, 'infra/.env.synology':sha256_file(env)} +def cms_without_synology_metadata(files, label): + """Partition only NAS EA streams attached to a present application file. + + Synology exposes these files to POSIX but hides them from SMB. They are + never application payload or build input. Unknown paths remain rejected. + """ + application = {} + metadata = {} + for rel, digest in files.items(): + parts = PurePosixPath(rel).parts + if '@eaDir' not in parts: + application[rel] = digest + continue + if (len(parts) != 3 or parts[0] not in ('admin', 'server') + or parts[1] != '@eaDir' or not parts[2].endswith('@SynoEAStream')): + die(label + ' has an unrecognized Synology metadata path: ' + rel) + sibling = parts[0] + '/' + parts[2][:-len('@SynoEAStream')] + cms_release_path(sibling) + if sibling not in files: + die(label + ' has orphaned Synology metadata: ' + rel) + metadata[rel] = digest + return application, metadata + + +def cms_application_inventory(): + files = collect_exact_files(CMS_ROOT, ('admin', 'server', *CMS_DEPENDENCY_FILES), 'CMS installed app') + return cms_without_synology_metadata(files, 'CMS installed app') + + def cms_installed_release(): for row in load_state(FAILED_STATE_FILE): if row.get('component') in ('dc-cms-release','dc-cms-autodeploy') and row.get('started_apply') and not str(row.get('rollback_status','')).startswith('ok:'): @@ -42992,8 +43021,11 @@ def cms_installed_release(): # Initial transition is independently anchored in the exact live CMS source. descriptor = {'sourceCommit':CMS_BASELINE['sourceCommit'],'runNumber':0,'releaseId':'dc-cms-4c6f133'} expected = {**CMS_BASELINE['filesSha256'], **{p:CMS_BASELINE['foundationSha256'][p] for p in CMS_DEPENDENCY_FILES}} - if collect_exact_files(CMS_ROOT, ('admin','server',*CMS_DEPENDENCY_FILES), 'CMS installed app') != expected: - die('CMS installed application differs from its canonical predecessor') + actual, _ = cms_application_inventory() + if actual != expected: + delta = {'missing':sorted(set(expected)-set(actual)), 'unexpected':sorted(set(actual)-set(expected)), + 'changed':sorted(p for p in set(actual)&set(expected) if actual[p]!=expected[p])} + die('CMS installed application differs from its canonical predecessor: ' + json.dumps(delta, sort_keys=True)) cms_foundation() return descriptor @@ -43049,13 +43081,13 @@ def preflight_cms_release(payload, entries, identity): previous = cms_installed_release() if d['runNumber'] <= previous['runNumber'] or d['sourceCommit'] == previous['sourceCommit']: die('CMS release is stale or already installed') - installed = collect_exact_files(CMS_ROOT,('admin','server',*CMS_DEPENDENCY_FILES),'CMS rollback source') + installed, metadata = cms_application_inventory() # 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() return {'descriptor':d,'entries':list(entries),'predecessor':previous['sourceCommit'], 'runtime':cms_runtime_snapshot(),'otherServices':cms_other_services(), - 'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed} + 'foundation':cms_foundation(),'data':cms_preserved_data(),'installedFiles':installed,'installedMetadata':metadata} def build_cms_release(before): @@ -43078,9 +43110,17 @@ def run_cms_release_compose(): def cms_image_files(identity): - script="const fs=require('fs'),p=require('path'),c=require('crypto'),r={};for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){const f='/app/'+d+'/'+n;if(!fs.lstatSync(f).isFile())throw Error('unexpected runtime path');r[d+'/'+n]=c.createHash('sha256').update(fs.readFileSync(f)).digest('hex')}process.stdout.write(JSON.stringify(r))" + script="""const fs=require('fs'),c=require('crypto'),r={}; +for(const d of ['admin','server'])for(const n of fs.readdirSync('/app/'+d)){ + const rel=d+'/'+n,f='/app/'+rel,s=fs.lstatSync(f); + if(s.isFile())r[rel]=c.createHash('sha256').update(fs.readFileSync(f)).digest('hex'); + else if(n==='@eaDir'&&s.isDirectory())for(const m of fs.readdirSync(f)){ + const q=f+'/'+m;if(!fs.lstatSync(q).isFile())throw Error('unexpected runtime metadata path'); + r[rel+'/'+m]=c.createHash('sha256').update(fs.readFileSync(q)).digest('hex'); + }else throw Error('unexpected runtime path'); +}process.stdout.write(JSON.stringify(r))""" proc=subprocess.run([str(DOCKER),'exec',identity,'node','-e',script],capture_output=True,text=True,check=True,timeout=30) - return json.loads(proc.stdout) + return cms_without_synology_metadata(json.loads(proc.stdout), 'CMS running image')[0] def accept_cms_release(before, *, rollback=False): @@ -43094,7 +43134,8 @@ def accept_cms_release(before, *, rollback=False): expected_foundation=before['foundation'] if rollback else {**CMS_FOUNDATION,'infra/.env.synology':before['foundation']['infra/.env.synology']} if cms_other_services()!=before['otherServices'] or cms_foundation()!=expected_foundation or cms_preserved_data()!=before['data']: die('CMS release changed preserved applications or project data') - actual=collect_exact_files(CMS_ROOT,('admin','server',*CMS_DEPENDENCY_FILES),'CMS installed app') + actual, metadata=cms_application_inventory() + if metadata != before['installedMetadata']:die('CMS release changed preserved Synology metadata') if rollback: if actual!=before['installedFiles']:die('CMS rollback source mismatch') else: @@ -43422,7 +43463,7 @@ def cms_ci_inventory_preserved(before): return all(current.get(identity)==row for identity,row in before.items()) # DC CMS outbound automatic deployment. All authority stays in this file. -CMS_AUTODEPLOY_ID = 'dc-cms-autodeploy-v1-20261104-001' +CMS_AUTODEPLOY_ID = 'dc-cms-autodeploy-v1-20261104-002' CMS_AUTODEPLOY_ENTRY = 'deployment/dc-cms-autodeploy-v1.json' CMS_AUTODEPLOY_ENTRIES = CMS_CI_V4_ENTRIES CMS_AUTODEPLOY_ROOT = Path('/volume1/docker/nodedc-cms-autodeploy')