fix(cms-deploy): resolve base from scoped image ancestry

This commit is contained in:
DCCONSTRUCTIONS
2026-11-05 09:25:11 +03:00
parent bf3c2444ae
commit dc95821766
7 changed files with 328 additions and 57 deletions
+91 -23
View File
@@ -43136,12 +43136,47 @@ def cms_image_env(config):
return result
CMS_BUILD_BASE_ERROR_CODES = frozenset((
'cms-base-docker-timeout','cms-base-docker-unavailable','cms-base-docker-failed',
'cms-base-json-invalid','cms-base-output-limit','cms-base-image-mismatch',
'cms-base-parent-invalid','cms-base-parent-cycle','cms-base-parent-depth',
'cms-base-parent-layers','cms-base-parent-platform','cms-base-inventory-format',
'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous',
))
class CmsBuildBaseError(DeployError):
def __init__(self, code):
if code not in CMS_BUILD_BASE_ERROR_CODES:
raise ValueError('Unknown CMS base error code')
self.code=code
super().__init__(code)
def cms_base_docker_json(args, *, lines=False):
# CMS-only bounded read. Neither Docker stderr nor image Env is public.
try:
proc=subprocess.run([str(DOCKER),*args],capture_output=True,text=True,check=True,timeout=30)
except subprocess.TimeoutExpired:
raise CmsBuildBaseError('cms-base-docker-timeout') from None
except subprocess.CalledProcessError:
raise CmsBuildBaseError('cms-base-docker-failed') from None
except (OSError,UnicodeError):
raise CmsBuildBaseError('cms-base-docker-unavailable') from None
if len(proc.stdout)>8*1024*1024:
raise CmsBuildBaseError('cms-base-output-limit')
try:
return [json.loads(line) for line in proc.stdout.splitlines()] if lines else json.loads(proc.stdout)
except (ValueError,TypeError):
raise CmsBuildBaseError('cms-base-json-invalid') from None
def cms_inspect_image(identity):
if not re.fullmatch('sha256:[a-f0-9]{64}',str(identity)):
die('CMS immutable image identity is invalid')
rows=docker_json(['image','inspect',identity],'CMS immutable image')
if not isinstance(rows,list) or len(rows)!=1 or rows[0].get('Id')!=identity:
die('CMS immutable image inspection mismatch')
rows=cms_base_docker_json(['image','inspect',identity])
if not isinstance(rows,list) or len(rows)!=1 or not isinstance(rows[0],dict) or rows[0].get('Id')!=identity:
raise CmsBuildBaseError('cms-base-image-mismatch')
return rows[0]
@@ -43176,26 +43211,52 @@ def cms_node_base_matches(image, accepted):
def cms_resolve_build_base(runtime):
accepted=cms_inspect_image(runtime['imageId'])
proc=subprocess.run([str(DOCKER),'image','ls','--all','--quiet','--no-trunc'],
capture_output=True,text=True,check=True,timeout=30)
identities=sorted(set(proc.stdout.split()))
if not 1<=len(identities)<=2048 or any(not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in identities):
die('CMS local base image inventory is invalid or outside bounds')
matches=[]
for start in range(0,len(identities),64):
batch=identities[start:start+64]
images=docker_json(['image','inspect',*batch],'CMS local base inventory')
if not isinstance(images,list) or sorted(image.get('Id','') for image in images)!=batch:
die('CMS local base inventory changed during inspection')
for image in images:
# Legacy builds retain immutable Parent edges, including untagged bases.
# Follow this app's ancestry, never enumerate another component's cache.
current=accepted;seen={accepted['Id']};base=None
for depth in range(128):
parent=current.get('Parent')
if parent in ('',None):break
if not re.fullmatch('sha256:[a-f0-9]{64}',str(parent)):
raise CmsBuildBaseError('cms-base-parent-invalid')
if parent in seen:raise CmsBuildBaseError('cms-base-parent-cycle')
seen.add(parent);image=cms_inspect_image(parent)
layers=(image.get('RootFS') or {}).get('Layers')
child=(current.get('RootFS') or {}).get('Layers')
if ((image.get('RootFS') or {}).get('Type')!='layers'
or (current.get('RootFS') or {}).get('Type')!='layers'
or not isinstance(layers,list) or not isinstance(child,list)
or len(layers)>len(child) or child[:len(layers)]!=layers
or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in child)):
raise CmsBuildBaseError('cms-base-parent-layers')
if any(image.get(k)!=current.get(k) for k in ('Os','Architecture','Variant')):
raise CmsBuildBaseError('cms-base-parent-platform')
if cms_node_base_matches(image,accepted):
base=image;break
current=image
else:
raise CmsBuildBaseError('cms-base-parent-depth')
method='parent-chain'
if base is None:
# BuildKit/pulled images may have no Parent. Only inspect local official
# Node repository candidates; a tag never substitutes for ancestry proof.
rows=cms_base_docker_json(['image','ls','--all','--no-trunc',
'--filter','reference=node:*','--filter','reference=docker.io/library/node:*',
'--format','{{json .ID}}'],lines=True)
if len(rows)>256:raise CmsBuildBaseError('cms-base-inventory-limit')
if any(not isinstance(v,str) or not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in rows):
raise CmsBuildBaseError('cms-base-inventory-format')
matches=[]
for identity in sorted(set(rows)):
image=cms_inspect_image(identity)
if cms_node_base_matches(image,accepted):matches.append(image)
if len(matches)!=1:
die('CMS exact cached Node base is missing or ambiguous; no image pull or runtime change permitted')
base=matches[0]
if not matches:raise CmsBuildBaseError('cms-base-missing')
if len(matches)!=1:raise CmsBuildBaseError('cms-base-ambiguous')
base=matches[0];method='node-cache'
proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'],
'layersSha256':cms_audit_digest(base['RootFS']['Layers']),
'configSha256':cms_audit_digest(base['Config'])}
print('cms_build_base=accepted-image-ancestor;immutable-id='+base['Id']+';pull=never')
print('cms_build_base=accepted-image-ancestor;lookup='+method+';immutable-id='+base['Id']+';pull=never')
return proof
@@ -43968,6 +44029,16 @@ def cms_autodeploy_publish_status(result):
print('cms_autodeploy_tick=' + json.dumps(result, sort_keys=True))
def cms_autodeploy_error_status(error, policy_errors):
result={'status':'attention','errorType':type(error).__name__}
if isinstance(error,policy_errors):result['reason']=str(error)[:200]
# Only fixed CMS codes are added. External stderr/raw exception text stays
# private, even if a caller mutates the exception's message or code.
if isinstance(error,CmsBuildBaseError) and error.code in CMS_BUILD_BASE_ERROR_CODES:
result['reason']=error.code
return result
def cms_autodeploy_tick():
require_root()
ensure_layout()
@@ -43995,10 +44066,7 @@ def cms_autodeploy_tick():
try:
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
# can originate in external tools and is never copied to status.
if isinstance(error,errors):result['reason']=str(error)[:200]
result = cms_autodeploy_error_status(error,errors)
finally:
queue.close()
cms_autodeploy_publish_status(result)