From 323371f5d303a957f32285e2d03eb39052d13d2c Mon Sep 17 00:00:00 2001 From: Kevin Harder Date: Thu, 12 Nov 2026 17:22:47 -0600 Subject: [PATCH 1/3] Fix cancellation test ordering and retain CI failure diagnostics --- .github/scripts/ci-command.js | 66 ++++++++++++++++++++++++++ .github/scripts/ci-command.test.js | 63 +++++++++++++++++++++++++ .github/scripts/ci-smoke.ps1 | 18 ++++++++ .github/workflows/ci.yml | 74 +++++++++++++++++++----------- .github/workflows/release.yml | 15 ++++-- tests/ListNavigationTests.cs | 15 +++++- tests/WorkflowUiTests.cs | 12 +++-- 7 files changed, 225 insertions(+), 38 deletions(-) create mode 100644 .github/scripts/ci-command.js create mode 100644 .github/scripts/ci-command.test.js create mode 100644 .github/scripts/ci-smoke.ps1 diff --git a/.github/scripts/ci-command.js b/.github/scripts/ci-command.js new file mode 100644 index 0000000..49a1515 --- /dev/null +++ b/.github/scripts/ci-command.js @@ -0,0 +1,66 @@ +// Keep a small diagnostic tail without changing the command's exit status. +const { spawn } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { stripVTControlCharacters } = require('node:util'); + +const LIMIT = 32 * 1024; + +function sanitize(text, env = process.env) { + text = stripVTControlCharacters(text); + for (const [name, value] of Object.entries(env)) { + if (/token|password|secret|credential|connection.?string/i.test(name) && value?.length >= 4) { + text = text.split(value).join('[REDACTED]'); + } + } + return text + .replace(/(authorization\s*[:=]\s*)(?:bearer|basic)\s+\S+/gi, '$1[REDACTED]') + .replace(/((?:access_token|token|password|secret)=)[^\s&]+/gi, '$1[REDACTED]') + .replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+)\b/g, '[REDACTED]') + .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ''); +} + +// Retain complete final lines. Dropping a partial first line also avoids keeping +// only the suffix of a credential that straddles the capture boundary. +function tail(text) { + if (Buffer.byteLength(text) <= LIMIT) return text; + text = Buffer.from(text).subarray(-LIMIT).toString('utf8'); + return '[earlier output omitted]\n' + text.slice(text.indexOf('\n') + 1 || text.length); +} + +async function run(phase, command, args) { + if (!/^[a-z][a-z0-9-]*$/.test(phase || '') || !command) throw new Error('Usage: ci-command.js [args...]'); + let stdout = '', stderr = ''; + const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }); + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + child.stdout.on('data', data => { process.stdout.write(data); stdout = tail(stdout + data); }); + child.stderr.on('data', data => { process.stderr.write(data); stderr = tail(stderr + data); }); + child.on('error', error => { stderr += `Could not start command: ${error.code}\n`; }); + const code = await new Promise(resolve => child.on('close', (status, signal) => { + resolve(status !== null && status >= 0 ? status : signal ? 128 + (os.constants.signals[signal] || 0) : 127); + })); + try { + const directory = path.join('obj', 'ci-diagnostics'); + fs.mkdirSync(directory, { recursive: true }); + const sdk = JSON.parse(fs.readFileSync('global.json', 'utf8')).sdk.version; + const metadata = `Phase: ${phase}\nExit code: ${code}\nOS/architecture: ${os.platform()}/${os.arch()}\nSDK pin: ${sdk}\n`; + const output = sanitize(metadata) + `\nstdout (tail):\n${tail(sanitize(stdout))}\nstderr (tail):\n${tail(sanitize(stderr))}`; + fs.writeFileSync(path.join(directory, `${phase}.log`), output); + if (code !== 0 && process.env.GITHUB_STEP_SUMMARY) { + fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, + `### Failed ${phase}\n\n\`\`\`text\n${sanitize(metadata).replace(/`/g, "'")}\`\`\`\n\nSee the failure-diagnostics artifact for bounded output.\n`); + } + } catch (error) { + // Reporting failure must never replace the test/smoke command's result. + process.stderr.write(`Diagnostic capture failed (${error.code || error.name}); original exit code: ${code}\n`); + } + return code; +} + +module.exports = { run, sanitize, tail, LIMIT }; +if (require.main === module) { + run(...process.argv.slice(2, 4), process.argv.slice(4)).then(code => { process.exitCode = code; }) + .catch(error => { console.error(error.message); process.exitCode = 1; }); +} diff --git a/.github/scripts/ci-command.test.js b/.github/scripts/ci-command.test.js new file mode 100644 index 0000000..4529bc3 --- /dev/null +++ b/.github/scripts/ci-command.test.js @@ -0,0 +1,63 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); +const { sanitize, tail, LIMIT } = require('./ci-command.js'); +const runner = path.join(__dirname, 'ci-command.js'); + +test('diagnostic output removes control sequences and credentials', () => { + const clean = sanitize('\x1b[31mfailure\x1b[0m\x00\nAuthorization: Bearer abc123\n?token=private&x=1\nknown-value\nghp_example', + { SOME_SECRET: 'known-value' }); + assert.match(clean, /failure/); + for (const value of ['\x1b', '\x00', 'abc123', 'private', 'known-value', 'ghp_example']) assert.ok(!clean.includes(value)); +}); + +test('bounded capture drops partial first lines and retains final evidence', () => { + const output = tail('x'.repeat(LIMIT * 2) + '\nfinal failure\n'); + assert.match(output, /earlier output omitted/); + assert.match(output, /final failure/); + assert.ok(Buffer.byteLength(output) <= LIMIT + 32); + assert.ok(!output.includes('xxx')); +}); + +for (const code of [0, 7]) { + test(`command exit ${code} is preserved and both output streams are retained`, () => { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'scout-ci-command-')); + try { + fs.writeFileSync(path.join(cwd, 'global.json'), JSON.stringify({ sdk: { version: '10.0.403' } })); + const summary = path.join(cwd, 'summary.md'); + const result = spawnSync(process.execPath, [runner, 'managed-tests', process.execPath, '-e', + `console.log('test output'); console.error('test failure fixture-secret'); process.exit(${code});`], + { cwd, env: { ...process.env, FIXTURE_SECRET: 'fixture-secret', GITHUB_STEP_SUMMARY: summary }, encoding: 'utf8' }); + assert.equal(result.status, code, result.stderr); + const log = fs.readFileSync(path.join(cwd, 'obj/ci-diagnostics/managed-tests.log'), 'utf8'); + assert.match(log, /test output/); + assert.match(log, /test failure \[REDACTED\]/); + assert.match(log, new RegExp(`Exit code: ${code}`)); + assert.equal(fs.existsSync(summary), code !== 0); + } finally { fs.rmSync(cwd, { recursive: true, force: true }); } + }); +} + +test('reporting failure cannot replace the original failing exit code', () => { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'scout-ci-report-failure-')); + try { + fs.writeFileSync(path.join(cwd, 'obj'), 'not a directory'); + const result = spawnSync(process.execPath, [runner, 'native-smoke', process.execPath, '-e', 'process.exit(19)'], + { cwd, encoding: 'utf8' }); + assert.equal(result.status, 19); + assert.match(result.stderr, /Diagnostic capture failed/); + } finally { fs.rmSync(cwd, { recursive: true, force: true }); } +}); + +test('missing executable fails and retains prerequisite evidence', () => { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'scout-ci-missing-')); + try { + fs.writeFileSync(path.join(cwd, 'global.json'), JSON.stringify({ sdk: { version: '10.0.403' } })); + const result = spawnSync(process.execPath, [runner, 'managed-tests', 'scout-command-that-does-not-exist'], { cwd, encoding: 'utf8' }); + assert.equal(result.status, 127); + assert.match(fs.readFileSync(path.join(cwd, 'obj/ci-diagnostics/managed-tests.log'), 'utf8'), /ENOENT/); + } finally { fs.rmSync(cwd, { recursive: true, force: true }); } +}); diff --git a/.github/scripts/ci-smoke.ps1 b/.github/scripts/ci-smoke.ps1 new file mode 100644 index 0000000..92281e8 --- /dev/null +++ b/.github/scripts/ci-smoke.ps1 @@ -0,0 +1,18 @@ +param([Parameter(Mandatory)][string]$ApplicationPath) +$ErrorActionPreference = 'Stop' +# Preserve the existing managed smoke deadline and stderr checks. +$proc = Start-Process -FilePath 'dotnet' -ArgumentList $ApplicationPath, '--smoke' -PassThru -RedirectStandardOutput smoke.out -RedirectStandardError smoke.err +$timedOut = !$proc.WaitForExit(15000) +if ($timedOut) { + Stop-Process -Id $proc.Id -Force +} +$proc.WaitForExit() +Get-Content smoke.out +Get-Content smoke.err | ForEach-Object { [Console]::Error.WriteLine($_) } +if ($timedOut) { throw 'Mock run did not complete graceful shutdown within 15 seconds' } +if ($proc.ExitCode -ne 0) { + exit $proc.ExitCode +} +if ((Get-Item smoke.err).Length -gt 0) { + throw 'Mock run produced stderr output' +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c8cd4ae..1362787 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: uses: rhysd/actionlint@914e7df21a07ef503a81201c76d2b11c789d3fca # v1.7.12 - name: Test critical dependency monitor - run: node --test .github/scripts/critical-dependencies.test.js + run: node --test .github/scripts/critical-dependencies.test.js .github/scripts/ci-command.test.js dependency-review: if: github.event_name == 'pull_request' @@ -58,16 +58,31 @@ jobs: run: dotnet build tests/WinGetScout.Tests.csproj --no-restore --no-dependencies --configuration Release - name: Test - run: dotnet test --project tests/WinGetScout.Tests.csproj --no-build --configuration Release --verbosity normal --minimum-expected-tests 245 + run: node .github/scripts/ci-command.js managed-tests dotnet test --project tests/WinGetScout.Tests.csproj --no-build --configuration Release --verbosity normal --minimum-expected-tests 245 - name: Graceful mock smoke run: | - timeout 15s dotnet bin/Release/net10.0/wingetscout.dll --smoke 2> smoke.err - if [ -s smoke.err ]; then - echo "::error::Mock run produced stderr output" - cat smoke.err - exit 1 - fi + # The variables below belong to the child bash process. + # shellcheck disable=SC2016 + node .github/scripts/ci-command.js managed-smoke bash -e -c ' + status=0 + timeout 15s dotnet bin/Release/net10.0/wingetscout.dll --smoke 2> smoke.err || status=$? + cat smoke.err >&2 + if [ "$status" -ne 0 ]; then exit "$status"; fi + if [ -s smoke.err ]; then + echo "::error::Mock run produced stderr output" + exit 1 + fi + ' + + - name: Upload failure diagnostics + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: failure-diagnostics-linux + path: obj/ci-diagnostics/*.log + if-no-files-found: ignore + retention-days: 7 build-and-test: needs: workflow-lint @@ -130,30 +145,15 @@ jobs: /p:InformationalVersion=${{ steps.version.outputs.ci_version }} - name: Test - run: dotnet test --project tests/WinGetScout.Tests.csproj --no-build --configuration Release --verbosity normal --minimum-expected-tests 245 + run: node .github/scripts/ci-command.js managed-tests dotnet test --project tests/WinGetScout.Tests.csproj --no-build --configuration Release --verbosity normal --minimum-expected-tests 245 # The app self-stops through its normal shutdown path. The outer deadline is only a # deadlock guard; force-kill is failure cleanup, never the successful path. - name: Graceful mock smoke shell: pwsh run: | - $proc = Start-Process -FilePath "dotnet" -ArgumentList "bin/Release/net10.0/wingetscout.dll", "--smoke" -PassThru -RedirectStandardError err.log - if (!$proc.WaitForExit(15000)) { - Stop-Process -Id $proc.Id -Force - Write-Host "::error::Mock run did not complete graceful shutdown within 15 seconds" - exit 1 - } - $proc.WaitForExit() - if ($proc.ExitCode -ne 0) { - Write-Host "::error::Mock run exited with code $($proc.ExitCode)" - if ((Get-Item err.log).Length -gt 0) { Get-Content err.log } - exit 1 - } - if ((Get-Item err.log).Length -gt 0) { - Write-Host "::error::Mock run produced stderr output" - Get-Content err.log - exit 1 - } + node .github/scripts/ci-command.js managed-smoke pwsh -NoLogo -NoProfile -File .github/scripts/ci-smoke.ps1 -ApplicationPath bin/Release/net10.0/wingetscout.dll + exit $LASTEXITCODE - name: Upload CI build outputs uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -164,6 +164,15 @@ jobs: tests/bin/Release/net10.0/** retention-days: 7 + - name: Upload failure diagnostics + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: failure-diagnostics-windows + path: obj/ci-diagnostics/*.log + if-no-files-found: ignore + retention-days: 7 + native-aot-smoke: name: Native AOT ${{ matrix.rid }} if: github.event_name == 'pull_request' @@ -195,7 +204,7 @@ jobs: foreach ($name in @('wingetscout.exe', 'WindowsPackageManager.dll', 'Microsoft.Management.Deployment.InProc.dll')) { if (-not (Test-Path (Join-Path $folder $name))) { throw "Missing $name from native publish" } } - & (Join-Path $folder 'wingetscout.exe') --smoke + node .github/scripts/ci-command.js native-smoke (Join-Path $folder 'wingetscout.exe') --smoke if ($LASTEXITCODE -ne 0) { throw "Native mock smoke failed: $LASTEXITCODE" } - name: Publish MSIX Identity build with locked dependencies @@ -207,5 +216,14 @@ jobs: foreach ($name in @('wingetscout.exe', 'Microsoft.Management.Deployment.winmd')) { if (-not (Test-Path (Join-Path $folder $name))) { throw "Missing $name from Identity publish" } } - & (Join-Path $folder 'wingetscout.exe') --smoke + node .github/scripts/ci-command.js identity-smoke (Join-Path $folder 'wingetscout.exe') --smoke if ($LASTEXITCODE -ne 0) { throw "Identity mock smoke failed: $LASTEXITCODE" } + + - name: Upload failure diagnostics + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: failure-diagnostics-${{ matrix.rid }} + path: obj/ci-diagnostics/*.log + if-no-files-found: ignore + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cb360db..1f049ce 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -80,7 +80,7 @@ jobs: uses: rhysd/actionlint@914e7df21a07ef503a81201c76d2b11c789d3fca # v1.7.12 - name: Test critical dependency monitor - run: node --test .github/scripts/critical-dependencies.test.js + run: node --test .github/scripts/critical-dependencies.test.js .github/scripts/ci-command.test.js tests: needs: [validate-tag, workflow-lint] @@ -98,9 +98,18 @@ jobs: - name: Restore locked dependencies run: dotnet restore tests/WinGetScout.Tests.csproj --locked-mode - name: Run tests - run: dotnet test --project tests/WinGetScout.Tests.csproj -c Release --no-restore --minimum-expected-tests 245 + run: node .github/scripts/ci-command.js managed-tests dotnet test --project tests/WinGetScout.Tests.csproj -c Release --no-restore --minimum-expected-tests 245 - name: Smoke test - run: dotnet run --project WinGetScout.csproj -c Release -f net10.0 --no-restore -- --smoke + run: node .github/scripts/ci-command.js managed-smoke dotnet run --project WinGetScout.csproj -c Release -f net10.0 --no-restore -- --smoke + + - name: Upload failure diagnostics + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: failure-diagnostics-release-tests + path: obj/ci-diagnostics/*.log + if-no-files-found: ignore + retention-days: 7 build: needs: [validate-tag, tests] diff --git a/tests/ListNavigationTests.cs b/tests/ListNavigationTests.cs index 15a0178..895c425 100644 --- a/tests/ListNavigationTests.cs +++ b/tests/ListNavigationTests.cs @@ -536,7 +536,8 @@ public void Pump () Application.LayoutAndDraw (); } - public void PumpUntil (Func complete) + public void PumpUntil (Func complete, + [System.Runtime.CompilerServices.CallerArgumentExpression (nameof (complete))] string checkpoint = "") { System.Diagnostics.Stopwatch deadline = System.Diagnostics.Stopwatch.StartNew (); while (!complete () && deadline.Elapsed < TimeSpan.FromSeconds (3)) @@ -544,7 +545,17 @@ public void PumpUntil (Func complete) Pump (); Thread.Sleep (1); } - Assert.True (complete (), "UI work did not complete within three seconds"); + if (!complete ()) + { + static string Brief (string? value) => new ((value ?? "").Take (256) + .Select (c => char.IsControl (c) ? ' ' : c).ToArray ()); + Assert.Fail ($"UI checkpoint did not complete within three seconds: {Brief (checkpoint)}\n" + + $"Mode={State.Mode}; loading={State.Loading}; detailLoading={State.DetailLoading}; " + + $"rows={State.Filtered.Count}; selectedRow={Table.Value?.SelectedCell.Y}; " + + $"focus={Window.MostFocused?.GetType ().Name}; modal={Application.TopRunnable?.GetType ().Name}; " + + $"backgroundComplete={CaptureBackgroundWorkCompletion ().IsCompleted}; " + + $"backgroundFailures={Window.BackgroundFailures.Count}; status={Brief (State.StatusMessage)}"); + } Assert.Empty (Window.BackgroundFailures); } diff --git a/tests/WorkflowUiTests.cs b/tests/WorkflowUiTests.cs index 0ec1d10..12fd319 100644 --- a/tests/WorkflowUiTests.cs +++ b/tests/WorkflowUiTests.cs @@ -263,15 +263,15 @@ public void WrongSourceOrIdDetailsBecomeAnUncachedStub (bool wrongSource) [Theory] [InlineData (true)] [InlineData (false)] - public void SingleRunRecordsOnlyItsOwnCancellationAsSkipped (bool matchingToken) + public async Task SingleRunRecordsOnlyItsOwnCancellationAsSkipped (bool matchingToken) { string root = Path.Combine (Path.GetTempPath (), "scout-cancel-identity-" + Guid.NewGuid ().ToString ("N")); try { WorkflowStore store = new (root); TaskCompletionSource completion = new (TaskCreationOptions.RunContinuationsAsynchronously); - CancellationToken operationToken = default; - RecordingBackend backend = new () { InstallResult = ct => { operationToken = ct; return completion.Task; } }; + TaskCompletionSource started = new (TaskCreationOptions.RunContinuationsAsynchronously); + RecordingBackend backend = new () { InstallResult = ct => { started.SetResult (ct); return completion.Task; } }; using ListNavigationTests.UiSession ui = new (AppMode.Search, 1, backend, store); ui.Application.AddTimeout (TimeSpan.FromMilliseconds (1), () => { @@ -282,8 +282,10 @@ public void SingleRunRecordsOnlyItsOwnCancellationAsSkipped (bool matchingToken) return false; }); ui.Invoke ("ConfirmAndInstall", ui.State.Packages [0], null!, null!); - ui.PumpUntil (() => backend.Mutations == 1 || !ui.State.Loading); - Assert.True (backend.Mutations == 1, $"Operation did not start: {ui.State.StatusMessage}"); + // The mutation counter advances before InstallResult is called. Wait for the + // token itself so cancellation cannot race the fake backend's startup. + ui.PumpUntil (() => started.Task.IsCompleted); + CancellationToken operationToken = await started.Task; ui.Press (KeyCode.Esc); Assert.True (operationToken.IsCancellationRequested); using CancellationTokenSource unrelated = new (); From 919a88aeeb45a43c970cb2762855dd987fb483dd Mon Sep 17 00:00:00 2001 From: Kevin Harder Date: Thu, 12 Nov 2026 17:28:09 -0600 Subject: [PATCH 2/3] Address Sonnet review of CI diagnostic edge cases --- .github/scripts/ci-command.js | 16 +++++++++------ .github/scripts/ci-command.test.js | 31 ++++++++++++++++++++++++++++++ .github/scripts/ci-smoke.ps1 | 13 +++++++++++-- tests/ListNavigationTests.cs | 6 +++++- 4 files changed, 57 insertions(+), 9 deletions(-) diff --git a/.github/scripts/ci-command.js b/.github/scripts/ci-command.js index 49a1515..c4c986d 100644 --- a/.github/scripts/ci-command.js +++ b/.github/scripts/ci-command.js @@ -8,6 +8,7 @@ const { stripVTControlCharacters } = require('node:util'); const LIMIT = 32 * 1024; function sanitize(text, env = process.env) { + // Redact known credential forms; this is not a filter for arbitrary private data. text = stripVTControlCharacters(text); for (const [name, value] of Object.entries(env)) { if (/token|password|secret|credential|connection.?string/i.test(name) && value?.length >= 4) { @@ -15,18 +16,20 @@ function sanitize(text, env = process.env) { } } return text - .replace(/(authorization\s*[:=]\s*)(?:bearer|basic)\s+\S+/gi, '$1[REDACTED]') - .replace(/((?:access_token|token|password|secret)=)[^\s&]+/gi, '$1[REDACTED]') + .replace(/(\bhttps?:\/\/)[^/\s@]+@/gi, '$1[REDACTED]@') + .replace(/(["']?\b(?:authorization|access_token|token|password|secret)\b["']?\s*[:=]\s*)("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?:bearer|basic)\s+[^\s,;&]+|[^\s,;&]+)/gi, '$1[REDACTED]') .replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+)\b/g, '[REDACTED]') .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ''); } -// Retain complete final lines. Dropping a partial first line also avoids keeping -// only the suffix of a credential that straddles the capture boundary. +// Prefer complete final lines, but retain a bounded fragment when a tool emits +// one long line (including carriage-return progress output). function tail(text) { if (Buffer.byteLength(text) <= LIMIT) return text; text = Buffer.from(text).subarray(-LIMIT).toString('utf8'); - return '[earlier output omitted]\n' + text.slice(text.indexOf('\n') + 1 || text.length); + const newline = text.indexOf('\n'); + const completeLines = newline >= 0 ? text.slice(newline + 1) : ''; + return '[earlier output omitted]\n' + (completeLines.trim() ? completeLines : text); } async function run(phase, command, args) { @@ -44,7 +47,8 @@ async function run(phase, command, args) { try { const directory = path.join('obj', 'ci-diagnostics'); fs.mkdirSync(directory, { recursive: true }); - const sdk = JSON.parse(fs.readFileSync('global.json', 'utf8')).sdk.version; + let sdk = 'unavailable'; + try { sdk = JSON.parse(fs.readFileSync('global.json', 'utf8')).sdk?.version ?? sdk; } catch { /* Still retain the command output. */ } const metadata = `Phase: ${phase}\nExit code: ${code}\nOS/architecture: ${os.platform()}/${os.arch()}\nSDK pin: ${sdk}\n`; const output = sanitize(metadata) + `\nstdout (tail):\n${tail(sanitize(stdout))}\nstderr (tail):\n${tail(sanitize(stderr))}`; fs.writeFileSync(path.join(directory, `${phase}.log`), output); diff --git a/.github/scripts/ci-command.test.js b/.github/scripts/ci-command.test.js index 4529bc3..4e289cf 100644 --- a/.github/scripts/ci-command.test.js +++ b/.github/scripts/ci-command.test.js @@ -22,6 +22,24 @@ test('bounded capture drops partial first lines and retains final evidence', () assert.ok(!output.includes('xxx')); }); +test('long lines and carriage-return progress retain the final failure', () => { + for (const separator of ['', '\r']) { + for (const ending of ['', '\n', '\n\n']) { + const output = tail(('progress' + separator).repeat(LIMIT) + 'final failure' + ending); + assert.match(output, /final failure\s*$/); + assert.ok(Buffer.byteLength(output) <= LIMIT + 32); + } + } +}); + +test('common credential fields and URL userinfo are redacted', () => { + for (const input of ['"password":"x"', 'password = x', 'token: x', 'https://user:pw@host', '"Authorization":"Bearer x"']) { + const output = sanitize(input, {}); + assert.match(output, /\[REDACTED\]/); + assert.ok(!output.includes('"x"') && !output.endsWith(' x') && !output.includes('user:pw')); + } +}); + for (const code of [0, 7]) { test(`command exit ${code} is preserved and both output streams are retained`, () => { const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'scout-ci-command-')); @@ -61,3 +79,16 @@ test('missing executable fails and retains prerequisite evidence', () => { assert.match(fs.readFileSync(path.join(cwd, 'obj/ci-diagnostics/managed-tests.log'), 'utf8'), /ENOENT/); } finally { fs.rmSync(cwd, { recursive: true, force: true }); } }); + +test('unreadable SDK metadata does not discard failing command output', () => { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'scout-ci-invalid-sdk-')); + try { + fs.writeFileSync(path.join(cwd, 'global.json'), 'invalid JSON'); + const result = spawnSync(process.execPath, [runner, 'managed-tests', process.execPath, '-e', + "console.error('original failure'); process.exit(7)"], { cwd, encoding: 'utf8' }); + assert.equal(result.status, 7); + const log = fs.readFileSync(path.join(cwd, 'obj/ci-diagnostics/managed-tests.log'), 'utf8'); + assert.match(log, /SDK pin: unavailable/); + assert.match(log, /original failure/); + } finally { fs.rmSync(cwd, { recursive: true, force: true }); } +}); diff --git a/.github/scripts/ci-smoke.ps1 b/.github/scripts/ci-smoke.ps1 index 92281e8..de39132 100644 --- a/.github/scripts/ci-smoke.ps1 +++ b/.github/scripts/ci-smoke.ps1 @@ -9,10 +9,19 @@ if ($timedOut) { $proc.WaitForExit() Get-Content smoke.out Get-Content smoke.err | ForEach-Object { [Console]::Error.WriteLine($_) } -if ($timedOut) { throw 'Mock run did not complete graceful shutdown within 15 seconds' } +if ($timedOut) { + Write-Host '::error::Mock run did not complete graceful shutdown within 15 seconds' + exit 1 +} +if ($null -eq $proc.ExitCode) { + Write-Host '::error::Mock run did not provide an exit code' + exit 1 +} if ($proc.ExitCode -ne 0) { + Write-Host "::error::Mock run exited with $($proc.ExitCode)" exit $proc.ExitCode } if ((Get-Item smoke.err).Length -gt 0) { - throw 'Mock run produced stderr output' + Write-Host '::error::Mock run produced stderr output' + exit 1 } diff --git a/tests/ListNavigationTests.cs b/tests/ListNavigationTests.cs index 895c425..386e2bf 100644 --- a/tests/ListNavigationTests.cs +++ b/tests/ListNavigationTests.cs @@ -549,12 +549,16 @@ public void PumpUntil (Func complete, { static string Brief (string? value) => new ((value ?? "").Take (256) .Select (c => char.IsControl (c) ? ' ' : c).ToArray ()); + IReadOnlyList failures = Window.BackgroundFailures; + Exception? firstFailure = failures.FirstOrDefault (); Assert.Fail ($"UI checkpoint did not complete within three seconds: {Brief (checkpoint)}\n" + $"Mode={State.Mode}; loading={State.Loading}; detailLoading={State.DetailLoading}; " + $"rows={State.Filtered.Count}; selectedRow={Table.Value?.SelectedCell.Y}; " + $"focus={Window.MostFocused?.GetType ().Name}; modal={Application.TopRunnable?.GetType ().Name}; " + $"backgroundComplete={CaptureBackgroundWorkCompletion ().IsCompleted}; " - + $"backgroundFailures={Window.BackgroundFailures.Count}; status={Brief (State.StatusMessage)}"); + + $"backgroundFailures={failures.Count}; " + + $"firstFailure={firstFailure?.GetType ().Name}: {Brief (firstFailure?.Message)}; " + + $"status={Brief (State.StatusMessage)}"); } Assert.Empty (Window.BackgroundFailures); } From 458b48459caa83dd045acec35ccca6de334b6d3a Mon Sep 17 00:00:00 2001 From: Kevin Harder Date: Thu, 12 Nov 2026 21:13:05 -0600 Subject: [PATCH 3/3] Preserve redaction for prefixed credential names --- .github/scripts/ci-command.js | 2 +- .github/scripts/ci-command.test.js | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/scripts/ci-command.js b/.github/scripts/ci-command.js index c4c986d..7bd895d 100644 --- a/.github/scripts/ci-command.js +++ b/.github/scripts/ci-command.js @@ -17,7 +17,7 @@ function sanitize(text, env = process.env) { } return text .replace(/(\bhttps?:\/\/)[^/\s@]+@/gi, '$1[REDACTED]@') - .replace(/(["']?\b(?:authorization|access_token|token|password|secret)\b["']?\s*[:=]\s*)("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?:bearer|basic)\s+[^\s,;&]+|[^\s,;&]+)/gi, '$1[REDACTED]') + .replace(/(["']?\b[A-Za-z0-9_.-]*(?:authorization|access_token|token|password|secret)\b["']?\s*[:=]\s*)("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?:bearer|basic)\s+[^\s,;&]+|[^\s,;&]+)/gi, '$1[REDACTED]') .replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+)\b/g, '[REDACTED]') .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ''); } diff --git a/.github/scripts/ci-command.test.js b/.github/scripts/ci-command.test.js index 4e289cf..be89eb2 100644 --- a/.github/scripts/ci-command.test.js +++ b/.github/scripts/ci-command.test.js @@ -40,6 +40,15 @@ test('common credential fields and URL userinfo are redacted', () => { } }); +test('prefixed credential names are redacted without relying on environment values', () => { + for (const name of ['client_secret', 'GITHUB_TOKEN', 'db_password', 'NUGET_API_TOKEN', 'auth.access_token', 'client-secret']) { + for (const value of ['x', 'abc12345']) { + const output = sanitize(`${name}=${value}`, {}); + assert.equal(output, `${name}=[REDACTED]`); + } + } +}); + for (const code of [0, 7]) { test(`command exit ${code} is preserved and both output streams are retained`, () => { const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'scout-ci-command-'));