From 9133e520fd6ea877b665ab815f78c3a53df6db8c Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sun, 29 Nov 2026 19:58:57 +0000 Subject: [PATCH] Isolate unattended Development builds and preserve deployment receipts --- AGENTS.md | 12 ++ Docs/Codex/Deployment.md | 40 +++++++ .../boundary-verification.json | 49 ++++++++ .../validation-receipt.json | 29 +++++ .../Unattended-20261129/verification.json | 36 ++++++ Docs/Deployment/Unattended-20261129.md | 112 ++++++++++++++++++ Tools/Deployment/development_release.py | 40 ++++++- .../provision/install-unattended-release.sh | 11 ++ Tools/Deployment/release.py | 11 +- Tools/Deployment/sandbox_build.py | 55 +++++++++ Tools/Deployment/test_development_release.py | 30 +++++ Tools/Deployment/test_sandbox_build.py | 41 +++++++ 12 files changed, 457 insertions(+), 9 deletions(-) create mode 100644 Docs/Deployment/Evidence/Unattended-20261129/boundary-verification.json create mode 100644 Docs/Deployment/Evidence/Unattended-20261129/validation-receipt.json create mode 100644 Docs/Deployment/Evidence/Unattended-20261129/verification.json create mode 100644 Docs/Deployment/Unattended-20261129.md create mode 100755 Tools/Deployment/provision/install-unattended-release.sh create mode 100644 Tools/Deployment/sandbox_build.py create mode 100644 Tools/Deployment/test_development_release.py create mode 100644 Tools/Deployment/test_sandbox_build.py diff --git a/AGENTS.md b/AGENTS.md index 578ba0b1..164c31f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,3 +191,15 @@ verify the inherited lease, then explicitly start InProgress. Complete or releas normally; exit after blocking assistance. Stop/reconcile on lost ownership. Read `/home/nick/cyj-planner/CONTROLLER.md` for recovery, emergency stop and authority. Manual sessions retain their existing claim maintenance responsibilities. + +## Unattended Development acceptance + +Development deployment is required before CYJ user acceptance readiness, except +where the brief explicitly defines a later acceptance milestone. After testing and +committing, follow `Docs/Codex/Deployment.md` and the shared toolkit's `DEPLOYMENT.md`. +In a controller execution use `deployment-request` / `deployment-result` for the +configured `application-development` target. Never bypass no_new_privs or expose +signing keys. Verify the deployed full commit, perform the brief's live acceptance +(including genuine database persistence/reload), then record receipt, tests, feature +URL and factual effort in CYJ before completion. Reconcile uncertain deployment +outcomes before retrying. Production remains separately authorised. diff --git a/Docs/Codex/Deployment.md b/Docs/Codex/Deployment.md index d05f8ffd..aeef0c9c 100644 --- a/Docs/Codex/Deployment.md +++ b/Docs/Codex/Deployment.md @@ -186,3 +186,43 @@ repository/service on Atlas port 5051; its publishing commands live in other service. Application root health now accepts the normal redirect to Projects; public marketing smoke tests belong to the independent website. Production cutover requires separate explicit approval and is not implied by Development qualification. + +## Unattended CYJ Development releases + +Development deployment is a normal requirement for CYJ assignments reaching user +acceptance. Implement, verify, commit, deploy, check running identity, perform the +required live acceptance, then record the deployed commit, helper receipt, tests and +feature URL in CYJ before completion. Larger projects may explicitly define later +acceptance milestones. Production remains separately authorised. + +The unattended Codex sandbox cannot invoke sudo: `no_new_privs` is intentional. +The long-lived controller also inherited groups predating the deployment-group +membership. Consequently task 52 could neither read the baseline nor write the +inbox. A fresh interactive deployer can use `sg`; doing so inside the sandbox cannot +overcome `no_new_privs`. Do not disable either protection or expose signing keys. + +The controller now accepts bounded Development requests and calls a root-installed +snapshot of **this existing** `development_release.py` with `--isolate-build`. +That optional mode runs all publishing and regression processes in an unprivileged +namespace with only OS tools, source, scratch output and public NuGet packages. +Host home, signing material, controller/worker records, SQL/runtime configuration +and the inbox are absent. The normal interactive command remains supported. +Package preparation still uses `release.prepare`; its default Production path is +unchanged. Existing signing, schema qualification, locking, backup, activation, +health checks, rollback and receipts are retained. The orchestration now preserves +the original activation receipt alongside `submission.json`, including on failure. + +Review/test and install the unprivileged snapshot with the administrator-only +`Tools/Deployment/provision/install-unattended-release.sh`. This does not alter the +privileged helper, sudoers or running application. The shared toolkit's +`/home/nick/cyj-planner/DEPLOYMENT.md` documents root-owned policy installation, +standing Development acceptance authority, exact task/commit approvals, worker +commands, service-level probes and recovery. The policy binds resource 7 to this +repository and `application-development`; workers submit no commands or paths. +Remove broad controller-state write grants before enabling the capability. + +A successful request is only deployment evidence. Task 52 must still resume through +Clara's normal assistance-response workflow, retain its prior effort, and perform +its authenticated persistence/reload acceptance checks. Never manually complete it +or resolve stage 53 to test the integration. Reconcile any existing receipt before +requesting deployment again; uncertain attempts are not automatically repeated. diff --git a/Docs/Deployment/Evidence/Unattended-20261129/boundary-verification.json b/Docs/Deployment/Evidence/Unattended-20261129/boundary-verification.json new file mode 100644 index 00000000..cf2a3a7c --- /dev/null +++ b/Docs/Deployment/Evidence/Unattended-20261129/boundary-verification.json @@ -0,0 +1,49 @@ +{ + "fixture_only": true, + "real_deployments": 0, + "real_cyj_writes": 0, + "results": [ + { + "variant": "authorised", + "status": "recovery_required", + "no_new_privs": true, + "secrets_masked": true, + "controller_state_protected": true + }, + { + "variant": "production", + "status": "rejected", + "no_new_privs": true, + "secrets_masked": true, + "controller_state_protected": true + }, + { + "variant": "task", + "status": "rejected", + "no_new_privs": true, + "secrets_masked": true, + "controller_state_protected": true + }, + { + "variant": "worker", + "status": "rejected", + "no_new_privs": true, + "secrets_masked": true, + "controller_state_protected": true + }, + { + "variant": "command", + "status": "rejected", + "no_new_privs": true, + "secrets_masked": true, + "controller_state_protected": true + }, + { + "variant": "path", + "status": "rejected", + "no_new_privs": true, + "secrets_masked": true, + "controller_state_protected": true + } + ] +} diff --git a/Docs/Deployment/Evidence/Unattended-20261129/validation-receipt.json b/Docs/Deployment/Evidence/Unattended-20261129/validation-receipt.json new file mode 100644 index 00000000..f7323fea --- /dev/null +++ b/Docs/Deployment/Evidence/Unattended-20261129/validation-receipt.json @@ -0,0 +1,29 @@ +{ + "format": 1, + "deployment_id": "20261129T194919Z-8129c5a64940", + "operation": "validate", + "status": "validated", + "origin": "web1", + "started_utc": "2026-11-29T19:49:19.283+00:00", + "completed_utc": "2026-11-29T19:49:27.002+00:00", + "release": { + "application_sha256": "da5f485ff846918fcdeb8ccdd4ad77daf6d8b4068712d21d5d09b4e2646ac4ed", + "dll_sha256": "af335ad57096b6fecffadfe16231723ad3c4ba755e8b7fb0aa26682fa78da187", + "id": "development-b5672f20b5bb-20261129T194558Z", + "manifest_sha256": "3f772d17ae908296ceeb7e91c8299563f9f99183e0008ccccd5ca3be4e7865fd", + "package_sha256": "b5af34ba779cced625e1fe5829b8e7561282e829be3cda685d4ef0e3110d124e", + "source_commit": "b5672f20b5bb2cd22f31a486f6269cb3eaea28cf", + "version": "1.0.0" + }, + "checks": {}, + "migrations": { + "baselined": null, + "executed": null + }, + "timing": { + "clock": "monotonic; UTC timestamps for correlation only", + "measured_top_level_seconds": 6.436509, + "total_seconds": 7.719393, + "unattributed_seconds": 1.282884 + } +} diff --git a/Docs/Deployment/Evidence/Unattended-20261129/verification.json b/Docs/Deployment/Evidence/Unattended-20261129/verification.json new file mode 100644 index 00000000..b7fd66ed --- /dev/null +++ b/Docs/Deployment/Evidence/Unattended-20261129/verification.json @@ -0,0 +1,36 @@ +{ + "date": "2026-11-29", + "toolkit_version": "1.3.0", + "toolkit_commit": "322a4f070f80d50e49a643710a57ff9c45188bb3", + "toolkit_archive_sha256": "26daf88dbf0aee6b4e1e60bd75a1dd813a460a8082a94992c89621974ba4ed1e", + "installed_release_files_sha256": { + "development_release.py": "f9820098e12e878b7606ee34ef1f8e9864e56f4a505cc7c412106c9a526aec01", + "sandbox_build.py": "b8f0d869260f0c44a130ccd6ee59f6f92b21126ad06df718fbc4e59a71c33c7f", + "release.py": "fed4acba1eae2cf328a8d6f738440278d35ae335cdf8c892a63fc9814c0b6d87", + "transport.py": "66c5adf1eeaf28fa050d188e9c7607234116fa6bb5f289301a79ca58e3a3e601", + "receipt.py": "d92324e00862f773ef663332dedc0e061bb0561b5397e83728e05ce42c142d21", + "activate.py": "a4d9ffb3745555f08db5b3433f66c79eedbe52f94328286a7133bb594fe19271" + }, + "original_implementation_commit": "b5672f20b5bb2cd22f31a486f6269cb3eaea28cf", + "real_release_operation": "validate-only", + "validation_receipt": "20261129T194919Z-8129c5a64940", + "validations": { + "solution_build": "passed; 0 warnings, 0 errors", + "application_harness_checks": 897, + "deployment_python_tests": 83, + "toolkit_tests": 85, + "toolkit_native_windows_skips": 1, + "systemd_sandbox_fixture_scenarios": 6, + "configured_application_and_website_identity_queue_reads": "passed; no real CYJ writes", + "process_containment": "passed", + "generic_sandbox": "passed" + }, + "development_running_release": "/opt/plotdirector-dev/releases/development-a36e1d8c172f-20261127T224044Z/app", + "public_health_status": 200, + "feature_url": "https://dev.plotdirector.com/Timeline", + "feature_status": 302, + "real_activations": 0, + "production_operations": 0, + "task_52_manually_completed": false, + "assistance_53_modified": false +} diff --git a/Docs/Deployment/Unattended-20261129.md b/Docs/Deployment/Unattended-20261129.md new file mode 100644 index 00000000..7f16e8c2 --- /dev/null +++ b/Docs/Deployment/Unattended-20261129.md @@ -0,0 +1,112 @@ +# Unattended Development deployment integration — 29 November 2026 + +The failure was an execution boundary mismatch. The controller retained an OS group +list from before `nick` joined `plotdirector-dev-deploy`; the baseline is root/group +0750 and the inbox root/group 2770. Inside Codex, `no_new_privs` additionally prevents +sudo/setgid elevation. Interactive deployment can refresh membership with `sg` and +invoke the existing helper; the sandboxed worker cannot. The app and database were +healthy, and task 52 had stopped before publishing or external effects. + +The existing helper alone could not cross that boundary. The existing controller +now admits bounded requests and invokes the existing release procedure outside the +model sandbox. No new daemon, privileged helper, general execution API, sudo rule or +replacement deployment pipeline was introduced. Untrusted source publishing/testing +runs in a separate unprivileged namespace without host home, deployment credentials, +inbox, runtime settings or controller state. Signing and the established activation +helper remain outside that namespace. Source bundling is isolated too, and trusted +release code is installed root-owned outside worker repositories. + +Root-owned configuration binds organisation/resource/repository, a Development-only +target, deployment group and fixed installed command. The controller checks assigned, +unblocked InProgress tasks, completed dependencies, current server claim ownership, +full commit and standing acceptance authority or exact task/project/commit approval. +Standing authority permits the captured committed HEAD only. Exact approval for task +52 permits its existing `b5672f20…` implementation. Workers cannot submit commands, +paths, another worker/execution/task, or Production. All registered workers inherit +denials for current/historical deployment secret roots. Controller code, registry +and authoritative state cannot be worker write roots; only the current execution +exchange is writable. `no_new_privs`, existing sandbox and privilege protections stay. + +Attempts are recorded before external work and keyed by worker/task/commit. Retries, +new request keys and restarts return the prior outcome rather than reactivate. Unknown +outcomes require operator reconciliation of health, active marker and existing helper +receipt. An already admitted privileged activation may finish after its caller stops; +never infer rollback from termination. Existing activation locks, backups, SQL ledger, +signatures, health checks, rollback rules and protected receipts are unchanged. + +## Installed configuration and operations + +- Shared toolkit/controller: `/home/nick/cyj-planner`, version 1.3.0, commit `322a4f070f80d50e49a643710a57ff9c45188bb3`. +- Unprivileged release snapshot: `/usr/local/lib/plotdirector-dev-release`. +- Root-owned policy: `/etc/cyj/development-deployments.json`. +- Private registry: application `development_policy` enabled; broad controller state + write grants removed from both workers. Backup retained outside Git. +- Existing user controller service was drained/stopped for maintenance and restored + after verification. No application service restart or Production operation occurred. + +Installation and recovery are in [the Development guide](../Codex/Deployment.md) +and `/home/nick/cyj-planner/DEPLOYMENT.md`. Repository AGENTS.md, shared worker/reference, +controller, installation and distribution documentation now require Development +availability and live acceptance evidence before formal CYJ completion. Larger +projects may explicitly define acceptance milestones. + +## Verification and limits + +A transient **user-systemd service** exercised `Controller.run_execution` with the +actual installed Codex sandbox, fixed root-owned policy and existing installed release +entry point. Only CYJ ownership was simulated using disposable local fixtures; no +model inference or real CYJ writes occurred. An authorised request reached the actual +procedure and was refused before publishing because its fixture lacked the approved +SQL baseline. Production, wrong task/worker, command and path substitutions were +rejected. All six scenarios passed, including no_new_privs, secret denial and state +protection. Repeated requests returned the persisted outcome without another launch. +[Service-boundary evidence](Evidence/Unattended-20261129/boundary-verification.json). + +Both real workers also passed selected-identity/queue GETs through their configured +sandbox from user services. Resource 7 sees task 52 waiting; resource 8 sees no tasks. +No planner credentials or real task mutations were used. The extra outer Bubblewrap +wrapper tested initially did not compose with this host's namespace restrictions; +the final code uses Codex's supported exact deny-read profile rules. The separate +build namespace works without changing AppArmor, sandbox or no_new_privs protections. + +The real existing procedure separately completed isolated publish, the full regression +harness, signing, submission and **preactivation validation only** for +`b5672f20b5bb2cd22f31a486f6269cb3eaea28cf`: + +- Release: `development-b5672f20b5bb-20261129T194558Z`. +- Validation receipt: `20261129T194919Z-8129c5a64940`. +- [Original receipt fields](Evidence/Unattended-20261129/validation-receipt.json). +- All 897 application regression checks passed; zero activation/migrations/service + operations. Private logs/bundle remain under + `/home/nick/.local/share/plotdirector-development/unattended-verification/release-v2`. + +The shared helper receipt has a pre-existing `origin: web1` label even for its fixed +Atlas Development profile. That original field is preserved; the invoked Development +helper and enforced Atlas/Development target establish the actual destination. No +Production connection or change was made. The first isolated build attempt lacked +NSS metadata and was stopped before signing/submission; the namespace now includes +readonly public OS identity/NSS files, and qualification subsequently passed. + +Final regression gates: `dotnet build PlotLine.slnx` passed with zero warnings/errors; +83 deployment Python tests passed; 85 toolkit tests passed with one native Windows-only +skip; process containment, generic Codex sandbox and code-only packaging checks passed. +Production documentation and the default Production preparation path are unchanged. + +Website configuration is supported by the shared policy/request mechanism, but its +existing package/receipt contract requires a separately reviewed installed adapter. +It has no deployment authority enabled by this installation. No Companion or +Production automation was added. + +## Task 52 resumption + +Development was not activated and still runs `a36e1d8c172f` at +https://dev.plotdirector.com. The feature URL is +https://dev.plotdirector.com/Timeline (authentication required). Task 50 was not +reimplemented. Task 52 was not completed and assistance 53 was not resolved. + +The original application worker can safely resume after Clara's normal assistance +response/evaluation makes task 52 eligible and the controller acquires a fresh claim. +It should reconcile health/receipts, request its approved original implementation, +then perform all required authenticated live checks, genuine database persistence +and reload verification, and fixture cleanup before reporting acceptance/completion. +The prevalidated package is evidence, not proof that the feature is already deployed. diff --git a/Tools/Deployment/development_release.py b/Tools/Deployment/development_release.py index 86f615a0..938a3aad 100644 --- a/Tools/Deployment/development_release.py +++ b/Tools/Deployment/development_release.py @@ -3,6 +3,7 @@ import argparse import json import os +import re from pathlib import Path import shutil import socket @@ -10,6 +11,11 @@ import subprocess import tempfile from types import SimpleNamespace +# -I protects the installed unattended entry point from inherited Python paths. +import sys +if sys.flags.isolated: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from release import require, load, file_digest, canonical, prepare BASELINE = Path('/var/lib/plotdirector-dev-deployment/baseline') @@ -23,11 +29,25 @@ def run(args, log): require(result.returncode == 0, 'Release check failed; see '+str(log)) +def capture_activation_receipt(output, text): + identifiers = re.findall(r'(?m)^RECEIPT ([A-Za-z0-9][A-Za-z0-9._-]{0,119})$', text) + if not identifiers: + return None + require(len(identifiers) == 1, 'Ambiguous activation receipt; reconcile protected evidence') + result = subprocess.run(['sudo', '-n', HELPER, '--receipt', identifiers[0]], + capture_output=True, text=True, check=True) + receipt = json.loads(result.stdout) + require(receipt.get('deployment_id') == identifiers[0], 'Activation receipt identity mismatch') + (Path(output)/'activation-receipt.json').write_bytes(canonical(receipt)) + return receipt + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', required=True) parser.add_argument('--output', required=True) parser.add_argument('--activate', action='store_true') + parser.add_argument('--isolate-build', action='store_true', help='Run all repository build code without host secrets using Bubblewrap') args = parser.parse_args() require(socket.gethostname() == 'atlas' and os.geteuid() != 0, 'Run as the Atlas Development deployer') os.umask(0o077) @@ -37,6 +57,12 @@ def main(): commit = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip() require(not subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip(), 'Clean committed source required') baseline = load(BASELINE/'manifest.json') + def build(command, log, writable): + if args.isolate_build: + from sandbox_build import run_build + run_build(command, source, writable, log) + else: + run(command, log) changed_sql = subprocess.check_output(['git', '-C', str(source), 'diff', '--name-only', baseline['source_commit'], commit, '--', 'PlotLine/Sql'], text=True).strip() require(not changed_sql, 'Schema changes require a separately reviewed/qualified migration plan') require(baseline['starting_schema_sha256'] == baseline['resulting_schema_sha256'], 'Code-only Development baseline required') @@ -51,8 +77,8 @@ def main(): with tempfile.TemporaryDirectory(prefix='build-', dir=output) as work: work = Path(work) publish = work/'publish' - run(['dotnet', 'publish', str(source/'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), '-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId='+commit], output/'qualification-build.log') - run(['dotnet', 'run', '--project', str(source/'PlotLine.Tests/PlotLine.Tests.csproj')], output/'regression.log') + build(['dotnet', 'publish', str(source/'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), '-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId='+commit], output/'qualification-build.log', work) + build(['dotnet', 'run', '--project', str(source/'PlotLine.Tests/PlotLine.Tests.csproj')], output/'regression.log', work) evidence = work/'evidence' shutil.copytree(BASELINE/'evidence', evidence) plan = {k:baseline[k] for k in ('starting_schema_sha256', 'resulting_schema_sha256', 'migrations', 'omitted_migrations', 'prerequisites', 'postconditions', 'qualification')} @@ -66,17 +92,21 @@ def main(): plan_file = output/'plan.json' plan_file.write_bytes(canonical(plan)) prepare(SimpleNamespace(source=str(source), plan=str(plan_file), sql=str(BASELINE/'sql'), evidence=str(evidence), - output=str(output/'bundle'), release_id=release_id, signing_key=str(signing), compression='none', scope_base=baseline['source_commit'])) + output=str(output/'bundle'), release_id=release_id, signing_key=str(signing), compression='none', scope_base=baseline['source_commit']), + publish_runner=build if args.isolate_build else None) # Unprivileged submission; privileged helper snapshots and verifies it again. destination = INBOX/release_id require(not destination.exists(), 'Release identifier already submitted') shutil.copytree(output/'bundle', destination) result = subprocess.run(['sudo', '-n', HELPER, '--validate', release_id]) require(result.returncode == 0, 'Development validation refused') + activation_receipt = None if args.activate: - result = subprocess.run(['sudo', '-n', HELPER, '--activate', release_id]) + result = subprocess.run(['sudo', '-n', HELPER, '--activate', release_id], capture_output=True, text=True) + print(result.stdout, end='') + activation_receipt = capture_activation_receipt(output, result.stdout) require(result.returncode == 0, 'Development activation refused; inspect protected receipt') - (output/'submission.json').write_bytes(canonical({'release_id':release_id, 'source_commit':commit, 'operation':'activate' if args.activate else 'validate', 'target':'Development'})) + (output/'submission.json').write_bytes(canonical({'release_id':release_id, 'source_commit':commit, 'operation':'activate' if args.activate else 'validate', 'target':'Development', 'receipt':activation_receipt})) print(json.dumps({'release_id':release_id, 'source_commit':commit, 'status':'activated' if args.activate else 'validated'})) diff --git a/Tools/Deployment/provision/install-unattended-release.sh b/Tools/Deployment/provision/install-unattended-release.sh new file mode 100755 index 00000000..c9dd11b9 --- /dev/null +++ b/Tools/Deployment/provision/install-unattended-release.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Run only after reviewing/testing these source files. Does not activate a release. +set -eu +[ "$(id -u)" = 0 ] || { echo 'Administrator installation required' >&2; exit 1; } +source_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +target=/usr/local/lib/plotdirector-dev-release +install -d -o root -g root -m 755 "$target" +for name in development_release.py sandbox_build.py release.py transport.py receipt.py activate.py; do + install -o root -g root -m 644 "$source_dir/$name" "$target/$name" +done +printf '%s\n' 'Installed unprivileged Development release orchestration. Activation helper, sudo rules and Production are unchanged.' diff --git a/Tools/Deployment/release.py b/Tools/Deployment/release.py index b43a5e35..5e9fe407 100644 --- a/Tools/Deployment/release.py +++ b/Tools/Deployment/release.py @@ -272,7 +272,7 @@ def verify_bundle(source, work, public_key, meter=None): return manifest, authorization, payload -def prepare(args, meter=None): +def prepare(args, meter=None, publish_runner=None): from receipt import Receipt, write_local meter = meter or Receipt('atlas-preparation') repo = Path(args.source).resolve() @@ -295,9 +295,12 @@ def prepare(args, meter=None): work = Path(directory) publish = work / 'publish' with meter.phase('build'): - subprocess.run(['dotnet', 'publish', str(repo / 'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), - '-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId=' + commit], check=True, - stdout=(output / 'publish.log').open('w'), stderr=subprocess.STDOUT) + command = ['dotnet', 'publish', str(repo / 'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), + '-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId=' + commit] + if publish_runner: + publish_runner(command, output / 'publish.log', work) + else: + subprocess.run(command, check=True, stdout=(output / 'publish.log').open('w'), stderr=subprocess.STDOUT) with meter.phase('packaging_signing'): require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Build changed tracked source') files = {} diff --git a/Tools/Deployment/sandbox_build.py b/Tools/Deployment/sandbox_build.py new file mode 100644 index 00000000..8848e56a --- /dev/null +++ b/Tools/Deployment/sandbox_build.py @@ -0,0 +1,55 @@ +"""Isolate repository-controlled build code; signing and activation stay outside. + +Only OS tools, the source, scratch build output and public NuGet packages are +visible. No host home, signing keys, controller records, inbox or runtime config. +""" +from pathlib import Path +import subprocess +import tempfile + + +def build_command(command, source, writable, home): + source, writable = Path(source).resolve(), Path(writable).resolve() + if command[0] != 'dotnet' or command[1] not in ('publish', 'run'): + raise ValueError('Only existing dotnet release gates are supported') + if not (source / '.git').is_dir(): + raise ValueError('Isolated builds require a standalone committed checkout') + args = ['/usr/bin/bwrap', '--die-with-parent', '--unshare-all', '--share-net', + '--new-session', '--cap-drop', 'ALL', '--clearenv', + '--ro-bind', '/usr', '/usr', '--symlink', 'usr/bin', '/bin', + '--symlink', 'usr/lib', '/lib', '--symlink', 'usr/lib64', '/lib64', + '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp', + '--dir', '/etc', '--ro-bind', '/etc/ssl', '/etc/ssl', + '--ro-bind', '/etc/resolv.conf', '/etc/resolv.conf', + '--ro-bind', '/etc/hosts', '/etc/hosts', + '--bind', str(home), '/build-home', + '--bind', str(source), str(source), + '--ro-bind', str(source / '.git'), str(source / '.git'), + '--bind', str(writable), str(writable), + '--chdir', str(source), '--setenv', 'HOME', '/build-home', + '--setenv', 'DOTNET_CLI_HOME', '/build-home', + '--setenv', 'DOTNET_CLI_TELEMETRY_OPTOUT', '1', + '--setenv', 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE', '1', + '--setenv', 'PATH', '/usr/bin:/bin', '--setenv', 'TMPDIR', '/tmp'] + # NuGet/.NET use NSS identity lookups even when HOME is explicit. These + # world-readable OS metadata files contain no deployment credentials. + for filename in ('passwd', 'group', 'nsswitch.conf', 'os-release', 'localtime'): + path = Path('/etc')/filename + if path.exists(): + args += ['--ro-bind', str(path), str(path)] + packages = Path.home() / '.nuget/packages' + if packages.is_dir(): + args += ['--ro-bind', str(packages), '/nuget/packages', + '--setenv', 'NUGET_PACKAGES', '/nuget/packages'] + return args + ['--', *command] + + +def run_build(command, source, writable, log): + # A fresh home per invocation has no NuGet credentials or host configuration. + with tempfile.TemporaryDirectory(prefix='pd-build-home-') as home: + args = build_command(command, source, writable, home) + with Path(log).open('w') as stream: + result = subprocess.run(args, stdout=stream, stderr=subprocess.STDOUT, + env={'PATH': '/usr/bin:/bin'}, timeout=1800) + if result.returncode: + raise ValueError('Isolated release gate failed; inspect '+str(log)) diff --git a/Tools/Deployment/test_development_release.py b/Tools/Deployment/test_development_release.py new file mode 100644 index 00000000..80592529 --- /dev/null +++ b/Tools/Deployment/test_development_release.py @@ -0,0 +1,30 @@ +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock, patch + +from development_release import capture_activation_receipt, HELPER +from release import Refused + +class ActivationReceiptTests(unittest.TestCase): + def test_actual_timestamp_receipt_identifier_retained_for_success_and_failure(self): + identifier='20261129T194919Z-8129c5a64940' + for status in ('activated','failed'): + receipt=dict(deployment_id=identifier,status=status) + with tempfile.TemporaryDirectory() as directory, patch('development_release.subprocess.run',return_value=Mock(stdout=json.dumps(receipt))) as run: + actual=capture_activation_receipt(directory,'operation output\nRECEIPT '+identifier+'\n') + self.assertEqual(actual,receipt) + self.assertEqual(json.loads((Path(directory)/'activation-receipt.json').read_text()),receipt) + self.assertEqual(run.call_args.args[0],['sudo','-n',HELPER,'--receipt',identifier]) + def test_untrusted_or_ambiguous_marker_never_selects_arbitrary_helper_arguments(self): + with patch('development_release.subprocess.run') as run: + self.assertIsNone(capture_activation_receipt('/unused','RECEIPT ../etc/passwd\n')) + self.assertIsNone(capture_activation_receipt('/unused','RECEIPT x; id\n')) + with self.assertRaises(Refused):capture_activation_receipt('/unused','RECEIPT one\nRECEIPT two\n') + run.assert_not_called() + def test_wrong_receipt_identity_refused(self): + with patch('development_release.subprocess.run',return_value=Mock(stdout='{"deployment_id":"other"}')): + with self.assertRaises(Refused):capture_activation_receipt('/unused','RECEIPT requested\n') + +if __name__=='__main__':unittest.main() diff --git a/Tools/Deployment/test_sandbox_build.py b/Tools/Deployment/test_sandbox_build.py new file mode 100644 index 00000000..c5f82012 --- /dev/null +++ b/Tools/Deployment/test_sandbox_build.py @@ -0,0 +1,41 @@ +from pathlib import Path +import subprocess +import tempfile +import unittest + +from sandbox_build import build_command, run_build + +class IsolatedBuildTests(unittest.TestCase): + def test_secret_free_namespaces_and_readonly_git(self): + with tempfile.TemporaryDirectory() as directory: + root=Path(directory);source=root/'source';source.mkdir();(source/'.git').mkdir() + command=build_command(['dotnet','publish','project'],source,root,root/'home') + for option in ('--clearenv','--unshare-all','--cap-drop','--new-session'): + self.assertIn(option,command) + self.assertIn('--ro-bind',command) + self.assertIn(str(source/'.git'),command) + self.assertNotIn('/etc/plotdirector',command) + self.assertNotIn('private.pem',' '.join(command)) + def test_arbitrary_commands_and_worktree_git_pointer_refused(self): + with tempfile.TemporaryDirectory() as directory: + source=Path(directory);(source/'.git').write_text('gitdir: /elsewhere') + for command in (['sh','-c','id'],['dotnet','publish','project']): + with self.assertRaises(ValueError):build_command(command,source,source,source) + def test_real_build_namespace_hides_home_and_protects_git(self): + if not Path('/usr/bin/bwrap').exists():self.skipTest('Linux Bubblewrap installation gate') + with tempfile.TemporaryDirectory() as directory: + root=Path(directory);source=root/'source';source.mkdir();(source/'.git').mkdir() + (source/'.git/config').write_text('fixture') + secret=root/'host-secret';secret.write_text('synthetic secret') + # Use same mount construction; substitute a local probe for dotnet, no build or deployment. + command=build_command(['dotnet','publish','fixture'],source,root/'output',root/'home') + (root/'output').mkdir();(root/'home').mkdir() + index=command.index('--') + probe=f"from pathlib import Path; assert not Path({str(secret)!r}).exists(); assert not Path('/home/nick/.ssh').exists(); Path({str(source/'ok')!r}).write_text('ok'); Path({str(source/'.git/config')!r}).write_text('forbidden')" + result=subprocess.run(command[:index+1]+['/usr/bin/python3','-c',probe],capture_output=True,text=True,timeout=15) + self.assertNotEqual(result.returncode,0) + self.assertIn('Read-only file system',result.stderr) + self.assertEqual((source/'ok').read_text(),'ok') + self.assertEqual((source/'.git/config').read_text(),'fixture') + +if __name__=='__main__':unittest.main()