Bind CMS qualification to its private registered runner identity
This commit is contained in:
@@ -28,3 +28,12 @@ build inputs, and preserved byte-for-byte across application release/rollback.
|
||||
The same partition handles old images containing these non-code streams; all
|
||||
application hashes are still exact. Bootstrap 001 failed during read-only plan,
|
||||
never entered apply, and is superseded rather than retried or overwritten.
|
||||
|
||||
After bootstrap 002 was accepted, Gitea assigned CMS runner ID 2. The initial
|
||||
copied source verifier still required Device Core's ID 1 and rejected successful
|
||||
run 39 before staging or deployment. Qualification now receives the ID from the
|
||||
root-private CMS `data/.runner` registration; it verifies exact runner name,
|
||||
repository, labels, job, steps, run identity and artifact ownership. Registration
|
||||
IDs are allocated by Gitea, so no fixed numeric fallback is permitted. This
|
||||
controller correction preserves the accepted bootstrap 002 receipt and private
|
||||
queue; it does not rerun bootstrap or re-register/restart the build daemon.
|
||||
|
||||
@@ -335,7 +335,7 @@ def cms_autodeploy_tick():
|
||||
cms_autodeploy_root_path(path)
|
||||
queue = Queue(queue_path,first_run_number=1)
|
||||
try:
|
||||
result = Controller(queue,Source(token),CmsAutodeployInstaller()).tick()
|
||||
result = Controller(queue,Source(token,runner_id=cms_ci_registered_runner_id()),CmsAutodeployInstaller()).tick()
|
||||
except Exception as error:
|
||||
result = {'status':'attention','errorType':type(error).__name__}
|
||||
# Policy errors contain only fixed codes/IDs; other exception text
|
||||
|
||||
@@ -307,3 +307,36 @@ def cms_ci_inventory_preserved(before):
|
||||
# A registered worker can create ephemeral CI job containers immediately.
|
||||
# Every preexisting container must retain its exact image and generation.
|
||||
return all(current.get(identity)==row for identity,row in before.items())
|
||||
|
||||
|
||||
def cms_ci_registered_runner_id():
|
||||
"""Bind qualification to this registered daemon, not Device Core's ID 1."""
|
||||
path = CMS_CI_ROOT / 'data' / '.runner'
|
||||
for parent in path.parents:
|
||||
if parent.is_symlink():die('CMS CI registration path contains a symlink')
|
||||
directory = path.parent.lstat()
|
||||
if (not stat.S_ISDIR(directory.st_mode) or directory.st_uid != 0
|
||||
or stat.S_IMODE(directory.st_mode) != 0o700):
|
||||
die('CMS CI registration directory must remain root-private')
|
||||
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_uid != 0 or info.st_nlink != 1
|
||||
or stat.S_IMODE(info.st_mode) != 0o600 or not 1 <= info.st_size <= 16384):
|
||||
die('CMS CI registered identity metadata rejected')
|
||||
raw = stream.read(16385)
|
||||
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('CMS CI registered identity changed while reading')
|
||||
try:
|
||||
value = json.loads(raw)
|
||||
identity = value.get('id')
|
||||
valid = (type(identity) is int and 0 < identity < 2**53
|
||||
and value.get('name') == 'synology-cms-build'
|
||||
and value.get('address', '').rstrip('/') == 'https://git.dcserve.ru'
|
||||
and isinstance(value.get('uuid'), str) and value['uuid']
|
||||
and isinstance(value.get('token'), str) and value['token'])
|
||||
except (ValueError, UnicodeError, AttributeError, TypeError):
|
||||
valid = False
|
||||
if not valid:die('CMS CI registered identity content rejected')
|
||||
return identity
|
||||
|
||||
@@ -72,9 +72,11 @@ class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
|
||||
|
||||
class GiteaSource:
|
||||
def __init__(self, token):
|
||||
def __init__(self, token, *, runner_id=None):
|
||||
require(isinstance(token, str) and re.fullmatch(r"[0-9a-f]{40}", token), "invalid_read_token")
|
||||
require(runner_id is None or positive(runner_id), "invalid_registered_runner_id")
|
||||
self._token = token
|
||||
self._runner_id = runner_id
|
||||
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
||||
|
||||
def request(self, suffix, *, archive=False):
|
||||
@@ -164,6 +166,7 @@ class GiteaSource:
|
||||
return check
|
||||
|
||||
def successful_run(self, row):
|
||||
require(positive(self._runner_id), "registered_runner_identity_required")
|
||||
run = self.run(row["id"])
|
||||
require((run["run_number"], run["head_sha"], run["run_attempt"]) ==
|
||||
(row["number"], row["sha"], row["attempt"]), "qualified_run_changed")
|
||||
@@ -175,7 +178,8 @@ class GiteaSource:
|
||||
require(job.get("run_id") == run["id"] and job.get("head_sha") == run["head_sha"]
|
||||
and job.get("head_branch") == "master" 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 type(job.get("runner_id")) is int and job["runner_id"] == self._runner_id
|
||||
and job.get("runner_name") == "synology-cms-build" 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] ==
|
||||
|
||||
@@ -23,7 +23,7 @@ def run(number=8, sha=B):
|
||||
|
||||
def job(r):
|
||||
return dict(id=8, run_id=r['id'], head_sha=r['head_sha'], head_branch='master', run_attempt=1,
|
||||
name='qualify', labels=['nodedc-node22-build'], runner_id=1, status='completed', conclusion='success',
|
||||
name='qualify', labels=['nodedc-node22-build'], runner_id=2, runner_name='synology-cms-build', 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')])
|
||||
|
||||
@@ -43,7 +43,7 @@ def packed(r, mutate=None, names=None):
|
||||
|
||||
|
||||
class SourceTests(unittest.TestCase):
|
||||
def setUp(self):self.s=GiteaSource('a'*40)
|
||||
def setUp(self):self.s=GiteaSource('a'*40,runner_id=2)
|
||||
|
||||
def test_no_redirects_or_unapproved_routes(self):
|
||||
with self.assertRaises(SourceError):NoRedirect().redirect_request(None,None,302,'',{},'https://other/')
|
||||
@@ -98,10 +98,20 @@ class SourceTests(unittest.TestCase):
|
||||
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')]:
|
||||
for field,value in [('runner_id',1),('runner_id',True),('runner_name','synology-device-core-build'),('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_qualification_requires_explicit_registered_runner(self):
|
||||
for invalid in (0, True, -1, '2', 2**53):
|
||||
with self.assertRaises(SourceError):GiteaSource('a'*40,runner_id=invalid)
|
||||
with self.assertRaisesRegex(SourceError, 'registered_runner_identity_required'):
|
||||
GiteaSource('a'*40).successful_run(dict(id=8,number=8,sha=B,attempt=1))
|
||||
# Registration numbers are allocated by Gitea, never fixed at 1 or 2.
|
||||
source=GiteaSource('a'*40,runner_id=17);j=job(run());j['runner_id']=17
|
||||
with mock.patch.object(source,'run',return_value=run()),mock.patch.object(source,'pages',return_value=[j]):
|
||||
self.assertEqual(source.successful_run(dict(id=8,number=8,sha=B,attempt=1)),run())
|
||||
|
||||
def test_ancestry_proves_both_edges_and_stable_main(self):
|
||||
graph={C:[B],B:[A],A:[]}
|
||||
def get(path):
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""The qualification runner is allocated at registration, never Device Core's ID."""
|
||||
from contextlib import ExitStack
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from test_runner import r
|
||||
|
||||
|
||||
class RegisteredRunnerTests(unittest.TestCase):
|
||||
def fixture(self, root):
|
||||
data=root/'data';data.mkdir(mode=0o700)
|
||||
registration=data/'.runner'
|
||||
value={'id':2,'name':'synology-cms-build','address':'https://git.dcserve.ru',
|
||||
'uuid':'fixture-uuid','token':'fixture-private-token'}
|
||||
registration.write_text(json.dumps(value));registration.chmod(0o600)
|
||||
return registration,value
|
||||
|
||||
def read(self, root, *, file_owner=0, directory_owner=0, links=None):
|
||||
# Local tests run without root. Only ownership is emulated; modes, file
|
||||
# descriptors, symlink protection and content reads use real temp files.
|
||||
original_lstat=Path.lstat;original_fstat=os.fstat
|
||||
def fields(value, **changes):
|
||||
result={name:getattr(value,name) for name in ('st_mode','st_uid','st_nlink','st_size','st_mtime_ns','st_ctime_ns')}
|
||||
return SimpleNamespace(**{**result,**changes})
|
||||
def lstat(path, *args, **kwargs):
|
||||
value=original_lstat(path,*args,**kwargs)
|
||||
return fields(value,st_uid=directory_owner) if path==root/'data' else value
|
||||
def fstat(fd):
|
||||
value=original_fstat(fd)
|
||||
return fields(value,st_uid=file_owner,st_nlink=value.st_nlink if links is None else links)
|
||||
with patch.object(r,'CMS_CI_ROOT',root),patch.object(Path,'lstat',lstat),patch.object(r.os,'fstat',fstat):
|
||||
return r.cms_ci_registered_runner_id()
|
||||
|
||||
def test_allocated_id_is_read_from_registered_private_identity(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d).resolve();p,value=self.fixture(root)
|
||||
for identity in (2,17,293):
|
||||
value['id']=identity;p.write_text(json.dumps(value))
|
||||
self.assertEqual(self.read(root),identity)
|
||||
|
||||
def test_identity_metadata_must_remain_private_and_single_link(self):
|
||||
for kwargs in ({'file_owner':501},{'directory_owner':501},{'links':2}):
|
||||
with self.subTest(kwargs=kwargs),tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d).resolve();self.fixture(root)
|
||||
with self.assertRaises(r.DeployError):self.read(root,**kwargs)
|
||||
for rel,mode in (('data',0o755),('data/.runner',0o644)):
|
||||
with self.subTest(path=rel),tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d).resolve();self.fixture(root);(root/rel).chmod(mode)
|
||||
with self.assertRaises(r.DeployError):self.read(root)
|
||||
|
||||
def test_other_daemon_or_origin_and_invalid_id_are_rejected(self):
|
||||
for key,value in (('id',True),('id',0),('id','2'),('id',2**53),('name','synology-device-core-build'),
|
||||
('address','https://other.example'),('uuid',''),('token','')):
|
||||
with self.subTest(key=key,value=value),tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d).resolve();p,identity=self.fixture(root)
|
||||
identity[key]=value;p.write_text(json.dumps(identity))
|
||||
with self.assertRaises(r.DeployError):self.read(root)
|
||||
|
||||
def test_registration_symlink_is_rejected_without_reading_target(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d).resolve();p,_=self.fixture(root)
|
||||
target=root/'other';p.rename(target);p.symlink_to(target)
|
||||
with self.assertRaises(OSError):self.read(root)
|
||||
|
||||
def test_registration_input_is_bounded_and_malformed_data_is_rejected(self):
|
||||
for data in ('x'*16385,'not JSON','[]'):
|
||||
with self.subTest(length=len(data)),tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d).resolve();p,_=self.fixture(root);p.write_text(data)
|
||||
with self.assertRaises(r.DeployError):self.read(root)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -43462,6 +43462,39 @@ def cms_ci_inventory_preserved(before):
|
||||
# Every preexisting container must retain its exact image and generation.
|
||||
return all(current.get(identity)==row for identity,row in before.items())
|
||||
|
||||
|
||||
def cms_ci_registered_runner_id():
|
||||
"""Bind qualification to this registered daemon, not Device Core's ID 1."""
|
||||
path = CMS_CI_ROOT / 'data' / '.runner'
|
||||
for parent in path.parents:
|
||||
if parent.is_symlink():die('CMS CI registration path contains a symlink')
|
||||
directory = path.parent.lstat()
|
||||
if (not stat.S_ISDIR(directory.st_mode) or directory.st_uid != 0
|
||||
or stat.S_IMODE(directory.st_mode) != 0o700):
|
||||
die('CMS CI registration directory must remain root-private')
|
||||
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_uid != 0 or info.st_nlink != 1
|
||||
or stat.S_IMODE(info.st_mode) != 0o600 or not 1 <= info.st_size <= 16384):
|
||||
die('CMS CI registered identity metadata rejected')
|
||||
raw = stream.read(16385)
|
||||
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('CMS CI registered identity changed while reading')
|
||||
try:
|
||||
value = json.loads(raw)
|
||||
identity = value.get('id')
|
||||
valid = (type(identity) is int and 0 < identity < 2**53
|
||||
and value.get('name') == 'synology-cms-build'
|
||||
and value.get('address', '').rstrip('/') == 'https://git.dcserve.ru'
|
||||
and isinstance(value.get('uuid'), str) and value['uuid']
|
||||
and isinstance(value.get('token'), str) and value['token'])
|
||||
except (ValueError, UnicodeError, AttributeError, TypeError):
|
||||
valid = False
|
||||
if not valid:die('CMS CI registered identity content rejected')
|
||||
return identity
|
||||
|
||||
# DC CMS outbound automatic deployment. All authority stays in this file.
|
||||
CMS_AUTODEPLOY_ID = 'dc-cms-autodeploy-v1-20261104-002'
|
||||
CMS_AUTODEPLOY_ENTRY = 'deployment/dc-cms-autodeploy-v1.json'
|
||||
@@ -43799,7 +43832,7 @@ def cms_autodeploy_tick():
|
||||
cms_autodeploy_root_path(path)
|
||||
queue = Queue(queue_path,first_run_number=1)
|
||||
try:
|
||||
result = Controller(queue,Source(token),CmsAutodeployInstaller()).tick()
|
||||
result = Controller(queue,Source(token,runner_id=cms_ci_registered_runner_id()),CmsAutodeployInstaller()).tick()
|
||||
except Exception as error:
|
||||
result = {'status':'attention','errorType':type(error).__name__}
|
||||
# Policy errors contain only fixed codes/IDs; other exception text
|
||||
@@ -44067,9 +44100,11 @@ def cms_autodeploy_library():
|
||||
|
||||
|
||||
class GiteaSource:
|
||||
def __init__(self, token):
|
||||
def __init__(self, token, *, runner_id=None):
|
||||
require(isinstance(token, str) and re.fullmatch(r"[0-9a-f]{40}", token), "invalid_read_token")
|
||||
require(runner_id is None or positive(runner_id), "invalid_registered_runner_id")
|
||||
self._token = token
|
||||
self._runner_id = runner_id
|
||||
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
||||
|
||||
def request(self, suffix, *, archive=False):
|
||||
@@ -44159,6 +44194,7 @@ def cms_autodeploy_library():
|
||||
return check
|
||||
|
||||
def successful_run(self, row):
|
||||
require(positive(self._runner_id), "registered_runner_identity_required")
|
||||
run = self.run(row["id"])
|
||||
require((run["run_number"], run["head_sha"], run["run_attempt"]) ==
|
||||
(row["number"], row["sha"], row["attempt"]), "qualified_run_changed")
|
||||
@@ -44170,7 +44206,8 @@ def cms_autodeploy_library():
|
||||
require(job.get("run_id") == run["id"] and job.get("head_sha") == run["head_sha"]
|
||||
and job.get("head_branch") == "master" 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 type(job.get("runner_id")) is int and job["runner_id"] == self._runner_id
|
||||
and job.get("runner_name") == "synology-cms-build" 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] ==
|
||||
|
||||
Reference in New Issue
Block a user