Skip to content
Merged
48 changes: 48 additions & 0 deletions .github/scripts/CiScanMutation.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,15 @@ BeforeAll {
return $Path
}

function Test-FixedManifestHandoff {
param([Parameter(Mandatory = $true)][string]$Source)

return $Source -match 'CI_SCAN_MANIFEST_PATH: \$\{\{ runner\.temp \}\}/gh-aw/safe-jobs/agent/manifest_final\.json' -and
$Source -match 'argument-free `submit_ci_scan`' -and
$Source -notmatch '(?ms)^\s{6}inputs:\s*\r?\n\s{8}(?:manifest|manifest_path):' -and
$Source -notmatch 'one `manifest` argument'
}

function New-ProbeManifest {
param(
[string]$Path,
Expand Down Expand Up @@ -403,6 +412,45 @@ Describe 'CI scanner twin discovery mutation coverage' {
@(Get-CiScanTwin).Count | Should -Be 2
}

Describe 'CI scanner fixed manifest handoff mutation coverage' {
BeforeAll {
$script:WorkflowSources = @(
Get-Content -LiteralPath (Join-Path $PSScriptRoot '../workflows/ci-status-main.md') -Raw
Get-Content -LiteralPath (Join-Path $PSScriptRoot '../workflows/ci-status-net11.md') -Raw
)
$script:SafeJobStepsNeedle = " steps:`n - name: Require successful agent submission gate"
}

It 'baseline: both twins use the fixed argument-free artifact handoff' {
@($script:WorkflowSources | Where-Object { Test-FixedManifestHandoff -Source $_ }).Count |
Should -Be 2
}

It 'mutation "nested-string-transport": a manifest tool input fails the handoff invariant' {
foreach ($source in $script:WorkflowSources) {
$source.Contains($script:SafeJobStepsNeedle) | Should -BeTrue
$mutated = $source.Replace(
$script:SafeJobStepsNeedle,
" inputs:`n manifest:`n required: true`n type: string`n$($script:SafeJobStepsNeedle)")

$mutated | Should -Not -BeExactly $source
(Test-FixedManifestHandoff -Source $mutated) | Should -BeFalse
}
}

It 'mutation "agent-selected-path": a manifest_path tool input fails the handoff invariant' {
foreach ($source in $script:WorkflowSources) {
$source.Contains($script:SafeJobStepsNeedle) | Should -BeTrue
$mutated = $source.Replace(
$script:SafeJobStepsNeedle,
" inputs:`n manifest_path:`n required: true`n type: string`n$($script:SafeJobStepsNeedle)")

$mutated | Should -Not -BeExactly $source
(Test-FixedManifestHandoff -Source $mutated) | Should -BeFalse
}
}
}

It 'mutation "one-twin-omitted": discovery reports a single twin' {
# Proves the anti-vacuity assertion in Validate-CiScanPublisher.Tests.ps1
# is load-bearing: dropping a twin changes what discovery returns, so the
Expand Down
115 changes: 94 additions & 21 deletions .github/scripts/Validate-CiScanManifest.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,41 @@ Describe 'CI scanner issue payload gate' {
)

{ Test-CiScanManifest -Manifest $manifest } |
Should -Throw '*non-normalized or unsafe characters*'
Should -Throw '*unsafe characters*'
}

It 'canonicalizes the exact production uppercase fingerprint before publication' {
$productionFingerprint = 'ci-scan|main|maui-pr|runoniOS_MauiReleaseTrimFull|ios-simulator-boot-timeout|ios-simulator-64'
$canonicalFingerprint = 'ci-scan|main|maui-pr|runonios_mauireleasetrimfull|ios-simulator-boot-timeout|ios-simulator-64'
$body = (New-TestBody).Replace('- **Branch**: net11.0', '- **Branch**: main')
$manifest = New-CompleteManifest -MainSignatures @(
(New-TestSignature -Fingerprint $productionFingerprint -Body $body)
)
$evidenceRoot = New-DefaultEvidenceRoot

$plan = Test-CiScanManifest `
-Manifest $manifest `
-ExpectedBuilds (New-ExpectedBuilds) `
-TrustedEvidencePath $evidenceRoot `
-ScannerId 'ci-scan'

$plan.pipelines[0].signatures[0].fingerprint | Should -BeExactly $canonicalFingerprint
$plan.issues[0].Fingerprint | Should -BeExactly $canonicalFingerprint
$plan.issues[0].Body |
Should -Match "(?m)^<!-- ci-scan-fingerprint: $([regex]::Escape($canonicalFingerprint)) -->$"
$plan.issues[0].Body.Contains('runoniOS_MauiReleaseTrimFull') | Should -BeFalse
}

It 'rejects fingerprints that collide after trusted case canonicalization' {
$productionFingerprint = 'ci-scan|main|maui-pr|runoniOS_MauiReleaseTrimFull|ios-simulator-boot-timeout|ios-simulator-64'
$canonicalFingerprint = $productionFingerprint.ToLowerInvariant()
$manifest = New-CompleteManifest -MainSignatures @(
(New-TestSignature -Fingerprint $productionFingerprint -Disposition 'existing' -IssueNumber 36827),
(New-TestSignature -Fingerprint $canonicalFingerprint -Disposition 'existing' -IssueNumber 36828)
)

{ Test-CiScanManifest -Manifest $manifest -ScannerId 'ci-scan' } |
Should -Throw "*Duplicate fingerprint '$canonicalFingerprint'*"
}

<#
Expand Down Expand Up @@ -1237,51 +1271,80 @@ Describe 'CI scanner agent output gate' {
$path = Join-Path $TestDrive 'agent-output.json'
@{
items = @(
@{ type = 'submit_ci_scan'; manifest = '{}' },
@{ type = 'submit_ci_scan' },
@{ type = 'noop'; body = 'alternate output' }
)
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $path

{ Get-ScannerManifestFromAgentOutput -Path $path } |
{ Assert-ScannerSubmissionFromAgentOutput -Path $path } |
Should -Throw '*exactly one item of type submit_ci_scan and no alternate outputs*'
}

It 'rejects a manifest that is not a JSON string' {
# agent_output.json is agent-controlled. An already-decoded object used to be
# returned verbatim, so it reached validation without passing the emptiness or
# 500000-character limits that guard the string form.
$path = Join-Path $TestDrive 'object-manifest.json'
It 'rejects the production nested-string transport even when its JSON is valid' {
$path = Join-Path $TestDrive 'nested-manifest.json'
@{
items = @(
@{ type = 'submit_ci_scan'; manifest = @{ pipelines = @() } }
@{ type = 'submit_ci_scan'; manifest = '{"pipelines":[]}' }
)
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $path

{ Get-ScannerManifestFromAgentOutput -Path $path } |
Should -Throw '*manifest must be a JSON string*'
{ Assert-ScannerSubmissionFromAgentOutput -Path $path } |
Should -Throw '*authorization-only and must not contain manifest data or a path*'
}

It 'rejects a manifest string over the size limit' {
$path = Join-Path $TestDrive 'oversized-manifest.json'
It 'rejects agent selection of an arbitrary manifest path' {
$path = Join-Path $TestDrive 'manifest-path.json'
@{
items = @(
@{ type = 'submit_ci_scan'; manifest = ('x' * 500001) }
@{ type = 'submit_ci_scan'; manifest_path = '/tmp/gh-aw/agent/other.json' }
)
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $path

{ Get-ScannerManifestFromAgentOutput -Path $path } |
Should -Throw '*exceeds the 500000 character limit*'
{ Assert-ScannerSubmissionFromAgentOutput -Path $path } |
Should -Throw '*authorization-only and must not contain manifest data or a path*'
}

It 'accepts a well-formed manifest string' {
$path = Join-Path $TestDrive 'good-manifest.json'
It 'accepts exactly one argument-free submission authorization' {
$path = Join-Path $TestDrive 'authorization.json'
@{
items = @(
@{ type = 'submit_ci_scan'; manifest = '{"pipelines":[]}' }
@{ type = 'submit_ci_scan' }
)
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $path

$result = Get-ScannerManifestFromAgentOutput -Path $path
{ Assert-ScannerSubmissionFromAgentOutput -Path $path } | Should -Not -Throw
}

It 'reads multiline issue bodies from the fixed manifest file without nested JSON transport' {
$path = Join-Path $TestDrive 'manifest_final.json'
$body = "## Summary`nFirst line.`n`n## Error Message`nLiteral `"quoted`" line."
@{
pipelines = @(
@{
name = 'maui-pr'
signatures = @(@{ body = $body })
}
)
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $path

$result = Get-ScannerManifestFromFile -Path $path

$result.pipelines[0].signatures[0].body | Should -BeExactly $body
}

It 'rejects a fixed manifest file over the byte limit' {
$path = Join-Path $TestDrive 'oversized-manifest.json'
Set-Content -LiteralPath $path -Value ('x' * 500001) -NoNewline

{ Get-ScannerManifestFromFile -Path $path } |
Should -Throw '*exceeds the 500000 byte limit*'
}

It 'accepts a well-formed fixed manifest file' {
$path = Join-Path $TestDrive 'good-manifest.json'
Set-Content -LiteralPath $path -Value '{"pipelines":[]}'

$result = Get-ScannerManifestFromFile -Path $path
@($result.pipelines).Count | Should -Be 0
}
}
Expand Down Expand Up @@ -1315,7 +1378,17 @@ Describe 'CI scanner workflow source invariants: <_>' -ForEach @('ci-status-main

It 'requires exactly one complete submission and forbids alternate outputs' {
$workflowSource | Should -Match 'select\(\.type == "submit_ci_scan"\)'
$workflowSource | Should -Match 'Expected exactly one submit_ci_scan output and no alternate outputs'
$workflowSource | Should -Match 'Expected exactly one argument-free submit_ci_scan output and no alternate outputs'
}

It 'uses one bounded fixed same-run artifact file and no tool-selected transport' {
$workflowSource |
Should -Match 'CI_SCAN_MANIFEST_PATH: \$\{\{ runner\.temp \}\}/gh-aw/safe-jobs/agent/manifest_final\.json'
$workflowSource | Should -Match '/tmp/gh-aw/agent/manifest_final\.json'
$workflowSource | Should -Match 'same-run `agent` artifact'
$workflowSource | Should -Match 'argument-free `submit_ci_scan`'
$workflowSource | Should -Not -Match '(?ms)^\s{6}inputs:\s*\r?\n\s{8}(?:manifest|manifest_path):'
$workflowSource | Should -Not -Match 'one `manifest` argument'
}

It 'keeps custom publisher staging identical to framework staging' {
Expand Down
79 changes: 52 additions & 27 deletions .github/scripts/Validate-CiScanManifest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@

.DESCRIPTION
This script is the fail-closed boundary between a scanner agent and GitHub
issue writes. It does not call GitHub. It validates the single batched
safe-output payload against a trusted build inventory, recomputes filed-issue
match counts from frozen CI evidence, injects the canonical scanner markers
itself, and writes a normalized plan for the downstream GitHub API step.
issue writes. It does not call GitHub. It validates the single fixed-path
manifest from the same-run agent artifact against a trusted build inventory,
recomputes filed-issue match counts from frozen CI evidence, injects the
canonical scanner markers itself, and writes a normalized plan for the
downstream GitHub API step.

The agent never supplies the markers. gh-aw strips literal HTML comments out
of the compiled prompt, so any design that asks the agent to emit
Expand Down Expand Up @@ -173,34 +174,49 @@ function ConvertTo-PositiveIntegerArray {
return $normalized.ToArray()
}

function Get-ScannerManifestFromAgentOutput {
function Assert-ScannerSubmissionFromAgentOutput {
param([Parameter(Mandatory = $true)][string]$Path)

if (-not (Test-Path -LiteralPath $Path)) {
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
throw "Agent output '$Path' does not exist."
}

$payload = Get-Content -Raw -LiteralPath $Path | ConvertFrom-Json
$rawOutput = Get-Content -Raw -LiteralPath $Path
if ([string]::IsNullOrWhiteSpace($rawOutput) -or $rawOutput.Length -gt 100000) {
throw 'Agent output is empty or exceeds the 100000 character limit.'
}

$payload = $rawOutput | ConvertFrom-Json
$items = @($payload.items | Where-Object { $null -ne $_ })
if ($items.Count -ne 1 -or $items[0].type -ne 'submit_ci_scan') {
throw "Agent output must contain exactly one item of type submit_ci_scan and no alternate outputs."
}

$rawManifest = Get-RequiredProperty -Object $items[0] -Name 'manifest' -Context 'submit_ci_scan item'
# The safe-output tool declares `manifest` as a string, but agent_output.json is
# agent-controlled and this is the fail-closed boundary, so the contract is enforced
# rather than assumed. Accepting an already-decoded object would hand back a payload
# that never passed the emptiness and size limits below.
if ($rawManifest -isnot [string]) {
throw 'submit_ci_scan manifest must be a JSON string.'
$itemProperties = @($items[0].PSObject.Properties.Name)
if ($itemProperties.Count -ne 1 -or $itemProperties[0] -cne 'type') {
throw 'submit_ci_scan is authorization-only and must not contain manifest data or a path.'
}
if ([string]::IsNullOrWhiteSpace($rawManifest)) {
throw 'submit_ci_scan manifest is empty.'
}

function Get-ScannerManifestFromFile {
param([Parameter(Mandatory = $true)][string]$Path)

if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
throw "Fixed scanner manifest '$Path' does not exist."
}

$manifestFile = Get-Item -LiteralPath $Path
if (($manifestFile.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
throw 'Fixed scanner manifest must not be a symbolic link.'
}
if ($rawManifest.Length -gt 500000) {
throw 'submit_ci_scan manifest exceeds the 500000 character limit.'
if ($manifestFile.Length -eq 0 -or $manifestFile.Length -gt 500000) {
throw 'Fixed scanner manifest is empty or exceeds the 500000 byte limit.'
}

$rawManifest = Get-Content -Raw -LiteralPath $manifestFile.FullName
if ([string]::IsNullOrWhiteSpace($rawManifest)) {
throw 'Fixed scanner manifest is empty.'
}
return $rawManifest | ConvertFrom-Json
}

Expand Down Expand Up @@ -406,11 +422,14 @@ function Assert-ValidFingerprint {
if ($Fingerprint.Length -gt 512) {
throw 'Fingerprint exceeds 512 characters.'
}
if ($Fingerprint -cnotmatch '^[a-z0-9][a-z0-9 ._:/+()\-|]*$') {
throw "Fingerprint contains non-normalized or unsafe characters."
if ($Fingerprint -cnotmatch '^[A-Za-z0-9][A-Za-z0-9 ._:/+()\-|]*$') {
throw "Fingerprint contains unsafe characters."
}

$parts = @($Fingerprint.Split('|'))
# Casing is not a trust decision. Canonicalize the accepted ASCII alphabet at
# the trusted boundary so prompt compliance cannot determine marker identity.
$canonicalFingerprint = $Fingerprint.ToLowerInvariant()
$parts = @($canonicalFingerprint.Split('|'))
if ($parts.Count -ne 6 -or @($parts | Where-Object { [string]::IsNullOrWhiteSpace($_) }).Count -gt 0) {
throw 'Fingerprint must contain exactly six non-empty pipe-delimited fields.'
}
Expand All @@ -421,20 +440,22 @@ function Assert-ValidFingerprint {
"and pipeline '$PipelineName'.")
}

# The fingerprint is injected verbatim into the canonical
# The canonical fingerprint is injected verbatim into the
# `<!-- ci-scan-fingerprint: ... -->` marker. Downstream consumers (the fixer, the
# lock sweep, and this publisher's own dedup path) match that marker against issue
# bodies that have been through `ConvertTo-SafeIssueBody`, so a fingerprint that
# neutralization would rewrite is unmatchable. Today only the issue/PR-URL rule is
# reachable (`@` and `#` are already outside the allowed charset), but asserting the
# round-trip rather than enumerating URL shapes keeps this check correct for free if
# a neutralization rule is ever added or widened.
if (-not [string]::Equals((ConvertTo-SafeIssueBody -Body $Fingerprint), $Fingerprint,
if (-not [string]::Equals((ConvertTo-SafeIssueBody -Body $canonicalFingerprint), $canonicalFingerprint,
[System.StringComparison]::Ordinal)) {
throw ('Fingerprint would be rewritten by notification neutralization ' +
'(it contains a GitHub issue/PR URL, @mention, or #reference). ' +
'Normalize it in the scanner before filing.')
}

return $canonicalFingerprint
}

function Get-ValidatedMatchPattern {
Expand Down Expand Up @@ -898,11 +919,11 @@ function Test-CiScanManifest {

$signature = $signatures[$signatureIndex]
$signatureContext = "$context signature[$signatureIndex]"
$fingerprint = ConvertTo-TrimmedString (
$rawFingerprint = ConvertTo-TrimmedString (
Get-RequiredProperty -Object $signature -Name 'fingerprint' -Context $signatureContext
)
Assert-ValidFingerprint `
-Fingerprint $fingerprint `
$fingerprint = Assert-ValidFingerprint `
-Fingerprint $rawFingerprint `
-PipelineName $name `
-ScannerConfig $scannerConfig
if (-not $fingerprints.Add($fingerprint)) {
Expand Down Expand Up @@ -1119,6 +1140,9 @@ if ($MyInvocation.InvocationName -eq '.') {
if (-not $env:GH_AW_AGENT_OUTPUT) {
throw 'GH_AW_AGENT_OUTPUT is required.'
}
if (-not $env:CI_SCAN_MANIFEST_PATH) {
throw 'CI_SCAN_MANIFEST_PATH is required.'
}
if (-not $env:CI_SCAN_SCANNER_ID) {
throw 'CI_SCAN_SCANNER_ID is required.'
}
Expand All @@ -1133,7 +1157,8 @@ if (-not $env:CI_SCAN_TRUSTED_EVIDENCE_PATH) {
}

try {
$manifest = Get-ScannerManifestFromAgentOutput -Path $env:GH_AW_AGENT_OUTPUT
Assert-ScannerSubmissionFromAgentOutput -Path $env:GH_AW_AGENT_OUTPUT
$manifest = Get-ScannerManifestFromFile -Path $env:CI_SCAN_MANIFEST_PATH
$expectedBuilds = Get-CiScanExpectedBuilds -Path $env:CI_SCAN_EXPECTED_BUILDS_PATH
$plan = Test-CiScanManifest `
-Manifest $manifest `
Expand Down
Loading
Loading