Files
Pulse/scripts/tests/test_container_packaging.py
pulse-triage[bot] 5be27bffba Stage all root-sourced mirrored docs in Docker frontend builds
PR #5420 (b250914857) updated frontend-modern/scripts/sync-public-docs.mjs
to sync every mirrored markdown file under frontend-modern/public/docs/
during npm run build, including all four ROOT_SOURCED_DOCS (SECURITY.md,
TERMS.md, ARCHITECTURE.md, CONTRIBUTING.md). Both .dockerignore and the
frontend-builder stages in Dockerfile and
deploy/provider-msp/Dockerfile.control-plane still staged only SECURITY.md
and TERMS.md, breaking Core E2E image builds (main runs 46184827492 and
46185958697, PR #5439 job 141102369291) and source Docker builds with
ENOENT on /app/ARCHITECTURE.md.

- .dockerignore: allow ARCHITECTURE.md and CONTRIBUTING.md alongside
  SECURITY.md and TERMS.md.
- Dockerfile and deploy/provider-msp/Dockerfile.control-plane: copy
  ARCHITECTURE.md and CONTRIBUTING.md into /app/ in frontend-builder
  before npm run build, preserving the existing COPY SECURITY.md TERMS.md
  /app/ line checked by installtests.
- scripts/tests/test_container_packaging.py: add a regression test
  verifying .dockerignore and both frontend-builder Dockerfiles stage
  every root-sourced doc from scripts/check_docs_mirror.py and executing
  frontend-modern/scripts/sync-public-docs.mjs inside the resulting
  simulated container layout (with a missing-file negative control).

Contract-Neutral: Build-context and Dockerfile staging repair restoring container builds after #5420; no public interface or subsystem contract change.
Change-source: pulse-maintainer
2026-11-28 20:27:29 +00:00

413 lines
22 KiB
Python

#!/usr/bin/env python3
"""Packaging's normal smoke-suite controls; no Docker daemon is used here."""
import base64
import contextlib
import gzip
import hashlib
import importlib.util
import io
import json
import os
import shutil
import subprocess
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('packaging', ROOT/'scripts/test-container-packaging.py')
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
def archive(files):
stream = io.BytesIO()
with tarfile.open(fileobj=stream, mode='w') as tar:
for name, data, kind in files:
member = tarfile.TarInfo(name)
member.uid = member.gid = 1000
member.mode = 0o755
if kind == 'file':
member.size = len(data)
tar.addfile(member, io.BytesIO(data))
else:
member.type = tarfile.SYMTYPE
member.linkname = data
tar.addfile(member)
return stream.getvalue()
class InventoryTests(unittest.TestCase):
def test_bytes_metadata_and_links_are_retained_without_extraction(self):
blob = archive([('app/pulse', b'actual-server', 'file'),
('opt/pulse/bin/agent', b'agent', 'file'),
('usr/local/bin/pulse-agent', '/opt/pulse/bin/agent', 'link'),
('etc/hostname', b'ephemeral', 'file')])
result = packaging.inventory(io.BytesIO(blob))
self.assertEqual(set(result), {'app/pulse', 'opt/pulse/bin/agent', 'usr/local/bin/pulse-agent'})
self.assertEqual(result['app/pulse']['sha256'], hashlib.sha256(b'actual-server').hexdigest())
self.assertEqual(result['app/pulse']['uid'], 1000)
self.assertEqual(result['app/pulse']['mode'], 0o755)
self.assertEqual(result['usr/local/bin/pulse-agent']['link'], '/opt/pulse/bin/agent')
def test_duplicate_exported_paths_are_not_silently_overwritten(self):
with self.assertRaisesRegex(ValueError, 'duplicate exported path'):
packaging.inventory(io.BytesIO(archive([('app/pulse', b'a', 'file')]*2)))
def test_layer_inventory_counts_repeated_payload_and_explicit_reencoding(self):
layer = archive([('app/pulse', b'server', 'file'), ('opt/pulse/bin/agent', b'agent', 'file')])
image = archive([('one/layer.tar', layer, 'file'), ('two/layer.tar', layer, 'file'),
('manifest.json', json.dumps([{'Layers':['one/layer.tar','two/layer.tar']}]).encode(), 'file')])
measured = packaging.layers(io.BytesIO(image))
self.assertEqual(len(measured), 2)
self.assertEqual(sum(l['uncompressed_tar_bytes'] for l in measured), len(layer)*2)
self.assertTrue(all(0 < l['reencoded_gzip_bytes'] < len(layer) for l in measured))
packaging.no_payload_copyups(measured[:1])
with self.assertRaisesRegex(ValueError, 'more than one layer'):
packaging.no_payload_copyups(measured)
def test_absent_layer_or_payload_cannot_pass(self):
with self.assertRaisesRegex(ValueError, 'manifest'):
packaging.layers(io.BytesIO(archive([])))
with self.assertRaisesRegex(ValueError, 'payload missing'):
packaging.no_payload_copyups([])
def test_containerd_blob_paths_and_gzip_measure_uncompressed_bytes(self):
layer = archive([('app/pulse', b'server', 'file'), ('opt/pulse/bin/agent', b'agent', 'file')])
blob = gzip.compress(layer)
path = 'blobs/sha256/'+hashlib.sha256(blob).hexdigest()
image = archive([(path, blob, 'file'), ('unreferenced/layer.tar', layer, 'file'),
('manifest.json', json.dumps([{'Layers':[path]}]).encode(), 'file')])
measured = packaging.layers(io.BytesIO(image))
self.assertEqual(len(measured), 1)
self.assertEqual(measured[0]['archive_blob_bytes'], len(blob))
self.assertEqual(measured[0]['uncompressed_tar_bytes'], len(layer))
packaging.no_payload_copyups(measured)
def test_manifest_identity_missing_duplicate_and_multiimage_fail_closed(self):
for manifest in [[{'Layers':['missing']}], [{'Layers':['same','same']}],
[{'Layers':[]}], [{'Layers':['a']},{'Layers':['b']}], {}]:
with self.subTest(manifest=manifest), self.assertRaises(ValueError):
packaging.layers(io.BytesIO(archive([('manifest.json', json.dumps(manifest).encode(), 'file')])))
def test_every_compatibility_dimension_is_checked(self):
baseline = packaging.inventory(io.BytesIO(archive([('app/pulse', b'server', 'file')])))
for key, value in [('sha256', 'different'), ('mode', 0o644), ('uid', 0),
('gid', 0), ('link', 'wrong'), ('size', 0), ('type', '2')]:
with self.subTest(key=key), self.assertRaisesRegex(ValueError, 'changed final payload'):
changed = json.loads(json.dumps(baseline))
changed['app/pulse'][key] = value
packaging.compare(baseline, changed)
with self.assertRaises(ValueError):
packaging.compare(baseline, {})
def test_process_failure_cannot_become_a_successful_inventory(self):
with self.assertRaises(subprocess.CalledProcessError):
packaging.stream_command(['sh', '-c', 'printf partial; exit 19'], lambda f: f.read())
class DownloadConsumerTests(unittest.TestCase):
def test_actual_consumer_checks_every_body_and_both_sidecars(self):
# Execute the exact in-container consumer, substituting only its file
# root and HTTP transport. This is not a real-image/startup result.
for fault in ['', 'body', 'checksum', 'ed25519', 'sshsig', 'sidecar-mode']:
with self.subTest(fault=fault), tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
linux = ['linux-'+a for a in ['amd64','arm64','armv7','armv6','386']]
files = {}
for family, arches in [('pulse-agent', linux+['darwin-amd64','darwin-arm64',
'freebsd-amd64','freebsd-arm64','windows-amd64','windows-arm64','windows-386']),
('pulse-agent-helper', linux), ('pulse-agent-runner', linux)]:
for arch in arches:
name = family+'-'+arch+('.exe' if arch.startswith('windows-') else '')
files['/download/'+family+'?arch='+arch] = root/'bin'/name
for name in ['install.sh','install.ps1']:
files['/'+name] = root/'scripts'/name
for path in files.values():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(path.name.encode())
path.chmod(0o755)
for suffix in ['.sig','.sshsig']:
sidecar = Path(str(path)+suffix)
sidecar.write_bytes(('signature-'+path.name+suffix).encode())
sidecar.chmod(0o755 if fault == 'sidecar-mode' else 0o644)
called = []
def fetch(url, timeout):
route = url.removeprefix('http://127.0.0.1:7655')
path = files[route]
called.append(route)
response = io.BytesIO(path.read_bytes() if fault != 'body' else b'wrong')
response.headers = {
'X-Checksum-Sha256': hashlib.sha256(path.read_bytes()).hexdigest() if fault != 'checksum' else 'wrong',
'X-Signature-Ed25519': Path(str(path)+'.sig').read_text() if fault != 'ed25519' else 'wrong',
'X-Signature-SSHSIG': base64.b64encode(Path(str(path)+'.sshsig').read_bytes()).decode() if fault != 'sshsig' else 'd3Jvbmc=',
}
return response
code = packaging.DOWNLOAD_CHECK.replace("'/opt/pulse'", repr(str(root)))
capture = io.StringIO()
with patch('urllib.request.urlopen', side_effect=fetch), contextlib.redirect_stdout(capture):
if fault:
with self.assertRaises(AssertionError):
exec(compile(code, '<packaging-download-consumer>', 'exec'), {})
else:
exec(compile(code, '<packaging-download-consumer>', 'exec'), {})
self.assertEqual(set(called), set(files))
self.assertEqual(len(called), 24)
self.assertEqual(len(json.loads(capture.getvalue())), 24)
class DockerfileTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dockerfile = (ROOT/'Dockerfile').read_text()
text = cls.dockerfile.replace('\\\n', '')
cls.stages = {}
cls.parents = {}
current = None
for line in text.splitlines():
if line.startswith('FROM '):
source, current = line.split(' AS ')
cls.parents[current] = source.split()[-1]
cls.stages[current] = []
elif current and line.strip() and not line.startswith('#'):
cls.stages[current].append(line)
def test_final_server_copies_assign_metadata_before_any_runtime_layer(self):
for stage in ['pulse-runtime-base', 'prebuilt-runtime-base', 'e2e_runtime']:
commands = self.stages[stage]
pulse = next(c for c in commands if c.startswith('COPY ') and c.endswith(' ./pulse'))
self.assertIn('--chown=pulse:pulse', pulse)
self.assertIn('--chmod=0755', pulse)
self.assertFalse(any(c.startswith('RUN ') for c in commands))
def run_server_recipe(self, stage, *, target, tags, failing_arch=''):
# Execute the Dockerfile's shared shell recipe and actual stage
# arguments. Only the compiler and empty secret-mount paths are
# doubled; no host secrets or Docker daemon are read.
start = "COPY <<'PULSE_BUILD_SERVER' /usr/local/bin/pulse-build-server\n"
recipe = self.dockerfile.split(start, 1)[1].split('\nPULSE_BUILD_SERVER\n', 1)[0]
call = next(line.split('sh /usr/local/bin/pulse-build-server', 1)[1]
for line in self.stages[stage] if 'sh /usr/local/bin/pulse-build-server' in line)
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
script = root/'compile.sh'
script.write_text(recipe.replace('/run/secrets/', str(root/'empty')+'/'))
(root/'scripts').mkdir()
(root/'scripts'/'release_ldflags.sh').symlink_to(ROOT/'scripts'/'release_ldflags.sh')
(root/'VERSION').write_text('1.2.3\n')
compiler = root/'go'
compiler.write_text(
"#!/bin/sh\n"
"printf '<%s>' \"$GOOS/$GOARCH/$CGO_ENABLED\" \"$@\"\n"
"printf '\\n'\n"
"if [ \"$GOARCH\" = \"$FAIL_ARCH\" ]; then exit 19; fi\n"
)
compiler.chmod(0o755)
result = subprocess.run(
['sh', '-c', 'sh "$1"'+call, 'stage', str(script)], cwd=root,
env={'PATH': str(root)+os.pathsep+os.defpath, 'TARGETARCH': target,
'GO_BUILD_TAGS': tags, 'FAIL_ARCH': failing_arch},
text=True, capture_output=True, check=False,
)
return result
def test_e2e_compiles_only_the_architecture_its_image_consumes(self):
self.assertEqual(self.parents['backend-e2e-server'], 'backend-builder')
self.assertEqual(self.parents['e2e_runtime'], 'pulse-runtime-foundation')
for stage in ['backend-e2e-server', 'e2e_runtime']:
self.assertIn('ARG TARGETARCH', self.stages[stage])
self.assertIn('COPY --from=backend-e2e-server --chown=pulse:pulse --chmod=0755 '
'/app/pulse-linux-${TARGETARCH:-amd64} ./pulse', self.stages['e2e_runtime'])
for arch in ('amd64', 'arm64'):
with self.subTest(arch=arch):
result = self.run_server_recipe('backend-e2e-server', target=arch, tags='')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(len(result.stdout.splitlines()), 1)
self.assertIn(f'<linux/{arch}/0><build><-tags><>', result.stdout)
self.assertIn(f'<-buildvcs=false><-trimpath><-o><pulse-linux-{arch}><./cmd/pulse>', result.stdout)
def test_regular_runtime_still_compiles_and_consumes_both_downloads(self):
self.assertEqual(self.parents['runtime'], 'pulse-runtime-base')
self.assertEqual(self.parents['hosted_runtime'], 'pulse-runtime-base')
self.assertIn('COPY --from=backend-server-pair /app/VERSION ./VERSION',
self.stages['release-assets-builder'])
result = self.run_server_recipe('backend-server-pair', target='arm64', tags='release')
self.assertEqual(result.returncode, 0, result.stderr)
for arch, command in zip(('amd64', 'arm64'), result.stdout.splitlines(), strict=True):
self.assertIn(f'<linux/{arch}/0><build><-tags><release>', command)
self.assertIn(f'<-buildvcs=false><-trimpath><-o><pulse-linux-{arch}><./cmd/pulse>', command)
self.assertIn(f'COPY --chown=pulse:pulse --from=backend-server-pair '
f'/app/pulse-linux-{arch} /opt/pulse/bin/pulse-linux-{arch}', self.stages['runtime'])
self.assertIn('COPY --from=backend-server-pair --chown=pulse:pulse --chmod=0755 '
'/app/pulse-linux-${TARGETARCH:-amd64} ./pulse', self.stages['pulse-runtime-base'])
def test_e2e_compile_failure_is_not_retried_or_hidden(self):
result = self.run_server_recipe('backend-e2e-server', target='arm64', tags='', failing_arch='arm64')
self.assertEqual(result.returncode, 19, result.stderr)
self.assertEqual(len(result.stdout.splitlines()), 1)
self.assertIn('<linux/arm64/0><build>', result.stdout)
def test_all_source_payload_copies_have_final_ownership_not_recursive_copyup(self):
commands = self.stages['runtime']
for copy in (c for c in commands if c.startswith('COPY ')):
self.assertIn('--chown=pulse:pulse', copy)
if copy.endswith(('.sh', '.ps1')):
self.assertIn('--chmod=0755', copy)
text = '\n'.join(commands)
self.assertNotIn('chown -R', text)
self.assertIn('-type l -exec chown -h pulse:pulse {} +', text)
def test_final_candidate_copy_is_single_owned_payload_and_links_only(self):
commands = self.stages['runtime_prebuilt']
copies = [c for c in commands if c.startswith('COPY ')]
self.assertEqual(copies, ['COPY --from=prebuilt-downloads --chown=pulse:pulse /payload/ /opt/pulse/'])
text = '\n'.join(commands)
self.assertNotIn('chmod', text)
self.assertNotIn('chown -R', text)
self.assertIn('-type l -exec chown -h pulse:pulse {} +', text)
for arch in ['amd64', 'arm64', '386']:
for suffix in ['', '.sig', '.sshsig']:
self.assertIn(f'pulse-agent-windows-{arch}.exe{suffix}', text)
def test_actual_staging_recipe_preserves_every_byte_and_nonexecutable_sidecar(self):
recipe = next(c[4:] for c in self.stages['prebuilt-downloads'] if c.startswith('RUN '))
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)/'payload'
(root/'bin').mkdir(parents=True)
(root/'scripts').mkdir()
files = {}
for family, arches in [('pulse-agent', ['linux-amd64', 'linux-arm64', 'linux-armv7',
'linux-armv6', 'linux-386', 'darwin-amd64', 'darwin-arm64', 'windows-amd64.exe',
'windows-arm64.exe', 'windows-386.exe', 'freebsd-amd64', 'freebsd-arm64']),
('pulse-agent-helper', ['linux-'+a for a in ['amd64','arm64','armv7','armv6','386']]),
('pulse-agent-runner', ['linux-'+a for a in ['amd64','arm64','armv7','armv6','386']])]:
for arch in arches:
for suffix in ['', '.sig', '.sshsig']:
files[root/'bin'/f'{family}-{arch}{suffix}'] = suffix == ''
for arch in ['amd64', 'arm64']:
files[root/'bin'/f'pulse-linux-{arch}'] = True
for script in ['install.sh','install.ps1','install-container-agent.sh','install-docker.sh']:
files[root/'scripts'/script] = True
if script in ['install.sh','install.ps1']:
for suffix in ['.sig','.sshsig']:
files[root/'scripts'/(script+suffix)] = False
for path, executable in files.items():
path.write_bytes(path.name.encode())
path.chmod(0o755 if path.name.startswith('pulse-linux-') else 0o644)
before = {p: p.read_bytes() for p in files}
subprocess.run(['sh', '-ec', recipe.replace('/payload', str(root))], check=True)
for path, executable in files.items():
with self.subTest(path=path.name):
self.assertEqual(path.read_bytes(), before[path])
self.assertEqual(path.stat().st_mode & 0o777, 0o755 if executable else 0o644)
def test_frontend_builder_stages_every_mirrored_doc_source(self):
# Verify .dockerignore and every frontend-building Dockerfile stage all
# mirrored doc sources that sync-public-docs.mjs reads during npm run build.
mirror_spec = importlib.util.spec_from_file_location(
'check_docs_mirror', ROOT/'scripts/check_docs_mirror.py'
)
check_docs_mirror = importlib.util.module_from_spec(mirror_spec)
mirror_spec.loader.exec_module(check_docs_mirror)
expected_root_docs = set(check_docs_mirror.ROOT_SOURCED_DOCS)
self.assertTrue(expected_root_docs)
ignore_lines = [
line.strip()
for line in (ROOT/'.dockerignore').read_text().splitlines()
if line.strip() and not line.strip().startswith('#')
]
self.assertIn('*.md', ignore_lines)
md_idx = ignore_lines.index('*.md')
allowed_root_md = {
line[1:]
for line in ignore_lines[md_idx + 1:]
if line.startswith('!') and '/' not in line[1:] and line.endswith('.md')
}
self.assertTrue(
expected_root_docs.issubset(allowed_root_md),
f'.dockerignore missing root-sourced doc allowlist entries: '
f'{sorted(expected_root_docs - allowed_root_md)}',
)
self.assertIn('!docs/', ignore_lines)
self.assertIn('!docs/**', ignore_lines)
for df_path in (ROOT/'Dockerfile', ROOT/'deploy/provider-msp/Dockerfile.control-plane'):
with self.subTest(dockerfile=df_path.relative_to(ROOT).as_posix()):
text = df_path.read_text().replace('\\\n', '')
stage_lines = []
in_frontend = False
for raw in text.splitlines():
line = raw.strip()
if line.startswith('FROM '):
in_frontend = line.endswith(' AS frontend-builder')
continue
if not in_frontend or not line or line.startswith('#'):
continue
if line.startswith('RUN ') and 'npm run build' in line:
break
stage_lines.append(line)
copied_docs_dir = False
copied_root_md = set()
for line in stage_lines:
if not line.startswith('COPY '):
continue
args = [p for p in line.split()[1:] if not p.startswith('--')]
if len(args) < 2:
continue
srcs, dst = args[:-1], args[-1]
if dst == '/app/docs/' and 'docs/' in srcs:
copied_docs_dir = True
if dst == '/app/':
for src in srcs:
if src.endswith('.md') and '/' not in src:
copied_root_md.add(src)
self.assertTrue(copied_docs_dir, f'{df_path.name} frontend-builder must COPY docs/ /app/docs/')
self.assertTrue(
expected_root_docs.issubset(copied_root_md),
f'{df_path.name} frontend-builder missing COPY to /app/ for: '
f'{sorted(expected_root_docs - copied_root_md)}',
)
with tempfile.TemporaryDirectory() as tmp:
app = Path(tmp)/'app'
fm = app/'frontend-modern'
(fm/'scripts').mkdir(parents=True)
shutil.copy2(
ROOT/'frontend-modern/scripts/sync-public-docs.mjs',
fm/'scripts/sync-public-docs.mjs',
)
shutil.copytree(ROOT/'frontend-modern/public/docs', fm/'public/docs')
shutil.copytree(ROOT/'docs', app/'docs')
for doc in sorted(copied_root_md & allowed_root_md):
shutil.copy2(ROOT/doc, app/doc)
ok = subprocess.run(
['node', str(fm/'scripts/sync-public-docs.mjs')],
cwd=fm,
text=True,
capture_output=True,
check=False,
)
self.assertEqual(ok.returncode, 0, ok.stderr or ok.stdout)
self.assertIn('(0 updated,', ok.stdout)
(app/'ARCHITECTURE.md').unlink()
missing = subprocess.run(
['node', str(fm/'scripts/sync-public-docs.mjs')],
cwd=fm,
text=True,
capture_output=True,
check=False,
)
self.assertNotEqual(missing.returncode, 0)
self.assertIn('ARCHITECTURE.md', missing.stderr + missing.stdout)
if __name__ == '__main__':
unittest.main()