Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions .github/scripts/ci-command.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// 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) {
// 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) {
text = text.split(value).join('[REDACTED]');
}
}
return text
.replace(/(\bhttps?:\/\/)[^/\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, '');
}

// 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');
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) {
if (!/^[a-z][a-z0-9-]*$/.test(phase || '') || !command) throw new Error('Usage: ci-command.js <phase> <command> [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); });
Comment on lines +41 to +42
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 });
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);
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; });
}
103 changes: 103 additions & 0 deletions .github/scripts/ci-command.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
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'));
});

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'));
}
});

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-'));
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 }); }
});

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 }); }
});
27 changes: 27 additions & 0 deletions .github/scripts/ci-smoke.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
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) {
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) {
Write-Host '::error::Mock run produced stderr output'
exit 1
}
74 changes: 46 additions & 28 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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'
Expand Down Expand Up @@ -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
Expand All @@ -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
15 changes: 12 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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]
Expand Down
19 changes: 17 additions & 2 deletions tests/ListNavigationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -536,15 +536,30 @@ public void Pump ()
Application.LayoutAndDraw ();
}

public void PumpUntil (Func<bool> complete)
public void PumpUntil (Func<bool> complete,
[System.Runtime.CompilerServices.CallerArgumentExpression (nameof (complete))] string checkpoint = "")
{
System.Diagnostics.Stopwatch deadline = System.Diagnostics.Stopwatch.StartNew ();
while (!complete () && deadline.Elapsed < TimeSpan.FromSeconds (3))
{
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 ());
IReadOnlyList<Exception> 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={failures.Count}; "
+ $"firstFailure={firstFailure?.GetType ().Name}: {Brief (firstFailure?.Message)}; "
+ $"status={Brief (State.StatusMessage)}");
}
Assert.Empty (Window.BackgroundFailures);
}

Expand Down
Loading
Loading