diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index a7490f9..c3fa7a5 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -2962,6 +2962,10 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple( ) COMPONENTS = { + "device-core-autodeploy": { + "payload_root": Path("/volume1/docker/nodedc-device-autodeploy"), + "bootstrap_root": True, "artifact_only": True, "services": (), + }, "device-core-release-drift-audit": { "payload_root": DEVICE_PLANE_ROOT, "artifact_only": True, @@ -4975,6 +4979,10 @@ def denied_payload_path(component, rel): def allowed_payload_path(component, rel): validate_posix_path(rel) + if component == "device-core-autodeploy": + if rel in ("deployment", DEVICE_AUTODEPLOY_ENTRY): + return True + die("Device Core autodeploy accepts only its bootstrap descriptor") if component == "device-core-release-drift-audit": if rel in ("deployment", DEVICE_RELEASE_DRIFT_AUDIT_ENTRY): return True @@ -11599,6 +11607,8 @@ def load_artifact(artifact, work_dir): die(f"files.txt entry missing in payload: {rel}") validate_payload_tree(manifest["component"], payload_dir, entries) + if manifest["component"] == "device-core-autodeploy": + validate_device_autodeploy_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-core-release-drift-audit": validate_device_release_drift_audit_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-core-release-reconciliation": @@ -22453,6 +22463,10 @@ def is_platform_provider_catalog_only(entries): def component_services(component, entries=None): + if component == "device-core-autodeploy": + if tuple(entries or ()) != (DEVICE_AUTODEPLOY_ENTRY,): + die("Device Core autodeploy requires the exact descriptor entry") + return () if component == "device-core-release-drift-audit": if tuple(entries or ()) != (DEVICE_RELEASE_DRIFT_AUDIT_ENTRY,): die("Device Core drift audit requires the exact descriptor entry") @@ -32971,7 +32985,7 @@ def rollback_device_release(root, backup_dir, entries, current_stamp, before, ru for service in DEVICE_RELEASE_SERVICES: subprocess.run([str(DOCKER), "image", "tag", before["runtime"][service]["imageId"], "nodedc/" + service + ":local"], check=True) if runtime_started: - run_compose("device-core-release", DEVICE_RELEASE_SERVICES, entries) + run_device_release_compose(DEVICE_RELEASE_SERVICES, entries) run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES) accept_device_release(before, rollback=True) @@ -33028,6 +33042,12 @@ def plan_artifact(artifact): gitea_salvage_preflight = None with tempfile.TemporaryDirectory(prefix="plan-", dir=TMP_DIR) as tmp: manifest, entries, payload_dir = load_artifact(artifact, Path(tmp)) + if manifest["component"] == "device-core-autodeploy": + auto_before = preflight_device_autodeploy(payload_dir, entries, manifest["id"]) + print("device_autodeploy_scheduler=native-systemd;binary=" + auto_before["systemctl"]) + print("device_autodeploy_transport=outbound-https;ports=none;interval-after-completion=30s;first-run=8") + print("device_autodeploy_token=read-repository;private-root0600;queue=durable;installer=canonical-runner") + print("device_autodeploy_preserved=all-existing-applications,databases,volumes,ports;rollback=new-units-and-descriptor-only") if manifest["component"] == "device-core-release-drift-audit": device_release_drift_audit(payload_dir, entries, manifest["id"]) return @@ -37218,8 +37238,6 @@ def run_compose(component, services, entries=None): or touches_engine_credential_provisioner(component, entries) or (component == "engine" and ENGINE_CREDENTIAL_BACKEND_ACTIVATION_FILE.exists())): cmd.extend(["--pull", "never"]) - if component == "device-core-release": - cmd.extend(["--pull", "never", "--no-build"]) if COMPONENTS[component].get("compose_build"): cmd.append("--build") if component_compose_no_deps(component, entries): @@ -37253,6 +37271,19 @@ def run_compose(component, services, entries=None): ) +def run_device_release_compose(services, entries): + if tuple(services or ()) != DEVICE_RELEASE_SERVICES or tuple(entries or ()) != DEVICE_RELEASE_ENTRIES: + die("Device Core release Compose requires exact services and entries") + base = compose_base_cmd("device-core-release") + cmd = [*base, "up", "-d", "--force-recreate", "--pull", "never", "--no-build", "--no-deps", *services] + try: + subprocess.run(cmd, cwd=str(DEVICE_PLANE_ROOT), check=True) + except subprocess.CalledProcessError: + subprocess.run([*base, "logs", "--no-color", "--tail=180", *services], cwd=str(DEVICE_PLANE_ROOT), check=False) + raise + subprocess.run([*base, "ps"], cwd=str(DEVICE_PLANE_ROOT), check=True) + + def run_gitea_fresh_install_compose(services, entries): if ( tuple(services) != (GITEA_SERVICE,) @@ -40324,6 +40355,7 @@ def apply_artifact(artifact): gitea_ci_before = None device_release_before = None gitea_actions_before = None + device_autodeploy_before = None current_stamp = stamp() with DeployLock(): @@ -40378,6 +40410,8 @@ def apply_artifact(artifact): preflight_device_release_reconciliation(payload_dir, entries, patch_id) if component == "device-core-release": device_release_before = preflight_device_release(payload_dir, entries, patch_id) + if component == "device-core-autodeploy": + device_autodeploy_before = preflight_device_autodeploy(payload_dir, entries, patch_id) artifact_only = component_artifact_only(component) defer_bootstrap_root = is_gitea_bootstrap_slice( component, @@ -40903,6 +40937,10 @@ def apply_artifact(artifact): include_nginx_html = component == "engine" and component_publish_dist(component, entries) create_backup(root, backup_dir, entries, include_nginx_html) + if component == "device-core-autodeploy": + proof = backup_dir / "autodeploy-before.json" + proof.write_text(json.dumps(device_autodeploy_before, sort_keys=True) + "\n", encoding="utf-8") + proof.chmod(0o600) if component == "device-core-release": proof = backup_dir / "device-release-before.json" proof.write_text(json.dumps(device_release_before, sort_keys=True) + "\n", encoding="utf-8") @@ -40997,7 +41035,10 @@ def apply_artifact(artifact): elif component == "device-core-release": run_build(component, entries) runtime_started = True - run_compose(component, services, entries) + run_device_release_compose(services, entries) + elif component == "device-core-autodeploy": + runtime_started = True + apply_device_autodeploy(device_autodeploy_before) elif component == "gitea-actions-config": runtime_started = True apply_gitea_actions(gitea_actions_before, backup_dir) @@ -41037,6 +41078,8 @@ def apply_artifact(artifact): ): die("Engine L2 closed-loop app generation was not recreated") run_healthchecks(component, entries, services) + if component == "device-core-autodeploy": + accept_device_autodeploy(device_autodeploy_before) if component == "device-core-release": accept_device_release(device_release_before) if component == "gitea-ci": @@ -41113,7 +41156,13 @@ def apply_artifact(artifact): and backup_dir is not None and root is not None ): - if component == "device-core-release-reconciliation": + if component == "device-core-autodeploy": + try: + rollback_device_autodeploy(root, backup_dir, entries, current_stamp, device_autodeploy_before) + rollback_status = "ok:device-core-autodeploy-bootstrap" + except Exception as rollback_exc: + rollback_status = "failed:" + type(rollback_exc).__name__ + elif component == "device-core-release-reconciliation": try: restore_platform_overlay(root, backup_dir, entries, current_stamp) if any((root / entry).exists() or (root / entry).is_symlink() for entry in entries): @@ -41482,7 +41531,911 @@ def apply_artifact(artifact): raise +# Device Core outbound automatic deployment. All authority stays in this file. +DEVICE_AUTODEPLOY_ID = 'device-core-autodeploy-v1-20260929-001' +DEVICE_AUTODEPLOY_ENTRY = 'deployment/device-core-autodeploy-v1.json' +DEVICE_AUTODEPLOY_ROOT = Path('/volume1/docker/nodedc-device-autodeploy') +DEVICE_AUTODEPLOY_PRIVATE = Path('/var/lib/nodedc-device-autodeploy') +DEVICE_AUTODEPLOY_PENDING = RUNTIME_DIR / 'device-core-autodeploy' / 'enrollment.pending.json' +DEVICE_AUTODEPLOY_UNIT_DIR = Path('/usr/local/lib/systemd/system') +DEVICE_AUTODEPLOY_SERVICE = 'nodedc-device-autodeploy.service' +DEVICE_AUTODEPLOY_TIMER = 'nodedc-device-autodeploy.timer' +DEVICE_AUTODEPLOY_BASELINE = 'edf69068ec64e3d105d5324d39b8eaeface21215' +DEVICE_AUTODEPLOY_BASELINE_DIGEST = '7510c7d12e209415970556321a005675d0af61c59497da4226df8ed353184917' +DEVICE_AUTODEPLOY_DESCRIPTOR = { + 'schemaVersion': 'nodedc.device-core.autodeploy.v1', 'releaseId': DEVICE_AUTODEPLOY_ID, + 'repository': 'SILVER/NODEDC_DEVICE_CORE', 'repositoryId': 38, 'branch': 'main', + 'workflow': 'ci.yml@refs/heads/main', 'firstRunNumber': 8, + 'baselineSourceCommit': DEVICE_AUTODEPLOY_BASELINE, + 'baselineArtifactSha256': DEVICE_AUTODEPLOY_BASELINE_DIGEST, + 'transport': 'outbound-https', 'publishedPorts': [], 'scheduler': 'native-systemd-timer', + 'intervalAfterCompletionSeconds': 30, 'installer': '/usr/local/sbin/nodedc-deploy', + 'releaseComponent': 'device-core-release', 'services': ['device-control-core', 'device-manager'], +} + + +def device_autodeploy_units(): + return { + DEVICE_AUTODEPLOY_SERVICE: ( + '[Unit]\nDescription=NODE.DC Device Core canonical deployment controller\n' + 'After=network-online.target\nWants=network-online.target\n\n' + '[Service]\nType=oneshot\nUser=root\nGroup=root\nUMask=0077\n' + 'Environment=PATH=/usr/local/bin:/usr/bin:/bin\n' + 'ExecStart=/usr/bin/python3 /usr/local/sbin/nodedc-deploy --device-core-autodeploy-tick\n' + 'TimeoutStartSec=0\nTimeoutStopSec=300\nNice=10\n' + 'StandardOutput=journal\nStandardError=journal\n'), + DEVICE_AUTODEPLOY_TIMER: ( + '[Unit]\nDescription=Poll qualified Device Core releases without inbound ports\n\n' + '[Timer]\nOnBootSec=120s\nOnUnitInactiveSec=30s\nAccuracySec=1s\n' + 'Unit=nodedc-device-autodeploy.service\n\n[Install]\nWantedBy=timers.target\n'), + } + + +def validate_device_autodeploy_payload(payload, entries, identity): + if tuple(entries or ()) != (DEVICE_AUTODEPLOY_ENTRY,) or identity != DEVICE_AUTODEPLOY_ID: + die('Device Core autodeploy requires its exact bootstrap descriptor') + try: + # Canonical byte representation prevents duplicate-key ambiguity. + data = (payload / DEVICE_AUTODEPLOY_ENTRY).read_bytes() + expected = (json.dumps(DEVICE_AUTODEPLOY_DESCRIPTOR, indent=2, sort_keys=True) + '\n').encode() + if data != expected: + die('Device Core autodeploy descriptor differs from the registered contract') + except (OSError, ValueError): + die('Device Core autodeploy descriptor is unreadable') + return DEVICE_AUTODEPLOY_DESCRIPTOR + + +def device_autodeploy_root_path(path, directory=False): + """No runtime executable/state authority through a writable ancestor.""" + for candidate in [path] + list(path.parents): + info = candidate.lstat() + if (stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022 + or (candidate != path and not stat.S_ISDIR(info.st_mode))): + die('Device Core autodeploy root path metadata rejected: ' + str(candidate)) + info = path.lstat() + if not (stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode)): + die('Device Core autodeploy root path type rejected: ' + str(path)) + return info + + +def device_autodeploy_systemctl(): + if Path('/proc/1/comm').read_text().strip() != 'systemd' or not Path('/run/systemd/system').is_dir(): + die('Device Core autodeploy requires the native systemd manager') + device_autodeploy_root_path(DEVICE_AUTODEPLOY_UNIT_DIR, directory=True) + python = Path('/usr/bin/python3').resolve(strict=True) + device_autodeploy_root_path(python) + candidates = [] + for name in ('/bin/systemctl', '/usr/bin/systemctl'): + p = Path(name) + if p.exists(): + resolved = p.resolve(strict=True) + device_autodeploy_root_path(resolved) + if not os.access(str(resolved), os.X_OK): + die('Device Core autodeploy systemctl is not executable') + if resolved not in candidates: + candidates.append(resolved) + if len(candidates) != 1: + die('Device Core autodeploy native systemctl identity is ambiguous or missing') + return candidates[0] + + +def device_autodeploy_ctl(*args, check=True): + return subprocess.run([str(device_autodeploy_systemctl()), *args], text=True, + capture_output=True, check=check, timeout=35) + + +def device_autodeploy_read_token(private=False): + path = DEVICE_AUTODEPLOY_PRIVATE / 'gitea-read-token' if private else DEVICE_AUTODEPLOY_PENDING + for parent in path.parents: + if parent.is_symlink(): + die('Device Core autodeploy enrollment has a symlink ancestor') + allowed = (0,) if private else (0, pwd.getpwnam('dctouch').pw_uid) + fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, 'rb') as stream: + info = os.fstat(stream.fileno()) + if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid not in allowed + or not 1 <= info.st_size <= 1024 or (private and stat.S_IMODE(info.st_mode) != 0o600)): + die('Device Core autodeploy enrollment metadata rejected') + data = stream.read(1025) + after = os.fstat(stream.fileno()) + if (info.st_size, info.st_mtime_ns, info.st_ctime_ns) != (after.st_size, after.st_mtime_ns, after.st_ctime_ns): + die('Device Core autodeploy enrollment changed while reading') + try: + if private: + token = data.decode('ascii').strip() + else: + value = json.loads(data) + if set(value) != {'repository', 'token'} or value['repository'] != 'SILVER/NODEDC_DEVICE_CORE': + raise ValueError() + token = value['token'] + if not isinstance(token, str) or not re.fullmatch('[a-f0-9]{40}', token): + raise ValueError() + except (ValueError, UnicodeError, TypeError): + die('Device Core autodeploy enrollment format rejected') + if private: + device_autodeploy_root_path(DEVICE_AUTODEPLOY_PRIVATE, directory=True) + if stat.S_IMODE(DEVICE_AUTODEPLOY_PRIVATE.stat().st_mode) != 0o700: + die('Device Core autodeploy private directory mode must be 0700') + return token, info + + +def device_autodeploy_enrollment(): + pending = DEVICE_AUTODEPLOY_PENDING.exists() or DEVICE_AUTODEPLOY_PENDING.is_symlink() + token, _ = device_autodeploy_read_token(private=not pending) + if pending and (DEVICE_AUTODEPLOY_PRIVATE / 'gitea-read-token').exists(): + if token != device_autodeploy_read_token(private=True)[0]: + die('Device Core autodeploy enrollment conflicts with its private identity') + return token + + +def device_autodeploy_import_token(): + token = device_autodeploy_enrollment() + pending = DEVICE_AUTODEPLOY_PENDING.exists() + source_token, info = device_autodeploy_read_token(private=not pending) + if source_token != token: + die('Device Core autodeploy enrollment changed before import') + if DEVICE_AUTODEPLOY_PRIVATE.exists(): + device_autodeploy_root_path(DEVICE_AUTODEPLOY_PRIVATE, directory=True) + else: + device_autodeploy_root_path(DEVICE_AUTODEPLOY_PRIVATE.parent, directory=True) + DEVICE_AUTODEPLOY_PRIVATE.mkdir(mode=0o700) + target = DEVICE_AUTODEPLOY_PRIVATE / 'gitea-read-token' + if not target.exists(): + atomic_write_root_file(target, (token + '\n').encode()) + if device_autodeploy_read_token(private=True)[0] != token: + die('Device Core autodeploy private enrollment verification failed') + if pending: + current = DEVICE_AUTODEPLOY_PENDING.lstat() + if (current.st_dev,current.st_ino,current.st_size,current.st_mtime_ns) != (info.st_dev,info.st_ino,info.st_size,info.st_mtime_ns): + die('Device Core autodeploy enrollment staging changed') + DEVICE_AUTODEPLOY_PENDING.unlink() + fsync_directory(DEVICE_AUTODEPLOY_PENDING.parent) + + +def device_autodeploy_installed_source(): + rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-core-release'] + if not rows: + die('Device Core autodeploy has no installed normal release') + row = rows[-1] + with tempfile.TemporaryDirectory(prefix='autodeploy-baseline-', dir=TMP_DIR) as tmp: + manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp)) + d = validate_device_release_payload(payload, entries, row['id']) + if manifest['component'] != 'device-core-release' or manifest['id'] != row['id']: + die('Device Core autodeploy installed receipt mismatch') + if collect_exact_files(DEVICE_PLANE_ROOT, entries, 'installed source') != collect_exact_files(payload, entries, 'applied source'): + die('Device Core autodeploy installed source drift') + return d['sourceCommit'] + + +def preflight_device_autodeploy(payload, entries, identity): + require_root() + validate_device_autodeploy_payload(payload, entries, identity) + ctl = device_autodeploy_systemctl() + if device_autodeploy_installed_source() != DEVICE_AUTODEPLOY_BASELINE: + die('Device Core autodeploy bootstrap requires the accepted r7 baseline') + rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-core-release'] + if rows[-1].get('sha256') != DEVICE_AUTODEPLOY_BASELINE_DIGEST: + die('Device Core autodeploy r7 receipt digest mismatch') + if any(r.get('component') == 'device-core-autodeploy' for r in load_state(STATE_FILE)): + die('Device Core autodeploy bootstrap is already terminal applied') + for name in device_autodeploy_units(): + if (DEVICE_AUTODEPLOY_UNIT_DIR / name).exists() or (DEVICE_AUTODEPLOY_UNIT_DIR / name).is_symlink(): + die('Device Core autodeploy unit already exists') + result = device_autodeploy_ctl('show', name, '--property=LoadState', check=False) + if result.stdout.strip() != 'LoadState=not-found': + die('Device Core autodeploy unit name is already managed') + _, Source, _, _ = device_autodeploy_library() + source = Source(device_autodeploy_enrollment()) + source.discover() + source.successful_run({'id':7,'number':7,'sha':DEVICE_AUTODEPLOY_BASELINE,'attempt':1}) + run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES) + return {'systemctl':str(ctl), 'inventory':gitea_ci_inventory(), 'baseline':DEVICE_AUTODEPLOY_BASELINE} + + +def apply_device_autodeploy(before): + device_autodeploy_import_token() + for name, content in device_autodeploy_units().items(): + path = DEVICE_AUTODEPLOY_UNIT_DIR / name + fd, temporary = tempfile.mkstemp(prefix='.' + name + '.', dir=str(DEVICE_AUTODEPLOY_UNIT_DIR)) + try: + with os.fdopen(fd, 'w') as stream: + os.fchmod(stream.fileno(), 0o644) + stream.write(content);stream.flush();os.fsync(stream.fileno()) + os.link(temporary, str(path)) + finally: + os.unlink(temporary) + fsync_directory(DEVICE_AUTODEPLOY_UNIT_DIR) + device_autodeploy_ctl('daemon-reload') + device_autodeploy_ctl('enable', DEVICE_AUTODEPLOY_TIMER) + device_autodeploy_ctl('start', DEVICE_AUTODEPLOY_TIMER) + # The timer may fire immediately if boot was more than two minutes ago. + # Its worker refuses deployment until the canonical bootstrap receipt exists. + accept_device_autodeploy(before) + + +def accept_device_autodeploy(before): + for name, content in device_autodeploy_units().items(): + path = DEVICE_AUTODEPLOY_UNIT_DIR / name + device_autodeploy_root_path(path) + if path.read_text() != content: + die('Device Core autodeploy installed unit differs') + result = device_autodeploy_ctl('show', name, '--property=FragmentPath') + if result.stdout.strip() != 'FragmentPath=' + str(path): + die('Device Core autodeploy effective unit origin mismatch') + if device_autodeploy_ctl('show', name, '--property=DropInPaths').stdout.strip() != 'DropInPaths=': + die('Device Core autodeploy unit has an undeclared drop-in') + if device_autodeploy_ctl('is-enabled', DEVICE_AUTODEPLOY_TIMER).stdout.strip() != 'enabled': + die('Device Core autodeploy timer is not enabled') + if device_autodeploy_ctl('is-active', DEVICE_AUTODEPLOY_TIMER).stdout.strip() != 'active': + die('Device Core autodeploy timer is not active') + device_autodeploy_read_token(private=True) + if gitea_ci_inventory() != before['inventory'] or device_autodeploy_installed_source() != before['baseline']: + die('Device Core autodeploy bootstrap changed existing applications') + print('device_autodeploy_accept=outbound-timer;ports=none;baseline=r7;first-run=8;deploy-authority=canonical-runner') + + +def rollback_device_autodeploy(root, backup_dir, entries, current_stamp, before): + # This domain owns only two previously absent units and the descriptor. + device_autodeploy_ctl('stop', DEVICE_AUTODEPLOY_TIMER, check=False) + device_autodeploy_ctl('stop', DEVICE_AUTODEPLOY_SERVICE, check=False) + device_autodeploy_ctl('disable', DEVICE_AUTODEPLOY_TIMER, check=False) + for name, content in device_autodeploy_units().items(): + path = DEVICE_AUTODEPLOY_UNIT_DIR / name + if path.exists(): + device_autodeploy_root_path(path) + if path.read_text() != content: + die('Device Core autodeploy rollback unit ownership mismatch') + path.unlink() + device_autodeploy_ctl('daemon-reload') + restore_platform_overlay(root, backup_dir, entries, current_stamp) + for name in device_autodeploy_units(): + if (DEVICE_AUTODEPLOY_UNIT_DIR / name).exists(): + die('Device Core autodeploy rollback retained a unit') + if gitea_ci_inventory() != before['inventory']: + die('Device Core autodeploy rollback application preservation failed') + # Credentials/queue are deliberately retained, never erased by rollback. + + +def device_autodeploy_activated(): + rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-core-autodeploy'] + if not rows: + return False + if len(rows) != 1 or rows[0].get('id') != DEVICE_AUTODEPLOY_ID or rows[0].get('status') != 'ok': + die('Device Core autodeploy activation receipt mismatch') + row = rows[0] + with tempfile.TemporaryDirectory(prefix='autodeploy-activation-', dir=TMP_DIR) as tmp: + manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp)) + if manifest['component'] != 'device-core-autodeploy': + die('Device Core autodeploy activation component mismatch') + validate_device_autodeploy_payload(payload, entries, row['id']) + if (DEVICE_AUTODEPLOY_ROOT / DEVICE_AUTODEPLOY_ENTRY).read_bytes() != (payload / DEVICE_AUTODEPLOY_ENTRY).read_bytes(): + die('Device Core autodeploy activation descriptor drift') + return True + + +class DeviceAutodeployInstaller: + def installed_source(self): + return device_autodeploy_installed_source() + + def stage(self, row, receipt, data): + expected = 'nodedc-device-core-release-v1-r' + str(row['id']) + '-' + row['sha'] + '.tgz' + if receipt['artifact'] != expected or hashlib.sha256(data).hexdigest() != receipt['sha256']: + die('Device Core autodeploy staging identity mismatch') + identity = expected[len('nodedc-'):-4] + if any(r.get('id') == identity for r in load_state(STATE_FILE) + load_state(FAILED_STATE_FILE)): + die('Device Core autodeploy artifact already has a terminal journal record') + with tempfile.TemporaryDirectory(prefix='autodeploy-stage-', dir=TMP_DIR) as tmp: + candidate = Path(tmp) / expected;candidate.write_bytes(data) + unpack = Path(tmp) / 'unpack';unpack.mkdir() + manifest, entries, payload = load_artifact(candidate, unpack) + if manifest['component'] != 'device-core-release' or manifest['id'] != identity or tuple(entries) != DEVICE_RELEASE_ENTRIES: + die('Device Core autodeploy canonical component scope mismatch') + d = validate_device_release_payload(payload, entries, identity) + if (d['runId'],d['runNumber'],d['sourceCommit']) != (row['id'],row['number'],row['sha']): + die('Device Core autodeploy payload run mismatch') + target = INBOX / expected + if target.exists() or target.is_symlink(): + info = target.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or sha256_file(target) != receipt['sha256']: + die('Device Core autodeploy inbox conflict') + else: + # Link a complete, fsynced file into the inbox without overwrite. + candidate.chmod(0o600) + with candidate.open('rb') as stream:os.fsync(stream.fileno()) + os.link(str(candidate),str(target));candidate.unlink();fsync_directory(INBOX) + + def plan(self, artifact): + plan_artifact(INBOX / artifact) + + def apply(self, artifact): + apply_artifact(INBOX / artifact) + + def receipt(self, row): + identity = row['artifact'][len('nodedc-'):-4] + applied = [r for r in load_state(STATE_FILE) if r.get('id') == identity] + failed = [r for r in load_state(FAILED_STATE_FILE) if r.get('id') == identity] + if len(applied) + len(failed) != 1: + return 'ambiguous', 'canonical-receipt-missing-or-conflicting' + record = (applied or failed)[0] + if record.get('component') != 'device-core-release' or record.get('sha256') != row['digest']: + return 'ambiguous', 'canonical-receipt-identity-mismatch' + archive = (APPLIED_DIR if applied else FAILED_DIR) / str(record.get('artifact','')) + backup = BACKUPS_DIR / str(record.get('backup_id','')) + if (archive.parent not in (APPLIED_DIR,FAILED_DIR) or archive.is_symlink() or not archive.is_file() + or sha256_file(archive) != row['digest'] or backup.parent != BACKUPS_DIR + or backup.is_symlink() or not backup.is_dir()): + return 'ambiguous', 'canonical-archive-or-backup-mismatch' + if applied and record.get('status') == 'ok': + outcome = 'deployed' + elif failed and record.get('rollback_status') == 'ok:device-core-release': + outcome = 'rolled-back' + else: + return 'ambiguous', 'canonical-rollback-unconfirmed' + return outcome, 'canonical:' + str(record['backup_id']) + + +def device_autodeploy_publish_status(result): + # Public projection contains no credentials, API bodies or raw exceptions. + # It is an observation aid; only canonical journals authorize deployment. + result = dict(result, updatedAt=utc_now()) + data = (json.dumps(result, sort_keys=True) + '\n').encode() + atomic_write_root_file(DEVICE_AUTODEPLOY_PRIVATE / 'status.json', data) + if DEVICE_AUTODEPLOY_ROOT.is_symlink() or not DEVICE_AUTODEPLOY_ROOT.is_dir(): + die('Device Core autodeploy status destination is not its descriptor root') + fd, temporary = tempfile.mkstemp(prefix='.status-', dir=str(DEVICE_AUTODEPLOY_ROOT)) + try: + with os.fdopen(fd, 'wb') as stream: + os.fchmod(stream.fileno(), 0o644);stream.write(data);stream.flush();os.fsync(stream.fileno()) + os.replace(temporary, str(DEVICE_AUTODEPLOY_ROOT / 'runtime-status.json')) + fsync_directory(DEVICE_AUTODEPLOY_ROOT) + finally: + if os.path.exists(temporary):os.unlink(temporary) + print('device_autodeploy_tick=' + json.dumps(result, sort_keys=True)) + + +def device_autodeploy_tick(): + require_root() + ensure_layout() + if not device_autodeploy_activated(): + return 0 + device_autodeploy_root_path(DEVICE_AUTODEPLOY_PRIVATE,directory=True) + os.umask(0o077) + lock_path = DEVICE_AUTODEPLOY_PRIVATE / 'controller.lock' + fd = os.open(str(lock_path), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) + try: + try: + fcntl.flock(fd,fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return 0 + if LOCK_DIR.exists(): + device_autodeploy_publish_status({'status':'waiting','reason':'canonical-deploy-lock'}) + return 0 # Another canonical installation owns the runtime. + Queue, Source, Controller, errors = device_autodeploy_library() + token = device_autodeploy_read_token(private=True)[0] + queue_path = DEVICE_AUTODEPLOY_PRIVATE / 'queue.sqlite3' + for path in (queue_path,Path(str(queue_path)+'-wal'),Path(str(queue_path)+'-shm')): + if path.exists() or path.is_symlink(): + device_autodeploy_root_path(path) + queue = Queue(queue_path,first_run_number=8) + try: + result = Controller(queue,Source(token),DeviceAutodeployInstaller()).tick() + except Exception as error: + result = {'status':'attention','errorType':type(error).__name__} + # Policy errors contain only fixed codes/IDs; other exception text + # can originate in external tools and is never copied to status. + if isinstance(error,errors):result['reason']=str(error)[:200] + finally: + queue.close() + device_autodeploy_publish_status(result) + return 0 if result['status'] != 'attention' else 1 + finally: + os.close(fd) + + +# BEGIN GENERATED DEVICE CORE AUTODEPLOY LIBRARY +def device_autodeploy_library(): + # Source: infra/device-core-deploy/deployment_queue.py + """Durable release ordering. Pure state policy; no network or runtime authority. + + The canonical installer remains the only production executor. A controller may + reserve a verified artifact here, then must reconcile its canonical receipt + after any crash before admitting another deployment. + """ + import re + import sqlite3 + + + REPOSITORY = "SILVER/NODEDC_DEVICE_CORE" + REPOSITORY_ID = 38 + WORKFLOW = "ci.yml@refs/heads/main" + TERMINAL = {"deployed", "failed", "superseded", "blocked"} + SHA = re.compile(r"[0-9a-f]{40}") + DIGEST = re.compile(r"[0-9a-f]{64}") + + + class QueueError(ValueError): + pass + + + def positive(value): + return type(value) is int and 0 < value < 2**53 + + + def normalize_run(run): + if not isinstance(run, dict): + raise QueueError("invalid_run") + if not all(positive(run.get(key)) for key in ("id", "run_number", "run_attempt")): + raise QueueError("invalid_run_identity") + if not isinstance(run.get("head_sha"), str) or not SHA.fullmatch(run["head_sha"]): + raise QueueError("invalid_source_sha") + status = run.get("status") + if status not in ("queued", "waiting", "in_progress", "completed"): + raise QueueError("unknown_run_status") + conclusion = run.get("conclusion") + if status == "completed" and conclusion not in ( + "success", "failure", "cancelled", "skipped", "timed_out", "action_required", "neutral", "stale", + ): + raise QueueError("unknown_run_conclusion") + relevant = (run.get("event") == "push" and run.get("head_branch") == "main" + and run.get("path") == WORKFLOW) + phase = "pending" if status != "completed" else "ready" if conclusion == "success" else "unqualified" + if not relevant: + phase = "ignored" + return (run["id"], run["run_number"], run["head_sha"], str(run.get("event", "")), + str(run.get("head_branch", "")), str(run.get("path", "")), run["run_attempt"], phase) + + + class DeploymentQueue: + def __init__(self, path, *, first_run_number): + if not positive(first_run_number): + raise QueueError("invalid_activation_floor") + self.db = sqlite3.connect(str(path), timeout=10, isolation_level=None) + self.db.row_factory = sqlite3.Row + self.db.execute("PRAGMA journal_mode=WAL") + self.db.execute("PRAGMA synchronous=FULL") + self.db.executescript(""" + CREATE TABLE IF NOT EXISTS policy ( + id INTEGER PRIMARY KEY CHECK(id=1), + repository TEXT NOT NULL, repository_id INTEGER NOT NULL, + first_run INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS runs ( + id INTEGER PRIMARY KEY, number INTEGER NOT NULL UNIQUE, + sha TEXT NOT NULL, event TEXT NOT NULL, branch TEXT NOT NULL, + workflow TEXT NOT NULL, attempt INTEGER NOT NULL, phase TEXT NOT NULL, + artifact TEXT, digest TEXT, receipt TEXT + ); + CREATE INDEX IF NOT EXISTS runs_phase_number ON runs(phase,number); + CREATE INDEX IF NOT EXISTS runs_sha_phase ON runs(sha,phase); + """) + self.db.execute("INSERT OR IGNORE INTO policy VALUES(1,?,?,?)", (REPOSITORY, REPOSITORY_ID, first_run_number)) + policy = self.db.execute("SELECT * FROM policy WHERE id=1").fetchone() + if (policy["repository"], policy["repository_id"], policy["first_run"]) != (REPOSITORY, REPOSITORY_ID, first_run_number): + self.db.close() + raise QueueError("queue_policy_changed") + self.first_run = first_run_number + + def close(self): + self.db.close() + + def transaction(self, operation): + self.db.execute("BEGIN IMMEDIATE") + try: + value = operation() + self.db.execute("COMMIT") + return value + except BaseException: + self.db.execute("ROLLBACK") + raise + + def observe(self, runs, *, repository, repository_id): + if repository != REPOSITORY or type(repository_id) is not int or repository_id != REPOSITORY_ID: + raise QueueError("repository_identity_mismatch") + values = [normalize_run(run) for run in runs] + + def apply(): + for value in values: + identity, number, sha, event, branch, workflow, attempt, phase = value + if number < self.first_run: + continue + existing = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone() + if existing is None: + self.db.execute("INSERT INTO runs(id,number,sha,event,branch,workflow,attempt,phase) VALUES(?,?,?,?,?,?,?,?)", value) + continue + if tuple(existing[k] for k in ("number", "sha", "event", "branch", "workflow")) != (number, sha, event, branch, workflow): + raise QueueError("run_identity_changed") + if attempt < existing["attempt"]: + continue # A stale API page cannot rewind a rerun. + if existing["phase"] in TERMINAL or existing["phase"] == "deploying": + continue + if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase == "pending": + continue + if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase != existing["phase"]: + raise QueueError("terminal_run_outcome_changed") + self.db.execute("UPDATE runs SET phase=?,attempt=? WHERE id=?", (phase, attempt, identity)) + self.transaction(apply) + + def _next(self): + blocked = self.db.execute("SELECT id,phase FROM runs WHERE phase IN ('deploying','blocked') ORDER BY number LIMIT 1").fetchone() + if blocked: + raise QueueError("canonical_reconciliation_required:" + str(blocked["id"])) + while True: + row = self.db.execute("SELECT * FROM runs WHERE phase IN ('pending','ready') ORDER BY number LIMIT 1").fetchone() + if row is None or row["phase"] != "ready": + return None + newer = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND number>=? LIMIT 1", (row["number"],)).fetchone() + duplicate = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND sha=? LIMIT 1", (row["sha"],)).fetchone() + if newer or duplicate: + self.db.execute("UPDATE runs SET phase='superseded' WHERE id=?", (row["id"],)) + continue + return dict(row) + + def next_ready(self): + return self.transaction(self._next) + + def reserve(self, identity, *, digest, artifact): + if not isinstance(digest, str) or not DIGEST.fullmatch(digest): + raise QueueError("invalid_artifact_digest") + + def apply(): + row = self._next() + if row is None or row["id"] != identity: + raise QueueError("deployment_order_mismatch") + expected = "nodedc-device-core-release-v1-r" + str(identity) + "-" + row["sha"] + ".tgz" + if artifact != expected: + raise QueueError("artifact_identity_mismatch") + self.db.execute("UPDATE runs SET phase='deploying',digest=?,artifact=? WHERE id=?", (digest, artifact, identity)) + return {**row, "phase": "deploying", "digest": digest, "artifact": artifact} + return self.transaction(apply) + + def reconcile(self, identity, *, digest, artifact, outcome, receipt): + """Caller must prove the canonical applied/failed journal and archive. + + No receipt or uncertain/failed rollback => blocked, never automatic retry. + A clean rollback may be followed by a new release, never this artifact. + """ + if outcome not in ("deployed", "rolled-back", "ambiguous"): + raise QueueError("invalid_canonical_outcome") + if not isinstance(receipt, str) or not receipt or len(receipt) > 240: + raise QueueError("canonical_receipt_required") + phase = {"deployed": "deployed", "rolled-back": "failed", "ambiguous": "blocked"}[outcome] + + def apply(): + row = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone() + if row is None or (row["digest"], row["artifact"]) != (digest, artifact): + raise QueueError("canonical_artifact_mismatch") + if row["phase"] == phase and row["receipt"] == receipt: + return + if row["phase"] != "deploying": + raise QueueError("canonical_outcome_conflict") + self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity)) + self.transaction(apply) + + def snapshot(self): + return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")] + + # Source: infra/device-core-deploy/gitea_source.py + """Read-only, bounded Gitea source verification. No production execution authority. + + The privileged installer must independently validate the returned TGZ with its + canonical loader and reconcile its own journal. Nothing here accepts commands, + paths, origins, or credentials from a workflow artifact. + """ + import hashlib + import io + import json + import re + import stat + import urllib.error + import urllib.parse + import urllib.request + import zipfile + + + + ORIGIN = "https://git.dcserve.ru" + PREFIX = "/api/v1/repos/" + REPOSITORY + PAGE_SIZE = 50 + MAX_PAGES = 200 + MAX_JSON = 8 * 1024 * 1024 + MAX_ARCHIVE = 64 * 1024 * 1024 + + + class SourceError(ValueError): + pass + + + def require(condition, code): + if not condition: + raise SourceError(code) + + + def strict_json(data): + def unique(pairs): + result = {} + for key, value in pairs: + require(key not in result, "duplicate_json_key") + result[key] = value + return result + try: + return json.loads(data, object_pairs_hook=unique) + except (UnicodeError, ValueError): + raise SourceError("invalid_json") from None + + + def signed_artifact_redirect(original, target): + origin, dest = urllib.parse.urlsplit(original), urllib.parse.urlsplit(target) + if (origin.scheme + "://" + origin.netloc != ORIGIN + or dest.scheme + "://" + dest.netloc != ORIGIN or origin.query or dest.fragment + or not re.fullmatch(re.escape(PREFIX) + r"/actions/artifacts/[1-9][0-9]*/zip", origin.path) + or dest.path != origin.path + "/raw"): + return False + pairs = urllib.parse.parse_qsl(dest.query, keep_blank_values=True) + params = dict(pairs) + return (len(pairs) == 2 and set(params) == {"sig", "expires"} + and re.fullmatch(r"[A-Za-z0-9_-]{32,128}", params["sig"]) is not None + and re.fullmatch(r"[0-9]{10,13}", params["expires"]) is not None) + + + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + # Gitea 1.27 signs a same-origin /zip/raw URL. Only this exact route is + # allowed and the persistent token is deliberately NOT forwarded. + if (req is not None and req.get_method() == "GET" and code in (302, 303) + and signed_artifact_redirect(req.full_url, newurl)): + return urllib.request.Request(newurl, headers={"Accept": "application/octet-stream"}) + raise SourceError("api_redirect_refused") + + + class GiteaSource: + def __init__(self, token): + require(isinstance(token, str) and re.fullmatch(r"[0-9a-f]{40}", token), "invalid_read_token") + self._token = token + self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + + def request(self, suffix, *, archive=False): + require(isinstance(suffix, str) and (suffix == "" or suffix.startswith("/")), "invalid_api_path") + require(not any(value in suffix for value in ("..", "\\", "#", "@", "\r", "\n", "%")), "invalid_api_path") + # Only methods below construct suffixes; this additional allowlist keeps + # even accidental future callers from reading other API resources. + require(re.fullmatch( + r"(?:|/branches/main|/git/commits/[a-f0-9]{40}" + r"|/actions/runs(?:/[1-9][0-9]*(?:/jobs|/artifacts)?)?" + r"|/actions/artifacts/[1-9][0-9]*/zip)(?:\?page=[1-9][0-9]*&limit=50)?", suffix), + "api_route_not_allowed") + require(archive == suffix.endswith("/zip"), "api_response_type_mismatch") + maximum = MAX_ARCHIVE if archive else MAX_JSON + request = urllib.request.Request(ORIGIN + PREFIX + suffix, + headers={"Authorization": "token " + self._token, + "Accept": "application/octet-stream" if archive else "application/json"}) + try: + with self._opener.open(request, timeout=25) as response: + require(response.status == 200 and (response.geturl() == request.full_url or (archive and signed_artifact_redirect(request.full_url, response.geturl()))), "api_response_identity") + data = response.read(maximum + 1) + except urllib.error.HTTPError as error: + raise SourceError("api_http_" + str(error.code)) from None + except (OSError, urllib.error.URLError): + raise SourceError("api_unavailable") from None + require(len(data) <= maximum, "api_response_too_large") + return data if archive else strict_json(data) + + def repository(self): + repo = self.request("") + require(isinstance(repo, dict) and type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID + and repo.get("full_name") == REPOSITORY and repo.get("default_branch") == "main" + and repo.get("archived") is False and repo.get("mirror") is False, + "repository_identity_mismatch") + return repo + + def pages(self, suffix, key): + rows, identities, total = [], set(), None + for page in range(1, MAX_PAGES + 1): + data = self.request(suffix + "?page=" + str(page) + "&limit=50") + require(isinstance(data, dict) and type(data.get("total_count")) is int + and 0 <= data["total_count"] <= PAGE_SIZE * MAX_PAGES, "pagination_total_invalid") + require(total is None or total == data["total_count"], "pagination_changed") + total = data["total_count"] + batch = data.get(key) + require(isinstance(batch, list) and len(batch) <= PAGE_SIZE, "pagination_batch_invalid") + for item in batch: + require(isinstance(item, dict) and positive(item.get("id")) and item["id"] not in identities, + "pagination_duplicate_or_invalid_id") + identities.add(item["id"]) + rows.extend(batch) + require(len(rows) <= total, "pagination_overflow") + if len(rows) == total: + return rows + require(len(batch) == PAGE_SIZE, "pagination_incomplete") + raise SourceError("pagination_limit") + + def run(self, identity): + require(positive(identity), "invalid_run_id") + run = self.request("/actions/runs/" + str(identity)) + self.validate_run(run) + require(run["id"] == identity, "run_identity_mismatch") + return run + + @staticmethod + def validate_run(run): + normalize_run(run) + # Gitea 1.27.2 leaves top-level repository_id=0. The nested repository + # and fixed repository endpoint carry the actual identity instead. + repo = run.get("repository") or {} + require(type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID + and repo.get("full_name") == REPOSITORY, "run_repository_mismatch") + + def discover(self): + self.repository() + runs = self.pages("/actions/runs", "workflow_runs") + for run in runs: + self.validate_run(run) + require(len({run["run_number"] for run in runs}) == len(runs), "duplicate_run_number") + # A push/deletion while pages were read must not silently hide an older + # pending run. Recheck identity/count, without requiring phases to stop. + check = self.pages("/actions/runs", "workflow_runs") + identity = lambda values: sorted((r["id"], r["run_number"], r["head_sha"], r["event"], r["head_branch"], r["path"]) for r in values) + for run in check: + self.validate_run(run) + require(identity(runs) == identity(check), "discovery_changed") + return check + + def successful_run(self, row): + run = self.run(row["id"]) + require((run["run_number"], run["head_sha"], run["run_attempt"]) == + (row["number"], row["sha"], row["attempt"]), "qualified_run_changed") + require(run["path"] == WORKFLOW and run["event"] == "push" and run["head_branch"] == "main" + and run["status"] == "completed" and run["conclusion"] == "success", "run_not_qualified") + jobs = self.pages("/actions/runs/" + str(run["id"]) + "/jobs", "jobs") + require(len(jobs) == 1, "qualification_job_count") + job = jobs[0] + require(job.get("run_id") == run["id"] and job.get("head_sha") == run["head_sha"] + and job.get("head_branch") == "main" and job.get("run_attempt") == run["run_attempt"] + and job.get("name") == "qualify" and job.get("labels") == ["nodedc-node22-build"] + and job.get("runner_id") == 1 and job.get("status") == "completed" + and job.get("conclusion") == "success", "qualification_job_mismatch") + steps = job.get("steps") + require(isinstance(steps, list) and all(isinstance(s, dict) for s in steps) and [s.get("name") for s in steps] == + ["Check the exact pushed commit", "Retain the qualified release in this Gitea run"] + and all(s.get("status") == "completed" and s.get("conclusion") == "success" for s in steps), + "qualification_steps_mismatch") + return run + + def main_commit(self): + branch = self.request("/branches/main") + require(isinstance(branch, dict) and branch.get("name") == "main", "main_branch_mismatch") + sha = (branch.get("commit") or {}).get("id") + require(isinstance(sha, str) and SHA.fullmatch(sha), "main_commit_invalid") + return sha + + def ancestor(self, ancestor, descendant, *, limit=1024): + require(all(isinstance(s, str) and SHA.fullmatch(s) for s in (ancestor, descendant)), "ancestry_sha_invalid") + pending, seen = [descendant], set() + while pending: + sha = pending.pop() + if sha == ancestor: + return True + if sha in seen: + continue + require(len(seen) < limit, "ancestry_limit") + seen.add(sha) + commit = self.request("/git/commits/" + sha) + require(isinstance(commit, dict) and commit.get("sha") == sha, "commit_identity_mismatch") + parents = commit.get("parents") + require(isinstance(parents, list) and len(parents) <= 32, "commit_parents_invalid") + for parent in parents: + value = parent.get("sha") if isinstance(parent, dict) else None + require(isinstance(value, str) and SHA.fullmatch(value), "commit_parent_invalid") + pending.append(value) + return False + + def prove_lineage(self, installed, candidate): + main = self.main_commit() + require(candidate != installed and self.ancestor(installed, candidate) + and self.ancestor(candidate, main), "non_forward_main_release") + require(self.main_commit() == main, "main_changed_during_proof") + return main + + def artifact(self, run): + artifacts = self.pages("/actions/runs/" + str(run["id"]) + "/artifacts", "artifacts") + candidates = [a for a in artifacts if a.get("name") == "device-core-release"] + require(len(candidates) == 1, "qualified_artifact_count") + artifact = candidates[0] + owner = artifact.get("workflow_run") or {} + require(owner.get("id") == run["id"] and owner.get("repository_id") == REPOSITORY_ID + and owner.get("head_sha") == run["head_sha"] and artifact.get("expired") is False + and type(artifact.get("size_in_bytes")) is int and 0 < artifact["size_in_bytes"] <= MAX_ARCHIVE, + "artifact_owner_or_size_mismatch") + blob = self.request("/actions/artifacts/" + str(artifact["id"]) + "/zip", archive=True) + require(len(blob) == artifact["size_in_bytes"], "artifact_download_size_mismatch") + return unpack_artifact(blob, run) + + + def unpack_artifact(blob, run): + identity = "nodedc-device-core-release-v1-r" + str(run["id"]) + "-" + run["head_sha"] + ".tgz" + require(len(blob) <= MAX_ARCHIVE, "archive_too_large") + try: + with zipfile.ZipFile(io.BytesIO(blob)) as archive: + members = archive.infolist() + require(len(members) == 2 and set(archive.namelist()) == {identity, "release.json"}, "zip_entry_mismatch") + for member in members: + require(not member.is_dir() and stat.S_IFMT(member.external_attr >> 16) in (0, stat.S_IFREG) + and not member.flag_bits & 1 and 0 < member.file_size <= MAX_ARCHIVE, + "zip_member_invalid") + if member.filename == "release.json": + require(member.file_size <= 4096, "zip_receipt_too_large") + data = archive.read(identity) + receipt = strict_json(archive.read("release.json")) + except (zipfile.BadZipFile, RuntimeError, NotImplementedError, OSError): + raise SourceError("archive_invalid") from None + expected = {"artifact": identity, "sourceCommit": run["head_sha"], "runId": run["id"], + "runNumber": run["run_number"], "deployed": False, + "sha256": hashlib.sha256(data).hexdigest()} + require(receipt == expected and type(receipt.get("runId")) is int + and type(receipt.get("runNumber")) is int and receipt.get("deployed") is False, "release_receipt_mismatch") + return receipt, data + + # Source: infra/device-core-deploy/controller.py + """One polling cycle with an injected canonical installer, no shell authority.""" + + + class Controller: + def __init__(self, queue, source, installer): + self.queue, self.source, self.installer = queue, source, installer + + def reconcile(self): + for row in self.queue.snapshot(): + if row['phase'] != 'deploying': + continue + outcome, receipt = self.installer.receipt(row) + self.queue.reconcile(row['id'], digest=row['digest'], artifact=row['artifact'], + outcome=outcome, receipt=receipt) + + def observe(self): + runs = self.source.discover() + # A disappeared pending run cannot be silently skipped. Keep its local + # reservation/order; a source error is actionable, never an expiry. + ids = {r['id'] for r in runs} + for row in self.queue.snapshot(): + if row['phase'] in ('pending', 'ready') and row['id'] not in ids: + raise QueueError('observed_run_disappeared:' + str(row['id'])) + self.queue.observe(runs, repository=REPOSITORY, repository_id=REPOSITORY_ID) + + def tick(self): + self.reconcile() + self.observe() + row = self.queue.next_ready() + if row is None: + return {'status': 'waiting'} + run = self.source.successful_run(row) + baseline = self.installer.installed_source() + self.source.prove_lineage(baseline, row['sha']) + receipt, data = self.source.artifact(run) + # Staging validates the canonical payload and its relation to this run. + self.installer.stage(row, receipt, data) + self.installer.plan(receipt['artifact']) + # Recheck after potentially slow download/plan; a rerun/pending run may + # have appeared. Reserve still enforces the durable ordering atomically. + self.observe() + self.source.successful_run(row) + self.source.prove_lineage(baseline, row['sha']) + reserved = self.queue.reserve(row['id'], digest=receipt['sha256'], artifact=receipt['artifact']) + try: + self.installer.apply(receipt['artifact']) + finally: + # Even a clean rollback is terminal for this exact artifact. Missing + # or conflicting evidence blocks subsequent installs after restart. + outcome, canonical_receipt = self.installer.receipt(reserved) + self.queue.reconcile(row['id'], digest=receipt['sha256'], artifact=receipt['artifact'], + outcome=outcome, receipt=canonical_receipt) + return {'status': outcome, 'run': row['id'], 'source': row['sha']} + + return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError) +# END GENERATED DEVICE CORE AUTODEPLOY LIBRARY + + def main(argv): + if argv == ["--device-core-autodeploy-tick"]: + return device_autodeploy_tick() if sys.version_info < (3, 8): die("Python 3.8 or newer is required") parser = argparse.ArgumentParser(prog="nodedc-deploy") diff --git a/infra/deploy-runner/test_device_core_autodeploy.py b/infra/deploy-runner/test_device_core_autodeploy.py new file mode 100644 index 0000000..bed6f2f --- /dev/null +++ b/infra/deploy-runner/test_device_core_autodeploy.py @@ -0,0 +1,126 @@ +"""Canonical bootstrap scope, unit ownership, live-dispatch ordering and receipts.""" +import copy +from contextlib import ExitStack,redirect_stdout,redirect_stderr +import hashlib +import importlib.machinery +import importlib.util +import io +import json +from pathlib import Path +import stat +import sys +import tempfile +import unittest +from unittest import mock + +loader=importlib.machinery.SourceFileLoader('autodeploy_runner',str(Path(__file__).with_name('nodedc-deploy'))) +spec=importlib.util.spec_from_loader(loader.name,loader);R=importlib.util.module_from_spec(spec);loader.exec_module(R) +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'device-core-deploy')) +from build_autodeploy import bundle +from embed_library import section,START,END + +class AutodeployTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup);self.root=Path(self.tmp.name) + self.identity,self.data=bundle();self.artifact=self.root/'bootstrap.tgz';self.artifact.write_bytes(self.data) + self.work=self.root/'work';self.work.mkdir() + + def test_deterministic_archive_and_canonical_scope(self): + self.assertEqual(bundle()[1],self.data) + manifest,entries,payload=R.load_artifact(self.artifact,self.work) + self.assertEqual(manifest['id'],self.identity);self.assertEqual(entries,[R.DEVICE_AUTODEPLOY_ENTRY]) + self.assertEqual(R.component_services('device-core-autodeploy',entries),()) + self.assertEqual(R.component_builds('device-core-autodeploy',entries),()) + self.assertTrue(R.component_artifact_only('device-core-autodeploy')) + for path in ['deployment/other.json','runtime/token','docker-compose.yml','hook.py']: + with self.assertRaises(R.DeployError):R.allowed_payload_path('device-core-autodeploy',path) + + def test_descriptor_cannot_change_authority_or_baseline(self): + m,e,p=R.load_artifact(self.artifact,self.work) + for key,value in [('firstRunNumber',1),('installer','/tmp/runner'),('services',['device-postgres']),('publishedPorts',[9000]),('baselineSourceCommit','a'*40)]: + d=copy.deepcopy(R.DEVICE_AUTODEPLOY_DESCRIPTOR);d[key]=value + (p/e[0]).write_text(json.dumps(d,sort_keys=True,indent=2)+'\n') + with self.subTest(key=key),self.assertRaises(R.DeployError):R.validate_device_autodeploy_payload(p,e,m['id']) + + def test_generated_library_is_exact_and_operates_without_source_imports(self): + text=Path(R.__file__).read_text();actual=START+text.split(START,1)[1].split(END,1)[0]+END + self.assertEqual(actual,section()) + Q,S,C,errors=R.device_autodeploy_library();q=Q(self.root/'queue',first_run_number=8) + self.assertIsNone(q.next_ready());q.close() + self.assertEqual(S('a'*40)._token,'a'*40) + + def test_units_have_only_internal_worker_no_listeners_or_external_hooks(self): + units=R.device_autodeploy_units();self.assertEqual(set(units),{R.DEVICE_AUTODEPLOY_SERVICE,R.DEVICE_AUTODEPLOY_TIMER}) + self.assertIn('ExecStart=/usr/bin/python3 /usr/local/sbin/nodedc-deploy --device-core-autodeploy-tick',units[R.DEVICE_AUTODEPLOY_SERVICE]) + self.assertIn('OnUnitInactiveSec=30s',units[R.DEVICE_AUTODEPLOY_TIMER]) + self.assertNotIn('Listen',str(units));self.assertNotIn('/Volumes/',str(units));self.assertNotIn('/inbox/',str(units)) + + def test_bootstrap_worker_cannot_deploy_before_canonical_receipt(self): + with mock.patch.object(R,'require_root'),mock.patch.object(R,'ensure_layout'),mock.patch.object(R,'device_autodeploy_activated',return_value=False),mock.patch.object(R,'device_autodeploy_read_token') as token: + self.assertEqual(R.device_autodeploy_tick(),0);token.assert_not_called() + + def test_unit_install_and_rollback_preserve_applications_and_secrets(self): + unitdir=self.root/'units';unitdir.mkdir();live=self.root/'live';live.mkdir();secret=self.root/'secret';secret.write_text('retain') + before={'inventory':{'fixture':1}} + with mock.patch.object(R,'DEVICE_AUTODEPLOY_UNIT_DIR',unitdir),mock.patch.object(R,'device_autodeploy_import_token'),mock.patch.object(R,'device_autodeploy_ctl') as ctl,mock.patch.object(R,'accept_device_autodeploy'),mock.patch.object(R,'device_autodeploy_root_path'),mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R,'gitea_ci_inventory',return_value=before['inventory']): + R.apply_device_autodeploy(before) + for name,data in R.device_autodeploy_units().items():self.assertEqual((unitdir/name).read_text(),data) + R.rollback_device_autodeploy(live,self.root,[R.DEVICE_AUTODEPLOY_ENTRY],'stamp',before) + self.assertFalse(list(unitdir.iterdir()));self.assertEqual(secret.read_text(),'retain') + self.assertIn(mock.call('disable',R.DEVICE_AUTODEPLOY_TIMER,check=False),ctl.call_args_list) + + def test_wrong_unit_bytes_and_inventory_prevent_false_acceptance(self): + d=self.root/'units';d.mkdir() + for name,value in R.device_autodeploy_units().items():(d/name).write_text(value) + (d/R.DEVICE_AUTODEPLOY_SERVICE).write_text('changed') + with mock.patch.object(R,'DEVICE_AUTODEPLOY_UNIT_DIR',d),mock.patch.object(R,'device_autodeploy_root_path'),self.assertRaises(R.DeployError):R.accept_device_autodeploy({'inventory':{}}) + + def execute(self,fail=False): + live=self.root/'live' + for name in ['inbox','applied','failed','backups','state','tmp']:(self.root/name).mkdir() + a=self.root/'inbox/bootstrap.tgz';a.write_bytes(self.data) + events=[];before={'inventory':{},'baseline':R.DEVICE_AUTODEPLOY_BASELINE} + def acceptance(*args): + events.append('accept') + if fail:raise R.DeployError('injected acceptance failure') + def rollback(root,backup,entries,stamp,proof): + events.append('rollback');R.restore_platform_overlay(root,backup,entries,stamp) + with ExitStack() as stack: + for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),('LOCK_DIR',self.root/'lock')]:stack.enter_context(mock.patch.object(R,name,value)) + stack.enter_context(mock.patch.dict(R.COMPONENTS,{'device-core-autodeploy':{'payload_root':live,'bootstrap_root':True,'artifact_only':True,'services':()}})) + for name in ['require_root','ensure_layout','validate_artifact_location']:stack.enter_context(mock.patch.object(R,name)) + stack.enter_context(mock.patch.object(R,'preflight_device_autodeploy',return_value=before)) + stack.enter_context(mock.patch.object(R,'apply_device_autodeploy',side_effect=lambda b:events.append('install'))) + stack.enter_context(mock.patch.object(R,'accept_device_autodeploy',side_effect=acceptance)) + stack.enter_context(mock.patch.object(R,'rollback_device_autodeploy',side_effect=rollback)) + stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO())) + if fail: + with self.assertRaises(R.DeployError):R.apply_artifact(a) + else:R.apply_artifact(a) + applied=R.load_state(R.STATE_FILE);failed=R.load_state(R.FAILED_STATE_FILE) + return events,applied,failed + + def test_real_canonical_apply_success_after_acceptance(self): + events,applied,failed=self.execute() + self.assertEqual(events,['install','accept']);self.assertEqual(len(applied),1);self.assertFalse(failed) + self.assertEqual(applied[0]['sha256'],hashlib.sha256(self.data).hexdigest()) + + def test_real_canonical_failure_dispatches_only_own_rollback(self): + events,applied,failed=self.execute(True) + self.assertEqual(events,['install','accept','rollback']);self.assertFalse(applied) + self.assertEqual(failed[0]['rollback_status'],'ok:device-core-autodeploy-bootstrap') + + def test_receipt_requires_archive_backup_and_exact_digest(self): + applied=self.root/'applied';failed=self.root/'failed';backups=self.root/'backups' + for d in (applied,failed,backups):d.mkdir() + name='nodedc-device-core-release-v1-r8-'+'a'*40+'.tgz';identity=name[7:-4] + archive=applied/name;archive.write_bytes(b'archive');(backups/'backup').mkdir() + row={'artifact':name,'digest':hashlib.sha256(b'archive').hexdigest()} + record={'id':identity,'artifact':name,'component':'device-core-release','sha256':row['digest'],'backup_id':'backup','status':'ok'} + with mock.patch.object(R,'APPLIED_DIR',applied),mock.patch.object(R,'FAILED_DIR',failed),mock.patch.object(R,'BACKUPS_DIR',backups): + with mock.patch.object(R,'load_state',side_effect=[[record],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'deployed') + archive.write_bytes(b'changed') + with mock.patch.object(R,'load_state',side_effect=[[record],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'ambiguous') + with mock.patch.object(R,'load_state',side_effect=[[],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'ambiguous') + +if __name__=='__main__':unittest.main() diff --git a/infra/deploy-runner/test_device_core_release.py b/infra/deploy-runner/test_device_core_release.py index 017c38d..104830f 100644 --- a/infra/deploy-runner/test_device_core_release.py +++ b/infra/deploy-runner/test_device_core_release.py @@ -152,14 +152,14 @@ class ReleaseTests(unittest.TestCase): def test_rollback_uses_previous_images_without_build_or_registry(self): before={'runtime':runtime()}; calls=[] - with mock.patch.object(R,'restore_platform_overlay',side_effect=lambda *a:calls.append('source')),mock.patch.object(R.subprocess,'run',side_effect=lambda *a,**k:calls.append(a[0])),mock.patch.object(R,'run_compose',side_effect=lambda *a:calls.append('compose')),mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')),mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('accept')),mock.patch.object(R,'run_build') as build: + with mock.patch.object(R,'restore_platform_overlay',side_effect=lambda *a:calls.append('source')),mock.patch.object(R.subprocess,'run',side_effect=lambda *a,**k:calls.append(a[0])),mock.patch.object(R,'run_device_release_compose',side_effect=lambda *a:calls.append('compose')),mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')),mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('accept')),mock.patch.object(R,'run_build') as build: R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',before,True) self.assertEqual(calls[0],'source');self.assertEqual(calls[-3:],['compose','health','accept']);build.assert_not_called() self.assertEqual([x[1:3] for x in calls if isinstance(x,list)],[['image','tag'],['image','tag']]) self.assertEqual(calls[1][-2],before['runtime']['device-control-core']['imageId']) def test_build_failure_restores_tags_but_does_not_restart_services(self): - with mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R.subprocess,'run') as command,mock.patch.object(R,'run_compose') as compose,mock.patch.object(R,'run_healthchecks') as health,mock.patch.object(R,'accept_device_release'): + with mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R.subprocess,'run') as command,mock.patch.object(R,'run_device_release_compose') as compose,mock.patch.object(R,'run_healthchecks') as health,mock.patch.object(R,'accept_device_release'): R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',{'runtime':runtime()},False) self.assertEqual(command.call_count,2);compose.assert_not_called();health.assert_not_called() @@ -173,7 +173,7 @@ class ReleaseTests(unittest.TestCase): def test_compose_never_rebuilds_pulls_or_starts_dependencies(self): with mock.patch.object(R,'compose_base_cmd',return_value=['docker','compose']),mock.patch.object(R,'component_compose_root',return_value=self.root),mock.patch.object(R.subprocess,'run') as command: - R.run_compose('device-core-release',R.DEVICE_RELEASE_SERVICES,R.DEVICE_RELEASE_ENTRIES) + R.run_device_release_compose(R.DEVICE_RELEASE_SERVICES,R.DEVICE_RELEASE_ENTRIES) cmd=command.call_args_list[0].args[0] for arg in ['--no-deps','--no-build','--force-recreate']:self.assertIn(arg,cmd) self.assertEqual(cmd[cmd.index('--pull')+1],'never');self.assertEqual(cmd[-2:],list(R.DEVICE_RELEASE_SERVICES)) @@ -204,7 +204,7 @@ class ReleaseTests(unittest.TestCase): stack.enter_context(mock.patch.object(R,name)) stack.enter_context(mock.patch.object(R,'component_compose_files',return_value=(compose,))) stack.enter_context(mock.patch.object(R,'preflight_device_release',return_value=before)) - for name,label in [('run_build','build'),('run_compose','compose'),('run_healthchecks','health')]: + for name,label in [('run_build','build'),('run_device_release_compose','compose'),('run_healthchecks','health')]: stack.enter_context(mock.patch.object(R,name,side_effect=operation(label))) def acceptance(*args,**kwargs): if kwargs.get('rollback'): diff --git a/infra/device-core-deploy/README.md b/infra/device-core-deploy/README.md index 9f55764..f7b7aeb 100644 --- a/infra/device-core-deploy/README.md +++ b/infra/device-core-deploy/README.md @@ -1,7 +1,8 @@ # Device Core recurring deployment Status: 2026-09-29. The build runner is installed and push-to-main qualification -works. Production polling is **not activated**. DCPLATFORM-21 owns the deployment +works. Release r7 (`edf69068ec64e3d105d5324d39b8eaeface21215`) is accepted +in canonical ledger 385. Production polling is **not activated**. DCPLATFORM-21 owns the deployment contract; DCPLATFORM-37 tracks activation. ## Release domain @@ -42,17 +43,75 @@ for earlier pending runs, records artifact reservation before installation, skip duplicate/already superseded sources, and requires a canonical journal/archive receipt after a crash. It does not discover API pages or prove Git ancestry. +## Outbound controller v1 + +`gitea_source.py` verifies complete stable API pagination, exact repository/run/job +identity and successful qualification steps. Commit-parent traversal proves +installed → candidate → current main. Downloads accept only the API origin and +Gitea's exact signed `/zip/raw?sig&expires` redirect for the same artifact ID; +the persistent Authorization token is removed from that redirected request. +ZIP entries, uncompressed bounds and release receipt are checked before the +canonical TGZ loader independently validates the release. + +`controller.py` refreshes discovery, enforces queue order, stages and plans through +an injected canonical installer, rechecks qualification/ancestry, durably reserves, +then invokes apply. It reconciles canonical journal + archive digest + backup after +success, failure or restart. Missing/contradictory evidence stops further installs; +network errors before reservation preserve the ready queue. Failed CI is skipped, +pending CI retains its place, and completed releases are never installed twice. + +`embed_library.py` deterministically places these pure modules inside the reviewed +standalone root runner as ordinary Python in a private lexical scope. There is no +runtime import from SMB, dynamic exec or script payload. Tests compare embedded +bytes against source modules. + +The `device-core-autodeploy` bootstrap contains only +`deployment/device-core-autodeploy-v1.json`. Its fixed identity is +`device-core-autodeploy-v1-20260929-001`. The root installer creates exactly two +previously absent native units under `/usr/local/lib/systemd/system`: +`nodedc-device-autodeploy.service` and `.timer`. The timer starts 120s after boot +(or immediately when installed after that point), then 30s after each worker +completion. There is one worker, protected by flock, plus the existing canonical +deployment lock. It opens no listener and requires no Mac to remain online. +Commits from any computer qualify through the same Gitea main branch. + +Native systemd, trusted Python/systemctl paths and absence of unit collisions are +preconditions, checked in plan before mutation. No unsupported CFS/Pids controls +or fallback schedulers are assumed. The service invokes only the internal fixed +`/usr/bin/python3 /usr/local/sbin/nodedc-deploy --device-core-autodeploy-tick` entry. +Its worker requires a successful canonical bootstrap receipt/archive before any +release installation, preventing an early timer firing from bypassing acceptance. + +The dedicated `read:repository` token is imported from a bounded operator handoff +under `nodedc-deploy/runtime/device-core-autodeploy/enrollment.pending.json` into +`/var/lib/nodedc-device-autodeploy/gitea-read-token` (root:root 0600, directory0700). +It is absent from artifacts/build jobs/logs. The operator staging file is removed +only after private-copy verification. SQLite and private status live in the same +private directory. A sanitized `runtime-status.json` under the bootstrap descriptor +root gives SMB-readable operational status; it never authorizes installation. +Gitea's scope applies to repositories visible to that account; the controller's +API route allowlist is fixed to repository38. + +Bootstrap preserves all existing containers and the accepted r7 application tree. +It verifies unit bytes, effective FragmentPath/no drop-ins, enabled/active timer, +private credential metadata, API qualification and health. Rollback removes only +its new units and descriptor; it retains private credentials/queue and all apps. +The activation floor is run8, so historical r5/r6 cannot enter automatic delivery. + +The frozen generic `run_compose` function is byte-identical to the previous Engine +canon. Device Core uses its own exact Core+Manager Compose entry with unchanged +`--pull never --no-build --no-deps`, including rollback. + ## Remaining activation work -- Implement outbound authenticated Gitea polling with complete pagination and - refresh of pending runs; verify repository, run, jobs, artifact and Git ancestry. -- Import a narrowly scoped read token into root-private controller runtime. -- Add and test the canonical controller bootstrap domain and fixed service unit. -- Install via the root runner, then accept push → qualified artifact → canonical - plan/apply, serial commits, failed tests, rollback and restart recovery on NAS. +- Promote the reviewed root runner through the separate SHA-pinned admin gate. +- Build/stage the bootstrap via `build_autodeploy.py`, then fresh plan and apply. +- Accept a new main commit through CI → automatic canonical deployment, including + ordered commits, failed checks and recovery. Source tests are not NAS acceptance. +- Remove the temporary Mac token copy after private NAS import is verified. -No helper from this directory is installed by an application release. Do not run -helper code from SMB or use Docker as a deployment shortcut. +No helper from this directory is executed on NAS or installed by an application +release. User-facing NAS deployment commands remain canonical plan/apply. ## Validation diff --git a/infra/device-core-deploy/autodeploy-v1.json b/infra/device-core-deploy/autodeploy-v1.json new file mode 100644 index 0000000..dfaf555 --- /dev/null +++ b/infra/device-core-deploy/autodeploy-v1.json @@ -0,0 +1,21 @@ +{ + "baselineArtifactSha256": "7510c7d12e209415970556321a005675d0af61c59497da4226df8ed353184917", + "baselineSourceCommit": "edf69068ec64e3d105d5324d39b8eaeface21215", + "branch": "main", + "firstRunNumber": 8, + "installer": "/usr/local/sbin/nodedc-deploy", + "intervalAfterCompletionSeconds": 30, + "publishedPorts": [], + "releaseComponent": "device-core-release", + "releaseId": "device-core-autodeploy-v1-20260929-001", + "repository": "SILVER/NODEDC_DEVICE_CORE", + "repositoryId": 38, + "scheduler": "native-systemd-timer", + "schemaVersion": "nodedc.device-core.autodeploy.v1", + "services": [ + "device-control-core", + "device-manager" + ], + "transport": "outbound-https", + "workflow": "ci.yml@refs/heads/main" +} diff --git a/infra/device-core-deploy/build_autodeploy.py b/infra/device-core-deploy/build_autodeploy.py new file mode 100644 index 0000000..739f7ba --- /dev/null +++ b/infra/device-core-deploy/build_autodeploy.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Deterministic data-only controller bootstrap; executable policy is in the root runner.""" +import argparse +import gzip +import hashlib +import io +import json +from pathlib import Path +import tarfile +ROOT=Path(__file__).resolve().parent +ENTRY='deployment/device-core-autodeploy-v1.json' + + +def bundle(): + data=(ROOT/'autodeploy-v1.json').read_bytes() + identity=json.loads(data)['releaseId'] + members={'manifest.env':('id='+identity+'\ncomponent=device-core-autodeploy\ntype=app-overlay\n').encode(), + 'files.txt':(ENTRY+'\n').encode(),'payload/'+ENTRY:data} + output=io.BytesIO() + with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as compressed: + with tarfile.open(fileobj=compressed,mode='w') as archive: + for name,value in sorted(members.items()): + info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(value) + archive.addfile(info,io.BytesIO(value)) + return identity,output.getvalue() + +if __name__=='__main__': + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output-dir',required=True,type=Path) + args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True) + identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz') + with path.open('xb') as stream:stream.write(data) + print(json.dumps(dict(artifact=str(path),sha256=hashlib.sha256(data).hexdigest(),id=identity))) diff --git a/infra/device-core-deploy/controller.py b/infra/device-core-deploy/controller.py new file mode 100644 index 0000000..61e436c --- /dev/null +++ b/infra/device-core-deploy/controller.py @@ -0,0 +1,54 @@ +"""One polling cycle with an injected canonical installer, no shell authority.""" +from deployment_queue import REPOSITORY, REPOSITORY_ID, QueueError + + +class Controller: + def __init__(self, queue, source, installer): + self.queue, self.source, self.installer = queue, source, installer + + def reconcile(self): + for row in self.queue.snapshot(): + if row['phase'] != 'deploying': + continue + outcome, receipt = self.installer.receipt(row) + self.queue.reconcile(row['id'], digest=row['digest'], artifact=row['artifact'], + outcome=outcome, receipt=receipt) + + def observe(self): + runs = self.source.discover() + # A disappeared pending run cannot be silently skipped. Keep its local + # reservation/order; a source error is actionable, never an expiry. + ids = {r['id'] for r in runs} + for row in self.queue.snapshot(): + if row['phase'] in ('pending', 'ready') and row['id'] not in ids: + raise QueueError('observed_run_disappeared:' + str(row['id'])) + self.queue.observe(runs, repository=REPOSITORY, repository_id=REPOSITORY_ID) + + def tick(self): + self.reconcile() + self.observe() + row = self.queue.next_ready() + if row is None: + return {'status': 'waiting'} + run = self.source.successful_run(row) + baseline = self.installer.installed_source() + self.source.prove_lineage(baseline, row['sha']) + receipt, data = self.source.artifact(run) + # Staging validates the canonical payload and its relation to this run. + self.installer.stage(row, receipt, data) + self.installer.plan(receipt['artifact']) + # Recheck after potentially slow download/plan; a rerun/pending run may + # have appeared. Reserve still enforces the durable ordering atomically. + self.observe() + self.source.successful_run(row) + self.source.prove_lineage(baseline, row['sha']) + reserved = self.queue.reserve(row['id'], digest=receipt['sha256'], artifact=receipt['artifact']) + try: + self.installer.apply(receipt['artifact']) + finally: + # Even a clean rollback is terminal for this exact artifact. Missing + # or conflicting evidence blocks subsequent installs after restart. + outcome, canonical_receipt = self.installer.receipt(reserved) + self.queue.reconcile(row['id'], digest=receipt['sha256'], artifact=receipt['artifact'], + outcome=outcome, receipt=canonical_receipt) + return {'status': outcome, 'run': row['id'], 'source': row['sha']} diff --git a/infra/device-core-deploy/embed_library.py b/infra/device-core-deploy/embed_library.py new file mode 100644 index 0000000..69b4382 --- /dev/null +++ b/infra/device-core-deploy/embed_library.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""Embed reviewed pure Python into the standalone canonical runner; no runtime exec/import from SMB.""" +from pathlib import Path +ROOT=Path(__file__).resolve().parent +RUNNER=ROOT.parent/'deploy-runner/nodedc-deploy' +START='# BEGIN GENERATED DEVICE CORE AUTODEPLOY LIBRARY\n' +END='# END GENERATED DEVICE CORE AUTODEPLOY LIBRARY\n' + +def section(): + output=START+'def device_autodeploy_library():\n' + for name in ('deployment_queue.py','gitea_source.py','controller.py'): + source=(ROOT/name).read_text() + lines=[line for line in source.splitlines() if not line.startswith('from deployment_queue import ')] + output+=' # Source: infra/device-core-deploy/'+name+'\n' + output+='\n'.join(' '+line if line else '' for line in lines)+'\n\n' + return output+' return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError)\n'+END + +if __name__=='__main__': + current=RUNNER.read_text() + if START in current: + before,rest=current.split(START,1);_,after=rest.split(END,1) + current=before+section()+after + else: + current=current.replace('\ndef main(argv):','\n'+section()+'\n\ndef main(argv):',1) + RUNNER.write_text(current) diff --git a/infra/device-core-deploy/gitea_source.py b/infra/device-core-deploy/gitea_source.py new file mode 100644 index 0000000..ed7be11 --- /dev/null +++ b/infra/device-core-deploy/gitea_source.py @@ -0,0 +1,259 @@ +"""Read-only, bounded Gitea source verification. No production execution authority. + +The privileged installer must independently validate the returned TGZ with its +canonical loader and reconcile its own journal. Nothing here accepts commands, +paths, origins, or credentials from a workflow artifact. +""" +import hashlib +import io +import json +import re +import stat +import urllib.error +import urllib.parse +import urllib.request +import zipfile + +from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW, SHA, normalize_run, positive + + +ORIGIN = "https://git.dcserve.ru" +PREFIX = "/api/v1/repos/" + REPOSITORY +PAGE_SIZE = 50 +MAX_PAGES = 200 +MAX_JSON = 8 * 1024 * 1024 +MAX_ARCHIVE = 64 * 1024 * 1024 + + +class SourceError(ValueError): + pass + + +def require(condition, code): + if not condition: + raise SourceError(code) + + +def strict_json(data): + def unique(pairs): + result = {} + for key, value in pairs: + require(key not in result, "duplicate_json_key") + result[key] = value + return result + try: + return json.loads(data, object_pairs_hook=unique) + except (UnicodeError, ValueError): + raise SourceError("invalid_json") from None + + +def signed_artifact_redirect(original, target): + origin, dest = urllib.parse.urlsplit(original), urllib.parse.urlsplit(target) + if (origin.scheme + "://" + origin.netloc != ORIGIN + or dest.scheme + "://" + dest.netloc != ORIGIN or origin.query or dest.fragment + or not re.fullmatch(re.escape(PREFIX) + r"/actions/artifacts/[1-9][0-9]*/zip", origin.path) + or dest.path != origin.path + "/raw"): + return False + pairs = urllib.parse.parse_qsl(dest.query, keep_blank_values=True) + params = dict(pairs) + return (len(pairs) == 2 and set(params) == {"sig", "expires"} + and re.fullmatch(r"[A-Za-z0-9_-]{32,128}", params["sig"]) is not None + and re.fullmatch(r"[0-9]{10,13}", params["expires"]) is not None) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + # Gitea 1.27 signs a same-origin /zip/raw URL. Only this exact route is + # allowed and the persistent token is deliberately NOT forwarded. + if (req is not None and req.get_method() == "GET" and code in (302, 303) + and signed_artifact_redirect(req.full_url, newurl)): + return urllib.request.Request(newurl, headers={"Accept": "application/octet-stream"}) + raise SourceError("api_redirect_refused") + + +class GiteaSource: + def __init__(self, token): + require(isinstance(token, str) and re.fullmatch(r"[0-9a-f]{40}", token), "invalid_read_token") + self._token = token + self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + + def request(self, suffix, *, archive=False): + require(isinstance(suffix, str) and (suffix == "" or suffix.startswith("/")), "invalid_api_path") + require(not any(value in suffix for value in ("..", "\\", "#", "@", "\r", "\n", "%")), "invalid_api_path") + # Only methods below construct suffixes; this additional allowlist keeps + # even accidental future callers from reading other API resources. + require(re.fullmatch( + r"(?:|/branches/main|/git/commits/[a-f0-9]{40}" + r"|/actions/runs(?:/[1-9][0-9]*(?:/jobs|/artifacts)?)?" + r"|/actions/artifacts/[1-9][0-9]*/zip)(?:\?page=[1-9][0-9]*&limit=50)?", suffix), + "api_route_not_allowed") + require(archive == suffix.endswith("/zip"), "api_response_type_mismatch") + maximum = MAX_ARCHIVE if archive else MAX_JSON + request = urllib.request.Request(ORIGIN + PREFIX + suffix, + headers={"Authorization": "token " + self._token, + "Accept": "application/octet-stream" if archive else "application/json"}) + try: + with self._opener.open(request, timeout=25) as response: + require(response.status == 200 and (response.geturl() == request.full_url or (archive and signed_artifact_redirect(request.full_url, response.geturl()))), "api_response_identity") + data = response.read(maximum + 1) + except urllib.error.HTTPError as error: + raise SourceError("api_http_" + str(error.code)) from None + except (OSError, urllib.error.URLError): + raise SourceError("api_unavailable") from None + require(len(data) <= maximum, "api_response_too_large") + return data if archive else strict_json(data) + + def repository(self): + repo = self.request("") + require(isinstance(repo, dict) and type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID + and repo.get("full_name") == REPOSITORY and repo.get("default_branch") == "main" + and repo.get("archived") is False and repo.get("mirror") is False, + "repository_identity_mismatch") + return repo + + def pages(self, suffix, key): + rows, identities, total = [], set(), None + for page in range(1, MAX_PAGES + 1): + data = self.request(suffix + "?page=" + str(page) + "&limit=50") + require(isinstance(data, dict) and type(data.get("total_count")) is int + and 0 <= data["total_count"] <= PAGE_SIZE * MAX_PAGES, "pagination_total_invalid") + require(total is None or total == data["total_count"], "pagination_changed") + total = data["total_count"] + batch = data.get(key) + require(isinstance(batch, list) and len(batch) <= PAGE_SIZE, "pagination_batch_invalid") + for item in batch: + require(isinstance(item, dict) and positive(item.get("id")) and item["id"] not in identities, + "pagination_duplicate_or_invalid_id") + identities.add(item["id"]) + rows.extend(batch) + require(len(rows) <= total, "pagination_overflow") + if len(rows) == total: + return rows + require(len(batch) == PAGE_SIZE, "pagination_incomplete") + raise SourceError("pagination_limit") + + def run(self, identity): + require(positive(identity), "invalid_run_id") + run = self.request("/actions/runs/" + str(identity)) + self.validate_run(run) + require(run["id"] == identity, "run_identity_mismatch") + return run + + @staticmethod + def validate_run(run): + normalize_run(run) + # Gitea 1.27.2 leaves top-level repository_id=0. The nested repository + # and fixed repository endpoint carry the actual identity instead. + repo = run.get("repository") or {} + require(type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID + and repo.get("full_name") == REPOSITORY, "run_repository_mismatch") + + def discover(self): + self.repository() + runs = self.pages("/actions/runs", "workflow_runs") + for run in runs: + self.validate_run(run) + require(len({run["run_number"] for run in runs}) == len(runs), "duplicate_run_number") + # A push/deletion while pages were read must not silently hide an older + # pending run. Recheck identity/count, without requiring phases to stop. + check = self.pages("/actions/runs", "workflow_runs") + identity = lambda values: sorted((r["id"], r["run_number"], r["head_sha"], r["event"], r["head_branch"], r["path"]) for r in values) + for run in check: + self.validate_run(run) + require(identity(runs) == identity(check), "discovery_changed") + return check + + def successful_run(self, row): + run = self.run(row["id"]) + require((run["run_number"], run["head_sha"], run["run_attempt"]) == + (row["number"], row["sha"], row["attempt"]), "qualified_run_changed") + require(run["path"] == WORKFLOW and run["event"] == "push" and run["head_branch"] == "main" + and run["status"] == "completed" and run["conclusion"] == "success", "run_not_qualified") + jobs = self.pages("/actions/runs/" + str(run["id"]) + "/jobs", "jobs") + require(len(jobs) == 1, "qualification_job_count") + job = jobs[0] + require(job.get("run_id") == run["id"] and job.get("head_sha") == run["head_sha"] + and job.get("head_branch") == "main" and job.get("run_attempt") == run["run_attempt"] + and job.get("name") == "qualify" and job.get("labels") == ["nodedc-node22-build"] + and job.get("runner_id") == 1 and job.get("status") == "completed" + and job.get("conclusion") == "success", "qualification_job_mismatch") + steps = job.get("steps") + require(isinstance(steps, list) and all(isinstance(s, dict) for s in steps) and [s.get("name") for s in steps] == + ["Check the exact pushed commit", "Retain the qualified release in this Gitea run"] + and all(s.get("status") == "completed" and s.get("conclusion") == "success" for s in steps), + "qualification_steps_mismatch") + return run + + def main_commit(self): + branch = self.request("/branches/main") + require(isinstance(branch, dict) and branch.get("name") == "main", "main_branch_mismatch") + sha = (branch.get("commit") or {}).get("id") + require(isinstance(sha, str) and SHA.fullmatch(sha), "main_commit_invalid") + return sha + + def ancestor(self, ancestor, descendant, *, limit=1024): + require(all(isinstance(s, str) and SHA.fullmatch(s) for s in (ancestor, descendant)), "ancestry_sha_invalid") + pending, seen = [descendant], set() + while pending: + sha = pending.pop() + if sha == ancestor: + return True + if sha in seen: + continue + require(len(seen) < limit, "ancestry_limit") + seen.add(sha) + commit = self.request("/git/commits/" + sha) + require(isinstance(commit, dict) and commit.get("sha") == sha, "commit_identity_mismatch") + parents = commit.get("parents") + require(isinstance(parents, list) and len(parents) <= 32, "commit_parents_invalid") + for parent in parents: + value = parent.get("sha") if isinstance(parent, dict) else None + require(isinstance(value, str) and SHA.fullmatch(value), "commit_parent_invalid") + pending.append(value) + return False + + def prove_lineage(self, installed, candidate): + main = self.main_commit() + require(candidate != installed and self.ancestor(installed, candidate) + and self.ancestor(candidate, main), "non_forward_main_release") + require(self.main_commit() == main, "main_changed_during_proof") + return main + + def artifact(self, run): + artifacts = self.pages("/actions/runs/" + str(run["id"]) + "/artifacts", "artifacts") + candidates = [a for a in artifacts if a.get("name") == "device-core-release"] + require(len(candidates) == 1, "qualified_artifact_count") + artifact = candidates[0] + owner = artifact.get("workflow_run") or {} + require(owner.get("id") == run["id"] and owner.get("repository_id") == REPOSITORY_ID + and owner.get("head_sha") == run["head_sha"] and artifact.get("expired") is False + and type(artifact.get("size_in_bytes")) is int and 0 < artifact["size_in_bytes"] <= MAX_ARCHIVE, + "artifact_owner_or_size_mismatch") + blob = self.request("/actions/artifacts/" + str(artifact["id"]) + "/zip", archive=True) + require(len(blob) == artifact["size_in_bytes"], "artifact_download_size_mismatch") + return unpack_artifact(blob, run) + + +def unpack_artifact(blob, run): + identity = "nodedc-device-core-release-v1-r" + str(run["id"]) + "-" + run["head_sha"] + ".tgz" + require(len(blob) <= MAX_ARCHIVE, "archive_too_large") + try: + with zipfile.ZipFile(io.BytesIO(blob)) as archive: + members = archive.infolist() + require(len(members) == 2 and set(archive.namelist()) == {identity, "release.json"}, "zip_entry_mismatch") + for member in members: + require(not member.is_dir() and stat.S_IFMT(member.external_attr >> 16) in (0, stat.S_IFREG) + and not member.flag_bits & 1 and 0 < member.file_size <= MAX_ARCHIVE, + "zip_member_invalid") + if member.filename == "release.json": + require(member.file_size <= 4096, "zip_receipt_too_large") + data = archive.read(identity) + receipt = strict_json(archive.read("release.json")) + except (zipfile.BadZipFile, RuntimeError, NotImplementedError, OSError): + raise SourceError("archive_invalid") from None + expected = {"artifact": identity, "sourceCommit": run["head_sha"], "runId": run["id"], + "runNumber": run["run_number"], "deployed": False, + "sha256": hashlib.sha256(data).hexdigest()} + require(receipt == expected and type(receipt.get("runId")) is int + and type(receipt.get("runNumber")) is int and receipt.get("deployed") is False, "release_receipt_mismatch") + return receipt, data diff --git a/infra/device-core-deploy/test_controller.py b/infra/device-core-deploy/test_controller.py new file mode 100644 index 0000000..ad699a4 --- /dev/null +++ b/infra/device-core-deploy/test_controller.py @@ -0,0 +1,74 @@ +import hashlib +from pathlib import Path +import tempfile +import unittest +from unittest import mock +from deployment_queue import DeploymentQueue, QueueError +from controller import Controller +from test_gitea_source import run,A,B,C + + +class ControllerTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) + self.path=Path(self.tmp.name)/'queue.db' + self.q=DeploymentQueue(self.path,first_run_number=8);self.addCleanup(self.q.close) + self.s=mock.Mock();self.i=mock.Mock() + self.i.installed_source.return_value=A + self.r=run();self.s.discover.return_value=[self.r];self.s.successful_run.return_value=self.r + self.data=b'archive';self.artifact='nodedc-device-core-release-v1-r8-'+B+'.tgz' + self.receipt={'artifact':self.artifact,'sha256':hashlib.sha256(self.data).hexdigest()} + self.s.artifact.return_value=(self.receipt,self.data) + self.i.receipt.return_value=('deployed','canonical:line1') + self.c=Controller(self.q,self.s,self.i) + + def test_success_is_reserved_before_apply_and_never_repeated(self): + def apply(a):self.assertEqual(self.q.snapshot()[0]['phase'],'deploying') + self.i.apply.side_effect=apply + self.assertEqual(self.c.tick()['status'],'deployed') + self.assertEqual(self.c.tick()['status'],'waiting') + self.i.apply.assert_called_once_with(self.artifact) + + def test_earlier_pending_blocks_newer_ready_but_failed_ci_does_not(self): + pending=run();pending.update(status='in_progress',conclusion=None) + self.s.discover.return_value=[run(9,C),pending] + self.assertEqual(self.c.tick()['status'],'waiting');self.i.apply.assert_not_called() + pending.update(status='completed',conclusion='failure');self.c.observe() + self.assertEqual(self.q.next_ready()['id'],9) + + def test_failure_with_clean_rollback_is_terminal(self): + self.i.apply.side_effect=RuntimeError('failure');self.i.receipt.return_value=('rolled-back','failed:line1') + with self.assertRaises(RuntimeError):self.c.tick() + self.assertEqual(self.q.snapshot()[0]['phase'],'failed') + self.assertEqual(self.c.tick()['status'],'waiting');self.assertEqual(self.i.apply.call_count,1) + + def test_missing_receipt_blocks_restart(self): + self.i.apply.side_effect=RuntimeError('crash');self.i.receipt.return_value=('ambiguous','missing-receipt') + with self.assertRaises(RuntimeError):self.c.tick() + with self.assertRaises(QueueError):self.c.tick() + self.assertEqual(self.i.apply.call_count,1) + + def test_restart_reconciles_success_without_second_apply(self): + self.c.observe();self.q.reserve(8,digest=self.receipt['sha256'],artifact=self.artifact) + self.assertEqual(self.c.tick()['status'],'waiting') + self.i.apply.assert_not_called();self.assertEqual(self.q.snapshot()[0]['phase'],'deployed') + + def test_network_or_plan_error_before_reservation_preserves_ready_queue(self): + self.i.plan.side_effect=RuntimeError('network') + with self.assertRaises(RuntimeError):self.c.tick() + self.assertEqual(self.q.snapshot()[0]['phase'],'ready');self.i.apply.assert_not_called() + + def test_new_rerun_before_reservation_prevents_apply(self): + pending=run();pending.update(run_attempt=2,status='in_progress',conclusion=None) + self.s.discover.side_effect=[[run()],[pending]] + with self.assertRaises(QueueError):self.c.tick() + self.i.apply.assert_not_called() + + def test_disappeared_pending_run_never_skipped(self): + pending=run();pending.update(status='in_progress',conclusion=None) + self.s.discover.return_value=[pending];self.c.observe() + self.s.discover.return_value=[run(9,C)] + with self.assertRaisesRegex(QueueError,'disappeared'):self.c.tick() + self.i.apply.assert_not_called() + +if __name__=='__main__':unittest.main() diff --git a/infra/device-core-deploy/test_gitea_source.py b/infra/device-core-deploy/test_gitea_source.py new file mode 100644 index 0000000..af23133 --- /dev/null +++ b/infra/device-core-deploy/test_gitea_source.py @@ -0,0 +1,136 @@ +"""Untrusted API/ZIP boundaries and complete source lineage.""" +import copy +import hashlib +import io +import json +import stat +import unittest +from unittest import mock +import zipfile +import urllib.request + +from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW +from gitea_source import GiteaSource, SourceError, NoRedirect, strict_json, unpack_artifact + +A, B, C = 'a'*40, 'b'*40, 'c'*40 + + +def run(number=8, sha=B): + return dict(id=number, run_number=number, run_attempt=1, head_sha=sha, + event='push', head_branch='main', path=WORKFLOW, status='completed', conclusion='success', + repository={'id':38, 'full_name':REPOSITORY}) + + +def job(r): + return dict(id=8, run_id=r['id'], head_sha=r['head_sha'], head_branch='main', run_attempt=1, + name='qualify', labels=['nodedc-node22-build'], runner_id=1, status='completed', conclusion='success', + steps=[dict(name=n,status='completed',conclusion='success') for n in + ('Check the exact pushed commit','Retain the qualified release in this Gitea run')]) + + +def packed(r, mutate=None, names=None): + name='nodedc-device-core-release-v1-r'+str(r['id'])+'-'+r['head_sha']+'.tgz' + data=b'qualified tgz fixture' + receipt=dict(artifact=name,sourceCommit=r['head_sha'],runId=r['id'],runNumber=r['run_number'], + deployed=False,sha256=hashlib.sha256(data).hexdigest()) + if mutate:mutate(receipt) + out=io.BytesIO() + with zipfile.ZipFile(out,'w') as z: + z.writestr(name,data) + z.writestr('release.json',json.dumps(receipt)) + for n in names or []:z.writestr(n,b'extra') + return out.getvalue() + + +class SourceTests(unittest.TestCase): + def setUp(self):self.s=GiteaSource('a'*40) + + def test_no_redirects_or_unapproved_routes(self): + with self.assertRaises(SourceError):NoRedirect().redirect_request(None,None,302,'',{},'https://other/') + for path in ['/../../user','/actions/runs?token=a','//user','/branches/other','/actions/artifacts/1/zip%3f']: + with self.subTest(path=path),self.assertRaises(SourceError):self.s.request(path) + + def test_observed_signed_download_redirect_strips_persistent_token(self): + url='https://git.dcserve.ru/api/v1/repos/SILVER/NODEDC_DEVICE_CORE/actions/artifacts/6/zip' + target=url+'/raw?sig='+'a'*43+'&expires=1790708000' + req=urllib.request.Request(url,headers={'Authorization':'token '+'b'*40}) + redirected=NoRedirect().redirect_request(req,None,302,'',{},target) + self.assertIsNone(redirected.get_header('Authorization')) + self.assertEqual(redirected.full_url,target) + for bad in [target.replace('git.dcserve.ru','example.com'),target.replace('/6/','/7/'), + target+'&extra=1',target+'&sig='+'c'*43,target.replace('https:','http:')]: + with self.subTest(url=bad),self.assertRaises(SourceError):NoRedirect().redirect_request(req,None,302,'',{},bad) + with self.assertRaises(SourceError):NoRedirect().redirect_request(redirected,None,302,'',{},target) + + def test_duplicate_json_keys_and_token_format(self): + for value in [b'{"id":1,"id":2}',b'invalid',b'\xff']: + with self.assertRaises(SourceError):strict_json(value) + for token in ['', 'A'*40,'a'*40+'\n','secret']: + with self.assertRaises(SourceError):GiteaSource(token) + + def test_paginated_complete_unique(self): + with mock.patch.object(self.s,'request',side_effect=[dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=51,items=[dict(id=51)])]) as get: + self.assertEqual(len(self.s.pages('/actions/runs','items')),51) + self.assertEqual(get.call_args.args[0],'/actions/runs?page=2&limit=50') + + def test_partial_changed_and_duplicate_pages_fail(self): + scenarios=[ + [dict(total_count=2,items=[dict(id=1)])], + [dict(total_count=2,items=[dict(id=1),dict(id=1)])], + [dict(total_count=True,items=[])], + [dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=50,items=[])], + ] + for pages in scenarios: + with self.subTest(pages=len(pages)),mock.patch.object(self.s,'request',side_effect=pages),self.assertRaises(SourceError):self.s.pages('/actions/runs','items') + + def test_run_nested_repository_identity_not_broken_top_level_field(self): + r=run();r['repository_id']=0;self.s.validate_run(r) + r['repository']['id']=39 + with self.assertRaises(SourceError):self.s.validate_run(r) + + def test_discovery_rejects_change_between_complete_scans(self): + with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[run()],[run(),run(9,C)]]),self.assertRaises(SourceError):self.s.discover() + + def test_discovery_allows_status_progress_without_loss(self): + pending=run();pending.update(status='in_progress',conclusion=None) + with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[pending],[run()]]):self.assertEqual(self.s.discover(),[run()]) + + def test_success_must_have_exact_job_and_steps(self): + r=run();row=dict(id=8,number=8,sha=B,attempt=1) + with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[job(r)]):self.assertEqual(self.s.successful_run(row),r) + for field,value in [('runner_id',2),('labels',['ubuntu-latest']),('steps',[]),('head_sha',A),('conclusion','failure')]: + j=job(r);j[field]=value + with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[j]),self.assertRaises(SourceError):self.s.successful_run(row) + + def test_ancestry_proves_both_edges_and_stable_main(self): + graph={C:[B],B:[A],A:[]} + def get(path): + sha=path.rsplit('/',1)[1] + return dict(sha=sha,parents=[dict(sha=p) for p in graph[sha]]) + with mock.patch.object(self.s,'request',side_effect=get),mock.patch.object(self.s,'main_commit',return_value=C): + self.assertEqual(self.s.prove_lineage(A,B),C) + with self.assertRaises(SourceError):self.s.prove_lineage(B,A) + with self.assertRaises(SourceError):self.s.prove_lineage(B,B) + with mock.patch.object(self.s,'ancestor',return_value=True),mock.patch.object(self.s,'main_commit',side_effect=[B,C]),self.assertRaises(SourceError):self.s.prove_lineage(A,B) + + def test_ancestry_malformed_and_bound(self): + with mock.patch.object(self.s,'request',return_value=dict(sha=B,parents=[dict(sha=C)])),self.assertRaisesRegex(SourceError,'ancestry_limit'):self.s.ancestor(A,B,limit=1) + with mock.patch.object(self.s,'request',return_value=dict(sha=C,parents=[])),self.assertRaisesRegex(SourceError,'commit_identity'):self.s.ancestor(A,B) + + def test_zip_requires_exact_receipt_and_only_two_files(self): + r=run();receipt,data=unpack_artifact(packed(r),r) + self.assertEqual(receipt['sha256'],hashlib.sha256(data).hexdigest()) + for change in [lambda d:d.update(sourceCommit=A),lambda d:d.update(deployed=True),lambda d:d.update(sha256='f'*64),lambda d:d.update(extra='value')]: + with self.assertRaises(SourceError):unpack_artifact(packed(r,change),r) + for name in ['../../script','runtime/token','.DS_Store']: + with self.assertRaises(SourceError):unpack_artifact(packed(r,names=[name]),r) + with self.assertRaises(SourceError):unpack_artifact(b'bad zip',r) + + def test_artifact_owner_download_digest_bound_to_run(self): + r=run();blob=packed(r) + a=dict(id=8,name='device-core-release',workflow_run=dict(id=8,repository_id=38,head_sha=B),expired=False,size_in_bytes=len(blob)) + with mock.patch.object(self.s,'pages',return_value=[a]),mock.patch.object(self.s,'request',return_value=blob):self.assertEqual(self.s.artifact(r)[0]['sourceCommit'],B) + a['workflow_run']['repository_id']=39 + with mock.patch.object(self.s,'pages',return_value=[a]),self.assertRaises(SourceError):self.s.artifact(r) + +if __name__=='__main__':unittest.main()