Add canonical outbound Device Core deployment controller

This commit is contained in:
Codex
2026-09-29 21:25:03 +03:00
parent d46ecc4cb1
commit f7416bc59a
11 changed files with 1757 additions and 18 deletions
File diff suppressed because it is too large Load Diff
@@ -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()
@@ -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'):
+68 -9
View File
@@ -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
@@ -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"
}
@@ -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)))
+54
View File
@@ -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']}
+25
View File
@@ -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)
+259
View File
@@ -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
@@ -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()
@@ -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()