diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..86aa73a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +* +!csrun.ps1 +!container-entrypoint.ps1 +!container-build.ps1 diff --git a/.github/actionlint.yml b/.github/actionlint.yml new file mode 100644 index 0000000..6f437f5 --- /dev/null +++ b/.github/actionlint.yml @@ -0,0 +1,6 @@ +# GitHub-hosted labels verified against the official runner reference. +# This supplements actionlint's label inventory; these are not self-hosted jobs. +self-hosted-runner: + labels: + - ubuntu-26.04 + - ubuntu-26.04-arm diff --git a/.github/workflows/container.yml b/.github/workflows/container.yml new file mode 100644 index 0000000..7590d27 --- /dev/null +++ b/.github/workflows/container.yml @@ -0,0 +1,81 @@ +name: Container validation + +on: + workflow_call: + +permissions: + contents: read + +jobs: + container: + name: Native ${{ matrix.arch.architecture }} SDK ${{ matrix.sdk }} + runs-on: ${{ matrix.arch.runner }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + sdk: ['10', '11', '10-11'] + arch: + - { architecture: amd64, runner: ubuntu-26.04 } + - { architecture: arm64, runner: ubuntu-26.04-arm } + steps: + - uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + - uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + - name: Install OCI transfer tool + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends skopeo + - name: Enable OCI exporter + run: docker buildx create --driver docker-container --use + - name: Validate OCI integrity and promotion contracts + run: python tests/oci.Tests.py + - name: Validate publishing contract + shell: pwsh + run: ./tests/BuildAndPublish.Tests.ps1 + - name: Build once and execute exported candidate on native CPU + shell: pwsh + env: + SDK_CHANNELS: ${{ matrix.sdk }} + TARGET_PLATFORM: linux/${{ matrix.arch.architecture }} + run: | + $ErrorActionPreference = 'Stop' + $installed = @(& dotnet --list-sdks) + if ($LASTEXITCODE -ne 0) { throw 'Unable to list installed SDKs.' } + $versions = foreach ($major in $env:SDK_CHANNELS.Split('-')) { + $sdk = $installed | ForEach-Object { + if ($_ -match "^($major\.0\.\d+)\s+\[") { $Matches[1] } + } | Sort-Object { [version]$_ } -Descending | Select-Object -First 1 + if (-not $sdk) { throw "Codebelt did not provide a .NET $major GA SDK." } + $sdk + } + $version = if ($env:GITHUB_REF_TYPE -eq 'tag') { $env:GITHUB_REF_NAME } else { 'v0.2.0' } + Import-Module ./BuildAndPublish.psm1 -Force + BuildAndPublish -SdkVersion $versions -Platform $env:TARGET_PLATFORM -EnginePath ./csrun.ps1 -EngineVersion $version -BuildOnly -PassThru | Format-List + - name: Preserve exact tested OCI content and native result + if: github.event_name == 'push' && github.ref_type == 'tag' + uses: actions/upload-artifact@v7 + with: + name: container-${{ matrix.sdk }}--${{ matrix.arch.architecture }} + path: artifacts/* + compression-level: 0 + if-no-files-found: error + retention-days: 1 + - name: Preserve PR validation metadata without large image transfers + if: github.event_name != 'push' || github.ref_type != 'tag' + uses: actions/upload-artifact@v7 + with: + name: container-metadata-${{ matrix.sdk }}--${{ matrix.arch.architecture }}-${{ github.run_attempt }} + path: artifacts/*.json + if-no-files-found: error + retention-days: 7 + quality: + name: Both native architectures and all SDK variants + if: always() + needs: [container] + runs-on: ubuntu-26.04 + steps: + - env: + RESULT: ${{ needs.container.result }} + run: test "$RESULT" = success diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..6b3ad0e --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,108 @@ +name: Deploy Docker Hub images + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: Published latest release to recover; existing verified artifacts only + required: true + type: string + +permissions: + contents: read + +concurrency: + group: csrun-production + cancel-in-progress: false + +jobs: + resolve: + name: Resolve latest published engine once + runs-on: ubuntu-26.04 + timeout-minutes: 60 + outputs: + sha: ${{ steps.resolve.outputs.sha }} + steps: + - uses: codebeltnet/git-checkout@v1 + with: + ref: main + - id: resolve + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ github.event.release.tag_name || inputs.tag }} + run: python tools/release-images.py resolve + - uses: actions/upload-artifact@v7 + with: + name: resolved-release + path: resolved/* + retention-days: 7 + if-no-files-found: error + + verify: + name: Validate saved SDK ${{ matrix.sdk }} release artifact + needs: resolve + runs-on: ubuntu-26.04 + timeout-minutes: 60 + permissions: + contents: read + actions: read + strategy: + fail-fast: false + matrix: + sdk: ['10', '11', '10-11'] + steps: + - uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ needs.resolve.outputs.sha }} + - uses: actions/download-artifact@v8 + with: + name: resolved-release + path: resolved + - name: Validate release run, native results, checksums and attestations + env: + GH_TOKEN: ${{ github.token }} + SDK_VARIANT: ${{ matrix.sdk }} + run: python tools/release-images.py restore "$SDK_VARIANT" + + publish: + name: Promote SDK ${{ matrix.sdk }} to Docker Hub + needs: [resolve, verify] + runs-on: ubuntu-26.04 + timeout-minutes: 60 + environment: Production + permissions: + contents: read + actions: read + strategy: + fail-fast: false + max-parallel: 1 + matrix: + sdk: ['10', '11', '10-11'] + steps: + - uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ needs.resolve.outputs.sha }} + - uses: actions/download-artifact@v8 + with: + name: resolved-release + path: resolved + - name: Restore exact verified release artifact + env: + GH_TOKEN: ${{ github.token }} + SDK_VARIANT: ${{ matrix.sdk }} + run: python tools/release-images.py restore "$SDK_VARIANT" + - name: Install OCI transfer tool + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends skopeo + - name: Authenticate, promote without rebuild and inspect registry content + env: + GH_TOKEN: ${{ github.token }} + DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + run: | + set -euo pipefail + 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 + python tools/release-images.py publish diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index b2777d9..6827438 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -13,9 +13,12 @@ concurrency: cancel-in-progress: true jobs: + containers: + uses: ./.github/workflows/container.yml + test: name: Windows .NET 11 integration tests - runs-on: windows-latest + runs-on: windows-2025 timeout-minutes: 20 steps: - name: Checkout @@ -46,7 +49,7 @@ jobs: compatibility: name: Windows .NET 10 compatibility - runs-on: windows-latest + runs-on: windows-2025 timeout-minutes: 10 steps: - name: Checkout @@ -67,3 +70,13 @@ jobs: } | Sort-Object { [version]$_ } -Descending | Select-Object -First 1 if (-not $sdk) { throw 'Codebelt did not provide a .NET 10 GA SDK.' } pwsh -NoProfile -File ./tests/csrun.Tests.ps1 -CompatibilityOnly -SdkVersion $sdk + + quality: + name: Required quality gate + if: always() + needs: [test, compatibility, containers] + runs-on: ubuntu-26.04 + steps: + - env: + RESULTS: ${{ toJSON(needs) }} + run: echo "$RESULTS" | jq -e 'all(.[]; .result == "success")' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7c34be5..d6159d5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,9 +12,12 @@ concurrency: cancel-in-progress: false jobs: + containers: + uses: ./.github/workflows/container.yml + test: name: Test tagged script - runs-on: windows-latest + runs-on: windows-2025 timeout-minutes: 20 steps: - name: Validate release version @@ -51,7 +54,7 @@ jobs: compatibility: name: Test tagged script on .NET 10 - runs-on: windows-latest + runs-on: windows-2025 timeout-minutes: 10 steps: - name: Checkout tagged commit @@ -73,20 +76,79 @@ jobs: if (-not $sdk) { throw 'Codebelt did not provide a .NET 10 GA SDK.' } pwsh -NoProfile -File ./tests/csrun.Tests.ps1 -CompatibilityOnly -SdkVersion $sdk + images: + name: Preserve verified SDK ${{ matrix.sdk }} index + timeout-minutes: 45 + needs: [test, compatibility, containers] + runs-on: ubuntu-26.04 + strategy: + fail-fast: false + matrix: + sdk: ['10', '11', '10-11'] + steps: + - uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + - uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + - uses: actions/download-artifact@v8 + with: + pattern: container-${{ matrix.sdk }}--* + path: inputs + - name: Assemble exact native-tested content + env: + SDK_VARIANT: ${{ matrix.sdk }} + run: python tools/release-images.py assemble "$SDK_VARIANT" + - id: identity + run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" + - uses: codebeltnet/oci-artifact-verify@v1 + with: + archive-path: ${{ github.workspace }}/out/image.tar + checksum-path: ${{ github.workspace }}/out/image.tar.sha256 + version: ${{ steps.identity.outputs.version }} + revision: ${{ github.sha }} + - name: Split release assets below GitHub's per-file limit + env: + SDK_VARIANT: ${{ matrix.sdk }} + run: python tools/release-images.py split "$SDK_VARIANT" + - uses: actions/upload-artifact@v7 + with: + name: release-image-${{ matrix.sdk }} + path: assets/* + compression-level: 0 + retention-days: 1 + if-no-files-found: error + release: name: Create draft release - needs: [test, compatibility] - runs-on: ubuntu-latest - timeout-minutes: 5 + needs: [test, compatibility, containers, images] + runs-on: ubuntu-26.04 + timeout-minutes: 15 permissions: - actions: read + actions: write contents: write env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} RELEASE_TAG: ${{ github.ref_name }} steps: + - uses: actions/download-artifact@v8 + with: + pattern: release-image-* + path: release + merge-multiple: true - name: Download tested script run: gh run download "$GITHUB_RUN_ID" --name "csrun-$RELEASE_TAG" --dir release - - name: Create draft with tested standalone asset - run: gh release create "$RELEASE_TAG" release/csrun.ps1 --verify-tag --draft --generate-notes --title "$RELEASE_TAG" + - name: Create draft with tested engine and OCI assets + run: | + cd release + sha256sum csrun.ps1 > csrun.ps1.sha256 + gh release create "$RELEASE_TAG" ./* --verify-tag --draft --generate-notes --title "$RELEASE_TAG" + - name: Remove transient CI copies after durable release attachment + continue-on-error: true + run: | + gh api "repos/$GH_REPO/actions/runs/$GITHUB_RUN_ID/artifacts?per_page=100" --jq '.artifacts[].id' | + while read -r artifact_id; do + gh api --method DELETE "repos/$GH_REPO/actions/artifacts/$artifact_id" + done diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..318d1ea --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/artifacts/ + +__pycache__/ diff --git a/AGENTS.md b/AGENTS.md index 999d021..6d42473 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,8 @@ - Reference actions and reusable workflows with floating version tags, not commit SHAs. - Use external actions only where the Codebelt ecosystem has no suitable equivalent. +- Use fixed `ubuntu-26.04` (AMD64) and `ubuntu-26.04-arm` (ARM64) runners for every Linux job. Never use `ubuntu-latest` or older Ubuntu runner labels. Keep Windows validation on `windows-2025`; runner upgrades require review. + ## .NET support policy - Use only .NET 10 and later SDKs, runtimes, and application/test target frameworks. Do not introduce .NET 8, .NET 9, or older execution targets. diff --git a/BuildAndPublish.psm1 b/BuildAndPublish.psm1 new file mode 100644 index 0000000..34bebd5 --- /dev/null +++ b/BuildAndPublish.psm1 @@ -0,0 +1,309 @@ +function Resolve-DotNetSdkTagSet { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string]$SdkVersion + ) + + $trimmedVersion = $SdkVersion.Trim() + $match = [regex]::Match($trimmedVersion, '^(?\d+)\.(?\d+)\.(?\d+)(?-.+)?$') + + if (-not $match.Success) { + throw "Unsupported .NET SDK version '$SdkVersion'. Expected forms like '10.0.404' or '11.0.100-rc.1.26425.128'." + } + + $major = $match.Groups['Major'].Value + $minor = $match.Groups['Minor'].Value + $feature = $match.Groups['Feature'].Value + $suffix = $match.Groups['Suffix'].Value + + $coreVersion = '{0}.{1}.{2}' -f $major, $minor, $feature + $publishTag = $trimmedVersion + + if ($suffix) { + $suffixSegments = $suffix.TrimStart('-').Split('.') + $hasBuildSuffix = $suffixSegments.Count -ge 4 -and + [regex]::IsMatch($suffixSegments[-1], '^\d+$') -and + [regex]::IsMatch($suffixSegments[-2], '^\d+$') + + if ($hasBuildSuffix) { + $publishTag = '{0}-{1}' -f $coreVersion, ($suffixSegments[0..($suffixSegments.Count - 3)] -join '.') + } + } + + [pscustomobject]@{ + FullVersion = $trimmedVersion + MajorTag = $major + MajorMinorTag = '{0}.{1}' -f $major, $minor + PublishTag = $publishTag + } +} + +function Assert-UniqueResolvedTags { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [object[]]$ResolvedVersion + ) + + $duplicateChecks = @{ + MajorTag = 'major' + MajorMinorTag = 'major.minor' + PublishTag = 'publish' + } + + foreach ($entry in $duplicateChecks.GetEnumerator()) { + $duplicates = $ResolvedVersion | + Group-Object -Property $entry.Key | + Where-Object Count -gt 1 | + Select-Object -ExpandProperty Name + + if ($duplicates) { + throw "Each SDK version must resolve to a unique $($entry.Value) tag. Duplicates: $($duplicates -join ', ')." + } + } +} + +function Get-CsrunSdkRelease($Version, $Index) { + $channel = ($Version -split '\.')[0..1] -join '.' + $entry = @($Index | Where-Object { $_.product -eq '.NET' -and $_.'channel-version' -ceq $channel }) + if ([version]$channel -lt [version]'10.0' -or $entry.Count -ne 1) { throw "Unsupported SDK channel '$channel'." } + $entry = $entry[0] + $supported = $entry.'release-type' -in @('lts', 'sts') -and $entry.'support-phase' -in @('active', 'maintenance') + $preview = @($Index | Where-Object { $_.'release-type' -in @('lts', 'sts') -and $_.'support-phase' -in @('preview', 'go-live') } | Sort-Object { [version]$_.'channel-version' } -Descending | Select-Object -First 1) + if (-not $supported -and -not ($preview.Count -eq 1 -and $preview[0].'channel-version' -ceq $channel)) { throw "SDK channel '$channel' is unsupported or EOL." } + $metadata = Invoke-RestMethod -Uri $entry.'releases.json' + $sdks = @($metadata.releases | ForEach-Object { $_.sdks } | Where-Object { $_.version -ceq $Version }) + if ($sdks.Count -lt 1) { throw "Exact SDK '$Version' is absent from Microsoft's channel metadata; no substitution is allowed." } + return $sdks[0] +} + +function Invoke-CsrunDocker([string[]] $Arguments) { + & docker @Arguments | Out-Host + if ($LASTEXITCODE -ne 0) { throw "docker $($Arguments[0]) failed with exit $LASTEXITCODE." } +} + +function BuildAndPublish { + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory, Position = 0, ValueFromRemainingArguments = $true)] + [string[]]$SdkVersion, + + [string]$ImageName = 'csrun', + + [Alias('Registry')][string]$Repository = 'docker.io/codebeltnet/', + + [string]$Dockerfile = './csrun.Dockerfile', + + [ValidateSet('linux/amd64', 'linux/arm64')][string[]]$Platform, + + [hashtable]$DockerContext = @{}, + + [hashtable]$Builder = @{}, + + [switch]$BuildOnly, + + [string]$EnginePath, + + [string]$EngineVersion, + + [string]$EngineRepository = 'codebeltnet/csrun', + + [string]$SourceRepository = 'https://github.com/codebeltnet/csrun', + + [string]$ArchivePath = './artifacts/csrun.oci.tar', + + [string]$MetadataFile = './artifacts/csrun-image.json', + + [switch]$PassThru + ) + + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $false + if (-not $Platform) { + $Platform = if ($BuildOnly) { @('linux/' + [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant().Replace('x64', 'amd64')) } else { @('linux/amd64', 'linux/arm64') } + } + $resolvedVersions = @(foreach ($version in $SdkVersion) { + Resolve-DotNetSdkTagSet -SdkVersion $version + }) + + Assert-UniqueResolvedTags -ResolvedVersion $resolvedVersions + + $majorTags = $resolvedVersions.MajorTag -join '-' + $majorMinorTags = $resolvedVersions.MajorMinorTag -join '-' + $publishTags = $resolvedVersions.PublishTag -join '-' + foreach ($version in $resolvedVersions) { + 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.' } + 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 (-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.' } + } + + $invocation = [pscustomobject]@{ + ImageName = $ImageName + Repository = $Repository + Dockerfile = $Dockerfile + SourceRepository = $SourceRepository + SdkVersions = @($resolvedVersions.FullVersion) + MajorTags = $majorTags + MajorMinorTags = $majorMinorTags + PublishTags = $publishTags + BuildArgs = @() + Tags = @($tags | ForEach-Object { "${image}:$_" }) + Platforms = $Platform + DockerContexts = $DockerContext + Builders = $Builder + EngineVersion = $null + EngineSha256 = $null + BaseImage = $null + MetadataFile = [IO.Path]::GetFullPath($MetadataFile) + Published = $false + ImageId = $null + SizeBytes = $null + ConfigDigest = $null + OciArchiveBytes = $null + } + + $targetImage = $invocation.Tags[0] + + $action = if ($BuildOnly) { 'Build and test local Docker image' } else { 'Build, natively test and publish Docker image' } + if ($PSCmdlet.ShouldProcess($targetImage, $action)) { + $dockerfilePath = (Resolve-Path -LiteralPath $Dockerfile).Path + if (-not $BuildOnly) { + $status = & git -C $PSScriptRoot status --porcelain + if ($LASTEXITCODE -ne 0 -or $status) { throw 'Publication requires a clean, reviewed source commit. Use BuildOnly for worktree validation.' } + } + foreach ($architecture in $Platform) { + $contextArgs = if ($DockerContext.ContainsKey($architecture)) { @('--context', [string]$DockerContext[$architecture]) } else { @() } + $daemon = & docker @contextArgs info --format '{{.OSType}}/{{.Architecture}}' + if ($LASTEXITCODE -ne 0) { throw "Cannot access native Docker host for $architecture. Configure -DockerContext and -Builder." } + $normalized = $daemon.Trim().Replace('x86_64', 'amd64').Replace('aarch64', 'arm64') + if ($normalized -cne $architecture) { throw "Native Docker host required for $architecture; got $normalized. Configure an explicit remote -DockerContext; emulation is insufficient." } + } + & python (Join-Path $PSScriptRoot 'tools/oci.py') check-skopeo + if ($LASTEXITCODE -ne 0) { throw 'Skopeo transport prerequisites failed. Remote utility Docker daemons require native Skopeo on the client.' } + $index = (Invoke-RestMethod 'https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json').'releases-index' + $sdks = @($resolvedVersions | ForEach-Object { Get-CsrunSdkRelease $_.FullVersion $index }) + $base = $resolvedVersions | Sort-Object { [version](($_.FullVersion -split '-')[0]) } -Descending | Select-Object -First 1 + $available = (Invoke-RestMethod 'https://mcr.microsoft.com/v2/dotnet/sdk/tags/list').tags + $baseTag = @('resolute', 'noble') | ForEach-Object { "$($base.PublishTag)-$_" } | Where-Object { $_ -cin $available } | Select-Object -First 1 + if (-not $baseTag) { throw "No verified Ubuntu SDK image for $($base.FullVersion)." } + $baseImage = "mcr.microsoft.com/dotnet/sdk:$baseTag" + $inspection = & docker buildx imagetools inspect $baseImage + if ($LASTEXITCODE -ne 0) { throw 'Unable to resolve base image digest.' } + $digest = [regex]::Match(($inspection -join "`n"), '(?m)^Digest:\s+(sha256:[a-f0-9]{64})\s*$') + if (-not $digest.Success) { throw 'Missing base image digest.' } + $invocation.BaseImage = "$baseImage@$($digest.Groups[1].Value)" + $context = Join-Path ([IO.Path]::GetTempPath()) ('csrun-image-' + [guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $context + try { + Copy-Item -LiteralPath $dockerfilePath -Destination (Join-Path $context 'csrun.Dockerfile') + $dockerfilePath = Join-Path $context 'csrun.Dockerfile' + $engine = Join-Path $context 'csrun.ps1' + $engineUrl = "https://github.com/$EngineRepository/releases/latest/download/csrun.ps1" + if ($EnginePath) { + Copy-Item -LiteralPath $EnginePath -Destination $engine + if ($SourceRepository -cne 'https://github.com/codebeltnet/csrun') { $engineUrl = 'file:csrun.ps1' } + $release = @{tag_name=$EngineVersion} + $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.' } + } + $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 + $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 + if ($LASTEXITCODE -ne 0) { throw 'Unable to identify packaging source commit.' } + $extra = @($sdks | Where-Object version -CNE $base.FullVersion | ForEach-Object { @{version=$_.version; files=@($_.files | Where-Object { $_.rid -in @('linux-x64', 'linux-arm64') -and $_.url.EndsWith('.tar.gz') })} }) + $buildArgs = @('--build-arg', "BASE_IMAGE=$($invocation.BaseImage)", '--build-arg', "SDK_ARTIFACTS_JSON=$(ConvertTo-Json -InputObject $extra -Depth 8 -Compress)", '--build-arg', "ENGINE_VERSION=$($invocation.EngineVersion)", '--build-arg', "ENGINE_SHA256=$hash", '--build-arg', "ENGINE_URL=$engineUrl", '--label', "org.opencontainers.image.version=$($invocation.EngineVersion)", '--label', "org.opencontainers.image.source=$SourceRepository", '--label', "org.opencontainers.image.revision=$revision") + $invocation.BuildArgs = @($buildArgs[1], $buildArgs[3], $buildArgs[5], $buildArgs[7]) + $null = New-Item -ItemType Directory -Force -Path (Split-Path $invocation.MetadataFile) + $archiveRoot = [IO.Path]::GetFullPath($ArchivePath) + $archives = @() + $verification = @() + foreach ($architecture in $Platform) { + $cpu = ($architecture -split '/')[1] + $contextArgs = if ($DockerContext.ContainsKey($architecture)) { @('--context', [string]$DockerContext[$architecture]) } else { @() } + $builderArgs = if ($Builder.ContainsKey($architecture)) { @('--builder', [string]$Builder[$architecture]) } else { @() } + $archive = "$archiveRoot.$cpu.tar" + $null = New-Item -ItemType Directory -Force -Path (Split-Path $archive) + $created = [DateTime]::UtcNow.ToString('o') + Invoke-CsrunDocker ($contextArgs + @('buildx', 'build') + $builderArgs + @('--output', "type=oci,name=$targetImage,dest=$archive", '--sbom=true', '--provenance=mode=max', '--platform', $architecture, '--file', $dockerfilePath, '--label', "org.opencontainers.image.created=$created", '--label', "net.codebelt.csrun.sdks=$($resolvedVersions.FullVersion -join ',')") + $buildArgs + @($context)) + & python (Join-Path $PSScriptRoot 'tools/oci.py') verify $archive --version $release.tag_name --revision $revision --engine $hash --source $SourceRepository --platform $cpu + if ($LASTEXITCODE -ne 0) { throw 'OCI verification failed.' } + $localImage = 'csrun-verify:' + $cpu + '-' + [guid]::NewGuid().ToString('N') + $loadArchive = Join-Path $context "image-$cpu.docker.tar" + if (Get-Command skopeo -ErrorAction SilentlyContinue) { + & skopeo copy --override-os linux --override-arch $cpu "oci-archive:$archive" "docker-archive:${loadArchive}:$localImage" + if ($LASTEXITCODE -ne 0) { throw 'Cannot load the exported OCI artifact for native testing.' } + } else { + Invoke-CsrunDocker @('run', '--rm', '--user', '0', '--volume', "$(Split-Path $archive):/oci:ro", '--volume', "${context}:/converted", 'quay.io/skopeo/stable:v1.20.0', 'copy', '--override-os', 'linux', '--override-arch', $cpu, "oci-archive:/oci/$(Split-Path $archive -Leaf)", "docker-archive:/converted/$(Split-Path $loadArchive -Leaf):$localImage") + } + Invoke-CsrunDocker ($contextArgs + @('load', '--input', $loadArchive)) + Remove-Item -LiteralPath $loadArchive -Force + & (Join-Path $PSScriptRoot 'tests/container.Tests.ps1') -Image $localImage -SdkVersion $resolvedVersions.FullVersion -Platform $architecture -EngineSha256 $hash -EngineUrl $engineUrl -RequireNative -DockerContext $(if ($DockerContext.ContainsKey($architecture)) { [string]$DockerContext[$architecture] } else { '' }) + if ($LASTEXITCODE -ne 0) { throw "Container tests failed on $architecture." } + $details = @(& docker @contextArgs image inspect $localImage | ConvertFrom-Json)[0] + if ($LASTEXITCODE -ne 0) { throw 'Unable to inspect tested image.' } + $verifyContextArgs = if ($DockerContext.ContainsKey($architecture)) { @('--context', [string]$DockerContext[$architecture]) } else { @() } + $configDigest = & python (Join-Path $PSScriptRoot 'tools/oci.py') loaded-config $archive --platform $cpu --image $localImage @verifyContextArgs + if ($LASTEXITCODE -ne 0) { throw 'Loaded image differs from exported OCI artifact.' } + $invocation.ConfigDigest = $configDigest + $invocation.ImageId = $details.Id + $invocation.SizeBytes = $details.Size + $invocation.OciArchiveBytes = (Get-Item -LiteralPath $archive).Length + $archives += $archive + $verification += [pscustomobject]@{Platform=$architecture; ImageId=$details.Id; ConfigDigest=$configDigest; SizeBytes=$details.Size; NativeVerified=$true} + } + $invocation | Add-Member Verification $verification + $invocation | Add-Member ArchivePaths $archives + $invocation | Add-Member SourceCommit $revision + $invocation | Add-Member NativeVerified $true + $invocation | ConvertTo-Json -Depth 8 | Set-Content $invocation.MetadataFile + if ($BuildOnly) { + foreach ($tag in $invocation.Tags) { Invoke-CsrunDocker ($contextArgs + @('tag', $localImage, $tag)) } + } else { + if (-not $EnginePath) { + $currentRelease = Invoke-RestMethod "https://api.github.com/repos/$EngineRepository/releases/latest" + if ($currentRelease.id -ne $release.id) { throw 'Latest engine release changed during native verification; refusing stale alias publication.' } + } + $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) + 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) + $invocation | ConvertTo-Json -Depth 10 | Set-Content $invocation.MetadataFile + } + } finally { + # Only remove the exact temporary context created by this invocation. + if ([IO.Path]::GetDirectoryName($context) -cne [IO.Path]::GetTempPath().TrimEnd([IO.Path]::DirectorySeparatorChar) -or [IO.Path]::GetFileName($context) -cnotmatch '^csrun-image-[a-f0-9]{32}$') { throw 'Unsafe build context cleanup path.' } + Remove-Item -LiteralPath $context -Recurse -Force + } + } + + if ($PassThru) { + return $invocation + } +} + +Export-ModuleMember -Function BuildAndPublish diff --git a/CHANGELOG.md b/CHANGELOG.md index 10f38d3..5b672f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ 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.0] - 2026-11-15 + +This minor release adds optional disposable Ubuntu container execution and SDK environment publishing, while the standalone native PowerShell engine (`csrun.ps1`) and manifest schema version 1 remain unchanged. + +### Added + +- Added `csrun.Dockerfile` and a UTF-8 stdin entry point, so a manifest piped to `docker run --rm -i` runs the bundled engine inside a Linux container with the selected .NET SDKs preinstalled, for console samples and xUnit v3 tests, +- Added the `BuildAndPublish` module, which resolves exact .NET SDK versions to environment tags, builds the container image, writes an OCI archive with image identity metadata, and publishes only when explicitly requested, +- Added Docker integration tests in `tests/container.Tests.ps1` that cover SDK inventories, stdin execution, exit codes, and hardened read-only execution, plus Ubuntu AMD64 and ARM64 container validation in CI, +- Added README and `docs/container-validation.md` documentation for container usage, isolation limits, and SDK environment publishing. + +### Changed + +- Changed the release workflow to attach the tested OCI image archives and a `csrun.ps1.sha256` checksum to the draft GitHub release, +- Changed the pull request workflow to add a required quality gate that fails unless the Windows and container jobs succeed, and to pin Windows jobs to `windows-2025`. + ## [0.1.0] - 2026-11-15 This is the first release that introduces csrun as a standalone PowerShell script for running complete C# console programs and xUnit v3 tests from a manifest, a source file, or inline source, with framework defaults resolved from Microsoft's official .NET release index. @@ -21,4 +37,5 @@ 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.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 diff --git a/README.md b/README.md index 12a9a19..37a5aa2 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,14 @@ # csrun -Run a complete C# console example or genuine xUnit v3 tests with one standalone PowerShell script. No clone, project creation, IDE, or global installation is required for readers. +Run a complete C# console example or genuine xUnit v3 tests with one command. Choose native PowerShell execution or a disposable Linux container; both consume manifest schema version 1 through the same csrun engine. -Requires PowerShell 7 and an installed .NET 10+ SDK with support for file-based applications and the requested target framework/runtime. The samples and integration suite use .NET SDK **11.0.100**, targeting **net11.0**. The runner never installs SDKs or retargets source. NuGet access is required for packages not already cached. +Native execution requires PowerShell 7 and an installed .NET 10+ SDK with support for file-based applications and the requested target framework/runtime. Container execution requires Docker with Linux containers, and supplies PowerShell and the explicitly selected SDKs inside the image. Docker Desktop on Windows works from PowerShell 7 without installing .NET on the host. Network access is required for Microsoft's release metadata and uncached NuGet dependencies. The runner never installs SDKs or retargets source. ## Copy & Run -The release URL below becomes usable after the maintainer publishes the first release in `codebeltnet/csrun`. - ```powershell -& ([scriptblock]::Create((irm 'https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1'))) -ManifestJson '{"schemaVersion":1,"mode":"console","framework":"net11.0","source":"System.Console.WriteLine(\"Hello from Codebelt!\");"}' +& ([scriptblock]::Create((irm 'https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1'))) -Source 'Console.WriteLine(42);' +$LASTEXITCODE ``` For longer source, use an inline JSON here-string in the same invocation: @@ -28,7 +27,53 @@ For longer source, use an inline JSON here-string in the same invocation: Executing remote code requires trusting **both the script publisher and the C# source**, including NuGet packages and their build assets. Everything runs with your current permissions. This is not a sandbox. Review the script before execution when appropriate. No other scripts are downloaded or executed by csrun. The scriptblock invocation supports parameters; `irm ... | iex` alone does not provide that interface. -## Local use +## Disposable container execution + +After the maintainer publishes the Docker images, pipe the same manifest directly to Docker. No clipboard operation, file, clone, volume mount, or profile customization is needed: + +The examples use PowerShell syntax; any shell that can write UTF-8 JSON to Docker's stdin can use the container path without host PowerShell. + +```powershell +'{"schemaVersion":1,"mode":"console","framework":"net10.0","source":"Console.WriteLine(42);"}' | docker run --rm -i codebeltnet/csrun:10 +$LASTEXITCODE # 0; C# prints 42 + +'{"schemaVersion":1,"mode":"test","framework":"net10.0","source":"using Xunit; public class SmokeTest { [Fact] public void Pass() => Assert.True(true); }"}' | docker run --rm -i codebeltnet/csrun:10 +$LASTEXITCODE # 0; one discovered, passing test +``` + +Use `-i` for stdin; a TTY (`-t`) is unnecessary. The entry point reads the complete UTF-8 JSON document, delegates to the bundled engine, streams its output, and preserves its exit status. Compilation failures are nonzero, failing assertions return MTP exit `2`, and no discovered tests return `8`. + +Docker pulls a missing image on the first invocation and subsequently reuses its local image cache. Use `docker pull codebeltnet/csrun:10` to explicitly update it. This does **not** create a persistent NuGet cache: each new container may restore packages again. Generated source, projects, package caches and build artifacts remain inside container-owned storage and disappear with `--rm`. No host directories, Docker socket, host credentials or host environment are passed automatically. + +SDK tags identify environments, not csrun versions. `:10` contains only its explicitly built .NET 10 SDK and associated runtimes; `:11` contains only .NET 11; `:10-11` contains both. Always specify a compatible manifest framework when using a single-SDK image. In particular, while .NET 10 is the highest supported GA LTS, an omitted framework selects `net10.0` even in `:11`, where it fails because the runtime is absent. The adapter never substitutes `net11.0`. A combined image normally selects the newest installed SDK and can execute either supported TFM with its installed runtime. + +Production Codebelt images bundle the verified [latest published release asset](https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1). Release preparation builds with the candidate script; deployment resolves the published asset once and requires its release identity and checksum to match the tested image. The standalone manual builder resolves the latest asset once for all architectures by default; forks can supply their own engine. The image contains the script and never downloads it at startup. The csrun release version, explicit SDK versions and manifest schema version remain independent. + +All SDK tags are mutable. An already cached image stays unchanged until pulled or removed. Use a published digest when an immutable identity is required: `docker run --rm -i codebeltnet/csrun@sha256:`. Inspect the engine identity and packaging revision with: + +```powershell +docker image inspect codebeltnet/csrun:10 --format '{{json .Config.Labels}}' +docker buildx imagetools inspect codebeltnet/csrun:10 +docker run --rm --entrypoint dotnet codebeltnet/csrun:10 --list-sdks +docker run --rm --entrypoint dotnet codebeltnet/csrun:10 --list-runtimes +``` + +The `net.codebelt.csrun.engine.release` and `net.codebelt.csrun.engine.sha256` labels identify the exact bundled asset. OCI `version` identifies that engine release; OCI `revision` identifies the packaging source commit. Published Buildx metadata records the registry digest; retain it with release notes for immutable consumers. + +### Isolation and writable paths + +The default user is Microsoft's unprivileged `app` user. The image uses `/tmp` for its working directory, home, PowerShell configuration, .NET user state, NuGet caches and temporary builds. A hardened invocation supplies executable writable temporary storage while protecting the root filesystem: + +```powershell +'{"schemaVersion":1,"mode":"console","framework":"net10.0","source":"Console.WriteLine(42);"}' | docker run --rm -i --read-only --tmpfs /tmp:rw,exec,nosuid,nodev,size=1g,mode=1777 --cap-drop=ALL --security-opt=no-new-privileges --cpus=2 --memory=2g --pids-limit=256 codebeltnet/csrun:10 +$LASTEXITCODE +``` + +The integration suite verifies console and genuine xUnit execution with these restrictions. Do not add `noexec` to build-artifact storage: compiled applications and tests must execute there. Adjust the limits for larger samples. Network remains enabled for metadata and NuGet. + +Docker provides meaningful isolation, but **does not guarantee safe execution of arbitrary hostile code**. Docker permissions, vulnerabilities, outbound network access and resource exhaustion still matter. This is not a secure public code-execution sandbox. Do not add privileged mode, host namespaces, Docker socket mounts, host credential forwarding or unnecessary host mounts. + +## Local native use ```powershell # Canonical manifest input @@ -77,6 +122,65 @@ The Codebelt example discovers one passing test and displays `started`, `2`, and Pinned package/TFM execution is distinct from downloading the latest script release. Complete reproduction also depends on the installed SDK/runtime, NuGet configuration and transitive dependencies, platform, and any external services used by the program. Test projects live outside the caller's directory and do not depend on its `dotnet test` runner selection; the selected `dotnet` SDK still respects applicable `global.json` selection. There is no implicit runtime roll-forward or SDK installation. +## Build and publish SDK environments + +The self-contained module requires PowerShell 7, Git and Docker with Buildx. It uses native Docker CLI argument arrays and requires no personal PowerShell modules. Run from the repository root. These commands deliberately **build, test and publish** to Docker Hub; run them only after publication approval and `docker login docker.io`: + +```powershell +Import-Module .\BuildAndPublish.psm1 -Force + +BuildAndPublish 10.0.404 +BuildAndPublish 11.0.100 +BuildAndPublish 10.0.404 11.0.100 +``` + +| Exact SDK inputs | Published 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. + +```powershell +# Plan only: no downloads, build, tests, or publication +BuildAndPublish 10.0.404 11.0.100 -WhatIf -PassThru + +# Local build and full container validation, with no registry writes +BuildAndPublish 10.0.404 -BuildOnly -PassThru -MetadataFile ./artifacts/10.json + +# Optional names/paths; Registry is an alias for the reference module's Repository +BuildAndPublish 10.0.404 -ImageName csrun -Registry docker.io/codebeltnet/ -Dockerfile ./csrun.Dockerfile -WhatIf +``` + +`-WhatIf -PassThru` reports SDK aliases without network access or side effects. `-BuildOnly` exports an OCI archive with BuildKit SBOM and provenance, loads that exact artifact for the native container suite, and records its config identity, size, SDK inventory and engine checksum. Use separate `-ArchivePath` and `-MetadataFile` paths when retaining several builds. Build-only defaults to the host CPU; specify a supported platform explicitly when using a remote native host. Cross-architecture execution fails rather than substituting emulation. + +The positional publishing commands build independently with local Docker/Buildx or explicitly configured remote builders. They do not call GitHub Actions, read CI-produced artifacts, use Codebelt credentials, or require the GitHub CLI. Publication defaults to both architectures; both native Docker hosts must be reachable before construction starts. A machine with only AMD64 support fails clearly for ARM64. To publish a deliberately single-architecture fork image, explicitly pass `-Platform linux/amd64`; this does not claim ARM64 support. `-BuildOnly` defaults to the host CPU and performs no registry writes. + +```powershell +# Configure ordinary Docker contexts/builders once for your own native hosts. +# Both named contexts below must already exist and point to the indicated CPUs. +$contexts = @{ 'linux/amd64' = 'native-amd64'; 'linux/arm64' = 'native-arm64' } +$builders = @{ 'linux/amd64' = 'builder-amd64'; 'linux/arm64' = 'builder-arm64' } +BuildAndPublish 10.0.404 11.0.100 -DockerContext $contexts -Builder $builders ` + -Registry docker.io/my-account/ -ImageName csrun + +# A fork can package its own reviewed engine without any Codebelt release asset. +BuildAndPublish 11.0.100 -DockerContext $contexts -Builder $builders ` + -Registry docker.io/my-account/ -EnginePath ./csrun.ps1 -EngineVersion v0.2.0 ` + -SourceRepository https://github.com/my-account/csrun +``` + +Local builds need PowerShell 7, Python 3.11+ (standard library only), Docker and an OCI-capable Buildx `docker-container` builder. Select a builder deliberately with `docker buildx create --name csrun-builder --driver docker-container --use`, set `BUILDX_BUILDER`, or supply the architecture-to-builder map above. `-DockerContext` selects each **runtime test host**, which must report the corresponding native CPU. A Buildx platform declaration alone never substitutes for this runtime check. Builds export once; native tests consume those exact exports; publishing merges and promotes the tested manifests without rebuilding. + +Skopeo performs OCI transport, either installed locally or in a versioned utility container launched through Docker. If the active utility Docker daemon uses SSH or TCP (including localhost TCP), install native Skopeo on the client: remote utility containers cannot bind-mount client archives or registry credentials. This prerequisite is checked before building. Remote runtime test hosts selected through `-DockerContext` can still use a local utility daemon. Its temporary Docker-format conversion for `docker load` preserves the original config and filesystem identities. Python checks the raw config exported by the test daemon; Docker's displayed image ID may instead be a manifest digest on containerd-backed installations. No utility socket or credentials enter the csrun product image. Publishing requires authentication to your chosen registry: use native `skopeo login` or supply `REGISTRY_AUTH_FILE` containing a scoped registry auth configuration for the utility container. Credentials never become build arguments or release artifacts. A clean reviewed checkout is required for publication. `-PassThru` returns the invocation, engine identity, native results, sizes and final registry digests. + +The default engine source remains the verified canonical latest Codebelt GitHub Release asset, resolved once per invocation. A fork can select `-EngineRepository owner/repository` for its own latest published engine, or explicitly supply its local engine with `-EnginePath` and `-EngineVersion`. Local-engine publication is refused for the default Codebelt production repository. `-SourceRepository` sets the fork's source identity label. No CI artifacts are involved in manual builds. + +The newest requested SDK supplies the official Ubuntu base (verified Resolute or Noble tag, pinned to a digest). Its SDK and PowerShell are retained. Additional SDK archives come from Microsoft's exact release metadata, are checked against SHA-512, and install side by side without overwriting existing host files, runtimes or packs. Both NETCore and ASP.NET Core runtimes and the official image's Git remain available. No debugger or unrelated development packages are added. + +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. + ## Validation and releases Run the dependency-free regression and integration suite: @@ -87,21 +191,42 @@ pwsh -NoProfile -File ./tests/csrun.Tests.ps1 # Pin the SDK, even when newer SDKs are also installed pwsh -NoProfile -File ./tests/csrun.Tests.ps1 -SdkVersion 11.0.100 pwsh -NoProfile -File ./tests/csrun.Tests.ps1 -CompatibilityOnly -SdkVersion 10.0.115 + +# Publishing contract checks; no Docker or network required +pwsh -NoProfile -File ./tests/BuildAndPublish.Tests.ps1 +python ./tests/oci.Tests.py + +# Build and execute Docker integration tests without publishing +Import-Module ./BuildAndPublish.psm1 -Force +BuildAndPublish 10.0.404 -BuildOnly +BuildAndPublish 11.0.100 -BuildOnly +BuildAndPublish 10.0.404 11.0.100 -BuildOnly ``` -Tests invoke the actual standalone script in child processes, including local scriptblock invocation of the release asset. Fixtures preserve the supplied full DateSpan and Codebelt xUnit examples. DateSpan with Cuemon.Kernel 11.0.0 prints `0 years`, `9 months`, **`40 weeks`**, `273 days`, `6552 hours`, `393,120 minutes`, and `23,587,200 seconds`. Windows is the locally validated platform; paths and process invocation are portable, but Linux/macOS are not yet locally verified. +Native tests invoke the actual standalone script in child processes, including local scriptblock invocation. Fixtures preserve the supplied full DateSpan and Codebelt xUnit examples. DateSpan with Cuemon.Kernel 11.0.0 prints `0 years`, `9 months`, **`40 weeks`**, `273 days`, `6552 hours`, `393,120 minutes`, and `23,587,200 seconds`. Native regression tests remain on Windows; Docker integration tests execute the candidate engine in PR/release preparation and verify it against the published engine before promotion. Native macOS remains unverified. Both workflows test .NET 11 and .NET 10 channel compatibility using the highest installed GA SDK in each channel after Codebelt SDK setup. The harness writes an isolated `global.json` with roll-forward disabled and verifies that exact selected SDK for each run. CI does not guarantee coverage of the older SDK versions shown in the local commands above or establish minimum SDK version compatibility. The compatibility run targets `net10.0` and covers console stdin, forced file execution beside an existing project, and real MTP success, failure, empty discovery, compilation failure, and restore failure. Both suites include runs with normal compiler/MSBuild server settings, checking exit codes and removal of csrun's own disposable artifacts. These runs retain the normal host temp location for SDK-managed compiler caches; they neither delete those caches nor shut down unrelated servers. The remaining tests disable server reuse to keep their isolated harness directory disposable. Assertions remove ANSI colors and terminal hyperlinks; raw stdout/stderr remain available for diagnostics. A regression forces MTP's real ANSI formatter and still requires all three Codebelt output lines. The standalone runner preserves the original child output. -The workflows follow the [claude-autoupdate release pattern](https://github.com/gimlichael/claude-autoupdate/tree/main/.github/workflows): PR validation; independent validation of a tagged commit; upload of the tested root script; a separate least-privilege job creating a **draft** release from that artifact. Workflows prefer Codebelt actions with floating version tags: `codebeltnet/git-checkout@v1` and `codebeltnet/install-dotnet@v3`. CI follows the current supported GA SDKs using patch precision, then selects the highest installed GA SDK for each required channel (.NET 11 and .NET 10) and verifies that exact version during tests. `actions/upload-artifact@v7` handles script artifacts because the Codebelt ecosystem has no suitable equivalent. No additional repository secrets are needed. GitHub-hosted workflow execution must be verified after an approved push. +PR and tagged-release validation build the checked-out **candidate** engine. Windows regression jobs use `windows-2025`. Every Linux job uses a fixed Ubuntu 26.04 label; actual container execution uses `ubuntu-26.04` for AMD64 and `ubuntu-26.04-arm` for ARM64. Each CPU runs all three SDK variants and checks image/daemon/runtime architecture, PowerShell startup, SDK/runtime inventories, real console compilation and xUnit discovery/pass/failure, pinned Codebelt packages, disposal and hardened execution. Set branch protection to require **Required quality gate**; it rejects failed, cancelled or skipped dependencies. Native ARM64 remains unverified until GitHub-hosted CI actually runs. + +Release delivery follows these stages: + +1. After approval to tag and push, `release.yml` independently runs Windows and six native container jobs. Each job exports once with SBOM and maximum BuildKit provenance, verifies the archive graph and attestation subjects, imports that artifact for testing, and compares the loaded config digest with the OCI config. No registry credentials are available. +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. The separate `Production` environment job promotes the 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. + +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. + +For recovery, dispatch `deploy.yml` from `main` with the already-published latest release tag. It reuses the original release assets and successful native results, revalidates checksums, and never replaces missing content with a rebuild. Partial tag uploads can be retried idempotently against the same bytes. A release that is no longer latest is refused. New SDK patch versions require a reviewed release preparation run and newly verified artifacts; existing release recovery cannot silently change SDK versions. + +The DocFX-specific builder is unsuitable for csrun execution. The generic Codebelt verifier is reused after assembly. The generic publisher currently assumes one product SemVer tag, so the small `tools/oci.py` promotion path implements SDK aliases and post-push content verification. OCI verification, assembly and promotion are shared by CD and the independent manual module; release lifecycle orchestration belongs only to CI/CD. All action references use floating version tags. The Python OCI utilities use only the standard library. -To make the initial release, after reviewing and approving this local change: +The release/deploy separation follows [Cuemon's release workflow](https://github.com/codebeltnet/cuemon/blob/main/.github/workflows/release.yml) and [deployment workflow](https://github.com/codebeltnet/cuemon/blob/main/.github/workflows/deploy.yml). Runner labels follow the [GitHub-hosted runner reference](https://docs.github.com/en/actions/reference/runners/github-hosted-runners). Attestation validation follows [BuildKit's image attestation storage format](https://docs.docker.com/build/metadata/attestations/attestation-storage/); it verifies SBOM contents, manifest subjects and provenance build identities, without adding a separate signing authority. -1. Commit the feature branch and approve pushing/opening a PR. Merge the reviewed change into `main` after PR validation passes. -2. On the approved release commit, run the tests above, then create an annotated tag: `git tag -a v0.1.0 -m "csrun v0.1.0"`. -3. With approval, push that specific tag: `git push origin v0.1.0`. The tag workflow reruns tests and creates a draft with only `csrun.ps1` attached. -4. Review the draft and download the asset for inspection. With maintainer approval, publish the draft. The latest-release URL then resolves in the repository where the release was published. A version-specific URL (`https://github.com/codebeltnet/csrun/releases/download/v0.1.0/csrun.ps1`) pins script delivery too. +GitHub-hosted execution, native ARM64 results and real Docker Hub publication still require an approved push and run. SBOM/provenance checks in the implementation are not evidence of a successful registry publication. See [container validation results](docs/container-validation.md) for measured local results and remaining limits. Implementation references: [.NET file-based applications](https://learn.microsoft.com/en-us/dotnet/core/sdk/file-based-apps), [SDK stdin design and project precedence](https://github.com/dotnet/sdk/blob/main/documentation/general/dotnet-run-file.md), [xUnit MTP configuration](https://xunit.net/docs/getting-started/v3/microsoft-testing-platform), and [MTP exit codes](https://learn.microsoft.com/en-us/dotnet/core/testing/microsoft-testing-platform-exit-codes). diff --git a/container-build.ps1 b/container-build.ps1 new file mode 100644 index 0000000..80e8181 --- /dev/null +++ b/container-build.ps1 @@ -0,0 +1,27 @@ +#requires -Version 7.0 +# Build-time only. This file is removed before the image is used. +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false +try { + $rid = switch ($env:TARGETARCH) { 'amd64' { 'linux-x64' } 'arm64' { 'linux-arm64' } default { throw "Unsupported architecture '$env:TARGETARCH'." } } + foreach ($sdk in (ConvertFrom-Json -InputObject $env:SDK_ARTIFACTS_JSON)) { + if (Test-Path "/usr/share/dotnet/sdk/$($sdk.version)") { throw "SDK $($sdk.version) is already installed in the base image." } + $files = @($sdk.files | Where-Object { $_.rid -ceq $rid -and $_.url.EndsWith('.tar.gz') }) + if ($files.Count -ne 1) { throw "No unique SDK $($sdk.version) archive for $rid." } + $file = $files[0] + if ($file.url -notmatch '^https://(builds\.dotnet\.microsoft\.com|download\.visualstudio\.microsoft\.com)/' -or $file.hash -notmatch '^[a-fA-F0-9]{128}$') { throw 'Expected an official SDK URL and SHA-512 hash.' } + $archive = '/tmp/csrun-sdk.tar.gz' + Invoke-WebRequest -Uri $file.url -OutFile $archive + if ((Get-FileHash $archive -Algorithm SHA512).Hash -ine $file.hash) { throw "SDK $($sdk.version) checksum mismatch." } + # Keep the newest host and shared files from the base. Versioned SDKs, + # targeting packs and both NETCore/ASP.NET runtimes install side by side. + & tar --extract --gzip --file $archive --directory /usr/share/dotnet --skip-old-files --no-same-owner + if ($LASTEXITCODE -ne 0) { throw 'SDK archive extraction failed.' } + Remove-Item -LiteralPath $archive + } + & dotnet --list-sdks + if ($LASTEXITCODE -ne 0) { throw 'SDK inventory failed.' } + & dotnet --list-runtimes + if ($LASTEXITCODE -ne 0) { throw 'Runtime inventory failed.' } +} catch { [Console]::Error.WriteLine($_); exit 1 } diff --git a/container-entrypoint.ps1 b/container-entrypoint.ps1 new file mode 100644 index 0000000..1bd4287 --- /dev/null +++ b/container-entrypoint.ps1 @@ -0,0 +1,15 @@ +#requires -Version 7.0 +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +try { + [Console]::InputEncoding = [Text.UTF8Encoding]::new($false) + $manifest = [Console]::In.ReadToEnd() + if ([string]::IsNullOrWhiteSpace($manifest)) { throw 'Expected a UTF-8 JSON manifest on stdin; use docker run --rm -i.' } + # ExternalScriptInfo invocation exits PowerShell. A scriptblock returns here + # and exposes the engine's status, including MTP's nonzero test results. + & ([scriptblock]::Create([IO.File]::ReadAllText((Join-Path $PSScriptRoot 'csrun.ps1')))) -ManifestJson $manifest + exit $LASTEXITCODE +} catch { + [Console]::Error.WriteLine("csrun container: $($_.Exception.Message)") + exit 1 +} diff --git a/csrun.Dockerfile b/csrun.Dockerfile new file mode 100644 index 0000000..8c9aeca --- /dev/null +++ b/csrun.Dockerfile @@ -0,0 +1,33 @@ +ARG BASE_IMAGE=mcr.microsoft.com/dotnet/sdk:10.0.404-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb +FROM ${BASE_IMAGE} + +# Empty for a single-SDK build. BuildAndPublish resolves exact, hashed official +# SDK archives for additional versions; the base SDK and PowerShell are reused. +ARG SDK_ARTIFACTS_JSON=[] +ARG TARGETARCH +COPY container-build.ps1 /opt/csrun-build.ps1 +RUN pwsh -NoLogo -NoProfile -NonInteractive -File /opt/csrun-build.ps1 \ + && rm /opt/csrun-build.ps1 + +COPY csrun.ps1 container-entrypoint.ps1 /opt/csrun/ +ARG ENGINE_VERSION +ARG ENGINE_SHA256 +ARG ENGINE_URL=https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1 +RUN test -n "$ENGINE_VERSION" && test -n "$ENGINE_SHA256" \ + && echo "$ENGINE_SHA256 /opt/csrun/csrun.ps1" | sha256sum --check --strict +LABEL net.codebelt.csrun.engine.release=${ENGINE_VERSION} \ + net.codebelt.csrun.engine.sha256=${ENGINE_SHA256} \ + net.codebelt.csrun.engine.url=${ENGINE_URL} +ENV HOME=/tmp \ + DOTNET_CLI_HOME=/tmp \ + NUGET_PACKAGES=/tmp/.nuget/packages \ + XDG_CACHE_HOME=/tmp/.cache \ + XDG_CONFIG_HOME=/tmp/.config \ + XDG_DATA_HOME=/tmp/.local/share \ + TMPDIR=/tmp \ + DOTNET_CLI_TELEMETRY_OPTOUT=1 \ + POWERSHELL_TELEMETRY_OPTOUT=1 \ + TESTINGPLATFORM_TELEMETRY_OPTOUT=1 +WORKDIR /tmp +USER $APP_UID +ENTRYPOINT ["pwsh", "-NoLogo", "-NoProfile", "-NonInteractive", "-File", "/opt/csrun/container-entrypoint.ps1"] diff --git a/docs/container-validation.md b/docs/container-validation.md new file mode 100644 index 0000000..740761b --- /dev/null +++ b/docs/container-validation.md @@ -0,0 +1,66 @@ +# Container validation + +The initial validation below predates the OCI delivery changes. Local validation on 2026-11-15 uses Windows PowerShell 7, Docker Desktop 4.97.0 with Linux AMD64 containers, Docker Engine 29.9.2 and Buildx 0.38.1. No images were published. The native executor is unchanged from the released source. + +## Engine and base identities + +The canonical latest-release asset resolved to `v0.1.0` during these operations. GitHub's asset digest and the bundled file both matched SHA-256 `6609acb7ac9df5cbbbf70d58b3dbc40f2d242e34831f89c7b42d7069015db802`. Each build records this engine version/checksum in image labels. Future builds resolve the latest release again; there is no version-specific engine URL in the build tooling. + +| Environment | Exact installed SDKs | NETCore and ASP.NET Core runtimes | Official Ubuntu base index digest | +| --- | --- | --- | --- | +| `10` | `10.0.404` | `10.0.15` | Noble: `sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb` | +| `11` | `11.0.100` | `11.0.0` | Resolute: `sha256:65f3c7c6a25a239ab3e6719f2896147e7b68242ff2d8818dd70498bde6ef8bea` | +| `10-11` | `10.0.404`, `11.0.100` | `10.0.15`, `11.0.0` | Same Resolute base as `11` | + +Inventories are checked against Microsoft's exact per-channel SDK release metadata, including both runtime families. The combined environment contains both SDKs, not just extra runtimes, and executes manifests for both `net10.0` and `net11.0`. + +## Image sizes + +Docker's local image inspection reports these uncompressed logical sizes for `linux/amd64`; these are not compressed registry transfer sizes or incremental disk usage with shared layers: + +| Environment | Bytes | MiB | +| --- | ---: | ---: | +| `10` | 1,315,204,771 | 1,254.3 | +| `11` | 1,268,622,586 | 1,209.9 | +| `10-11` | 2,169,181,898 | 2,068.7 | + +The combined image adds about 859 MiB over the .NET 11 image to retain the .NET 10 SDK, targeting packs and shared runtimes. The .NET 11 single image is smaller than the .NET 10 image despite its newer SDK; the official Ubuntu image contents differ. Single-SDK images provide the smaller environment for one TFM. No persistent NuGet cache or debugger tooling is added. + +## Checks + +- Native Windows: 91 full regression/integration checks passed on SDK 11.0.100; 15 compatibility checks passed on SDK 10.0.115. `csrun.ps1` has no repository diff. +- Publishing contract: 9 checks passed, covering dry-run/PassThru tags, prerelease normalization, collisions, invalid inputs, custom options, unsupported metadata channels, exact historical SDK lookup and Docker error propagation without Docker or network access. +- Final AMD64 container suites passed: 21 checks for .NET 10, 21 for .NET 11 and 22 for the combined image (64 total). They cover exact SDK/runtime inventories, baked asset identity, stdin console samples and genuine xUnit v3 discovery, Codebelt console/test packages and visible MTP output, compilation and assertion failures, empty discovery, UTF-8/large manifests, validation failures, missing TFMs, the engine's LTS default, ASP.NET framework references, non-root/no-host-mount defaults, disposable storage, and hardened read-only execution with executable tmpfs and resource limits. +- All PowerShell files parsed successfully, all three workflow files passed actionlint, and `git diff --check` passed. Both `-WhatIf -PassThru` planning and actual `-BuildOnly -PassThru` operations were exercised. +- A real Git-tagged MinVer package build produces `1.2.3` with Git and falls back to `0.0.0-alpha.0` when Git is unavailable. This is why the official SDK image's Git installation is retained. +- Network-disabled JSON validation exercises the bundled engine without a startup download. Normal compilation and tests keep network enabled for release metadata and NuGet. Caching the release index alone did not make a console restore offline-capable; offline builds are not promised. + +Both exact console and xUnit stdin one-liners were executed from Windows PowerShell against the locally built `codebeltnet/csrun:10` image and returned `0`, with `42` and one passing test respectively. Further exit-code checks include console exit `23`, compilation exit `1`, MTP failed assertion exit `2` and no-test exit `8`. + +## OCI delivery verification + +The refreshed build path exports BuildKit OCI content once with SBOM and maximum provenance, converts that content for native testing, and compares raw Docker-exported config bytes with the original OCI config. This matters on Docker Desktop's containerd image store: its image ID can be a manifest digest rather than a config digest. A changed serialization is not treated as changed filesystem/config content. + +- The unchanged standalone engine again passed all 106 Windows checks: 91 with SDK 11.0.100 and 15 with SDK 10.0.115. +- Eleven publishing-module contracts pass, including fork registry/context plans and rejection of a foreign Docker CPU before downloads. +- Twenty offline artifact/lifecycle tests pass. They cover exact platform inventory, config/source/SDK/engine identity, missing or unrelated SBOM/provenance, provenance build arguments, corrupt archives/blobs, preservation of manifests during assembly, split/recovery byte identity, draft/stale releases, fork source identities, and rejection of Docker `latest` before any upload. +- The generic Codebelt `oci-artifact-verify@v1` verifier accepted an assembled two-platform contract fixture. This validates the archive contract, not ARM64 execution. +- Real AMD64 OCI exports include nonempty SPDX SBOMs and SLSA provenance bound to their platform manifests and source/engine/SDK build inputs. An unnamed BuildKit export initially emitted empty attestation subjects; the verifier rejected it. Naming the export fixed the subjects. +- All three refreshed OCI exports passed native AMD64 execution and exact exported-config verification: 22 checks for .NET 10, 22 for .NET 11, and 23 for the combined image (67 total). The combined image compiles and executes console and xUnit samples on both TFMs. + +Refreshed export measurements are below. Docker reports local image storage differently after Docker-format import; these values are not directly comparable with the initial build's logical size measurements. OCI archive bytes include compressed layers, manifests and attestations, and are a better guide to artifact transfer/storage. Neither measure promises incremental disk usage with shared layers. + +| Environment | Docker-reported local image bytes | OCI archive bytes | +| --- | ---: | ---: | +| `10` | 1,978,122,006 | 390,060,032 | +| `11` | 1,427,258,798 | 360,735,744 | +| `10-11` | 2,734,862,369 | 608,526,336 | + +Candidate verification uses checked-out bytes, annotated `v0.2.0`; this is not evidence that a v0.2.0 GitHub Release has been published. Their script checksum remains `6609acb7ac9df5cbbbf70d58b3dbc40f2d242e34831f89c7b42d7069015db802`. + +## Limits and release work + +- The earlier local ARM64 `exec format error` is a host execution limitation, not a confirmed image defect. No privileged emulation was installed. Real ARM64 execution is required on `ubuntu-26.04-arm`; AMD64 uses `ubuntu-26.04`. Neither GitHub-hosted runner has been exercised in this session, and native ARM64 support is not established by local exports or fixture tests. +- No Docker Hub credentials were used and no registry publication or registry attestation preservation has been verified. BuildKit predicate validation does not introduce a separate signing authority. Authorized CI execution and a real push plus immutable registry inspection remain required before release completion. +- 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. +- Configure required branch checks and reviewers for the `Production` environment before enabling publication. 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. diff --git a/tests/BuildAndPublish.Tests.ps1 b/tests/BuildAndPublish.Tests.ps1 new file mode 100644 index 0000000..13fed0b --- /dev/null +++ b/tests/BuildAndPublish.Tests.ps1 @@ -0,0 +1,111 @@ +#requires -Version 7.0 +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$module = Import-Module "$PSScriptRoot/../BuildAndPublish.psm1" -Force -PassThru +$passed = 0; $failed = 0 +function Test-Case([string] $Name, [scriptblock] $Body) { + try { & $Body; $script:passed++; Write-Host "PASS $Name" } + catch { $script:failed++; Write-Host "FAIL $Name`n$_" } +} +function Assert-Throws([scriptblock] $Body, [string] $Pattern) { + try { & $Body; throw 'Expected rejection.' } catch { if ($_ -notmatch $Pattern) { throw } } +} +Test-Case 'SDK-specific tags and PassThru with WhatIf' { + foreach ($case in @( + @{Versions=@('10.0.404'); Tags=@('10.0.404','10.0','10')}, + @{Versions=@('11.0.100'); Tags=@('11.0.100','11.0','11')}, + @{Versions=@('10.0.404','11.0.100'); Tags=@('10.0.404-11.0.100','10.0-11.0','10-11')} + )) { + $plan = BuildAndPublish -SdkVersion $case.Versions -WhatIf -PassThru + $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.' } + } +} +Test-Case 'reference prerelease normalization preserves exact SDK input' { + $plan = BuildAndPublish '11.0.100-rc.1.26425.128' -WhatIf -PassThru + if ($plan.PublishTags -cne '11.0.100-rc.1' -or $plan.SdkVersions -cne '11.0.100-rc.1.26425.128') { throw 'Prerelease normalization changed.' } +} +Test-Case 'duplicate and ambiguous SDK channels are rejected' { + Assert-Throws { BuildAndPublish 10.0.404 10.0.404 -WhatIf } 'unique' + Assert-Throws { BuildAndPublish 10.0.404 10.0.115 -WhatIf } 'unique' + Assert-Throws { BuildAndPublish 11.0.100-rc.1.26425.128 11.0.100-rc.1.26425.129 -WhatIf } 'unique' +} +Test-Case 'invalid, older and floating SDK inputs fail' { + foreach ($version in @('9.0.100','latest','10.0','10.0.*','10.0.404;whoami','10.0.404-invalid suffix')) { Assert-Throws { BuildAndPublish $version -WhatIf } 'SDK|tag' } +} +Test-Case 'custom image, registry and Dockerfile options' { + $plan = BuildAndPublish 10.0.404 -ImageName custom -Registry localhost:5000/team -Dockerfile ./custom.Dockerfile -WhatIf -PassThru + if ($plan.Tags[0] -cne 'localhost:5000/team/custom:10.0.404' -or $plan.Dockerfile -cne './custom.Dockerfile') { throw 'Custom options were lost.' } +} +Test-Case 'publication aliases are absent' { + if ((Get-Command BuildAndPublish).Parameters.ContainsKey('Latest')) { throw 'Unexpected Latest parameter.' } +} +Test-Case 'manual builds support independent registry and native Docker contexts' { + $contexts = @{ 'linux/amd64'='my-amd64'; 'linux/arm64'='my-arm64' } + $builders = @{ 'linux/amd64'='builder-amd64'; 'linux/arm64'='builder-arm64' } + $plan = BuildAndPublish 10.0.404 11.0.100 -Registry registry.example/team -DockerContext $contexts -Builder $builders -WhatIf -PassThru + if ($plan.Tags[0] -cne 'registry.example/team/csrun:10.0.404-11.0.100' -or $plan.Platforms.Count -ne 2 -or $plan.DockerContexts['linux/arm64'] -cne 'my-arm64' -or $plan.Builders['linux/amd64'] -cne 'builder-amd64') { throw 'Independent manual build plan changed.' } +} +Test-Case 'a foreign CPU fails before downloads rather than using emulation' { + & $module { + function docker { $global:LASTEXITCODE = 0; 'linux/x86_64' } + try { + $rejected = $false + try { BuildAndPublish 10.0.404 -BuildOnly -Platform linux/arm64 } catch { $rejected = $_ -match 'Native Docker host required for linux/arm64' } + if (-not $rejected) { throw 'Foreign Docker CPU was accepted.' } + } finally { Remove-Item Function:docker } + } +} +Test-Case 'unavailable Skopeo transport fails before downloads or builds' { + & $module { + function docker { $global:LASTEXITCODE = 0; 'linux/x86_64' } + function python { + if ($args[-1] -cne 'check-skopeo') { throw 'Expected transport preflight.' } + $global:LASTEXITCODE = 1 + } + function Invoke-RestMethod { throw 'External metadata should not be downloaded.' } + try { + $rejected = $false + try { BuildAndPublish 10.0.404 -BuildOnly -Platform linux/amd64 } catch { $rejected = $_ -match 'Remote utility Docker daemons require native Skopeo' } + if (-not $rejected) { throw 'Missing native Skopeo was not rejected before construction.' } + } finally { + Remove-Item Function:docker, Function:python, Function:Invoke-RestMethod + } + } +} +Test-Case 'unsupported/EOL metadata channels fail before exact SDK lookup' { + $fixture = (Get-Content "$PSScriptRoot/fixtures/releases-index.json" -Raw | ConvertFrom-Json -AsHashtable)['releases-index'] + & $module { + param($Index) + foreach ($version in @('9.0.100','12.0.100','99.0.100')) { + $rejected = $false + try { Get-CsrunSdkRelease $version $Index } catch { $rejected = $_ -match 'unsupported|EOL' } + if (-not $rejected) { throw "Did not reject $version." } + } + } $fixture +} +Test-Case 'native Docker errors are not swallowed' { + & $module { + function docker { $global:LASTEXITCODE = 37 } + try { + $rejected = $false + try { Invoke-CsrunDocker @('buildx','version') } catch { $rejected = $_ -match 'exit 37' } + if (-not $rejected) { throw 'Docker failure was lost.' } + } finally { Remove-Item Function:docker } + } +} +Test-Case 'exact historical SDK lookup uses channel metadata without substitution' { + & $module { + function Invoke-RestMethod { param($Uri) @{releases=@(@{sdks=@(@{version='10.0.115'; files=@()})})} } + try { + $index = @(@{product='.NET'; 'channel-version'='10.0'; 'release-type'='lts'; 'support-phase'='active'; 'latest-sdk'='10.0.404'; 'releases.json'='https://example.invalid/releases.json'}) + if ((Get-CsrunSdkRelease '10.0.115' $index).version -cne '10.0.115') { throw 'Historical SDK was substituted.' } + $rejected = $false + try { Get-CsrunSdkRelease '10.0.999' $index } catch { $rejected = $_ -match 'Exact SDK.*absent' } + if (-not $rejected) { throw 'Unknown exact SDK was accepted.' } + } finally { Remove-Item Function:Invoke-RestMethod } + } +} +Write-Host "BuildAndPublish tests: $passed passed, $failed failed" +exit ([int]($failed -gt 0)) diff --git a/tests/container.Tests.ps1 b/tests/container.Tests.ps1 new file mode 100644 index 0000000..289e203 --- /dev/null +++ b/tests/container.Tests.ps1 @@ -0,0 +1,231 @@ +#requires -Version 7.0 +[CmdletBinding()] +param( + [Parameter(Mandatory)][string] $Image, + [Parameter(Mandatory)][string[]] $SdkVersion, + [ValidateSet('linux/amd64', 'linux/arm64')][string] $Platform = 'linux/amd64', + [switch] $RequireNative, + [string] $DockerContext, + [string] $EngineUrl = 'https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1', + [string] $EngineSha256 +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false +$passed = 0; $failed = 0 +$docker = (Get-Command docker -CommandType Application | Select-Object -First 1).Source +function Invoke-Docker([string[]] $Arguments, [string] $InputText = '') { + $containerName = $null + if ($Arguments.Count -gt 0 -and $Arguments[0] -eq 'run') { + $containerName = 'csrun-test-' + [guid]::NewGuid().ToString('N') + $Arguments = @('run', '--name', $containerName) + $Arguments[1..($Arguments.Count - 1)] + } + if ($DockerContext) { $Arguments = @('--context', $DockerContext) + $Arguments } + $start = [Diagnostics.ProcessStartInfo]::new($docker) + $start.UseShellExecute = $false + $start.RedirectStandardInput = $true + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + $start.StandardInputEncoding = [Text.UTF8Encoding]::new($false) + $start.StandardOutputEncoding = [Text.Encoding]::UTF8 + $start.StandardErrorEncoding = [Text.Encoding]::UTF8 + foreach ($argument in $Arguments) { $start.ArgumentList.Add($argument) } + $process = [Diagnostics.Process]::Start($start) + try { + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + $process.StandardInput.Write($InputText) + $process.StandardInput.Close() + if (-not $process.WaitForExit(300000)) { $process.Kill($true); throw 'Docker test timed out after 300 seconds.' } + $out = $stdout.GetAwaiter().GetResult(); $err = $stderr.GetAwaiter().GetResult() + return @{ Code=$process.ExitCode; Out=$out; Err=$err; Text=($out + "`n" + $err -replace '\x1B\[[0-?]*[ -/]*[@-~]', '') } + } finally { + if ($containerName -and -not $process.HasExited) { $process.Kill($true); $process.WaitForExit() } + if ($containerName -and $process.ExitCode -ne 0) { + $contextArgs = if ($DockerContext) { @('--context', $DockerContext) } else { @() } + & $docker @contextArgs rm --force $containerName 2>$null | Out-Null + } + $process.Dispose() + } +} +function Assert-Result($Result, [int] $Code = 0, [string] $Pattern = '') { + if ($Result.Code -ne $Code -or ($Pattern -and $Result.Text -notmatch $Pattern)) { throw "Expected exit $Code and /$Pattern/; got $($Result.Code):`n$($Result.Text)" } +} +function Test-Case([string] $Name, [scriptblock] $Body) { + try { & $Body; $script:passed++; Write-Host "PASS $Name" } + catch { $script:failed++; Write-Host "FAIL $Name`n$_" } +} +function Invoke-Manifest([hashtable] $Manifest, [switch] $Hardened) { + $options = if ($Hardened) { @('--read-only', '--tmpfs', '/tmp:rw,exec,nosuid,nodev,size=1g,mode=1777', '--cap-drop=ALL', '--security-opt=no-new-privileges', '--cpus=2', '--memory=2g', '--pids-limit=256') } else { @() } + Invoke-Docker (@('run', '--rm', '-i', '--platform', $Platform) + $options + @($Image)) ($Manifest | ConvertTo-Json -Depth 10 -Compress) +} +function New-Manifest([string] $Source, [string] $Mode = 'console', [string] $Framework = $script:framework) { + @{schemaVersion=1; mode=$Mode; framework=$Framework; source=$Source} +} +$channels = @($SdkVersion | ForEach-Object { ($_ -split '\.')[0..1] -join '.' }) +$framework = 'net' + ($channels | Sort-Object { [version]$_ } | Select-Object -First 1) +Test-Case 'native CPU, image architecture, PowerShell and .NET runtime architecture' { + $expectedCpu = ($Platform -split '/')[1] + if ($RequireNative) { + $hostCpu = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant().Replace('x64', 'amd64') + if (-not $DockerContext -and $hostCpu -cne $expectedCpu) { throw "Native runner required: $hostCpu != $expectedCpu" } + $daemon = Invoke-Docker @('info', '--format', '{{.Architecture}}') + Assert-Result $daemon 0 $(if ($expectedCpu -eq 'amd64') { '^(x86_64|amd64)\s*$' } else { '^(aarch64|arm64)\s*$' }) + } + $config = Invoke-Docker @('image', 'inspect', $Image) + Assert-Result $config + if (@($config.Out | ConvertFrom-Json)[0].Architecture -cne $expectedCpu) { throw 'Image CPU mismatch.' } + $runtimeCpu = if ($expectedCpu -eq 'amd64') { 'X64' } else { 'Arm64' } + Assert-Result (Invoke-Docker @('run', '--rm', '--platform', $Platform, '--entrypoint', 'pwsh', $Image, '-NoProfile', '-Command', '$PSVersionTable.PSVersion.ToString()')) 0 '^7\.' + Assert-Result (Invoke-Manifest (New-Manifest 'Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture);')) 0 "(?m)^$runtimeCpu\r?$" +} +Test-Case 'exact installed SDK and associated runtime inventories' { + $sdks = Invoke-Docker @('run', '--rm', '--platform', $Platform, '--entrypoint', 'dotnet', $Image, '--list-sdks') + $runtimes = Invoke-Docker @('run', '--rm', '--platform', $Platform, '--entrypoint', 'dotnet', $Image, '--list-runtimes') + Assert-Result $sdks; Assert-Result $runtimes + Write-Host $sdks.Out; Write-Host $runtimes.Out + $installed = @($sdks.Out -split '\r?\n' | Where-Object { $_ } | ForEach-Object { ($_ -split ' ')[0] }) + if (@(Compare-Object $SdkVersion $installed).Count) { throw 'SDK inventory differs from explicit build inputs.' } + $index = (Invoke-RestMethod 'https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json').'releases-index' + $expected = @() + foreach ($channel in $channels) { + $metadata = Invoke-RestMethod ($index | Where-Object { $_.'channel-version' -ceq $channel }).'releases.json' + foreach ($version in $SdkVersion | Where-Object { $_.StartsWith("$channel.") }) { + $release = $metadata.releases | Where-Object { $version -cin @($_.sdks.version) } | Select-Object -First 1 + $expected += "Microsoft.NETCore.App $($release.runtime.version)" + $expected += "Microsoft.AspNetCore.App $($release.'aspnetcore-runtime'.version)" + } + } + $actual = @($runtimes.Out -split '\r?\n' | Where-Object { $_ } | ForEach-Object { ($_ -split ' ')[0..1] -join ' ' }) + if (@(Compare-Object @($expected | Select-Object -Unique) $actual).Count) { throw 'Runtime inventory differs from requested SDK-associated runtimes.' } +} +Test-Case 'bundled release asset hash and image metadata' { + $config = Invoke-Docker @('image', 'inspect', $Image) + Assert-Result $config + $info = @($config.Out | ConvertFrom-Json)[0] + $labels = $info.Config.Labels + if (-not $EngineSha256) { $script:EngineSha256 = $labels.'net.codebelt.csrun.engine.sha256' } + $hash = Invoke-Docker @('run', '--rm', '--platform', $Platform, '--entrypoint', 'sha256sum', $Image, '/opt/csrun/csrun.ps1') + Assert-Result $hash 0 "^$EngineSha256 " + if ($labels.'net.codebelt.csrun.engine.sha256' -cne $EngineSha256 -or $labels.'net.codebelt.csrun.engine.release' -notmatch '^v\d+\.\d+\.\d+' -or $labels.'net.codebelt.csrun.engine.url' -cne $EngineUrl) { throw 'Engine identity labels are missing or inconsistent.' } +} +foreach ($channel in $channels) { + Test-Case "console stdin executes net$channel" { + Assert-Result (Invoke-Manifest (New-Manifest 'Console.WriteLine(42);' -Framework "net$channel")) 0 '(?m)^42\r?$' + } + Test-Case "genuine xUnit discovery and passing Fact net$channel" { + $result = Invoke-Manifest (New-Manifest 'using Xunit; public class SmokeTest { [Fact] public void Pass() => Assert.True(true); }' test "net$channel") + Assert-Result $result 0 'total:\s+1' + if ($result.Text -notmatch 'succeeded:\s+1' -or $result.Text -notmatch 'failed:\s+0') { throw $result.Text } + Write-Host $result.Text + } +} +Test-Case 'complete explicit Main and program stderr/exit status' { + Assert-Result (Invoke-Manifest (New-Manifest 'using System; class Program { static int Main() { Console.WriteLine("main"); Console.Error.WriteLine("stderr"); return 23; } }')) 23 'stderr' +} +Test-Case 'pinned Codebelt console dependency' { + $manifest = Get-Content "$PSScriptRoot/../samples/datespan.json" -Raw | ConvertFrom-Json -AsHashtable + $manifest.framework = $framework + Assert-Result (Invoke-Manifest $manifest) 0 '273 days' +} +Test-Case 'pinned Codebelt test dependency and visible MTP live output' { + $manifest = New-Manifest (Get-Content "$PSScriptRoot/fixtures/OutputLinesTest.cs" -Raw) test + $manifest.dependsOn = @('Codebelt.Extensions.Xunit@13.0.0') + $result = Invoke-Manifest $manifest + Assert-Result $result 0 'succeeded:\s+1' + foreach ($line in @('started', '2', 'finished')) { if ($result.Text -notmatch "(?m)^OUTPUT: .*\] $line\r?$") { throw "Missing live output '$line': $($result.Text)" } } + Write-Host $result.Text +} +Test-Case 'Git preserves real MinVer package build behavior' { + $manifest = New-Manifest 'using System.Reflection; Console.WriteLine(Assembly.GetExecutingAssembly().GetCustomAttribute()!.InformationalVersion);' + $manifest.dependsOn = @('MinVer@8.0.0') + $repository = 'git config --global --add safe.directory /tmp; git -C /tmp init -q; git -C /tmp -c user.name=csrun-test -c user.email=test@example.invalid commit --allow-empty -qm fixture; git -C /tmp tag 1.2.3; ' + $entrypoint = 'exec pwsh -NoProfile -NonInteractive -File /opt/csrun/container-entrypoint.ps1' + $inputJson = $manifest | ConvertTo-Json -Compress + Assert-Result (Invoke-Docker @('run', '--rm', '-i', '--platform', $Platform, '--entrypoint', 'sh', $Image, '-c', ($repository + $entrypoint)) $inputJson) 0 '(?m)^1\.2\.3\+' + # MinVer falls back to a default version when git cannot discover the repo. + # Retaining git prevents that observable compatibility regression. + $noGit = 'mkdir /tmp/no-git; printf "#!/bin/sh\nexit 127\n" > /tmp/no-git/git; chmod +x /tmp/no-git/git; export PATH=/tmp/no-git:$PATH; ' + Assert-Result (Invoke-Docker @('run', '--rm', '-i', '--platform', $Platform, '--entrypoint', 'sh', $Image, '-c', ($repository + $noGit + $entrypoint)) $inputJson) 0 '(?m)^0\.0\.0-alpha\.0' +} +Test-Case 'compilation failure remains nonzero' { + Assert-Result (Invoke-Manifest (New-Manifest 'this is not C#;')) 1 'error CS' +} +Test-Case 'failing xUnit assertion preserves MTP exit 2' { + Assert-Result (Invoke-Manifest (New-Manifest 'using Xunit; public class T { [Fact] public void Fail() => Assert.True(false); }' test)) 2 'failed:\s+1' +} +Test-Case 'no tests preserves MTP exit 8' { + Assert-Result (Invoke-Manifest (New-Manifest 'public class NoTests { }' test)) 8 'total:\s+0' +} +Test-Case 'multiline quotes apostrophes Unicode and escaped characters' { + $source = @' +using System; +Console.WriteLine("æøå 世界 🚀 \"quotes\" apostrophe's \\slash"); +Console.WriteLine("line\nnext\ttab"); +'@ + Assert-Result (Invoke-Manifest (New-Manifest $source)) 0 'æøå 世界 🚀 "quotes" apostrophe''s \\slash' +} +Test-Case 'large manifest is not truncated' { + $source = '/*' + ('transport ' * 30000) + '*/ Console.WriteLine("large complete");' + Assert-Result (Invoke-Manifest (New-Manifest $source)) 0 'large complete' +} +Test-Case 'invalid JSON and empty stdin' { + Assert-Result (Invoke-Docker @('run', '--rm', '-i', '--platform', $Platform, $Image) '{bad') 1 'Invalid manifest JSON' + Assert-Result (Invoke-Docker @('run', '--rm', '-i', '--platform', $Platform, $Image)) 1 'Expected a UTF-8 JSON manifest' +} +Test-Case 'unsupported framework and conflicting pins fail' { + Assert-Result (Invoke-Manifest (New-Manifest 'Console.WriteLine(42);' -Framework net9.0)) 1 'framework|supported' + $manifest = New-Manifest 'Console.WriteLine(42);' + $manifest.dependsOn = @('Cuemon.Kernel@11.0.0', 'Cuemon.Kernel@11.0.1') + Assert-Result (Invoke-Manifest $manifest) 1 'conflict' +} +if ($channels.Count -eq 1) { + Test-Case 'missing target fails without retargeting' { + $missing = if ($channels[0] -eq '10.0') { 'net11.0' } else { 'net10.0' } + Assert-Result (Invoke-Manifest (New-Manifest 'Console.WriteLine(42);' -Framework $missing)) 1 'cannot build|Missing .*runtime' + } +} +Test-Case 'omitted framework retains engine LTS default' { + $manifest = New-Manifest 'Console.WriteLine(42);' + $manifest.Remove('framework') + $result = Invoke-Manifest $manifest + # Current supported GA LTS must be present; otherwise the engine must fail. + $index = (Invoke-RestMethod 'https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json').'releases-index' + $lts = $index | Where-Object { $_.'release-type' -eq 'lts' -and $_.'support-phase' -in @('active','maintenance') -and $_.'latest-release' -match '^\d+\.\d+\.\d+$' } | Sort-Object { [version]$_.'channel-version' } -Descending | Select-Object -First 1 + if ($lts.'channel-version' -in $channels) { Assert-Result $result 0 "net$($lts.'channel-version')" } + else { Assert-Result $result 1 'Missing .*runtime' } +} +Test-Case 'ASP.NET shared framework is usable by tests' { + $manifest = New-Manifest 'using Xunit; using Microsoft.AspNetCore.Http; public class T { [Fact] public void Pass() => Assert.Equal(200, new DefaultHttpContext().Response.StatusCode); }' test + $manifest.frameworkReferences = @('Microsoft.AspNetCore.App') + Assert-Result (Invoke-Manifest $manifest) 0 'succeeded:\s+1' +} +Test-Case 'non-root and no implicit host mounts; disposable storage' { + $name = 'csrun-isolation-' + [guid]::NewGuid().ToString('N') + try { + Assert-Result (Invoke-Docker @('create', '--name', $name, '--platform', $Platform, '--entrypoint', 'sh', $Image, '-c', 'id -u; echo isolated > /tmp/csrun-marker')) + $inspect = Invoke-Docker @('inspect', $name) + Assert-Result $inspect + $info = @($inspect.Out | ConvertFrom-Json)[0] + if ($info.Mounts.Count -or $info.HostConfig.Privileged -or $info.Config.User -in @('', '0', 'root')) { throw 'Unsafe default container configuration.' } + $result = Invoke-Docker @('start', '--attach', $name) + Assert-Result $result 0 '(?m)^[1-9][0-9]*\r?$' + } finally { Assert-Result (Invoke-Docker @('rm', '--force', $name)) } + $removed = Invoke-Docker @('inspect', $name) + if ($removed.Code -eq 0) { throw 'Container storage was not removed.' } + Assert-Result (Invoke-Docker @('run', '--rm', '--platform', $Platform, '--entrypoint', 'sh', $Image, '-c', 'test ! -e /tmp/csrun-marker')) +} +Test-Case 'read-only root, writable executable tmpfs and resource restrictions' { + Assert-Result (Invoke-Manifest (New-Manifest 'Console.WriteLine("hardened console");') -Hardened) 0 'hardened console' + Assert-Result (Invoke-Manifest (New-Manifest 'using Xunit; public class T { [Fact] public void Pass() => Assert.True(true); }' test) -Hardened) 0 'succeeded:\s+1' + Assert-Result (Invoke-Manifest (New-Manifest 'using Xunit; public class T { [Fact] public void Fail() => Assert.True(false); }' test) -Hardened) 2 'failed:\s+1' +} +Test-Case 'bundled engine validates input without network access' { + # Invalid JSON is rejected by csrun itself before metadata/NuGet access. + # This proves startup does not need GitHub to retrieve the engine, while + # ordinary execution intentionally retains network access for dependencies. + Assert-Result (Invoke-Docker @('run', '--rm', '-i', '--platform', $Platform, '--network', 'none', $Image) '{bad') 1 'Invalid manifest JSON' +} +Write-Host "Container tests ($Platform): $passed passed, $failed failed" +$global:LASTEXITCODE = [int]($failed -gt 0) +if ($MyInvocation.MyCommand -is [System.Management.Automation.ExternalScriptInfo]) { exit $LASTEXITCODE } diff --git a/tests/oci.Tests.py b/tests/oci.Tests.py new file mode 100644 index 0000000..f6516d9 --- /dev/null +++ b/tests/oci.Tests.py @@ -0,0 +1,270 @@ +"""Fail-closed artifact tests; no Docker, credentials, network or third-party packages.""" +import hashlib +import contextlib +import importlib.util +import json +from pathlib import Path +import sys +import shutil +import tarfile +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) +import oci +spec = importlib.util.spec_from_file_location('release_images', Path(__file__).resolve().parents[1] / 'tools/release-images.py') +release_images = importlib.util.module_from_spec(spec) +spec.loader.exec_module(release_images) + + +class ArtifactTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.args = SimpleNamespace(version='v0.2.0', revision='a' * 40, engine='b' * 64, sdks=['11.0.100']) + + def tearDown(self): + self.temp.cleanup() + + def fixture(self, cpu, *, missing=None, subject=None, engine=None, provenance_engine=None, source=oci.SOURCE): + blobs = {} + + def blob(value, media='application/vnd.oci.image.manifest.v1+json'): + data = oci.encoded(value) + digest = hashlib.sha256(data).hexdigest() + blobs['blobs/sha256/' + digest] = data + return {'digest': 'sha256:' + digest, 'size': len(data), 'mediaType': media} + + config = blob({'architecture': cpu, 'os': 'linux', 'config': {'Labels': { + 'org.opencontainers.image.source': source, + 'org.opencontainers.image.version': self.args.version, + 'org.opencontainers.image.revision': self.args.revision, + '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'}}}) + image = blob({'config': config, 'layers': []}) + image['platform'] = {'os': 'linux', 'architecture': cpu} + layers = [] + for predicate, body in [('https://spdx.dev/Document', {'spdxVersion': 'SPDX-2.3', 'packages': [{}]}), + ('https://slsa.dev/provenance/v0.2', {'buildType': 'https://mobyproject.org/buildkit@v1', 'invocation': {'parameters': {'args': { + 'build-arg:ENGINE_SHA256': provenance_engine or self.args.engine, + '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'}}}})]: + if predicate == missing: + continue + subjects = [] if subject is False else [{'digest': {'sha256': subject or image['digest'][7:]}}] + layers.append(blob({'predicateType': predicate, 'predicate': body, 'subject': subjects})) + att = blob({'layers': layers}) + att['platform'] = {'os': 'unknown', 'architecture': 'unknown'} + att['annotations'] = {'vnd.docker.reference.digest': image['digest'], 'vnd.docker.reference.type': 'attestation-manifest'} + path = self.root / (cpu + '.tar') + with tarfile.open(path, 'w') as tar: + for name, data in blobs.items(): + oci.add_bytes(tar, name, data) + oci.add_bytes(tar, 'index.json', oci.encoded({'schemaVersion': 2, 'mediaType': oci.INDEX, 'manifests': [image, att]})) + oci.add_bytes(tar, 'oci-layout', oci.encoded({'imageLayoutVersion': '1.0.0'})) + oci.seal(path) + return path, image, config + + def test_native_archive_identity_and_attestations(self): + path, image, config = self.fixture('amd64') + self.assertEqual(oci.Archive(path).verify(self.args, ['amd64']), [image]) + + def test_fork_source_identity_is_supported_without_ci(self): + self.args.source = 'https://github.com/fork-owner/csrun' + path, image, _ = self.fixture('amd64', source=self.args.source) + self.assertEqual(oci.Archive(path).verify(self.args, ['amd64']), [image]) + + def test_arm64_cannot_be_replaced_by_amd64(self): + path, _, _ = self.fixture('amd64') + with self.assertRaisesRegex(ValueError, 'platform inventory'): + oci.Archive(path).verify(self.args, ['arm64']) + + def test_extra_untested_runtime_platform_is_rejected(self): + path, _, _ = self.fixture('amd64') + archive = oci.Archive(path) + archive.index['manifests'].append({'platform': {'os': 'windows', 'architecture': 'amd64'}}) + with self.assertRaisesRegex(ValueError, 'Unexpected runtime'): + archive.verify(self.args, ['amd64']) + + def test_missing_sbom_blocks_verification(self): + path, _, _ = self.fixture('amd64', missing='https://spdx.dev/Document') + with self.assertRaisesRegex(ValueError, 'SBOM or provenance missing'): + oci.Archive(path).verify(self.args, ['amd64']) + + def test_wrong_attestation_subject_blocks_verification(self): + path, _, _ = self.fixture('amd64', subject='c' * 64) + with self.assertRaisesRegex(ValueError, 'subject mismatch'): + oci.Archive(path).verify(self.args, ['amd64']) + + def test_empty_buildkit_subject_is_rejected(self): + path, _, _ = self.fixture('amd64', subject=False) + with self.assertRaisesRegex(ValueError, 'subject mismatch'): + oci.Archive(path).verify(self.args, ['amd64']) + + def test_wrong_engine_blocks_verification(self): + path, _, _ = self.fixture('amd64', engine='c' * 64) + with self.assertRaisesRegex(ValueError, 'Identity mismatch'): + oci.Archive(path).verify(self.args, ['amd64']) + + def test_provenance_for_a_different_engine_is_rejected(self): + path, _, _ = self.fixture('amd64', provenance_engine='c' * 64) + with self.assertRaisesRegex(ValueError, 'Provenance build identity mismatch'): + oci.Archive(path).verify(self.args, ['amd64']) + + def test_sdk_labels_must_match_release_record(self): + path, _, _ = self.fixture('amd64') + self.args.sdks = ['10.0.404'] + with self.assertRaisesRegex(ValueError, 'SDK identity'): + oci.Archive(path).verify(self.args, ['amd64']) + + def test_merge_preserves_tested_child_manifests_and_configs(self): + amd, image1, config1 = self.fixture('amd64') + arm, image2, config2 = self.fixture('arm64') + self.args.archive = str(self.root / 'combined.tar') + self.args.inputs = [str(amd), str(arm)] + oci.merge(self.args) + archive = oci.Archive(self.args.archive) + images = archive.verify(self.args, ['amd64', 'arm64']) + self.assertEqual([image1, image2], images) + self.assertEqual([config1, config2], [archive.blob(d)['config'] for d in images]) + oci.check_seal(self.args.archive) + + def test_corrupted_transferred_archive_is_rejected(self): + path, _, _ = self.fixture('amd64') + with path.open('ab') as stream: + stream.write(b'changed') + with self.assertRaisesRegex(ValueError, 'checksum mismatch'): + oci.check_seal(path) + + def test_corrupted_blob_is_rejected_even_if_archive_resealed(self): + path, _, _ = self.fixture('amd64') + data = path.read_bytes().replace(b'11.0.100', b'11.0.999') + path.write_bytes(data) + oci.seal(path) + with self.assertRaisesRegex(ValueError, 'Corrupt OCI blob'): + oci.Archive(path) + + def test_missing_native_platform_blocks_assembly(self): + path, _, _ = self.fixture('amd64') + self.args.archive = str(self.root / 'combined.tar') + self.args.inputs = [str(path)] + with self.assertRaisesRegex(ValueError, 'platform inventory'): + 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'] + for cpu in ('amd64', 'arm64'): + path, _, config = self.fixture(cpu) + target = self.root / 'inputs' / cpu + target.mkdir(parents=True) + archive = target / ('image.' + cpu + '.tar') + shutil.copyfile(path, archive) + oci.seal(archive) + (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, + '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, + 'GITHUB_RUN_ID': '123', 'GITHUB_RUN_ATTEMPT': '1', 'GITHUB_REPOSITORY': 'codebeltnet/csrun'}): + release_images.assemble('11') + original = oci.checksum('out/image.tar') + release_images.split('11') + Path('resolved').mkdir() + assets = {p.name: {'browser_download_url': p.resolve().as_uri(), 'size': p.stat().st_size, + 'digest': 'sha256:' + oci.checksum(p)} for p in Path('assets').iterdir()} + Path('resolved/identity.json').write_text(json.dumps({ + 'tag': self.args.version, 'sha': self.args.revision, 'engine': self.args.engine, 'assets': assets})) + run = {'event': 'push', 'path': '.github/workflows/release.yml', 'head_sha': self.args.revision, + 'head_branch': self.args.version, 'run_attempt': 1, 'conclusion': 'success'} + def get_run(endpoint): + if endpoint == 'repos/codebeltnet/csrun/actions/runs/123/attempts/1': + return run + if endpoint == 'repos/codebeltnet/csrun/actions/runs/123': + 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)): + 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}): + with self.assertRaisesRegex(ValueError, 'Authoritative tag release run'): + release_images.restore('11') + self.assertEqual(original, oci.checksum('out/image.tar')) + + def test_latest_alias_is_rejected_before_any_registry_upload(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 = ['docker.io/fork/csrun:11', 'docker.io/fork/csrun:latest'] + oci.merge(self.args) + with patch.object(oci, 'skopeo') as transfer: + with self.assertRaisesRegex(ValueError, 'Invalid publishing destination'): + oci.publish(self.args) + transfer.assert_not_called() + + +class SkopeoTransportTests(unittest.TestCase): + def test_native_skopeo_does_not_need_a_local_docker_daemon(self): + with patch.dict('os.environ', {'DOCKER_HOST': 'ssh://builder'}, clear=True), patch.object(oci.shutil, 'which', return_value='/usr/bin/skopeo'), patch.object(oci.subprocess, 'run') as execute, patch.object(oci.subprocess, 'check_output') as inspect: + oci.skopeo(['copy', 'oci-archive:client.tar', 'docker://registry/image:11']) + execute.assert_called_once_with(['skopeo', 'copy', 'oci-archive:client.tar', 'docker://registry/image:11'], check=True) + inspect.assert_not_called() + + def test_remote_environment_host_is_rejected_before_container_launch(self): + for host in ('ssh://builder', 'tcp://builder:2376', 'tcp://localhost:2375'): + with self.subTest(host=host), patch.dict('os.environ', {'DOCKER_HOST': host}, clear=True), patch.object(oci.shutil, 'which', return_value=None), patch.object(oci.subprocess, 'run') as execute, patch.object(oci.subprocess, 'check_output') as inspect: + with self.assertRaisesRegex(ValueError, 'Native Skopeo is required'): + oci.skopeo(['copy', 'oci-archive:client.tar', 'docker://registry/image:11']) + execute.assert_not_called() + inspect.assert_not_called() + + def test_remote_active_context_is_rejected(self): + for environment in ({}, {'DOCKER_CONTEXT': 'remote', 'DOCKER_HOST': 'unix:///var/run/docker.sock'}): + with self.subTest(environment=environment), patch.dict('os.environ', environment, clear=True), patch.object(oci.shutil, 'which', return_value=None), patch.object(oci.subprocess, 'check_output', return_value='ssh://builder\n'), patch.object(oci.subprocess, 'run') as execute: + with self.assertRaisesRegex(ValueError, 'Native Skopeo is required'): + oci.skopeo(['inspect', '--raw', 'docker://registry/image:11'], capture=True) + execute.assert_not_called() + + def test_local_context_overrides_remote_host_and_keeps_container_fallback(self): + for host in ('unix:///var/run/docker.sock', 'npipe:////./pipe/docker_engine'): + with self.subTest(host=host), patch.dict('os.environ', {'DOCKER_CONTEXT': 'local', 'DOCKER_HOST': 'ssh://builder'}, clear=True), patch.object(oci.shutil, 'which', return_value=None), patch.object(oci.subprocess, 'check_output', return_value=host), patch.object(oci.subprocess, 'run') as execute: + oci.skopeo(['copy', 'oci-archive:client.tar', 'docker://registry/image:11']) + command = execute.call_args.args[0] + self.assertEqual(command[:3], ['docker', 'run', '--rm']) + self.assertIn('oci-archive:/archive1/client.tar', command) + + +class DeploymentIdentityTests(unittest.TestCase): + 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'): + release_images.resolve() + + def test_unexpected_release_tag_is_rejected(self): + with patch.dict('os.environ', {'GITHUB_REPOSITORY': 'codebeltnet/csrun', 'RELEASE_TAG': 'latest'}): + with self.assertRaisesRegex(ValueError, 'Unexpected release tag'): + release_images.resolve() + + def test_draft_release_cannot_be_promoted(self): + release = {'id': 1, 'draft': True, 'tag_name': 'v0.2.0'} + with patch.dict('os.environ', {'GITHUB_REPOSITORY': 'codebeltnet/csrun', 'RELEASE_TAG': 'v0.2.0', 'GITHUB_EVENT_NAME': 'workflow_dispatch', 'GITHUB_REF': 'refs/heads/main'}), patch.object(release_images, 'gh', return_value=release): + with self.assertRaisesRegex(ValueError, 'latest published stable release'): + release_images.resolve() + + def test_old_published_release_cannot_overwrite_current_aliases(self): + release = {'id': 1, 'draft': False, 'prerelease': False, 'published_at': '2026-11-15'} + with patch.dict('os.environ', {'GITHUB_REPOSITORY': 'codebeltnet/csrun', 'RELEASE_TAG': 'v0.2.0', 'GITHUB_EVENT_NAME': 'workflow_dispatch', 'GITHUB_REF': 'refs/heads/main'}), patch.object(release_images, 'gh', side_effect=[release, {'id': 2}]): + with self.assertRaisesRegex(ValueError, 'latest published stable release'): + release_images.resolve() + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/oci.py b/tools/oci.py new file mode 100644 index 0000000..a8fcc64 --- /dev/null +++ b/tools/oci.py @@ -0,0 +1,311 @@ +"""Verify, assemble and promote csrun OCI content without rebuilding it (stdlib only).""" +import argparse +import hashlib +import json +import os +import re +import shutil +from pathlib import Path +import subprocess +import tarfile +import tempfile +import weakref + +INDEX = 'application/vnd.oci.image.index.v1+json' +SOURCE = 'https://github.com/codebeltnet/csrun' + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def encoded(value): + return json.dumps(value, separators=(',', ':'), sort_keys=True).encode() + + +class Archive: + def __init__(self, path): + self.path = Path(path) + self.tar = tarfile.open(path) + self._close = weakref.finalize(self, self.tar.close) + self.members = {} + for member in self.tar: + if member.isdir(): + continue + name = member.name.removeprefix('./') + require(member.isfile() and name not in self.members, 'Unsafe or duplicate tar member') + require(name in ('index.json', 'oci-layout') or name.startswith('blobs/sha256/'), 'Unexpected OCI member') + self.members[name] = member + if name.startswith('blobs/'): + h = hashlib.sha256() + with self.tar.extractfile(member) as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + 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') + # 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]) + require(self.index.get('schemaVersion') == 2 and self.index.get('mediaType') == INDEX, 'Expected an OCI image index') + + def read(self, name): + with self.tar.extractfile(self.members[name]) as stream: + return json.load(stream) + + def blob(self, descriptor): + name = 'blobs/' + descriptor['digest'].replace(':', '/') + require(name in self.members and self.members[name].size == descriptor['size'], 'Missing or truncated OCI content') + return self.read(name) + + def verify(self, args, platforms): + runnable = [d for d in self.index['manifests'] if d.get('platform', {}).get('os') == 'linux'] + actual = [d['platform']['architecture'] for d in runnable] + require(sorted(actual) == sorted(platforms), f'Unexpected platform inventory: {actual}') + image_digests = {d['digest'] for d in runnable} + for desc in self.index['manifests']: + if desc in runnable: + continue + annotations = desc.get('annotations', {}) + require(desc.get('platform') == {'os': 'unknown', 'architecture': 'unknown'} + and annotations.get('vnd.docker.reference.type') == 'attestation-manifest' + and annotations.get('vnd.docker.reference.digest') in image_digests, + 'Unexpected runtime or unattached attestation in image index') + for desc in runnable: + manifest = self.blob(desc) + config = self.blob(manifest['config']) + require(config['architecture'] == desc['platform']['architecture'] and config['os'] == 'linux', 'Config CPU mismatch') + labels = config['config']['Labels'] + for key, value in { + 'org.opencontainers.image.source': getattr(args, 'source', SOURCE), + 'org.opencontainers.image.revision': args.revision, + 'org.opencontainers.image.version': args.version, + 'net.codebelt.csrun.engine.release': args.version, + 'net.codebelt.csrun.engine.sha256': args.engine, + }.items(): + require(labels.get(key) == value, f'Identity mismatch: {key}') + require(labels.get('net.codebelt.csrun.sdks') and labels.get('org.opencontainers.image.created'), 'Missing build identity') + if getattr(args, 'sdks', None): + require(labels['net.codebelt.csrun.sdks'].split(',') == args.sdks, 'OCI SDK identity differs from release inventory') + for layer in manifest['layers']: + name = 'blobs/' + layer['digest'].replace(':', '/') + require(name in self.members and self.members[name].size == layer['size'], 'Missing image layer') + predicates = set() + for att in self.index['manifests']: + if att.get('annotations', {}).get('vnd.docker.reference.digest') != desc['digest']: + continue + for layer in self.blob(att)['layers']: + statement = self.blob(layer) + require(any(s.get('digest', {}).get('sha256') == desc['digest'][7:] for s in statement['subject']), 'Attestation subject mismatch') + predicate = statement['predicateType'] + body = statement['predicate'] + if predicate == 'https://spdx.dev/Document': + require(body.get('spdxVersion') and body.get('packages'), 'Empty SBOM') + if predicate.startswith('https://slsa.dev/provenance/'): + require(body.get('buildType') or body.get('buildDefinition'), 'Empty provenance') + parameters = body.get('buildDefinition', {}).get('externalParameters', {}).get('request', {}).get('args') + if parameters is None: + parameters = body.get('invocation', {}).get('parameters', {}).get('args', {}) + for key, value in { + 'build-arg:ENGINE_SHA256': args.engine, + 'build-arg:ENGINE_VERSION': args.version, + 'label:org.opencontainers.image.revision': args.revision, + 'label:org.opencontainers.image.source': getattr(args, 'source', SOURCE), + 'label:net.codebelt.csrun.sdks': labels['net.codebelt.csrun.sdks'], + }.items(): + require(parameters.get(key) == value, 'Provenance build identity mismatch: ' + key) + predicates.add(predicate) + require('https://spdx.dev/Document' in predicates and any(p.startswith('https://slsa.dev/provenance/') for p in predicates), 'SBOM or provenance missing') + return runnable + + +def checksum(path): + with open(path, 'rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def seal(path): + Path(str(path) + '.sha256').write_text(checksum(path) + ' ' + Path(path).name + '\n') + + +def check_seal(path): + require(Path(str(path) + '.sha256').read_text().split()[0] == checksum(path), 'Archive checksum mismatch') + + +def add_bytes(tar, name, data): + import io + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + + +def check_skopeo(): + """Require native transport when the utility daemon cannot mount client files.""" + if shutil.which('skopeo'): + return True + # DOCKER_CONTEXT overrides DOCKER_HOST, just as it does in the Docker CLI. + host = os.environ.get('DOCKER_HOST') if not os.environ.get('DOCKER_CONTEXT') else None + if not host: + host = subprocess.check_output( + ['docker', 'context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'], text=True).strip() + require(host.startswith(('unix://', 'npipe://')), + 'Native Skopeo is required when the active Docker daemon uses SSH or TCP; ' + 'the utility container cannot bind-mount client archives or credentials. ' + 'Install skopeo locally or select a local Docker context.') + return False + + +def skopeo(arguments, *, capture=False): + """Use native Skopeo or a versioned utility container, including on Windows.""" + if check_skopeo(): + command = ['skopeo', *arguments] + else: + command = ['docker', 'run', '--rm', '--user', '0'] + converted = [] + for position, argument in enumerate(arguments): + if argument.startswith('oci-archive:'): + path = Path(argument[len('oci-archive:'):]).resolve() + mount = '/archive' + str(position) + command.extend(['--volume', str(path.parent) + ':' + mount]) + argument = 'oci-archive:' + mount + '/' + path.name + converted.append(argument) + auth = os.environ.get('REGISTRY_AUTH_FILE') + if auth: + 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) + subprocess.run(command, check=True) + + +def loaded_config(args, archive): + """Check raw config bytes from Docker, whose image ID may be a manifest ID.""" + desc = next(d for d in archive.index['manifests'] if d.get('platform', {}).get('architecture') == args.platform) + expected = archive.blob(desc)['config']['digest'] + command = ['docker'] + if args.context: + command += ['--context', args.context] + command += ['image', 'save', args.image] + process = subprocess.Popen(command, stdout=subprocess.PIPE) + found = False + try: + with tarfile.open(fileobj=process.stdout, mode='r|') as saved: + for member in saved: + name = member.name.removeprefix('./') + if name in ('blobs/' + expected.replace(':', '/'), expected[7:] + '.json'): + with saved.extractfile(member) as stream: + require('sha256:' + hashlib.file_digest(stream, 'sha256').hexdigest() == expected, 'Loaded config bytes changed') + found = True + require(process.wait() == 0 and found, 'Loaded config differs from exported OCI artifact') + print(expected) + finally: + process.stdout.close() + if process.poll() is None: + process.kill() + process.wait() + + +def merge(args): + archives = [Archive(p) for p in args.inputs] + manifests = [] + for archive in archives: + cpus = [d['platform']['architecture'] for d in archive.index['manifests'] if d.get('platform', {}).get('os') == 'linux'] + require(len(cpus) == 1, 'Expected one tested platform per input') + archive.verify(args, cpus) + check_seal(archive.path) + manifests.extend(archive.index['manifests']) + index = encoded({'schemaVersion': 2, 'mediaType': INDEX, 'manifests': manifests, 'annotations': { + 'org.opencontainers.image.version': args.version.removeprefix('v'), 'org.opencontainers.image.revision': args.revision}}) + digest = hashlib.sha256(index).hexdigest() + layout = {'schemaVersion': 2, 'mediaType': INDEX, 'manifests': [{'mediaType': INDEX, 'digest': 'sha256:' + digest, + 'size': len(index), 'annotations': {'org.opencontainers.image.ref.name': args.version.removeprefix('v')}}]} + with tarfile.open(args.archive, 'w') as output: + seen = set() + for archive in archives: + for name, member in archive.members.items(): + if name.startswith('blobs/') and name not in seen: + with archive.tar.extractfile(member) as stream: + info = tarfile.TarInfo(name) + info.size = member.size + output.addfile(info, stream) + seen.add(name) + add_bytes(output, 'blobs/sha256/' + digest, index) + add_bytes(output, 'index.json', encoded(layout)) + add_bytes(output, 'oci-layout', encoded({'imageLayoutVersion': '1.0.0'})) + Archive(args.archive).verify(args, [args.platform] if getattr(args, 'platform', None) else ['amd64', 'arm64']) + seal(args.archive) + print('Assembled sha256:' + digest) + return 'sha256:' + digest + + +def publish(args): + 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(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') + for tag in args.tags: + skopeo(['copy', '--all', '--preserve-digests', 'oci-archive:' + args.archive, '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() + digests.add(digest) + with tempfile.TemporaryDirectory() as temp: + downloaded = str(Path(temp) / 'registry.tar') + skopeo(['copy', '--all', '--preserve-digests', 'docker://' + tag.rsplit(':', 1)[0] + '@' + digest, 'oci-archive:' + downloaded]) + Archive(downloaded).verify(args, [args.platform] if getattr(args, 'platform', None) else ['amd64', 'arm64']) + print(tag + '@' + digest) + published.append({'tag': tag, 'digest': digest}) + require(len(digests) == 1, 'SDK aliases resolved to different indexes') + Path(str(args.archive) + '.published.json').write_bytes(encoded(published)) + 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') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('command', choices=['verify', 'merge', 'publish', 'config', 'loaded-config', 'check-skopeo']) + parser.add_argument('archive', nargs='?') + parser.add_argument('--version') + parser.add_argument('--revision') + parser.add_argument('--engine') + parser.add_argument('--source', default=SOURCE) + parser.add_argument('--platform', choices=['amd64', 'arm64']) + parser.add_argument('--expected') + parser.add_argument('--image') + parser.add_argument('--context') + parser.add_argument('--tags', nargs='+') + parser.add_argument('inputs', nargs='*') + args = parser.parse_intermixed_args() + if args.command == 'check-skopeo': + check_skopeo() + return + if not args.archive: + parser.error('archive is required') + if args.command == 'merge': + merge(args) + elif args.command == 'publish': + publish(args) + else: + archive = Archive(args.archive) + if args.command == 'loaded-config': + loaded_config(args, archive) + elif args.command == 'config': + desc = next(d for d in archive.index['manifests'] if d.get('platform', {}).get('architecture') == args.platform) + require(archive.blob(desc)['config']['digest'] == args.expected, 'Loaded config differs from tested archive') + else: + archive.verify(args, [args.platform] if args.platform else ['amd64', 'arm64']) + seal(args.archive) + + +if __name__ == '__main__': + main() diff --git a/tools/release-images.py b/tools/release-images.py new file mode 100644 index 0000000..07d08a5 --- /dev/null +++ b/tools/release-images.py @@ -0,0 +1,183 @@ +"""Release artifact lifecycle. No image build commands belong in this file.""" +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import urllib.request +from types import SimpleNamespace +import oci + + +def gh(endpoint): + return json.loads(subprocess.check_output(['gh', 'api', endpoint])) + + +def write(path, value): + Path(path).write_text(json.dumps(value, indent=2) + '\n') + + +def identity(meta): + return SimpleNamespace(version=meta['EngineVersion'], revision=meta['SourceCommit'], engine=meta['EngineSha256'], sdks=meta['SdkVersions']) + + +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({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') + 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') + for archive_path in archives: + cpu = 'arm64' if archive_path.endswith('.arm64.tar') else 'amd64' + record = next(m for m in metadata if m['Platforms'] == ['linux/' + cpu]) + saved = oci.Archive(archive_path) + runnable = saved.verify(identity(first), [cpu])[0] + oci.require(saved.blob(runnable)['config']['digest'] == record['ConfigDigest'], 'Native test record does not identify the assembled image config') + args = identity(first) + args.inputs = archives + args.archive = 'out/image.tar' + first['OciIndexDigest'] = oci.merge(args) + first['Verification'] = metadata + first['ReleaseRunId'] = os.environ['GITHUB_RUN_ID'] + first['ReleaseRunAttempt'] = os.environ['GITHUB_RUN_ATTEMPT'] + first['Variant'] = variant + write('out/release.json', first) + summary(first) + + +def split(variant): + Path('assets').mkdir(exist_ok=True) + pieces = [] + with open('out/image.tar', 'rb') as source: + number = 0 + while True: + block = source.read(1024 * 1024) + if not block: + break + path = Path(f'assets/csrun-{variant}.oci.part{number:03}') + size = 0 + with path.open('wb') as target: + while block: + target.write(block) + size += len(block) + if size >= 1024 ** 3: + break + block = source.read(1024 * 1024) + pieces.append({'name': path.name, 'sha256': oci.checksum(path), 'size': path.stat().st_size}) + number += 1 + meta = json.loads(Path('out/release.json').read_text()) + meta['Pieces'] = pieces + meta['ArchiveSha256'] = oci.checksum('out/image.tar') + write(f'assets/csrun-{variant}.json', meta) + + +def resolve(): + repo = os.environ['GITHUB_REPOSITORY'] + oci.require(repo == 'codebeltnet/csrun', 'Production deployment is restricted to codebeltnet/csrun') + tag = os.environ['RELEASE_TAG'] + oci.require(re.fullmatch(r'v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)', tag), 'Unexpected release tag') + event = os.environ['GITHUB_EVENT_NAME'] + if event == 'workflow_dispatch': + oci.require(os.environ['GITHUB_REF'] == 'refs/heads/main', 'Recovery must be dispatched from main') + else: + data = json.loads(Path(os.environ['GITHUB_EVENT_PATH']).read_text()) + oci.require(event == 'release' and data['action'] == 'published' and data['release']['tag_name'] == tag, 'Unexpected release event') + release = gh(f'repos/{repo}/releases/tags/{tag}') + latest = gh(f'repos/{repo}/releases/latest') + oci.require(not release['draft'] and not release['prerelease'] and release['published_at'] and latest['id'] == release['id'], 'Requested release must be the latest published stable release') + if event == 'release': + oci.require(data['release']['id'] == release['id'], 'Release ID changed') + # Follow annotated tags through GitHub's commit endpoint. + commit = gh(f'repos/{repo}/commits/{tag}')['sha'] + comparison = gh(f'repos/{repo}/compare/{commit}...main') + oci.require(comparison['status'] in ('ahead', 'identical'), 'Release source is not in main history') + assets = {a['name']: a for a in release['assets']} + asset = assets['csrun.ps1'] + Path('resolved').mkdir(exist_ok=True) + engine = Path('resolved/csrun.ps1') + # The one and only moving engine download. All subsequent jobs consume identity.json. + urllib.request.urlretrieve('https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1', engine) + digest = oci.checksum(engine) + oci.require(asset.get('digest') == 'sha256:' + digest and asset['size'] == engine.stat().st_size, 'Latest script checksum or release identity changed') + write('resolved/identity.json', {'tag': tag, 'releaseId': release['id'], 'sha': commit, 'engine': digest, 'assets': assets}) + with open(os.environ['GITHUB_OUTPUT'], 'a') as stream: + stream.write('sha=' + commit + '\n') + + +def download(asset, destination): + oci.require(asset.get('digest', '').startswith('sha256:'), 'Release asset has no authoritative digest') + urllib.request.urlretrieve(asset['browser_download_url'], destination) + oci.require('sha256:' + oci.checksum(destination) == asset['digest'] and Path(destination).stat().st_size == asset['size'], 'Release asset checksum mismatch') + + +def restore(variant, versions=None): + resolved = json.loads(Path('resolved/identity.json').read_text()) + Path('out').mkdir(exist_ok=True) + download(resolved['assets'][f'csrun-{variant}.json'], 'out/release.json') + meta = json.loads(Path('out/release.json').read_text()) + oci.require(meta['EngineVersion'] == resolved['tag'] and meta['SourceCommit'] == resolved['sha'] and meta['EngineSha256'] == resolved['engine'] and meta['Variant'] == variant, 'Artifact does not represent the resolved latest engine and release') + run = gh(f"repos/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{meta['ReleaseRunId']}/attempts/{meta['ReleaseRunAttempt']}") + oci.require(run['event'] == 'push' and run['path'] == '.github/workflows/release.yml' and run['head_sha'] == resolved['sha'] and run['head_branch'] == resolved['tag'] and run['run_attempt'] == int(meta['ReleaseRunAttempt']) and run['conclusion'] == 'success', 'Authoritative tag release run did not succeed') + if versions is not None: + oci.require(meta['SdkVersions'] == versions, 'Requested exact SDK versions differ from the saved release; never rebuild on recovery') + 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') + 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') + download(resolved['assets'][part['name']], 'out/part') + oci.require(oci.checksum('out/part') == part['sha256'] and Path('out/part').stat().st_size == part['size'], 'Piece differs from verified release record') + with open('out/part', 'rb') as stream: + shutil.copyfileobj(stream, archive) + 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']) + oci.seal('out/image.tar') + summary(meta) + + +def summary(meta): + path = os.environ.get('GITHUB_STEP_SUMMARY') + 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") + 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(): + 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()) + args = identity(meta) + args.archive = 'out/image.tar' + args.tags = meta['Tags'] + oci.publish(args) + + +if __name__ == '__main__': + command = sys.argv[1] + if command in ('assemble', 'split', 'restore'): + globals()[command](sys.argv[2]) + else: + globals()[command]()