From 22deb2b36cd37329334ac174e0250151b5048af6 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:03:06 +0100 Subject: [PATCH 1/9] =?UTF-8?q?=E2=9C=A8=20add=20release-versioned=20docke?= =?UTF-8?q?r=20tag=20aliases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Publishing now appends the verified csrun release to every SDK environment tag, such as 10.0.404-v0.2.2, so consumers can pin the image published for a given release. Convenience tags stay movable, and registry preflight rejects conflicting overwrites of versioned aliases. --- BuildAndPublish.psm1 | 49 ++++++++++++++++++++------- tools/oci.py | 70 ++++++++++++++++++++++++++++++++------- tools/release-images.py | 73 +++++++++++++++++++++++++++++++++-------- 3 files changed, 155 insertions(+), 37 deletions(-) diff --git a/BuildAndPublish.psm1 b/BuildAndPublish.psm1 index 34bebd5..0ea4afc 100644 --- a/BuildAndPublish.psm1 +++ b/BuildAndPublish.psm1 @@ -83,6 +83,27 @@ function Invoke-CsrunDocker([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "docker $($Arguments[0]) failed with exit $LASTEXITCODE." } } +function Resolve-CsrunImageTags([string[]] $ConvenienceTags, [string] $EngineVersion) { + if ($EngineVersion -and $EngineVersion -cnotmatch '^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$') { throw 'Engine release version must use vMAJOR.MINOR.PATCH.' } + $versioned = @(if ($EngineVersion) { $ConvenienceTags | ForEach-Object { "$_-$EngineVersion" } }) + $all = @($ConvenienceTags) + $versioned + if (@($all | Where-Object { $_.Length -gt 128 -or $_ -cnotmatch '^[A-Za-z0-9_][A-Za-z0-9_.-]*$' }).Count) { throw 'Invalid or overlong Docker tag.' } + if (@($all | Select-Object -Unique).Count -ne $all.Count) { throw 'Duplicate Docker tags.' } + [pscustomobject]@{ ConvenienceTags=@($ConvenienceTags); VersionedTags=$versioned; Tags=$all } +} + +function Get-CsrunPublishedEngine([string] $Repository, [string] $Destination, [string] $EngineVersion) { + if ($Repository -cnotmatch '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$') { throw 'Invalid engine repository.' } + $release = Invoke-RestMethod "https://api.github.com/repos/$Repository/releases/latest" + $asset = @($release.assets | Where-Object name -CEQ 'csrun.ps1') + if ($release.draft -or $release.prerelease -or $release.tag_name -cnotmatch '^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$' -or $asset.Count -ne 1 -or $asset[0].digest -cnotmatch '^sha256:[a-f0-9]{64}$') { throw 'Latest release has no verifiable csrun.ps1 asset.' } + if ($EngineVersion -and $EngineVersion -cne $release.tag_name) { throw 'Explicit engine version differs from the authoritative downloaded release.' } + Invoke-WebRequest "https://github.com/$Repository/releases/latest/download/csrun.ps1" -OutFile $Destination + $hash = (Get-FileHash $Destination -Algorithm SHA256).Hash.ToLowerInvariant() + if ("sha256:$hash" -cne $asset[0].digest -or (Get-Item $Destination).Length -ne $asset[0].size) { throw 'Latest engine asset changed or failed integrity validation.' } + [pscustomobject]@{ Release=$release; Hash=$hash } +} + function BuildAndPublish { [CmdletBinding(SupportsShouldProcess)] param( @@ -137,11 +158,12 @@ function BuildAndPublish { if ($version.FullVersion -cnotmatch '^(?:[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$' -or [version](($version.FullVersion -split '-')[0]) -lt [version]'10.0.0') { throw 'Supply exact .NET 10+ SDK versions.' } } $tags = @($publishTags, $majorMinorTags, $majorTags) - if (@($tags | Where-Object { $_.Length -gt 128 -or $_ -cnotmatch '^[A-Za-z0-9_][A-Za-z0-9_.-]*$' }).Count) { throw 'Invalid or overlong Docker tag.' } + $tagPlan = Resolve-CsrunImageTags $tags $EngineVersion if ($BuildOnly -and $Platform.Count -ne 1) { throw 'BuildOnly loads one architecture at a time; test each explicitly.' } $image = '{0}/{1}' -f $Repository.TrimEnd('/'), $ImageName if (@($Platform | Select-Object -Unique).Count -ne $Platform.Count) { throw 'Supply each target platform only once.' } - if ($EnginePath -and $EngineVersion -cnotmatch '^v\d+\.\d+\.\d+$') { throw 'Local engines require an explicit release version.' } + if ($EnginePath -and -not $EngineVersion) { throw 'Local engines require an explicit release version.' } + if ($PSBoundParameters.ContainsKey('EngineVersion') -and -not $EngineVersion) { throw 'Engine release version must not be empty.' } if (-not $BuildOnly -and $image -ceq 'docker.io/codebeltnet/csrun') { if ($Platform.Count -ne 2) { throw 'Codebelt production requires both native AMD64 and ARM64 verification.' } if ($EnginePath -or $EngineRepository -cne 'codebeltnet/csrun' -or $SourceRepository -cne 'https://github.com/codebeltnet/csrun') { throw 'Codebelt production images require the canonical source and verified latest published engine.' } @@ -157,11 +179,14 @@ function BuildAndPublish { MajorMinorTags = $majorMinorTags PublishTags = $publishTags BuildArgs = @() - Tags = @($tags | ForEach-Object { "${image}:$_" }) + Tags = @($tagPlan.Tags | ForEach-Object { "${image}:$_" }) + ConvenienceTags = @($tagPlan.ConvenienceTags | ForEach-Object { "${image}:$_" }) + VersionedTags = @($tagPlan.VersionedTags | ForEach-Object { "${image}:$_" }) + UnresolvedVersionedTags = @(if (-not $EngineVersion) { $tags | ForEach-Object { "${image}:$_-" } }) Platforms = $Platform DockerContexts = $DockerContext Builders = $Builder - EngineVersion = $null + EngineVersion = $EngineVersion EngineSha256 = $null BaseImage = $null MetadataFile = [IO.Path]::GetFullPath($MetadataFile) @@ -216,18 +241,18 @@ function BuildAndPublish { $hash = (Get-FileHash $engine -Algorithm SHA256).Hash.ToLowerInvariant() } else { # Resolve the moving reference once for all requested platforms. - if ($EngineRepository -cnotmatch '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$') { throw 'Invalid engine repository.' } - $release = Invoke-RestMethod "https://api.github.com/repos/$EngineRepository/releases/latest" - $asset = @($release.assets | Where-Object name -CEQ 'csrun.ps1') - if ($release.draft -or $release.tag_name -cnotmatch '^v\d+\.\d+\.\d+$' -or $asset.Count -ne 1 -or $asset[0].digest -cnotmatch '^sha256:[a-f0-9]{64}$') { throw 'Latest release has no verifiable csrun.ps1 asset.' } - Invoke-WebRequest $engineUrl -OutFile $engine - $hash = (Get-FileHash $engine -Algorithm SHA256).Hash.ToLowerInvariant() - if ("sha256:$hash" -cne $asset[0].digest -or (Get-Item $engine).Length -ne $asset[0].size) { throw 'Latest engine asset changed or failed integrity validation.' } + $publishedEngine = Get-CsrunPublishedEngine $EngineRepository $engine $EngineVersion + $release = $publishedEngine.Release + $hash = $publishedEngine.Hash } $tokens = $null; $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseFile($engine, [ref]$tokens, [ref]$errors) if ($errors.Count -or -not $ast.ParamBlock -or 'ManifestJson' -notin $ast.ParamBlock.Parameters.Name.VariablePath.UserPath) { throw 'Downloaded engine is not a valid manifest-capable PowerShell script.' } $invocation.EngineVersion = $release.tag_name + $tagPlan = Resolve-CsrunImageTags $tags $release.tag_name + $invocation.Tags = @($tagPlan.Tags | ForEach-Object { "${image}:$_" }) + $invocation.VersionedTags = @($tagPlan.VersionedTags | ForEach-Object { "${image}:$_" }) + $invocation.UnresolvedVersionedTags = @() $invocation.EngineSha256 = $hash foreach ($file in @('container-entrypoint.ps1', 'container-build.ps1')) { Copy-Item -LiteralPath (Join-Path $PSScriptRoot $file) -Destination $context } $revision = & git -C $PSScriptRoot rev-parse HEAD @@ -288,7 +313,7 @@ function BuildAndPublish { $platformArgs = if ($Platform.Count -eq 1) { @('--platform', ($Platform[0] -split '/')[1]) } else { @() } & python (Join-Path $PSScriptRoot 'tools/oci.py') merge $archiveRoot --version $release.tag_name --revision $revision --engine $hash --source $SourceRepository @platformArgs @archives if ($LASTEXITCODE -ne 0) { throw 'Cannot assemble native-verified artifacts.' } - & python (Join-Path $PSScriptRoot 'tools/oci.py') publish $archiveRoot --version $release.tag_name --revision $revision --engine $hash --source $SourceRepository @platformArgs --tags @($invocation.Tags) + & python (Join-Path $PSScriptRoot 'tools/oci.py') publish $archiveRoot --version $release.tag_name --revision $revision --engine $hash --source $SourceRepository @platformArgs --tags @($invocation.Tags) --versioned-tags @($invocation.VersionedTags) if ($LASTEXITCODE -ne 0) { throw 'Registry promotion or inspection failed.' } $invocation.Published = $true $invocation | Add-Member RegistryImages (Get-Content "$archiveRoot.published.json" -Raw | ConvertFrom-Json) diff --git a/tools/oci.py b/tools/oci.py index 4b137c7..8bb9e5e 100644 --- a/tools/oci.py +++ b/tools/oci.py @@ -45,10 +45,14 @@ def __init__(self, path): h.update(chunk) require(name == 'blobs/sha256/' + h.hexdigest(), 'Corrupt OCI blob') require(self.read('oci-layout') == {'imageLayoutVersion': '1.0.0'}, 'Invalid OCI layout') - self.index = self.read('index.json') + self.index_bytes = self.tar.extractfile(self.members['index.json']).read() + self.index = json.loads(self.index_bytes) # Buildx exports a layout index, which may wrap the actual image index. while len(self.index['manifests']) == 1 and self.index['manifests'][0]['mediaType'] == INDEX: - self.index = self.blob(self.index['manifests'][0]) + descriptor = self.index['manifests'][0] + self.blob(descriptor) # Validate the wrapper descriptor before unwrapping. + self.index_bytes = self.tar.extractfile(self.members['blobs/' + descriptor['digest'].replace(':', '/')]).read() + self.index = json.loads(self.index_bytes) require(self.index.get('schemaVersion') == 2 and self.index.get('mediaType') == INDEX, 'Expected an OCI image index') def read(self, name): @@ -188,7 +192,7 @@ def skopeo(arguments, *, capture=False): command.extend(['--volume', str(Path(auth).resolve()) + ':/auth.json:ro', '--env', 'REGISTRY_AUTH_FILE=/auth.json']) command.extend(['quay.io/skopeo/stable:v1.20.0', *converted]) if capture: - return subprocess.check_output(command) + return subprocess.check_output(command, stderr=subprocess.PIPE) subprocess.run(command, check=True) @@ -252,25 +256,64 @@ def merge(args): return 'sha256:' + digest -def publish(args): +def registry_digest(tag): + """Only an explicit registry missing-manifest response means absence.""" + try: + raw = skopeo(['inspect', '--raw', 'docker://' + tag], capture=True) + except subprocess.CalledProcessError as error: + message = (error.stderr or b'').decode(errors='replace') + if re.search(r'\b(?:manifest unknown|name unknown|MANIFEST_UNKNOWN|NAME_UNKNOWN)\b', message): + return None + raise + return 'sha256:' + hashlib.sha256(raw).hexdigest() + + +def preflight(args, *, require_versioned=False): check_seal(args.archive) archive = Archive(args.archive) archive.verify(args, [args.platform] if getattr(args, 'platform', None) else ['amd64', 'arm64']) - # Authentication is supplied by the caller, never embedded in the archive. - expected = {d['digest'] for d in archive.index['manifests']} - digests = set() - published = [] + require(re.fullmatch(r'v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)', args.version or ''), 'Invalid engine release identity') require(args.tags and len({t.rsplit(':', 1)[0] for t in args.tags}) == 1, 'SDK aliases must target one repository') for tag in args.tags: require(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]*:[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}', tag) and tag.rsplit(':', 1)[1] != 'latest', 'Invalid publishing destination') + versioned = getattr(args, 'versioned_tags', None) + legacy = getattr(args, 'legacy_convenience_only', False) and versioned == [] + require((versioned or legacy) and len(set(args.tags)) == len(args.tags) and len(set(versioned)) == len(versioned) + and set(versioned) < set(args.tags), 'Both unique tag families are required') + require(all(t.endswith('-' + args.version) for t in versioned), 'Versioned destination release mismatch') + digest = 'sha256:' + hashlib.sha256(archive.index_bytes).hexdigest() + if getattr(args, 'expected', None): + require(args.expected == digest, 'Saved OCI index digest mismatch') + for tag in versioned: + existing = registry_digest(tag) + require(existing == digest or (existing is None and not require_versioned), + f'Release-versioned tag conflict: {tag}; expected {digest}, found {existing}; refusing overwrite') + return archive, digest + + +def publish(args, *, family='all', before_convenience=None): + archive, expected_digest = preflight(args, require_versioned=family == 'convenience') + expected = {d['digest'] for d in archive.index['manifests']} + digests = set() + published = [] + convenience = [t for t in args.tags if t not in args.versioned_tags] + destinations = ([] if family == 'convenience' else list(args.versioned_tags)) + ([] if family == 'versioned' else convenience) # Skopeo's archive transport restores tar ownership, which fails rootless. with archive.layout() as layout: - for tag in args.tags: - skopeo(['copy', '--all', '--preserve-digests', 'oci:' + layout, 'docker://' + tag]) + for tag in destinations: + if tag in convenience and tag == convenience[0] and before_convenience: + before_convenience() + # Recheck immediately before each write. Registry policy is still needed + # to close the check/write race against external or concurrent writers. + existing = registry_digest(tag) if tag in args.versioned_tags else None + require(existing is None or existing == expected_digest, f'Release-versioned tag conflict: {tag}; refusing overwrite') + if existing is None: + skopeo(['copy', '--all', '--preserve-digests', 'oci:' + layout, 'docker://' + tag]) raw = skopeo(['inspect', '--raw', 'docker://' + tag], capture=True) index = json.loads(raw) require({d['digest'] for d in index['manifests']} == expected, 'Registry platform/attestation identities changed') digest = 'sha256:' + hashlib.sha256(raw).hexdigest() + require(digest == expected_digest, 'Registry OCI index digest changed') digests.add(digest) with tempfile.TemporaryDirectory() as temp: downloaded = str(Path(temp) / 'registry.tar') @@ -283,12 +326,12 @@ def publish(args): summary = os.environ.get('GITHUB_STEP_SUMMARY') if summary: with open(summary, 'a') as stream: - stream.write('\nPublished tags: ' + ', '.join(args.tags) + '\n\nDigest: ' + next(iter(digests)) + '\n') + stream.write('\nPublished tags: ' + ', '.join(destinations) + '\n\nDigest: ' + next(iter(digests)) + '\n') def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('command', choices=['verify', 'merge', 'publish', 'config', 'loaded-config', 'check-skopeo']) + parser.add_argument('command', choices=['verify', 'merge', 'publish', 'preflight', 'config', 'loaded-config', 'check-skopeo']) parser.add_argument('archive', nargs='?') parser.add_argument('--version') parser.add_argument('--revision') @@ -299,6 +342,7 @@ def main(): parser.add_argument('--image') parser.add_argument('--context') parser.add_argument('--tags', nargs='+') + parser.add_argument('--versioned-tags', nargs='+') parser.add_argument('inputs', nargs='*') args = parser.parse_intermixed_args() if args.command == 'check-skopeo': @@ -310,6 +354,8 @@ def main(): merge(args) elif args.command == 'publish': publish(args) + elif args.command == 'preflight': + preflight(args) else: archive = Archive(args.archive) if args.command == 'loaded-config': diff --git a/tools/release-images.py b/tools/release-images.py index 07d08a5..8c512eb 100644 --- a/tools/release-images.py +++ b/tools/release-images.py @@ -7,6 +7,7 @@ import shutil import subprocess import sys +import tempfile import urllib.request from types import SimpleNamespace import oci @@ -24,15 +25,29 @@ def identity(meta): return SimpleNamespace(version=meta['EngineVersion'], revision=meta['SourceCommit'], engine=meta['EngineSha256'], sdks=meta['SdkVersions']) +def validate_tags(meta): + # The PowerShell planner is the sole source of alias names, including in CD. + command = "Import-Module $env:CSRUN_MODULE -Force; BuildAndPublish -SdkVersion ($env:SDK_VERSIONS.Split(',')) -EngineVersion $env:ENGINE_VERSION -WhatIf -PassThru | ConvertTo-Json -Compress" + output = subprocess.check_output(['pwsh', '-NoProfile', '-Command', command], env={**os.environ, 'SDK_VERSIONS': ','.join(meta['SdkVersions']), 'ENGINE_VERSION': meta['EngineVersion'], 'CSRUN_MODULE': str(Path(__file__).resolve().parent.parent / 'BuildAndPublish.psm1')}, text=True) + plan = json.loads(output.strip().splitlines()[-1]) + if 'ConvenienceTags' not in meta and 'VersionedTags' not in meta: + # Historical records retain their original convenience-only contract. + # Recovery must never synthesize release aliases for older artifacts. + oci.require(plan['ConvenienceTags'] == meta['Tags'], 'Publishing aliases differ from historical version contract') + else: + oci.require(all(plan[k] == meta[k] for k in ('Tags', 'ConvenienceTags', 'VersionedTags')), 'Publishing aliases differ from version contract') + + def assemble(variant): root = Path('inputs') metadata = [json.loads(p.read_text(encoding='utf-8-sig')) for p in root.glob('*/csrun-image.json')] oci.require(len(metadata) == 2, 'Both native verification records required') first = dict(metadata[0]) for meta in metadata: - oci.require(meta['NativeVerified'] is True and all(meta[k] == first[k] for k in ('SdkVersions', 'EngineVersion', 'EngineSha256', 'SourceCommit', 'Tags')), 'Native verification identity mismatch') + oci.require(meta['NativeVerified'] is True and all(meta[k] == first[k] for k in ('SdkVersions', 'EngineVersion', 'EngineSha256', 'SourceCommit', 'Tags', 'ConvenienceTags', 'VersionedTags')), 'Native verification identity mismatch') oci.require({m['Platforms'][0] for m in metadata} == {'linux/amd64', 'linux/arm64'}, 'Both native CPUs required') oci.require(first['SourceCommit'] == os.environ['GITHUB_SHA'] and first['EngineVersion'] == os.environ['GITHUB_REF_NAME'], 'Release source mismatch') + validate_tags(first) Path('out').mkdir(exist_ok=True) archives = sorted(str(p) for p in root.glob('*/*.tar')) oci.require(len(archives) == 2, 'Exactly two native OCI inputs required') @@ -132,12 +147,8 @@ def restore(variant, versions=None): records = meta['Verification'] oci.require(len(records) == 2 and {r['Platforms'][0] for r in records} == {'linux/amd64', 'linux/arm64'}, 'Both native verifications required') for record in records: - oci.require(record['NativeVerified'] is True and all(record[k] == meta[k] for k in ('SdkVersions', 'EngineSha256', 'EngineVersion', 'SourceCommit', 'Tags')), 'Native result identity mismatch') - # Recompute aliases using the same module as the manual interface, without external resolution. - command = "Import-Module $env:CSRUN_MODULE -Force; $p = BuildAndPublish -SdkVersion ($env:SDK_VERSIONS.Split(',')) -WhatIf -PassThru; $p.Tags | ConvertTo-Json -Compress" - output = subprocess.check_output(['pwsh', '-NoProfile', '-Command', command], env={**os.environ, 'SDK_VERSIONS': ','.join(meta['SdkVersions']), 'CSRUN_MODULE': str(Path(__file__).resolve().parent.parent / 'BuildAndPublish.psm1')}, text=True) - tags = json.loads(output.strip().splitlines()[-1]) - oci.require(tags == meta['Tags'], 'Publishing aliases differ from version contract') + oci.require(record['NativeVerified'] is True and all(record.get(k) == meta.get(k) for k in ('SdkVersions', 'EngineSha256', 'EngineVersion', 'SourceCommit', 'Tags', 'ConvenienceTags', 'VersionedTags')), 'Native result identity mismatch') + validate_tags(meta) with open('out/image.tar', 'wb') as archive: for part in meta['Pieces']: oci.require(re.fullmatch(r'csrun-' + re.escape(variant) + r'\.oci\.part\d{3}', part['name']), 'Invalid piece identity') @@ -148,6 +159,8 @@ def restore(variant, versions=None): Path('out/part').unlink() oci.require(oci.checksum('out/image.tar') == meta['ArchiveSha256'], 'Reassembled archive checksum mismatch') oci.Archive('out/image.tar').verify(identity(meta), ['amd64', 'arm64']) + archive = oci.Archive('out/image.tar') + oci.require('sha256:' + hashlib.sha256(archive.index_bytes).hexdigest() == meta['OciIndexDigest'], 'Saved OCI index digest mismatch') oci.seal('out/image.tar') summary(meta) @@ -157,22 +170,56 @@ def summary(meta): if path: with open(path, 'a') as stream: stream.write(f"\nSDK image {meta['SdkVersions']}: [GitHub Release {meta['EngineVersion']}](https://github.com/codebeltnet/csrun/releases/tag/{meta['EngineVersion']}) at {meta['SourceCommit']}\n\ncsrun SHA256: {meta['EngineSha256']}\n\n") - stream.write(f"SDK aliases: {', '.join(meta['Tags'])}\n\nVerified OCI index: {meta.get('OciIndexDigest', 'platform build')}\n\n") + stream.write(f"Convenience aliases: {', '.join(meta.get('ConvenienceTags', meta['Tags']))}\n\nRelease-versioned aliases: {', '.join(meta.get('VersionedTags', []))}\n\nVerified OCI index: {meta.get('OciIndexDigest', 'platform build')}\n\n") for item in meta.get('Verification', [meta]): stream.write(f"- {item['Platforms']}: native runtime suite passed; SDK inventory {item['SdkVersions']}; image size {item['SizeBytes']} bytes\n") if item.get('OciArchiveBytes'): stream.write(f" OCI archive: {item['OciArchiveBytes']} bytes (compressed layers, manifests and attestations).\n") -def publish(): +def current_release(): resolved = json.loads(Path('resolved/identity.json').read_text()) latest = gh(f"repos/{os.environ['GITHUB_REPOSITORY']}/releases/latest") oci.require(latest['id'] == resolved['releaseId'] and latest['tag_name'] == resolved['tag'] and not latest['draft'], 'Latest release changed after verification; refusing stale SDK alias promotion') - meta = json.loads(Path('out/release.json').read_text()) + + +def publication_args(meta, archive): args = identity(meta) - args.archive = 'out/image.tar' + args.archive = str(archive) args.tags = meta['Tags'] - oci.publish(args) + args.versioned_tags = meta.get('VersionedTags', []) + args.legacy_convenience_only = 'ConvenienceTags' not in meta and 'VersionedTags' not in meta + args.expected = meta['OciIndexDigest'] + return args + + +def publish(): + current_release() + meta = json.loads(Path('out/release.json').read_text()) + validate_tags(meta) + oci.publish(publication_args(meta, 'out/image.tar'), before_convenience=current_release) + + +def publish_all(): + """Preflight every variant, publish all stable names, then move convenience names.""" + current_release() + with tempfile.TemporaryDirectory(prefix='csrun-promotion-', dir='.') as temp: + variants = [] + for variant in ('10', '11', '10-11'): + restore(variant) + destination = Path(temp) / variant + Path('out').rename(destination) + meta = json.loads((destination / 'release.json').read_text()) + variants.append(publication_args(meta, destination / 'image.tar')) + for args in variants: + oci.preflight(args) + for args in variants: + current_release() + if not args.legacy_convenience_only: + oci.publish(args, family='versioned') + for args in variants: + current_release() + oci.publish(args, family='convenience', before_convenience=current_release) if __name__ == '__main__': @@ -180,4 +227,4 @@ def publish(): if command in ('assemble', 'split', 'restore'): globals()[command](sys.argv[2]) else: - globals()[command]() + globals()[command.replace('-', '_')]() From 8bb17ebdcd0b7bc3c2d3243dccf65ae50966372f Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:03:06 +0100 Subject: [PATCH 2/9] =?UTF-8?q?=E2=9C=85=20add=20tests=20for=20release-ver?= =?UTF-8?q?sioned=20image=20publishing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cover the planner tag matrix, release identity validation, registry conflict and retry behavior, and all-variant preflight ordering so the alias contract is verified without registry writes. --- tests/BuildAndPublish.Tests.ps1 | 51 ++++++++ tests/oci.Tests.py | 204 ++++++++++++++++++++++++++++++-- 2 files changed, 248 insertions(+), 7 deletions(-) diff --git a/tests/BuildAndPublish.Tests.ps1 b/tests/BuildAndPublish.Tests.ps1 index 13fed0b..44f3e94 100644 --- a/tests/BuildAndPublish.Tests.ps1 +++ b/tests/BuildAndPublish.Tests.ps1 @@ -20,6 +20,30 @@ Test-Case 'SDK-specific tags and PassThru with WhatIf' { $actual = @($plan.Tags | ForEach-Object { ($_ -split ':')[-1] }) if (@(Compare-Object $actual $case.Tags).Count -or $plan.Published -or $plan.EngineVersion -or $plan.BaseImage) { throw 'Invalid dry-run plan, or WhatIf resolved external state.' } if ($plan.Repository -cne 'docker.io/codebeltnet/' -or $plan.Dockerfile -cne './csrun.Dockerfile') { throw 'Unexpected defaults.' } + if ($plan.VersionedTags.Count -ne 0 -or $plan.UnresolvedVersionedTags.Count -ne 3) { throw 'Missing unresolved release aliases.' } + $known = BuildAndPublish -SdkVersion $case.Versions -EngineVersion v0.2.2 -WhatIf -PassThru + $expected = @($case.Tags) + @($case.Tags | ForEach-Object { "$_-v0.2.2" }) + if (($known.Tags -join ',') -cne (($expected | ForEach-Object { "docker.io/codebeltnet/csrun:$_" }) -join ',') -or $known.VersionedTags.Count -ne 3 -or $known.ConvenienceTags.Count -ne 3 -or $known.UnresolvedVersionedTags.Count) { throw 'Release tagging matrix differs.' } + } +} +Test-Case 'release identities and Docker length limits are validated without side effects' { + foreach ($version in @('', '0.2.2','v01.2.3','v1.2.3-rc.1','latest','v1.2')) { + Assert-Throws { BuildAndPublish 10.0.404 -EngineVersion $version -WhatIf } 'Engine release' + } + Assert-Throws { BuildAndPublish 10.0.404 -EnginePath ./csrun.ps1 -WhatIf } 'explicit release' + $sdk = '11.0.100-' + ('a' * 119) + $null = BuildAndPublish $sdk -WhatIf -PassThru + Assert-Throws { BuildAndPublish $sdk -EngineVersion v0.2.2 -WhatIf } 'overlong' + & $module { + function Invoke-RestMethod { throw 'Network forbidden.' } + function Invoke-WebRequest { throw 'Network forbidden.' } + function docker { throw 'Docker forbidden.' } + function python { throw 'Python forbidden.' } + try { + $plan = BuildAndPublish 11.0.100-rc.1.26425.128 -EnginePath missing.ps1 -EngineVersion v0.2.2 -BuildOnly -Registry localhost:5000/fork -EngineRepository fork/csrun -WhatIf -PassThru + if ($plan.VersionedTags[0] -cne 'localhost:5000/fork/csrun:11.0.100-rc.1-v0.2.2') { throw 'Prerelease or custom destination changed.' } + $null = BuildAndPublish 10.0.404 -WhatIf -PassThru + } finally { Remove-Item Function:Invoke-RestMethod, Function:Invoke-WebRequest, Function:docker, Function:python } } } Test-Case 'reference prerelease normalization preserves exact SDK input' { @@ -107,5 +131,32 @@ Test-Case 'exact historical SDK lookup uses channel metadata without substitutio } finally { Remove-Item Function:Invoke-RestMethod } } } +Test-Case 'downloaded fork release is authoritative and explicit versions must match' { + & $module { + $destination = Join-Path ([IO.Path]::GetTempPath()) ('csrun-engine-test-' + [guid]::NewGuid().ToString('N')) + $script:release = @{id=123; draft=$false; prerelease=$false; tag_name='v1.2.3'; assets=@(@{name='csrun.ps1'; digest='sha256:6f5237ab16b004222196b68b22fbca3273d5803611518e1b3f2bcb303e0ab7637'; size=6})} + function Invoke-RestMethod { param($Uri) if ($Uri -cne 'https://api.github.com/repos/fork/csrun/releases/latest') { throw 'Unexpected repository.' }; $script:release } + function Invoke-WebRequest { param($Uri, $OutFile) if ($Uri -cne 'https://github.com/fork/csrun/releases/latest/download/csrun.ps1') { throw 'Unexpected download.' }; [IO.File]::WriteAllText($OutFile, 'engine') } + try { + # Use a fixture hash computed independently from the acquisition path. + $script:release.assets[0].digest = 'sha256:' + [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes('engine'))).ToLowerInvariant() + $actual = Get-CsrunPublishedEngine fork/csrun $destination '' + if ($actual.Release.tag_name -cne 'v1.2.3') { throw 'Lost authoritative engine identity.' } + $null = Get-CsrunPublishedEngine fork/csrun $destination v1.2.3 + Assert-Throws { Get-CsrunPublishedEngine fork/csrun $destination v1.2.4 } 'differs from the authoritative' + foreach ($tag in @('', 'v01.2.3', 'v1.2.3-rc.1')) { + $script:release.tag_name = $tag + Assert-Throws { Get-CsrunPublishedEngine fork/csrun $destination '' } 'verifiable' + } + $script:release.tag_name = 'v1.2.3' + $script:release.assets[0].digest = 'sha256:' + ('0' * 64) + Assert-Throws { Get-CsrunPublishedEngine fork/csrun $destination '' } 'integrity' + } finally { + Remove-Item Function:Invoke-RestMethod, Function:Invoke-WebRequest + if (Test-Path -LiteralPath $destination) { Remove-Item -LiteralPath $destination } + Remove-Variable release -Scope Script + } + } +} Write-Host "BuildAndPublish tests: $passed passed, $failed failed" exit ([int]($failed -gt 0)) diff --git a/tests/oci.Tests.py b/tests/oci.Tests.py index 40cc370..6078243 100644 --- a/tests/oci.Tests.py +++ b/tests/oci.Tests.py @@ -5,6 +5,7 @@ import json from pathlib import Path import sys +import subprocess import shutil import tarfile import tempfile @@ -44,7 +45,7 @@ def blob(value, media='application/vnd.oci.image.manifest.v1+json'): 'org.opencontainers.image.created': '2026-11-15T12:00:00Z', 'net.codebelt.csrun.engine.release': self.args.version, 'net.codebelt.csrun.engine.sha256': engine or self.args.engine, - 'net.codebelt.csrun.sdks': '11.0.100'}}}) + 'net.codebelt.csrun.sdks': ','.join(self.args.sdks)}}}) image = blob({'config': config, 'layers': []}) image['platform'] = {'os': 'linux', 'architecture': cpu} layers = [] @@ -54,7 +55,7 @@ def blob(value, media='application/vnd.oci.image.manifest.v1+json'): 'build-arg:ENGINE_VERSION': self.args.version, 'label:org.opencontainers.image.revision': self.args.revision, 'label:org.opencontainers.image.source': source, - 'label:net.codebelt.csrun.sdks': '11.0.100'}}}})]: + 'label:net.codebelt.csrun.sdks': ','.join(self.args.sdks)}}}})]: if predicate == missing: continue subjects = [] if subject is False else [{'digest': {'sha256': subject or image['digest'][7:]}}] @@ -158,7 +159,9 @@ def test_missing_native_platform_blocks_assembly(self): oci.merge(self.args) def test_release_assembly_split_and_recovery_reuse_the_tested_bytes(self): - tags = ['docker.io/codebeltnet/csrun:11.0.100', 'docker.io/codebeltnet/csrun:11.0', 'docker.io/codebeltnet/csrun:11'] + convenience = ['docker.io/codebeltnet/csrun:11.0.100', 'docker.io/codebeltnet/csrun:11.0', 'docker.io/codebeltnet/csrun:11'] + versioned = [t + '-v0.2.0' for t in convenience] + tags = convenience + versioned for cpu in ('amd64', 'arm64'): path, _, config = self.fixture(cpu) target = self.root / 'inputs' / cpu @@ -169,6 +172,7 @@ def test_release_assembly_split_and_recovery_reuse_the_tested_bytes(self): (target / 'csrun-image.json').write_text(json.dumps({ 'NativeVerified': True, 'SdkVersions': ['11.0.100'], 'EngineVersion': self.args.version, 'EngineSha256': self.args.engine, 'SourceCommit': self.args.revision, 'Tags': tags, + 'ConvenienceTags': convenience, 'VersionedTags': versioned, 'Platforms': ['linux/' + cpu], 'ConfigDigest': config['digest'], 'SizeBytes': 1234})) with contextlib.chdir(self.root), patch.dict('os.environ', { 'GITHUB_SHA': self.args.revision, 'GITHUB_REF_NAME': self.args.version, @@ -190,7 +194,7 @@ def get_run(endpoint): return {**run, 'run_attempt': 2, 'conclusion': 'failure'} self.fail('Unexpected GitHub endpoint: ' + endpoint) - with patch.object(release_images, 'gh', side_effect=get_run), patch.object(release_images.subprocess, 'check_output', return_value=json.dumps(tags)): + with patch.object(release_images, 'gh', side_effect=get_run): release_images.restore('11') for changes in ({'conclusion': 'failure'}, {'run_attempt': 2}, {'head_sha': 'c' * 40}, {'event': 'workflow_dispatch'}, {'path': '.github/workflows/other.yml'}, {'head_branch': 'main'}): with self.subTest(changes=changes), patch.object(release_images, 'gh', return_value={**run, **changes}): @@ -216,13 +220,18 @@ def test_publish_uses_owner_independent_layout_and_preserves_verified_bytes(self self.args.archive = str(self.root / 'combined.tar') self.args.inputs = [str(amd), str(arm)] self.args.tags = ['docker.io/fork/csrun:11.0.100', 'docker.io/fork/csrun:11'] + self.args.versioned_tags = ['docker.io/fork/csrun:11.0.100-v0.2.0', 'docker.io/fork/csrun:11-v0.2.0'] + self.args.tags += self.args.versioned_tags oci.merge(self.args) original = oci.checksum(self.args.archive) archive = oci.Archive(self.args.archive) layouts = [] + present = set() def transfer(arguments, *, capture=False): if arguments[0] == 'inspect': + if arguments[-1] not in present: + raise subprocess.CalledProcessError(1, arguments, stderr=b'manifest unknown') return oci.encoded(archive.index) self.assertEqual(arguments[:3], ['copy', '--all', '--preserve-digests']) if arguments[3].startswith('docker://'): @@ -231,6 +240,7 @@ def transfer(arguments, *, capture=False): self.assertTrue(arguments[3].startswith('oci:')) layout = Path(arguments[3].removeprefix('oci:')) layouts.append(layout) + present.add(arguments[-1]) self.assertEqual({p.relative_to(layout).as_posix() for p in layout.rglob('*') if p.is_file()}, set(archive.members)) for name, member in archive.members.items(): with archive.tar.extractfile(member) as source: @@ -239,17 +249,19 @@ def transfer(arguments, *, capture=False): with patch.object(oci, 'skopeo', side_effect=transfer), patch.object(oci.tarfile.TarFile, 'chown', side_effect=PermissionError('ownership restoration forbidden')): oci.publish(self.args) archive.tar.close() - self.assertEqual(len(layouts), 2) + self.assertEqual(len(layouts), 4) self.assertEqual(layouts[0], layouts[1]) self.assertFalse(layouts[0].exists()) self.assertEqual(original, oci.checksum(self.args.archive)) - self.assertEqual(len(json.loads(Path(self.args.archive + '.published.json').read_text())), 2) + self.assertEqual(len(json.loads(Path(self.args.archive + '.published.json').read_text())), 4) def test_publish_removes_temporary_layout_after_transfer_failure(self): path, _, _ = self.fixture('amd64') self.args.archive = str(path) self.args.platform = 'amd64' self.args.tags = ['docker.io/fork/csrun:11'] + self.args.versioned_tags = ['docker.io/fork/csrun:11-v0.2.0'] + self.args.tags += self.args.versioned_tags layouts = [] def fail_transfer(arguments): @@ -257,14 +269,153 @@ def fail_transfer(arguments): self.assertTrue(layouts[-1].is_dir()) raise RuntimeError('transfer failed') - with patch.object(oci, 'skopeo', side_effect=fail_transfer): + with patch.object(oci, 'registry_digest', return_value=None), patch.object(oci, 'skopeo', side_effect=fail_transfer): with self.assertRaisesRegex(RuntimeError, 'transfer failed'): oci.publish(self.args) self.assertFalse(layouts[0].exists()) self.assertFalse(Path(str(path) + '.published.json').exists()) + def publication(self): + amd, _, _ = self.fixture('amd64') + arm, _, _ = self.fixture('arm64') + self.args.archive = str(self.root / 'combined.tar') + self.args.inputs = [str(amd), str(arm)] + self.args.tags = ['localhost:5000/fork/csrun:11.0.100', 'localhost:5000/fork/csrun:11'] + self.args.versioned_tags = ['localhost:5000/fork/csrun:11.0.100-v0.2.0', 'localhost:5000/fork/csrun:11-v0.2.0'] + self.args.tags += self.args.versioned_tags + digest = oci.merge(self.args) + archive = oci.Archive(self.args.archive) + raw = archive.index_bytes + archive.tar.close() + return digest, raw + + def test_conflicting_historical_alias_blocks_all_writes(self): + digest, _ = self.publication() + for conflict in self.args.versioned_tags: + with self.subTest(conflict=conflict), patch.object(oci, 'registry_digest', side_effect=lambda tag: 'sha256:' + 'c' * 64 if tag == conflict else digest), patch.object(oci, 'skopeo') as transfer: + with self.assertRaisesRegex(ValueError, 'Release-versioned tag conflict.*refusing overwrite'): + oci.publish(self.args) + transfer.assert_not_called() + + def test_absent_matching_and_partial_retry_publish_one_index(self): + digest, raw = self.publication() + present = {} + writes = [] + fail = [True] + + def transfer(arguments, *, capture=False): + if arguments[0] == 'inspect': + tag = arguments[-1].removeprefix('docker://') + if tag not in present: + raise subprocess.CalledProcessError(1, arguments, stderr=b'MANIFEST_UNKNOWN') + return present[tag] + if arguments[3].startswith('docker://'): + shutil.copyfile(self.args.archive, arguments[4].removeprefix('oci-archive:')) + else: + tag = arguments[-1].removeprefix('docker://') + if tag == self.args.versioned_tags[1] and fail[0]: + fail[0] = False + raise RuntimeError('interrupted publication') + present[tag] = raw + writes.append(tag) + + with patch.object(oci, 'skopeo', side_effect=transfer): + with self.assertRaisesRegex(RuntimeError, 'interrupted publication'): + oci.publish(self.args) + self.assertEqual(writes, self.args.versioned_tags[:1]) + oci.publish(self.args) + self.assertEqual(writes, self.args.versioned_tags + self.args.tags[:2]) + previous = list(writes) + def stale(): + raise ValueError('refusing stale SDK alias promotion') + with self.assertRaisesRegex(ValueError, 'refusing stale'): + oci.publish(self.args, before_convenience=stale) + self.assertEqual(writes, previous) + oci.publish(self.args) + self.assertEqual(writes.count(self.args.versioned_tags[0]), 1) + self.assertEqual(writes.count(self.args.versioned_tags[1]), 1) + records = json.loads(Path(self.args.archive + '.published.json').read_text()) + self.assertEqual({r['digest'] for r in records}, {digest}) + self.assertEqual({r['tag'] for r in records}, set(self.args.tags)) + + def test_concurrent_conflict_on_recheck_never_overwrites(self): + self.publication() + with patch.object(oci, 'registry_digest', side_effect=[None, None, 'sha256:' + 'c' * 64]), patch.object(oci, 'skopeo') as transfer: + with self.assertRaisesRegex(ValueError, 'refusing overwrite'): + oci.publish(self.args) + transfer.assert_not_called() + + def test_same_children_with_different_index_bytes_are_rejected(self): + _, raw = self.publication() + with patch.object(oci, 'registry_digest', return_value=None), patch.object(oci, 'skopeo', return_value=raw + b'\n'): + with self.assertRaisesRegex(ValueError, 'OCI index digest changed'): + oci.publish(self.args) + + def test_duplicate_or_missing_versioned_families_are_rejected(self): + self.publication() + for versioned in ([], self.args.versioned_tags * 2, ['localhost:5000/fork/csrun:11-v0.1.0']): + with self.subTest(versioned=versioned), patch.object(oci, 'skopeo') as transfer: + args = SimpleNamespace(**{**vars(self.args), 'versioned_tags': versioned}) + with self.assertRaises(ValueError): + oci.publish(args) + transfer.assert_not_called() + + def test_convenience_phase_requires_all_versioned_aliases_to_exist(self): + self.publication() + with patch.object(oci, 'registry_digest', return_value=None), patch.object(oci, 'skopeo') as transfer: + with self.assertRaisesRegex(ValueError, 'refusing overwrite'): + oci.publish(self.args, family='convenience') + transfer.assert_not_called() + + def test_historical_recovery_keeps_original_convenience_only_contract(self): + _, raw = self.publication() + self.args.tags = self.args.tags[:2] + self.args.versioned_tags = [] + self.args.legacy_convenience_only = True + writes = [] + def transfer(arguments, *, capture=False): + if arguments[0] == 'inspect': + return raw + if arguments[3].startswith('docker://'): + shutil.copyfile(self.args.archive, arguments[4].removeprefix('oci-archive:')) + else: + writes.append(arguments[-1].removeprefix('docker://')) + with patch.object(oci, 'skopeo', side_effect=transfer): + oci.publish(self.args) + self.assertEqual(writes, self.args.tags) + + def test_all_six_aliases_share_exact_index_for_each_sdk_variant(self): + for sdks, aliases in ((['10.0.404'], ['10.0.404', '10.0', '10']), + (['11.0.100'], ['11.0.100', '11.0', '11']), + (['10.0.404', '11.0.100'], ['10.0.404-11.0.100', '10.0-11.0', '10-11'])): + with self.subTest(sdks=sdks): + self.args.sdks = sdks + digest, raw = self.publication() + convenience = ['registry.example/fork/csrun:' + tag for tag in aliases] + self.args.versioned_tags = [tag + '-v0.2.0' for tag in convenience] + self.args.tags = convenience + self.args.versioned_tags + def transfer(arguments, *, capture=False): + if arguments[0] == 'inspect': + return raw + if arguments[3].startswith('docker://'): + shutil.copyfile(self.args.archive, arguments[4].removeprefix('oci-archive:')) + with patch.object(oci, 'registry_digest', return_value=None), patch.object(oci, 'skopeo', side_effect=transfer): + oci.publish(self.args) + records = json.loads(Path(self.args.archive + '.published.json').read_text()) + self.assertEqual(len(records), 6) + self.assertEqual({r['tag'] for r in records}, set(self.args.tags)) + self.assertEqual({r['digest'] for r in records}, {digest}) + class SkopeoTransportTests(unittest.TestCase): + def test_registry_absence_is_distinct_from_auth_network_and_server_failures(self): + for message in (b'manifest unknown', b'MANIFEST_UNKNOWN', b'name unknown'): + with patch.object(oci, 'skopeo', side_effect=subprocess.CalledProcessError(1, 'inspect', stderr=message)): + self.assertIsNone(oci.registry_digest('registry/image:11')) + for message in (b'unauthorized', b'connection refused', b'500 Internal Server Error', b'404 proxy not found'): + with patch.object(oci, 'skopeo', side_effect=subprocess.CalledProcessError(1, 'inspect', stderr=message)): + with self.assertRaises(subprocess.CalledProcessError): + oci.registry_digest('registry/image:11') def test_local_container_mounts_oci_layout_directory(self): with patch.dict('os.environ', {'DOCKER_HOST': 'unix:///var/run/docker.sock'}, clear=True), patch.object(oci.shutil, 'which', return_value=None), patch.object(oci.subprocess, 'run') as execute: oci.skopeo(['copy', '--all', '--preserve-digests', 'oci:client-layout', 'docker://registry/image:11']) @@ -303,6 +454,45 @@ def test_local_context_overrides_remote_host_and_keeps_container_fallback(self): class DeploymentIdentityTests(unittest.TestCase): + def test_saved_metadata_validates_both_families_using_explicit_release(self): + convenience = ['docker.io/codebeltnet/csrun:11.0.100', 'docker.io/codebeltnet/csrun:11.0', 'docker.io/codebeltnet/csrun:11'] + versioned = ['docker.io/codebeltnet/csrun:11.0.100-v0.2.2', 'docker.io/codebeltnet/csrun:11.0-v0.2.2', 'docker.io/codebeltnet/csrun:11-v0.2.2'] + meta = {'EngineVersion': 'v0.2.2', 'SdkVersions': ['11.0.100'], 'ConvenienceTags': convenience, 'VersionedTags': versioned, 'Tags': convenience + versioned} + release_images.validate_tags(meta) + for key in ('Tags', 'ConvenienceTags', 'VersionedTags'): + with self.subTest(key=key): + with self.assertRaisesRegex(ValueError, 'aliases differ'): + release_images.validate_tags({**meta, key: ['docker.io/codebeltnet/csrun:11-v0.1.0']}) + legacy = {k: v for k, v in meta.items() if k not in ('ConvenienceTags', 'VersionedTags')} + legacy['Tags'] = convenience + release_images.validate_tags(legacy) + self.assertNotIn('VersionedTags', legacy) + + def test_all_variants_preflight_before_any_publication(self): + with tempfile.TemporaryDirectory() as temp, contextlib.chdir(temp): + def restore(variant): + Path('out').mkdir() + Path('out/release.json').write_text(json.dumps({'variant': variant})) + def args(meta, path): + return SimpleNamespace(variant=meta['variant'], legacy_convenience_only=False) + events = [] + with patch.object(release_images, 'current_release'), patch.object(release_images, 'restore', side_effect=restore), patch.object(release_images, 'publication_args', side_effect=args), patch.object(oci, 'preflight', side_effect=lambda a: events.append(('preflight', a.variant))), patch.object(oci, 'publish', side_effect=lambda a, **kw: events.append((kw['family'], a.variant))): + release_images.publish_all() + self.assertEqual(events, [(phase, variant) for phase in ('preflight', 'versioned', 'convenience') for variant in ('10', '11', '10-11')]) + with patch.object(release_images, 'current_release'), patch.object(release_images, 'restore', side_effect=restore), patch.object(release_images, 'publication_args', side_effect=args), patch.object(oci, 'preflight', side_effect=[None, None, ValueError('conflict')]), patch.object(oci, 'publish') as publish: + with self.assertRaisesRegex(ValueError, 'conflict'): + release_images.publish_all() + publish.assert_not_called() + + def test_latest_changing_after_verification_blocks_promotion(self): + with tempfile.TemporaryDirectory() as temp, contextlib.chdir(temp): + Path('resolved').mkdir() + Path('resolved/identity.json').write_text(json.dumps({'releaseId': 1, 'tag': 'v0.2.0'})) + with patch.dict('os.environ', {'GITHUB_REPOSITORY': 'codebeltnet/csrun'}), patch.object(release_images, 'gh', return_value={'id': 2}), patch.object(oci, 'publish') as publish: + with self.assertRaisesRegex(ValueError, 'refusing stale'): + release_images.publish() + publish.assert_not_called() + def test_recovery_from_a_feature_branch_is_rejected(self): with patch.dict('os.environ', {'GITHUB_REPOSITORY': 'codebeltnet/csrun', 'RELEASE_TAG': 'v0.2.0', 'GITHUB_EVENT_NAME': 'workflow_dispatch', 'GITHUB_REF': 'refs/heads/feature'}): with self.assertRaisesRegex(ValueError, 'from main'): From ce3eb2d394331e84d003c3bf8d4960c2f3e2e15f Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:03:06 +0100 Subject: [PATCH 3/9] =?UTF-8?q?=F0=9F=91=B7=20publish=20all=20sdk=20varian?= =?UTF-8?q?ts=20in=20deploy=20workflow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The deploy job now calls publish-all, which preflights every SDK variant, publishes release-versioned aliases first, and moves convenience aliases only after all versioned aliases verify. --- .github/workflows/deploy.yml | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 03f65e4..3d5f15d 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -98,15 +98,4 @@ jobs: export REGISTRY_AUTH_FILE="$RUNNER_TEMP/csrun-auth.json" trap 'rm -f "$REGISTRY_AUTH_FILE"' EXIT printf '%s' "$DOCKERHUB_TOKEN" | skopeo login --authfile "$REGISTRY_AUTH_FILE" --username "$DOCKERHUB_USERNAME" --password-stdin docker.io - status=0 - for sdk in 10 11 10-11; do - echo "::group::Promote SDK $sdk" - if python tools/release-images.py restore "$sdk" && python tools/release-images.py publish; then - echo "SDK $sdk promotion succeeded." - else - echo "::error::SDK $sdk promotion failed." - status=1 - fi - echo "::endgroup::" - done - exit "$status" + python tools/release-images.py publish-all From f6fcd054ce895ed08ea03cc3072236843e5e097c Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:03:07 +0100 Subject: [PATCH 4/9] =?UTF-8?q?=F0=9F=93=9D=20document=20release-versioned?= =?UTF-8?q?=20docker=20image=20tags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Explain both tag families, digest pinning, the planner output, and manual recovery for the new release-versioned aliases, and record the local validation performed for this change. --- README.md | 69 ++++++++++++++++++++++++++++++++++-- docs/container-validation.md | 16 +++++++++ 2 files changed, 82 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 09a59db..f733c3b 100644 --- a/README.md +++ b/README.md @@ -144,18 +144,21 @@ BuildAndPublish 11.0.100 BuildAndPublish 10.0.404 11.0.100 ``` -| Exact SDK inputs | Published SDK environment tags | +| Exact SDK inputs | Convenience SDK environment tags | | --- | --- | | `10.0.404` | `10.0.404`, `10.0`, `10` | | `11.0.100` | `11.0.100`, `11.0`, `11` | | `10.0.404 11.0.100` | `10.0.404-11.0.100`, `10.0-11.0`, `10-11` | -No additional aliases are generated. Input order determines tag order. Full prerelease SDK versions remain exact installation inputs; release-build suffixes normalize for image tags using the Ubuntu Test Runner convention (for example, `11.0.100-rc.1.26425.128` becomes `11.0.100-rc.1`). Duplicate major, major.minor or normalized publish tags are rejected before Docker runs. Only supported .NET 10+ GA channels and the latest explicitly requested preview/go-live channel are accepted. Exact SDK availability is checked in Microsoft's per-channel release metadata, not inferred from the release index's latest patch. +Each convenience alias also receives a release-versioned alias by appending the verified csrun release, as described in [Docker image versioning](#docker-image-versioning). Input order determines tag order. Full prerelease SDK versions remain exact installation inputs; release-build suffixes normalize for image tags using the Ubuntu Test Runner convention (for example, `11.0.100-rc.1.26425.128` becomes `11.0.100-rc.1`). Duplicate major, major.minor or normalized publish tags and Docker tags exceeding 128 characters are rejected before Docker runs when the release version is known, or before image construction once it is resolved. Only supported .NET 10+ GA channels and the latest explicitly requested preview/go-live channel are accepted. Exact SDK availability is checked in Microsoft's per-channel release metadata, not inferred from the release index's latest patch. ```powershell # Plan only: no downloads, build, tests, or publication BuildAndPublish 10.0.404 11.0.100 -WhatIf -PassThru +# Include both tag families in the offline plan +BuildAndPublish 10.0.404 11.0.100 -EngineVersion v0.2.2 -WhatIf -PassThru + # Local build and full container validation, with no registry writes BuildAndPublish 10.0.404 -BuildOnly -PassThru -MetadataFile ./artifacts/10.json @@ -191,6 +194,66 @@ The newest requested SDK supplies the official Ubuntu base (verified Resolute or Single-SDK images minimize download and local storage for one environment. Combined images add the explicitly requested SDK, runtimes and targeting packs, offering both TFMs at a larger size. See [container validation results](docs/container-validation.md) for measured local sizes and validation limits. +### Docker image versioning + +Docker tags select an SDK environment and, optionally, a csrun release. These examples illustrate the naming contract; they do not assert that the tags are currently published: + +```powershell +# Convenience: follows the current published environment +docker pull codebeltnet/csrun:10 + +# Explicit csrun release: stable published image +docker pull codebeltnet/csrun:10-v0.2.2 + +# Exact SDK environment and csrun release +docker pull codebeltnet/csrun:10.0.404-v0.2.2 +``` + +For SDK inputs `10.0.404` and `11.0.100` and verified csrun release `v0.2.2`, the planner produces: + +| SDK environment | Convenience aliases | Release-versioned aliases | +|---|---|---| +| .NET 10 | `10.0.404`, `10.0`, `10` | `10.0.404-v0.2.2`, `10.0-v0.2.2`, `10-v0.2.2` | +| .NET 11 | `11.0.100`, `11.0`, `11` | `11.0.100-v0.2.2`, `11.0-v0.2.2`, `11-v0.2.2` | +| Combined | `10.0.404-11.0.100`, `10.0-11.0`, `10-11` | `10.0.404-11.0.100-v0.2.2`, `10.0-11.0-v0.2.2`, `10-11-v0.2.2` | + +Existing convenience aliases remain movable and select the most recently published csrun release for that environment. The actual SDK/runtime inventory is determined by the image. Pulling an update may introduce new functionality, changed defaults or execution behavior, breaking API or manifest-contract changes, SDK/runtime patches, and security or maintenance updates. Convenience tags carry no backward-compatibility promise. Previously downloaded images remain cached until explicitly updated or removed. + +Release-versioned aliases preserve the originally published image for that csrun release and SDK environment. They must never intentionally be reassigned to different content. They do not automatically receive future security fixes or SDK patches: upstream SDK changes require a new verified csrun release/image publication. All six aliases for an environment reference one verified OCI index, without rebuilding or changing layers. No standalone csrun-version tag, Docker `latest`, `stable`, `current`, or `preview` alias is added. + +| Version | Responsibility | +|---|---| +| csrun release | Tool behavior, compatibility, and release identity | +| .NET SDK | Compiler, runtime, and SDK environment | +| Manifest `schemaVersion` | JSON manifest structure and semantics | + +A release-specific Docker tag does not guarantee compatibility with every manifest schema; compatibility is defined by that csrun release's contract. Manifest schema version 1 and the native script reference `releases/latest/download/csrun.ps1` remain unchanged. The canonical native download is intentionally independent of Docker tagging. + +For byte-for-byte immutable selection, pin the published OCI index digest, for example `docker pull codebeltnet/csrun@sha256:`. A versioned tag is stable by publishing policy; its `sha256` digest identifies immutable content. + +Before publication, the shared OCI publisher inspects every release-versioned destination. An absent tag permits publication; an identical index digest is an idempotent retry; different content fails explicitly without overwriting. Authentication, connectivity and unrecognized registry failures fail closed. Versioned aliases are published and verified before convenience aliases move, including a preflight across all CI SDK variants. Each destination's raw index digest must match the saved artifact, and registry content is downloaded by digest to reverify child manifests, blobs, SBOM and provenance. Interrupted promotion can be retried with the original release artifacts; a stale release cannot update current convenience aliases. + +Client-side checks cannot make the registry check/write sequence atomic against concurrent or external writes. Enable registry-enforced immutability for release-versioned aliases wherever available, while leaving convenience aliases movable. [Docker Hub supports selective immutable-tag rules](https://docs.docker.com/docker-hub/repos/manage/hub-images/immutable-tags/), for example the RE2 pattern `^.+-v[0-9]+\.[0-9]+\.[0-9]+$`. This is an administrator setting; the workflows do not enable it. Restrict other writers as well. Post-push verification detects changes but cannot prevent an external writer from changing a mutable tag afterward. + +Fork maintainers use the same module and policy with their own registry, native contexts/builders and engine release repository. The default acquisition path derives the version from the verified published GitHub Release; an explicit `-EngineVersion` must match it. A local `-EnginePath` requires a validated `-EngineVersion vMAJOR.MINOR.PATCH`. Release-workflow builds use the authoritative Git tag. No Codebelt secrets, environments or CI artifacts are required for manual publishing. + +After a partial manual publication, retain the merged local OCI archive, its `.sha256` seal and the build metadata. Retry promotion of those exact bytes through the shared publisher instead of rebuilding the same release. For a two-platform archive, after confirming that this is still the latest published engine release in your configured engine repository (or the current release under your local-engine publishing policy): + +```powershell +$record = Get-Content ./artifacts/csrun-image.json -Raw | ConvertFrom-Json +python ./tools/oci.py publish ./artifacts/csrun.oci.tar ` + --version $record.EngineVersion --revision $record.SourceCommit ` + --engine $record.EngineSha256 --source $record.SourceRepository ` + --tags @($record.Tags) --versioned-tags @($record.VersionedTags) +if ($LASTEXITCODE -ne 0) { throw 'OCI recovery failed.' } +``` + +For a deliberately single-platform fork archive, also supply `--platform amd64` or `--platform arm64` to match the saved native result. The publisher revalidates the archive, seal and registry content; conflicting release-versioned tags still fail. A fresh build may produce a different index even with identical SDK inputs and therefore cannot replace an already published release-versioned image. + +`-WhatIf -PassThru` performs no network access or build. With an explicit engine version, `Tags` contains the three original convenience aliases followed by their three versioned aliases; `ConvenienceTags` and `VersionedTags` expose each family. Without an engine version, `Tags` retains the original convenience aliases, `VersionedTags` is empty, and `UnresolvedVersionedTags` shows `` placeholders. These placeholders are planning metadata, never publishable tags. + +This contract is additive. Historical release metadata retains its original convenience-only recovery policy; recovery does not invent historical versioned aliases. Never synthesize historical aliases from rebuilt content. Older saved OCI artifacts may permit a separately approved backfill only after their original identity and native verification evidence have been revalidated. + ## Validation and releases Run the dependency-free regression and integration suite: @@ -227,7 +290,7 @@ Release delivery follows these stages: 2. Assembly combines the unchanged AMD64/ARM64 manifests and attestations into one index per SDK environment. `codebeltnet/oci-artifact-verify@v1` checks the checksum, released source identity and multi-platform contract; csrun also validates all blobs, config labels, native result records, SBOM and provenance. No layers are rebuilt. 3. The established release job creates a **draft GitHub Release** containing the tested standalone engine, its checksum, release records and tested OCI artifacts. Archives are split into 1 GiB assets to stay below GitHub's per-file limit. Large Actions artifacts have one-day retention and are deleted after successful durable release attachment; deployment recovery uses GitHub Release assets. PR jobs upload small JSON records rather than image archives. Expect several GiB of temporary release-run storage across six native builds and assembly; assembly is divided by SDK variant to limit runner disk use. The draft-creation job alone has Actions write permission to delete these transient copies. 4. After review and explicit approval, publish the draft as the latest GitHub Release. `deploy.yml` resolves `releases/latest/download/csrun.ps1` **once**, verifies GitHub's asset digest/size and release ID, and requires that release to match the deployment request. It verifies tag ancestry on main, the successful authoritative tag release run, both native results and the saved image engine checksum. Consequently the image built before publication must contain byte-identical released engine content. No build occurs after publication or during deployment. -5. One approval of the separate `Production` environment job covers all three SDK variants (`10`, `11`, `10-11`). The job promotes them sequentially, attempts every variant even if one fails, and fails overall if any promotion fails. It promotes each existing OCI index to `docker.io/codebeltnet/csrun`, preserving all platform and attestation manifests. SDK patch, major.minor and major aliases reference the same content. There is **no Docker `latest` tag**, JCR or GHCR destination. Promotion fails if Skopeo cannot preserve child digests. CD inspects each registry index, downloads the published content by immutable digest, and validates its platforms, blobs, SBOM and provenance again. Workflow summaries contain tags, final index digest, both native results, exact SDK inventories, sizes, GitHub Release, source commit and engine checksum. +5. One approval of the separate `Production` environment job covers all three SDK variants (`10`, `11`, `10-11`). The job restores and preflights every variant before any publication, promotes and verifies all release-versioned aliases, then updates convenience aliases. It stops on failure; retry reuses the same saved bytes and accepts already matching versioned aliases. It promotes each existing OCI index to `docker.io/codebeltnet/csrun`, preserving all platform and attestation manifests. Both tag families reference the same content per SDK environment. There is **no Docker `latest` tag**, JCR or GHCR destination. Promotion fails if Skopeo cannot preserve index or child digests. CD inspects each registry index, downloads the published content by immutable digest, and validates its platforms, blobs, SBOM and provenance again. Workflow summaries contain both tag families, final index digest, both native results, exact SDK inventories, sizes, GitHub Release, source commit and engine checksum. Configure the `Production` GitHub environment with required reviewers and restricted deployment refs **before enabling publication**. Store a Docker Hub account name in `DOCKERHUB_USERNAME` and a repository-scoped access token in `DOCKERHUB_TOKEN` as environment secrets. Only the publishing step receives these secrets; authentication uses stdin and a temporary auth file removed on exit. PRs, release preparation and artifact verification never receive Docker Hub credentials. Repository environment protection and branch required checks are administrator settings; adding workflow YAML does not configure them. diff --git a/docs/container-validation.md b/docs/container-validation.md index 63e8969..601f81b 100644 --- a/docs/container-validation.md +++ b/docs/container-validation.md @@ -98,3 +98,19 @@ Native ARM64 is unavailable in the configured local Docker contexts. The unchang - No Docker Hub credentials or publication are used for this patch's local validation. The successful v0.2.0 deployment is historical evidence; v0.2.1 publication and registry inspection require separate authorization. BuildKit predicate validation does not introduce a separate signing authority. - Release preparation packages the candidate engine and native-tested platform content into durable, checksummed draft GitHub Release assets. After publication, CD resolves the canonical latest script once, requires its release identity and exact checksum to match, and promotes existing content. Deployment recovery never rebuilds or substitutes missing artifacts. - Preserve required branch checks and the `Production` approval controls. Only its publishing step receives Docker Hub credentials. See the README for the independent manual builder, native remote contexts, release asset storage and controlled recovery procedures. + +## Release-versioned alias validation (0.2.2 worktree, 2026-11-16) + +The additive publishing contract was validated locally without building or publishing images. The standalone `csrun.ps1` remains unchanged with SHA-256 `6609acb7ac9df5cbbbf70d58b3dbc40f2d242e34831f89c7b42d7069015db802`; manifest schema version 1 and container execution are unchanged. + +- PowerShell publishing contracts: **14 passed**, covering the exact single/combined SDK matrices, unchanged convenience aliases, appended release identities, prerelease normalization, collisions, invalid/missing identities, the Docker tag-length limit, offline dry runs, custom registries/native contexts/builders, and verified fork-owned engine acquisition with explicit version mismatch and checksum rejection. +- Python OCI/release contracts: **39 passed**, including real offline PowerShell planner integration, both tag families in saved release metadata, exact index identity for all six aliases in each SDK environment, preserved child manifests/SBOM/provenance, absent/matching/conflicting registry tags, fail-closed registry errors, immediate conflict rechecks, partial-publication retries, stale-release rejection, and all-variant preflight before any writes. Registry operations use isolated mocks; they are not evidence of real registry publication. +- Matching versioned digests skip upload and still undergo registry content verification. Conflicting versioned destinations fail before convenience writes; versioned aliases are rechecked immediately before attempted publication. A simulated interruption preserves completed versioned aliases and recovery publishes the remaining names against the original index. +- Historical convenience-only metadata remains recoverable without inventing release-versioned aliases. This migration path preserves saved tag lists and refuses stale releases under the existing latest-release policy. +- The release/container workflow files remain unchanged: six native jobs still run SDK variants `10`, `11`, and `10-11` on `ubuntu-26.04` and `ubuntu-26.04-arm`. Deployment still requires `Production` approval and promotes saved verified OCI artifacts. Its publishing orchestration now restores all variants, preflights every versioned destination, publishes/verifies versioned names across all variants, and only then moves convenience names. Any failure stops promotion; retry uses the original artifacts. + +No native AMD64/ARM64 builds, GitHub-hosted jobs, Docker Hub writes, release publication or historical backfills were performed for this change. The tests establish the publishing contract with fixtures; the retained native CI matrix and real registry checks must still run before a release is considered validated in production. + +Client-side checks cannot close the registry check/write race against concurrent or external writers. Configure selective registry-enforced immutability for release-versioned tags when available, retain movable convenience aliases, and restrict registry writers. The tooling does not change repository settings. Consumers requiring immutable selection should pin the published index digest. + +Read-only GitHub release inspection found OCI parts and release records for all three variants in both `v0.2.0` and `v0.2.1`. These historical records predate release-versioned aliases. A safe backfill may be possible from the original saved artifacts after revalidating their checksums, native records, release identity, attestations and destination conflicts; the large OCI parts were not downloaded/revalidated here. No backfill is approved or performed, and no historical release notes or image identities were modified. From b767208bfa916ec29e5d6b05efd610afe2d3d48c Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:03:07 +0100 Subject: [PATCH 5/9] =?UTF-8?q?=F0=9F=92=AC=20update=20changelog=20for=20v?= =?UTF-8?q?0.2.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Record the release-versioned Docker alias additions, publishing safeguards, and regression coverage in the 0.2.2 changelog entry. --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 639e890..7f4b4c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.2.2] - 2026-11-16 + +This patch release extends Docker publishing with release-versioned SDK aliases alongside the existing movable convenience tags. The standalone native PowerShell engine (`csrun.ps1`), manifest schema version 1 and container execution contract remain unchanged. + +### Added + +- Added a `-vMAJOR.MINOR.PATCH` alias for every existing SDK environment tag, derived from the verified engine release or explicit validated local-engine version, with separate convenience/versioned `-PassThru` metadata and unresolved offline planning placeholders, +- Added release-versioned destination preflight, matching-digest retries, explicit conflict rejection and exact OCI index digest verification to the shared manual/CI publisher; deployment preflights every SDK variant and verifies all versioned aliases before moving convenience aliases, preserving native checks, attestations, saved release artifacts and stale-release protection without additional builds, +- Added regression coverage and documentation for both tag families, fork publishing and manual recovery, compatibility/version axes, registry concurrency and selective immutability, digest pinning and security-update expectations; historical convenience-only recovery retains its saved aliases without synthesizing historical versioned tags. + ## [0.2.1] - 2026-11-16 This patch release cleans disposable container output by skipping a specific .NET SDK first-run workload integrity check, with the verification trade-off and opt-in restoration documented. The standalone native PowerShell engine (`csrun.ps1`) and manifest schema version 1 remain unchanged. @@ -48,6 +58,7 @@ This is the first release that introduces csrun as a standalone PowerShell scrip - Added pull request and tag release workflows that run the test suite on Windows with the .NET 11 SDK and a .NET 10 compatibility job, then create a draft GitHub release with the tested `csrun.ps1` attached, - Added the MIT license. +[0.2.2]: https://github.com/codebeltnet/csrun/compare/v0.2.1...v0.2.2 [0.2.1]: https://github.com/codebeltnet/csrun/compare/v0.2.0...v0.2.1 [0.2.0]: https://github.com/codebeltnet/csrun/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/codebeltnet/csrun/releases/tag/v0.1.0 From abed0b274be6bf29f3c007051145d74ac5245e9a Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:16:14 +0100 Subject: [PATCH 6/9] =?UTF-8?q?=F0=9F=90=9B=20pass=20assert=20helper=20int?= =?UTF-8?q?o=20publishing=20contract=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Calling the PowerShell test file from a parent script hid its Assert-Throws helper from the module session. The helper is now passed explicitly to the scriptblock, and a Python regression test runs the file through a parent script to match the CI invocation. --- tests/BuildAndPublish.Tests.ps1 | 9 +++++---- tests/oci.Tests.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/tests/BuildAndPublish.Tests.ps1 b/tests/BuildAndPublish.Tests.ps1 index 44f3e94..c201b95 100644 --- a/tests/BuildAndPublish.Tests.ps1 +++ b/tests/BuildAndPublish.Tests.ps1 @@ -133,6 +133,7 @@ Test-Case 'exact historical SDK lookup uses channel metadata without substitutio } Test-Case 'downloaded fork release is authoritative and explicit versions must match' { & $module { + param([scriptblock] $AssertThrows) $destination = Join-Path ([IO.Path]::GetTempPath()) ('csrun-engine-test-' + [guid]::NewGuid().ToString('N')) $script:release = @{id=123; draft=$false; prerelease=$false; tag_name='v1.2.3'; assets=@(@{name='csrun.ps1'; digest='sha256:6f5237ab16b004222196b68b22fbca3273d5803611518e1b3f2bcb303e0ab7637'; size=6})} function Invoke-RestMethod { param($Uri) if ($Uri -cne 'https://api.github.com/repos/fork/csrun/releases/latest') { throw 'Unexpected repository.' }; $script:release } @@ -143,20 +144,20 @@ Test-Case 'downloaded fork release is authoritative and explicit versions must m $actual = Get-CsrunPublishedEngine fork/csrun $destination '' if ($actual.Release.tag_name -cne 'v1.2.3') { throw 'Lost authoritative engine identity.' } $null = Get-CsrunPublishedEngine fork/csrun $destination v1.2.3 - Assert-Throws { Get-CsrunPublishedEngine fork/csrun $destination v1.2.4 } 'differs from the authoritative' + & $AssertThrows { Get-CsrunPublishedEngine fork/csrun $destination v1.2.4 } 'differs from the authoritative' foreach ($tag in @('', 'v01.2.3', 'v1.2.3-rc.1')) { $script:release.tag_name = $tag - Assert-Throws { Get-CsrunPublishedEngine fork/csrun $destination '' } 'verifiable' + & $AssertThrows { Get-CsrunPublishedEngine fork/csrun $destination '' } 'verifiable' } $script:release.tag_name = 'v1.2.3' $script:release.assets[0].digest = 'sha256:' + ('0' * 64) - Assert-Throws { Get-CsrunPublishedEngine fork/csrun $destination '' } 'integrity' + & $AssertThrows { Get-CsrunPublishedEngine fork/csrun $destination '' } 'integrity' } finally { Remove-Item Function:Invoke-RestMethod, Function:Invoke-WebRequest if (Test-Path -LiteralPath $destination) { Remove-Item -LiteralPath $destination } Remove-Variable release -Scope Script } - } + } ${function:Assert-Throws} } Write-Host "BuildAndPublish tests: $passed passed, $failed failed" exit ([int]($failed -gt 0)) diff --git a/tests/oci.Tests.py b/tests/oci.Tests.py index 6078243..7075bee 100644 --- a/tests/oci.Tests.py +++ b/tests/oci.Tests.py @@ -3,6 +3,7 @@ import contextlib import importlib.util import json +import os from pathlib import Path import sys import subprocess @@ -407,6 +408,15 @@ def transfer(arguments, *, capture=False): self.assertEqual({r['digest'] for r in records}, {digest}) +class PowerShellInvocationTests(unittest.TestCase): + def test_publishing_contract_from_parent_script_matches_ci_invocation(self): + script = Path(__file__).resolve().with_name('BuildAndPublish.Tests.ps1') + result = subprocess.run(['pwsh', '-NoProfile', '-Command', '& $env:CSRUN_PUBLISHING_TESTS'], + env={**os.environ, 'CSRUN_PUBLISHING_TESTS': str(script)}, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('14 passed, 0 failed', result.stdout) + + class SkopeoTransportTests(unittest.TestCase): def test_registry_absence_is_distinct_from_auth_network_and_server_failures(self): for message in (b'manifest unknown', b'MANIFEST_UNKNOWN', b'name unknown'): From c4b5827a32b8d473216c3e24c4b3215a17b0840d Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:16:19 +0100 Subject: [PATCH 7/9] =?UTF-8?q?=F0=9F=90=9B=20retain=20skopeo=20stderr=20i?= =?UTF-8?q?n=20unexpected=20registry=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Captured Skopeo failures dropped stderr from the exception text, hiding auth and network causes from callers and CLI tracebacks. Unexpected errors now keep their diagnostics, while missing-manifest responses are still treated as absent tags. --- tests/oci.Tests.py | 14 +++++++++++++- tools/oci.py | 14 +++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/tests/oci.Tests.py b/tests/oci.Tests.py index 7075bee..b1a302c 100644 --- a/tests/oci.Tests.py +++ b/tests/oci.Tests.py @@ -418,9 +418,21 @@ def test_publishing_contract_from_parent_script_matches_ci_invocation(self): class SkopeoTransportTests(unittest.TestCase): + def test_captured_registry_errors_keep_diagnostics_in_exception_text(self): + for operation in (lambda: oci.registry_digest('registry/image:11'), + lambda: oci.skopeo(['inspect', '--raw', 'docker://registry/image:11'], capture=True)): + for message in (b'unauthorized: login expired', b'denied: access forbidden', b'connection refused'): + error = subprocess.CalledProcessError(23, ['skopeo', 'inspect'], output=b'', stderr=message) + with self.subTest(message=message, operation=operation), patch.object(oci, 'check_skopeo', return_value=True), patch.object(oci.subprocess, 'check_output', side_effect=error): + with self.assertRaises(subprocess.CalledProcessError) as caught: + operation() + self.assertIn(message.decode(), str(caught.exception)) + self.assertEqual(caught.exception.returncode, 23) + self.assertEqual(caught.exception.stderr, message) + def test_registry_absence_is_distinct_from_auth_network_and_server_failures(self): for message in (b'manifest unknown', b'MANIFEST_UNKNOWN', b'name unknown'): - with patch.object(oci, 'skopeo', side_effect=subprocess.CalledProcessError(1, 'inspect', stderr=message)): + with patch.object(oci, 'check_skopeo', return_value=True), patch.object(oci.subprocess, 'check_output', side_effect=subprocess.CalledProcessError(1, 'inspect', stderr=message)): self.assertIsNone(oci.registry_digest('registry/image:11')) for message in (b'unauthorized', b'connection refused', b'500 Internal Server Error', b'404 proxy not found'): with patch.object(oci, 'skopeo', side_effect=subprocess.CalledProcessError(1, 'inspect', stderr=message)): diff --git a/tools/oci.py b/tools/oci.py index 8bb9e5e..cb21bfc 100644 --- a/tools/oci.py +++ b/tools/oci.py @@ -172,6 +172,13 @@ def check_skopeo(): return False +class SkopeoError(subprocess.CalledProcessError): + """Retain captured diagnostics in CLI tracebacks and caller error messages.""" + def __str__(self): + detail = (self.stderr or b'').decode(errors='replace').strip() + return super().__str__() + ('\n' + detail if detail else '') + + def skopeo(arguments, *, capture=False): """Use native Skopeo or a versioned utility container, including on Windows.""" if check_skopeo(): @@ -192,7 +199,12 @@ def skopeo(arguments, *, capture=False): command.extend(['--volume', str(Path(auth).resolve()) + ':/auth.json:ro', '--env', 'REGISTRY_AUTH_FILE=/auth.json']) command.extend(['quay.io/skopeo/stable:v1.20.0', *converted]) if capture: - return subprocess.check_output(command, stderr=subprocess.PIPE) + try: + return subprocess.check_output(command, stderr=subprocess.PIPE) + except subprocess.CalledProcessError as error: + # Missing-manifest responses can still be handled quietly by the + # caller; unexpected errors retain stderr when propagated. + raise SkopeoError(error.returncode, error.cmd, output=error.output, stderr=error.stderr) from None subprocess.run(command, check=True) From d99f29cdc6b74acdcb1d0e5292941f19e80f987a Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:16:23 +0100 Subject: [PATCH 8/9] =?UTF-8?q?=F0=9F=93=9D=20document=20pr=207=20containe?= =?UTF-8?q?r=20validation=20follow-up?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Record the PR #7 publishing-contract failure, the scope fix that resolves it, and the local validation results. The hosted native matrix has not been rerun for this follow-up, and no registry writes were performed. --- docs/container-validation.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/container-validation.md b/docs/container-validation.md index 601f81b..5a38b2e 100644 --- a/docs/container-validation.md +++ b/docs/container-validation.md @@ -114,3 +114,9 @@ No native AMD64/ARM64 builds, GitHub-hosted jobs, Docker Hub writes, release pub Client-side checks cannot close the registry check/write race against concurrent or external writers. Configure selective registry-enforced immutability for release-versioned tags when available, retain movable convenience aliases, and restrict registry writers. The tooling does not change repository settings. Consumers requiring immutable selection should pin the published index digest. Read-only GitHub release inspection found OCI parts and release records for all three variants in both `v0.2.0` and `v0.2.1`. These historical records predate release-versioned aliases. A safe backfill may be possible from the original saved artifacts after revalidating their checksums, native records, release identity, attestations and destination conflicts; the large OCI parts were not downloaded/revalidated here. No backfill is approved or performed, and no historical release notes or image identities were modified. + +### PR #7 regression follow-up + +The first PR run failed all six container jobs in the publishing-contract step: calling the PowerShell test file from a parent script hid its `Assert-Throws` helper from the module session. The earlier direct `pwsh -File` invocation did not expose that scope boundary. Passing the assertion scriptblock explicitly fixes the existing test without changing the CI invocation or runner matrix. The CI-style `pwsh -Command '& ./tests/BuildAndPublish.Tests.ps1'` now passes all **14 checks** on Windows and in a local native Linux AMD64 container, using the already installed `codebeltnet/csrun:10` image with networking disabled and a read-only source mount. + +The Python suite now passes **41 tests**, including a parent-script invocation regression and captured Skopeo error diagnostics for both registry preflight and post-push inspection. Unexpected captured errors retain stderr in their exception text, return code and subprocess error type; expected missing-manifest responses remain handled as absent tags. This validates the fixes locally; the hosted native matrix has not been rerun for this follow-up, and no registry writes were performed. From cd781023f27fd45a934ec9c74de8f2c9e2251800 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Wed, 18 Nov 2026 01:23:30 +0100 Subject: [PATCH 9/9] =?UTF-8?q?=F0=9F=93=9D=20update=20release=20date=20fo?= =?UTF-8?q?r=20v0.2.2=20in=20changelog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f4b4c9..0733983 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [0.2.2] - 2026-11-16 +## [0.2.2] - 2026-11-18 This patch release extends Docker publishing with release-versioned SDK aliases alongside the existing movable convenience tags. The standalone native PowerShell engine (`csrun.ps1`), manifest schema version 1 and container execution contract remain unchanged.