Add verified storage tools and experimental daily Core driver
This commit is contained in:
parent
f6f8f41649
commit
0e1d928e86
14 changed files with 640 additions and 4 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -3,3 +3,5 @@ data/
|
|||
keys/
|
||||
*.secret
|
||||
*.log
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
|
|
|||
58
README.md
58
README.md
|
|
@ -26,9 +26,7 @@ storage. The initial empty catalog accurately represents the lack of eligible
|
|||
testing/stable releases. Source-only Material You-inspired styling and original
|
||||
artwork require no remote fonts, scripts or upstream logo redistribution.
|
||||
|
||||
## Remaining pipeline work
|
||||
|
||||
### External ingress
|
||||
## External ingress
|
||||
|
||||
For the known Moscow Docker Caddy ingress sites, run as root:
|
||||
`python3 deploy/integrate-ingress.py /path/to/conf/Caddyfile`.
|
||||
|
|
@ -38,7 +36,59 @@ inside `caddy-caddy-1`, saves a restricted backup and restores on reload failure
|
|||
Host paths: south `/app/caddy/conf/Caddyfile`, north
|
||||
`/home/no1_tx/apps/caddy/conf/Caddyfile`, west `/opt/caddy/conf/Caddyfile`.
|
||||
|
||||
### Build and update pipeline
|
||||
## Native OSTree storage
|
||||
|
||||
`compose.storage.yaml` runs the CLI storage administrator without network,
|
||||
capabilities, signing keys or a Docker socket, with a read-only container root.
|
||||
Build `containers/storage.Dockerfile` and pin its resulting image ID as
|
||||
`STORAGE_IMAGE`; its Debian OSTree is administrative tooling, not the target OS
|
||||
OSTree version. The image retains `/usr/share/archipelago/storage-packages.tsv`.
|
||||
Set `ARCHIPELAGO_BINARY` and `REGISTRY_ROOT` to one public or private storage root:
|
||||
|
||||
```sh
|
||||
docker compose -f compose.storage.yaml run --rm storage registry init /registry/layers
|
||||
docker compose -f compose.storage.yaml run --rm storage registry init /registry/images
|
||||
docker compose -f compose.storage.yaml run --rm storage registry verify /registry/layers
|
||||
```
|
||||
|
||||
These commands initialize/verify native archive repositories and create no releases.
|
||||
Private staging is never mounted into the web container. `tests/storage.sh` exercises
|
||||
native HTTP pull, locking, incompatible paths/modes and corrupted-object rejection
|
||||
in disposable storage. `tests/layer-conformance.py` compares the Rust parser/schema
|
||||
checker to approved fixtures and checks source registry YAMLs.
|
||||
|
||||
## Experimental daily Core
|
||||
|
||||
`pipeline/daily-core.py CONFIG.json` drives a real CLI build and QEMU acceptance.
|
||||
It records exact source-file hashes, Core Git revision, tools image ID, binary/ISO
|
||||
digests and resulting image commit. Failures and overlapping runs are recorded;
|
||||
only successful VM validation advances the private `latest-candidate.json` evidence
|
||||
pointer. This is not a signed release/channel document or an update client.
|
||||
|
||||
The first backend is the existing monolithic `archipelago build iso`, executed in
|
||||
host-managed Arch nspawn. Rust compilation uses a digest-pinned Docker container.
|
||||
It does not claim the future nested-Docker build-worker isolation profile or
|
||||
independently built Layer v1 artifacts. The selected Core YAML must match the reviewed
|
||||
profile digest; unsupported YAML changes fail rather than being ignored.
|
||||
The daily builder requires root on a dedicated build host, nspawn, Docker, QEMU/KVM,
|
||||
OVMF and Python pexpect. Source tree includes all CLI path dependencies and `rfc`.
|
||||
|
||||
Deployment configuration keys: `private_root`, `source_root`, `build_cache`,
|
||||
`cargo_cache`, `package_cache`, `bootstrap`, `tools_image`, `supported_core_sha256`,
|
||||
`ovmf_code`, `ovmf_vars`. Terra's binding is `/opt/archipelago/daily-core.json`.
|
||||
`deploy/daily-core.cron` schedules 03:00 in the host timezone; install only after a
|
||||
manual successful run. Changes to code are deployed into `source_root` explicitly;
|
||||
Core `main` is fetched and pinned per run. A new Git commit alone is not proof of
|
||||
a changed image. Build workspaces are retained for diagnosis; no automatic GC yet.
|
||||
|
||||
Snapshots and bulk mirror copying are **disabled** by D-073. Future capture policy
|
||||
is in `deploy/snapshot-policy.json`, with the approved three-monthly-snapshot cap.
|
||||
The prepared capture tool refuses execution while disabled; it does not run in cron.
|
||||
An enabled capture would still be transport evidence, not signature validation or
|
||||
a sealed Archipelago Snapshot. Retiring snapshots requires reference-aware GC;
|
||||
until implemented the tool stops at the cap instead of destroying retained inputs.
|
||||
|
||||
## Remaining build and update pipeline
|
||||
|
||||
The existing CLI ISO experiment is not yet a YAML-driven, independently built layer
|
||||
pipeline. Required sequence: strict Layer parser and locks → independent layer
|
||||
|
|
|
|||
45
STATUS.md
Normal file
45
STATUS.md
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
# Infrastructure implementation status
|
||||
|
||||
Recorded 2026-11-05. Acceptance of D-071–D-074 is separate from implementation.
|
||||
|
||||
## Verified on terra
|
||||
|
||||
- Public portal and native empty OSTree archive repositories: `layers`, `images`.
|
||||
Public `config` and `summary` return HTTP 200. Private stores are separate and are
|
||||
not mounted by the web container.
|
||||
- Storage CLI `registry init/verify`: idempotence, busy lock, incompatible mode,
|
||||
symlink/nonempty target rejection, actual loopback HTTP OSTree pull and corruption
|
||||
rejection. Evidence: `/opt/archipelago/evidence/storage-acceptance.log`.
|
||||
- Rust Layer parser: strict scalar/key tests; agreement on 28 structural/semantic
|
||||
validation cases with the 35-case reference suite; three registry YAML files.
|
||||
Evidence: `/opt/archipelago/evidence/layer-conformance.log`. Further source/adapter,
|
||||
package resolution, ownership and composition checks remain necessary.
|
||||
- Combined storage/Layer/disabled-capture/daily-driver checks passed using the image
|
||||
below; `/opt/archipelago/evidence/infrastructure-acceptance.log` also records
|
||||
snapshot-cap rejection, overlap handling and preservation of the previous candidate.
|
||||
- Storage tools image:
|
||||
`sha256:a7f09cdadffecf35297700c8f3513479c92d9a6a14cb6c0f95c71fdfb058a814`.
|
||||
Based on pinned Rust 1.90/bookworm; Debian tool installation is not claimed to be
|
||||
reproducible. Container image ID is pinned for execution. This is not target Arch
|
||||
OSTree/toolchain selection.
|
||||
- Source registry `core` commit `4a9eed2` explicitly requires `linux-firmware`.
|
||||
Builder and acceptance harness now request/check it in both target and live roots.
|
||||
|
||||
## In progress
|
||||
|
||||
First full daily-driver run with firmware on terra; retained state/logs under
|
||||
`/opt/archipelago/data/private/daily/`. No successful ISO/VM result is claimed here
|
||||
until that run completes. The cron file is prepared, not installed yet.
|
||||
Driver uses the existing monolithic CLI/nspawn backend, records source and artifact
|
||||
identities and runs the VM harness. It does not implement independent Layer v1
|
||||
build/composition or authenticated installed-host registry updates yet.
|
||||
|
||||
## Deferred
|
||||
|
||||
- Snapshot creation/bulk copying disabled by D-073. Empty `tank/archipelago` and
|
||||
`tank/archipelago/mirror-capture` datasets exist; no mirror data or snapshots were
|
||||
created. Future monthly limit is three; retirement requires reference checks.
|
||||
- Signed release/channel schemas, trust key custody, reproducibility evidence,
|
||||
public release publication and GUI/PackageKit integration remain pending.
|
||||
- `195.46.165.145` is terra's second physical uplink, confirmed by the user. Its
|
||||
unavailability is expected; routing configuration is shared and needs no change.
|
||||
17
compose.storage.yaml
Normal file
17
compose.storage.yaml
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
name: archipelago-storage
|
||||
services:
|
||||
storage:
|
||||
image: ${STORAGE_IMAGE:?Set the verified immutable storage tools image ID}
|
||||
network_mode: none
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
pids_limit: 128
|
||||
mem_limit: 1g
|
||||
cpus: 2
|
||||
tmpfs: [/tmp, /var/tmp]
|
||||
volumes:
|
||||
- ${ARCHIPELAGO_BINARY:?Set the verified CLI binary path}:/usr/local/bin/archipelago:ro
|
||||
- ${REGISTRY_ROOT:?Set one public or private OSTree root}:/registry:rw
|
||||
entrypoint: [archipelago]
|
||||
command: [registry, verify, /registry/layers]
|
||||
10
containers/storage.Dockerfile
Normal file
10
containers/storage.Dockerfile
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
# Administrative storage tooling, not an Arch layer build environment.
|
||||
FROM rust:1.90-bookworm@sha256:3914072ca0c3b8aad871db9169a651ccfce30cf58303e5d6f2db16d1d8a7e58f
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ostree python3 python3-jsonschema python3-yaml \
|
||||
&& mkdir -p /usr/share/archipelago \
|
||||
&& dpkg-query -W > /usr/share/archipelago/storage-packages.tsv \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# Deploy the resulting immutable image ID; this recipe does not claim a
|
||||
# reproducible toolchain build from mutable Debian package repositories.
|
||||
ENV CARGO_TARGET_DIR=/build/target
|
||||
WORKDIR /src
|
||||
161
deploy/capture-mirror.py
Normal file
161
deploy/capture-mirror.py
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Private mirror transport capture; not a sealed Archipelago Snapshot descriptor.
|
||||
|
||||
Does not install packages, trust signatures or publish anything. The retained
|
||||
databases contain upstream signatures for the subsequent Arch verification stage.
|
||||
"""
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
import datetime
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
|
||||
|
||||
def run(*args):
|
||||
return subprocess.check_output(args, text=True).strip()
|
||||
|
||||
|
||||
def inventory(database, repository, source):
|
||||
packages = []
|
||||
with tarfile.open(database, 'r:gz') as archive:
|
||||
for member in archive:
|
||||
if not member.isfile() or not member.name.endswith('/desc'):
|
||||
continue
|
||||
if member.size > 1024 * 1024:
|
||||
raise ValueError('Oversized package record')
|
||||
fields = {}
|
||||
for section in archive.extractfile(member).read().decode().strip().split('\n\n'):
|
||||
lines = section.splitlines()
|
||||
if lines[0] in fields:
|
||||
raise ValueError('Duplicate database field')
|
||||
fields[lines[0]] = lines[1:]
|
||||
def one(key):
|
||||
values = fields['%' + key + '%']
|
||||
if len(values) != 1:
|
||||
raise ValueError('Expected scalar database field: ' + key)
|
||||
return values[0]
|
||||
filename = one('FILENAME')
|
||||
if not re.fullmatch(r'[A-Za-z0-9@_+.:-]+\.pkg\.tar\.(zst|xz|gz)', filename):
|
||||
raise ValueError('Invalid package filename: ' + filename)
|
||||
digest = one('SHA256SUM')
|
||||
if not re.fullmatch('[a-f0-9]{64}', digest):
|
||||
raise ValueError('Invalid package digest')
|
||||
if not one('PGPSIG'):
|
||||
raise ValueError('Missing package signature')
|
||||
package = (source / repository / 'os/x86_64' / filename).resolve(strict=True)
|
||||
if not package.is_relative_to(source.resolve()) or not package.is_file():
|
||||
raise ValueError('Package escapes mirror: ' + filename)
|
||||
size = int(one('CSIZE'))
|
||||
if size <= 0 or package.stat().st_size != size:
|
||||
raise ValueError('Package size mismatch: ' + filename)
|
||||
packages.append({'repository': repository, 'name': one('NAME'),
|
||||
'version': one('VERSION'), 'filename': filename,
|
||||
'size': size, 'sha256': digest, 'source': package})
|
||||
if not packages or len({p['filename'] for p in packages}) != len(packages):
|
||||
raise ValueError('Empty or duplicate package catalog')
|
||||
return packages
|
||||
|
||||
|
||||
@contextmanager
|
||||
def mirror_lock():
|
||||
# The descriptor belongs to the same container/lock inode as /syncrepo.
|
||||
process = subprocess.Popen(['docker', 'exec', '-i', 'arch-syncronizator',
|
||||
'flock', '-w', '600', '/var/lock/syncrepo.lck',
|
||||
'sh', '-c', 'echo locked; cat >/dev/null'],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
|
||||
try:
|
||||
if process.stdout.readline().strip() != 'locked':
|
||||
raise RuntimeError('Could not acquire mirror synchronization lock')
|
||||
yield process
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('Mirror synchronization lock lost')
|
||||
finally:
|
||||
process.stdin.close()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
process.stdout.close()
|
||||
|
||||
|
||||
def capture(policy, month):
|
||||
if not policy.get('capture_enabled', False):
|
||||
raise ValueError('Mirror capture is disabled: experimental builds use the live mirror')
|
||||
dataset = policy['capture_dataset']
|
||||
if dataset != 'tank/archipelago/mirror-capture' or policy['monthly_snapshot_limit'] != 3:
|
||||
raise ValueError('Unsupported capture binding or retention limit')
|
||||
target = Path(run('zfs', 'get', '-H', '-o', 'value', 'mountpoint', dataset))
|
||||
if not target.is_absolute() or not target.is_dir():
|
||||
raise ValueError('Capture dataset must already be mounted')
|
||||
with (target / '.capture.lock').open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
snapshots = run('zfs', 'list', '-H', '-t', 'snapshot', '-o', 'name', '-r', policy['dataset']).splitlines()
|
||||
name = dataset + '@monthly-' + month
|
||||
if name in snapshots:
|
||||
raise ValueError('This month already exists; immutable captures are not replaced')
|
||||
monthly = [s for s in snapshots if '@monthly-' in s]
|
||||
if len(monthly) >= 3:
|
||||
raise ValueError('Three monthly snapshots retained; retire an unreferenced snapshot before capture')
|
||||
if any(target.glob('capture-*')):
|
||||
raise ValueError('Previous live capture remains; inspect it before another capture')
|
||||
source = Path(policy['source_root'])
|
||||
# A failed attempt is retained for inspection; never silently reuse it.
|
||||
work = target / ('capture-' + month)
|
||||
work.mkdir(mode=0o700)
|
||||
with mirror_lock() as guard:
|
||||
packages = []
|
||||
databases = []
|
||||
for repository in policy['repositories']:
|
||||
if repository not in ('core', 'extra'):
|
||||
raise ValueError('Unsupported repository')
|
||||
output = work / repository / 'os/x86_64'
|
||||
output.mkdir(parents=True)
|
||||
database = output / (repository + '.db')
|
||||
shutil.copyfile(source / repository / 'os/x86_64' / (repository + '.db'), database)
|
||||
databases.append({'repository': repository, 'sha256': hashlib.sha256(database.read_bytes()).hexdigest()})
|
||||
packages.extend(inventory(database, repository, source))
|
||||
for package in packages:
|
||||
if guard.poll() is not None:
|
||||
raise RuntimeError('Mirror synchronization lock lost')
|
||||
output = work / package['repository'] / 'os/x86_64' / package['filename']
|
||||
digest = hashlib.sha256()
|
||||
with package['source'].open('rb') as src, output.open('xb') as dst:
|
||||
while data := src.read(1024 * 1024):
|
||||
digest.update(data)
|
||||
dst.write(data)
|
||||
if output.stat().st_size != package['size'] or digest.hexdigest() != package['sha256']:
|
||||
raise ValueError('Package integrity mismatch: ' + package['filename'])
|
||||
del package['source']
|
||||
report = {'status': 'transport-verified-signatures-pending',
|
||||
'month': month, 'databases': databases, 'packages': packages}
|
||||
(work / 'capture-report.json').write_text(json.dumps(report, sort_keys=True, indent=2) + '\n')
|
||||
# ZFS snapshot synchronizes dataset writes. Only complete captures get this name.
|
||||
run('zfs', 'snapshot', name)
|
||||
snapshot_path = target / '.zfs/snapshot' / ('monthly-' + month) / work.name
|
||||
if not (snapshot_path / 'capture-report.json').is_file():
|
||||
raise RuntimeError('Snapshot is not readable; live capture retained')
|
||||
# The immutable snapshot retains this capture. Do not accumulate old live
|
||||
# copies inside subsequent snapshots, which would defeat the retention cap.
|
||||
shutil.rmtree(work)
|
||||
print(json.dumps({'snapshot': name, 'packages': len(packages),
|
||||
'status': report['status'], 'path': str(snapshot_path)}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--policy', type=Path, default=Path(__file__).with_name('snapshot-policy.json'))
|
||||
parser.add_argument('--month', default=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m'))
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r'\d{4}-(0[1-9]|1[0-2])', args.month):
|
||||
parser.error('Month must be YYYY-MM')
|
||||
if os.geteuid() != 0:
|
||||
parser.error('Run on the infrastructure host as root')
|
||||
capture(json.loads(args.policy.read_text()), args.month)
|
||||
3
deploy/daily-core.cron
Normal file
3
deploy/daily-core.cron
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# Install only after verifying the manual run on the selected build host.
|
||||
# 03:00 in the host cron timezone; no snapshot capture or public publication.
|
||||
0 3 * * * root /usr/bin/python3 /opt/archipelago/src/infrastructure/pipeline/daily-core.py /opt/archipelago/daily-core.json >> /opt/archipelago/evidence/daily-cron.log 2>&1
|
||||
10
deploy/snapshot-policy.json
Normal file
10
deploy/snapshot-policy.json
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"capture_enabled": false,
|
||||
"dataset": "tank/archipelago",
|
||||
"capture_dataset": "tank/archipelago/mirror-capture",
|
||||
"source_root": "/opt/mirror/data/archlinux",
|
||||
"repositories": ["core", "extra"],
|
||||
"architecture": "x86_64",
|
||||
"monthly_snapshot_limit": 3,
|
||||
"automatic_destroy": false
|
||||
}
|
||||
132
pipeline/daily-core.py
Normal file
132
pipeline/daily-core.py
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Experimental daily Core driver. Private results; no release/channel publishing.
|
||||
|
||||
The backend remains the tested monolithic CLI ISO experiment. Independent layer
|
||||
composition and installed-host registry updates are subsequent implementation work.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def digest(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def atomic(path, value):
|
||||
with tempfile.NamedTemporaryFile(mode='w', dir=path.parent, delete=False) as stream:
|
||||
json.dump(value, stream, sort_keys=True, indent=2)
|
||||
stream.write('\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(stream.name, path)
|
||||
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
|
||||
|
||||
def main():
|
||||
config = json.loads(Path(sys.argv[1]).read_text())
|
||||
root = Path(config['private_root'])
|
||||
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
now = datetime.now(timezone.utc)
|
||||
attempt = now.strftime('%Y%m%dT%H%M%S.%fZ')
|
||||
lock = (root / 'daily-core.lock').open('a')
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
atomic(root / ('skipped-' + attempt + '.json'), {'state': 'skipped-overlap', 'time': now.isoformat()})
|
||||
return
|
||||
run = root / attempt
|
||||
run.mkdir(mode=0o700)
|
||||
state = {'attempt': attempt, 'started': now.isoformat(), 'state': 'queued', 'public_release': False}
|
||||
def stage(name):
|
||||
state['state'] = name
|
||||
atomic(run / 'run.json', state)
|
||||
def call(args, logfile, timeout=3600, env=None):
|
||||
with (run / logfile).open('ab') as log:
|
||||
process = subprocess.Popen([str(a) for a in args], stdout=log, stderr=subprocess.STDOUT,
|
||||
env=env, start_new_session=True)
|
||||
try:
|
||||
status = process.wait(timeout=timeout)
|
||||
except BaseException:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
raise
|
||||
if status:
|
||||
raise subprocess.CalledProcessError(status, args)
|
||||
try:
|
||||
stage('pinning-sources')
|
||||
source = run / 'source'
|
||||
source.mkdir()
|
||||
for component in ['cli', 'builder', 'contracts', 'composer', 'installer', 'registry', 'system', 'rfc', 'test-lab']:
|
||||
shutil.copytree(Path(config['source_root']) / component, source / component,
|
||||
ignore=shutil.ignore_patterns('.git', 'target', '__pycache__', '*.pyc'))
|
||||
call(['git', 'clone', '--depth=1', 'https://git.fasoley.net/Archipelago/core.git', source / 'core'], 'source.log')
|
||||
state['core_commit'] = subprocess.check_output(['git', '-C', str(source / 'core'), 'rev-parse', 'HEAD'], text=True).strip()
|
||||
# This backend supports only its reviewed Core profile. New YAML content
|
||||
# fails explicitly until the builder is adapted; it is never ignored.
|
||||
manifest = source / 'core/layers/arch.yaml'
|
||||
if digest(manifest) != config['supported_core_sha256']:
|
||||
raise ValueError('Core YAML changed: this experimental backend requires profile review')
|
||||
hashes = {str(p.relative_to(source)): digest(p) for p in sorted(source.rglob('*'))
|
||||
if p.is_file() and '.git' not in p.parts}
|
||||
atomic(run / 'source-files.json', hashes)
|
||||
state['source_identity'] = hashlib.sha256(json.dumps(hashes, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
state['tools_image'] = config['tools_image']
|
||||
stage('compiling-cli')
|
||||
call(['docker', 'run', '--rm', '--network=none', '--cap-drop=ALL', '--security-opt=no-new-privileges',
|
||||
'--mount', f'type=bind,src={source},dst=/src,readonly',
|
||||
'--mount', f'type=bind,src={config["build_cache"]},dst=/build',
|
||||
'--mount', f'type=bind,src={config["cargo_cache"]},dst=/usr/local/cargo/registry,readonly',
|
||||
config['tools_image'], 'cargo', 'build', '--manifest-path', '/src/cli/Cargo.toml', '--offline', '--locked', '--release'], 'compile.log')
|
||||
binary = run / 'archipelago'
|
||||
shutil.copy2(Path(config['build_cache']) / 'target/release/archipelago', binary)
|
||||
state['binary_sha256'] = digest(binary)
|
||||
call([binary, 'layer', 'validate', manifest], 'manifest.log')
|
||||
bootstrap = Path(config['bootstrap'])
|
||||
if digest(bootstrap) != '655bc99849b80859173fa39338a6c910185e952173f6a1a61526cfa34ab8339c':
|
||||
raise ValueError('Bootstrap checksum mismatch')
|
||||
stage('building-iso')
|
||||
env = dict(os.environ, ARCHIPELAGO_PACKAGE_CACHE=config['package_cache'])
|
||||
call([binary, 'build', 'iso', run / 'build', bootstrap], 'build.log', timeout=21600, env=env)
|
||||
iso = run / 'build/output/archipelago-core-latest.iso'
|
||||
state['iso_sha256'] = digest(iso)
|
||||
state['image_commit'] = subprocess.check_output([
|
||||
'docker', 'run', '--rm', '--network=none', '--read-only', '--cap-drop=ALL',
|
||||
'--mount', f'type=bind,src={run / "build/repo"},dst=/repo,readonly',
|
||||
config['tools_image'], 'ostree', '--repo=/repo', 'rev-parse', 'core'], text=True).strip()
|
||||
stage('validating-vm')
|
||||
vms = run / 'vms'
|
||||
vms.mkdir()
|
||||
call(['python3', source / 'test-lab/probes/core_iso_acceptance.py', '--iso', iso,
|
||||
'--workdir', vms, '--extensions-sequence', '--firmware',
|
||||
'--ovmf-code', config['ovmf_code'], '--ovmf-vars', config['ovmf_vars']], 'acceptance.log', timeout=10800)
|
||||
stage('candidate-ready')
|
||||
# Local evidence pointer only, not an authenticated release/channel manifest.
|
||||
atomic(root / 'latest-candidate.json', state | {'directory': str(run), 'iso': str(iso)})
|
||||
except BaseException as error:
|
||||
state['error'] = str(error)
|
||||
stage('failed')
|
||||
raise
|
||||
finally:
|
||||
lock.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
34
tests/daily-driver.py
Normal file
34
tests/daily-driver.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
"""Failure and overlap must preserve the last successful candidate pointer."""
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
spec = importlib.util.spec_from_file_location('daily', Path(__file__).parents[1] / 'pipeline/daily-core.py')
|
||||
daily = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(daily)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
private = root / 'private'
|
||||
private.mkdir()
|
||||
pointer = private / 'latest-candidate.json'
|
||||
pointer.write_text('{"previous":true}\n')
|
||||
config = root / 'config.json'
|
||||
config.write_text(json.dumps({'private_root': str(private), 'source_root': str(root / 'absent')}))
|
||||
sys.argv = ['daily-core.py', str(config)]
|
||||
try:
|
||||
daily.main()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Missing inputs accepted')
|
||||
states = list(private.glob('*/run.json'))
|
||||
assert len(states) == 1 and json.loads(states[0].read_text())['state'] == 'failed'
|
||||
with (private / 'daily-core.lock').open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
daily.main()
|
||||
assert len(list(private.glob('skipped-*.json'))) == 1
|
||||
assert pointer.read_text() == '{"previous":true}\n'
|
||||
print('PASS: durable failure, overlap record, prior candidate preservation')
|
||||
42
tests/layer-conformance.py
Normal file
42
tests/layer-conformance.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"""Run the approved reference fixtures against the Rust CLI too."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
source = Path('/src/rfc/schemas/check-fixtures.py')
|
||||
namespace = {'__file__': str(source), '__name__': 'fixture_reference'}
|
||||
text = source.read_text()
|
||||
# Load reference functions before its fixtures execute, then wrap validate.
|
||||
prefix, fixtures = text.split('base = parse(', 1)
|
||||
exec(compile(prefix, str(source), 'exec'), namespace)
|
||||
reference = namespace['validate']
|
||||
binary = os.environ.get('ARCHIPELAGO_BINARY', '/build/target/release/archipelago')
|
||||
count = 0
|
||||
|
||||
|
||||
def validate(data):
|
||||
global count
|
||||
try:
|
||||
result = reference(data)
|
||||
expected = True
|
||||
except (ValueError, namespace['jsonschema'].ValidationError) as error:
|
||||
result = error
|
||||
expected = False
|
||||
with tempfile.NamedTemporaryFile(mode='w', suffix='.json') as stream:
|
||||
json.dump(data, stream)
|
||||
stream.flush()
|
||||
cli = subprocess.run([binary, 'layer', 'validate', stream.name], capture_output=True, text=True)
|
||||
assert (cli.returncode == 0) == expected, cli.stderr
|
||||
count += 1
|
||||
if not expected:
|
||||
raise result
|
||||
return result
|
||||
|
||||
|
||||
namespace['validate'] = validate
|
||||
exec(compile('base = parse(' + fixtures, str(source), 'exec'), namespace)
|
||||
for path in [Path('/src/core/layers/arch.yaml'), *Path('/src/purposes/proposals').glob('*.yaml')]:
|
||||
subprocess.run([binary, 'layer', 'validate', str(path)], check=True)
|
||||
print(f'PASS: Rust/reference agreement on {count} validation fixtures and three registry YAMLs')
|
||||
68
tests/snapshot.py
Normal file
68
tests/snapshot.py
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
"""Negative transport-capture checks without touching ZFS or the real mirror."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tarfile
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
spec = importlib.util.spec_from_file_location('capture', Path(__file__).parents[1] / 'deploy/capture-mirror.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
policy = json.loads((Path(__file__).parents[1] / 'deploy/snapshot-policy.json').read_text())
|
||||
|
||||
|
||||
def reject(call):
|
||||
try:
|
||||
call()
|
||||
except (ValueError, FileNotFoundError):
|
||||
return
|
||||
raise AssertionError('Invalid capture accepted')
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
with patch.object(module, 'run') as run:
|
||||
reject(lambda: module.capture(policy, '2026-11'))
|
||||
run.assert_not_called()
|
||||
policy['capture_enabled'] = True
|
||||
root = Path(directory)
|
||||
source = root / 'mirror'
|
||||
package_dir = source / 'core/os/x86_64'
|
||||
package_dir.mkdir(parents=True)
|
||||
payload = b'fixture package bytes'
|
||||
filename = 'fixture-1-1-x86_64.pkg.tar.zst'
|
||||
package = package_dir / filename
|
||||
package.write_bytes(payload)
|
||||
database = root / 'core.db'
|
||||
|
||||
def db(name=filename, size=len(payload), signature='fixture-untrusted-signature'):
|
||||
record = {'FILENAME': name, 'CSIZE': str(size), 'SHA256SUM': hashlib.sha256(payload).hexdigest(),
|
||||
'PGPSIG': signature, 'NAME': 'fixture', 'VERSION': '1-1'}
|
||||
text = ''.join(f'%{k}%\n{v}\n\n' for k, v in record.items()).encode()
|
||||
with tarfile.open(database, 'w:gz') as archive:
|
||||
info = tarfile.TarInfo('fixture-1-1/desc')
|
||||
info.size = len(text)
|
||||
archive.addfile(info, io.BytesIO(text))
|
||||
|
||||
db()
|
||||
assert len(module.inventory(database, 'core', source)) == 1
|
||||
db(name='../outside.pkg.tar.zst')
|
||||
reject(lambda: module.inventory(database, 'core', source))
|
||||
db(size=len(payload) + 1)
|
||||
reject(lambda: module.inventory(database, 'core', source))
|
||||
db()
|
||||
package.unlink()
|
||||
outside = root / filename
|
||||
outside.write_bytes(payload)
|
||||
package.symlink_to(outside)
|
||||
reject(lambda: module.inventory(database, 'core', source))
|
||||
target = root / 'capture'
|
||||
target.mkdir()
|
||||
snapshots = '\n'.join(policy['capture_dataset'] + '@monthly-2026-' + month for month in ('08', '09', '10'))
|
||||
with patch.object(module, 'run', side_effect=[str(target), snapshots]) as run:
|
||||
reject(lambda: module.capture(policy, '2026-11'))
|
||||
assert run.call_count == 2
|
||||
assert not (target / 'capture-2026-11').exists()
|
||||
print('PASS: database inventory, traversal, size, symlink escape, three-snapshot cap')
|
||||
27
tests/storage-http.py
Normal file
27
tests/storage-http.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
"""Native OSTree pull from a disposable loopback HTTP repository."""
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
||||
source, target, commit = sys.argv[1:]
|
||||
server = ThreadingHTTPServer(('127.0.0.1', 0), partial(SimpleHTTPRequestHandler, directory=source))
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
command = ['ostree', '--repo=' + target]
|
||||
subprocess.run(command + ['init', '--mode=archive'], check=True)
|
||||
# Explicit unsigned fixture only; this is not a production update client.
|
||||
subprocess.run(command + ['remote', 'add', '--no-gpg-verify', 'fixture',
|
||||
f'http://127.0.0.1:{server.server_port}/'], check=True)
|
||||
subprocess.run(command + ['pull', 'fixture', commit], check=True)
|
||||
subprocess.run(command + ['fsck'], check=True)
|
||||
checkout = target + '-checkout'
|
||||
subprocess.run(command + ['checkout', '--user-mode', commit, checkout], check=True)
|
||||
assert (Path(checkout) / 'marker').read_text() == 'native OSTree transport fixture\n'
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
server.server_close()
|
||||
35
tests/storage.sh
Normal file
35
tests/storage.sh
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
#!/bin/bash
|
||||
# Runs in the disposable storage tools container; never uses public storage.
|
||||
set -euo pipefail
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
cli=${ARCHIPELAGO_BINARY:-/build/target/release/archipelago}
|
||||
"$cli" registry init "$work/registry/layers"
|
||||
"$cli" registry init "$work/registry/images"
|
||||
"$cli" registry init "$work/registry/layers"
|
||||
"$cli" registry verify "$work/registry/layers"
|
||||
mkdir "$work/unrelated"
|
||||
echo keep > "$work/unrelated/file"
|
||||
if "$cli" registry init "$work/unrelated"; then exit 1; fi
|
||||
test "$(cat "$work/unrelated/file")" = keep
|
||||
ostree --repo="$work/bare" init --mode=bare-user
|
||||
if "$cli" registry init "$work/bare"; then exit 1; fi
|
||||
ln -s "$work/registry/layers" "$work/link"
|
||||
if "$cli" registry init "$work/link"; then exit 1; fi
|
||||
flock "$work/registry/.layers.archipelago.lock" bash -c 'if "$1" registry init "$2"; then exit 1; fi' _ "$cli" "$work/registry/layers"
|
||||
|
||||
# Native HTTP round-trip in an isolated network namespace. Test objects stay here.
|
||||
mkdir "$work/tree"
|
||||
echo 'native OSTree transport fixture' > "$work/tree/marker"
|
||||
commit=$(ostree --repo="$work/registry/layers" commit -b fixture --tree="dir=$work/tree")
|
||||
ostree --repo="$work/registry/layers" summary --update
|
||||
"$cli" registry verify "$work/registry/layers"
|
||||
python3 /src/infrastructure/tests/storage-http.py "$work/registry/layers" "$work/consumer" "$commit"
|
||||
|
||||
# Corrupting an object must fail verification without deleting it or changing refs.
|
||||
object="$work/registry/layers/objects/${commit:0:2}/${commit:2}.commit"
|
||||
printf corrupt > "$object"
|
||||
if "$cli" registry verify "$work/registry/layers"; then exit 1; fi
|
||||
test "$(ostree --repo="$work/registry/layers" rev-parse fixture)" = "$commit"
|
||||
test -f "$object"
|
||||
echo 'PASS: init, retry, mode/path/lock rejection, HTTP pull, corrupt-object rejection'
|
||||
Loading…
Add table
Reference in a new issue