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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ jobs:
run: |
dotnet test tests/CoreTest/CoreTest.csproj -c Release --no-build --filter "FullyQualifiedName!~ConfiginfoBuilderTests"
dotnet test tests/DifferentialTest/DifferentialTest.csproj -c Release --no-build
dotnet test tests/DrivelutionTest/DrivelutionTest.csproj -c Release --no-build --filter "FullyQualifiedName!~Acceptance"
Comment thread
JusterZhu marked this conversation as resolved.
Resolved

aot-verify:
strategy:
Expand Down
135 changes: 135 additions & 0 deletions scripts/acceptance/run-windows-acceptance.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
#Requires -Version 5.1
<#
.SYNOPSIS
GeneralUpdate.Drivelution Windows acceptance gate.
Runs REAL driver-store install/rollback tests on a DISPOSABLE Windows machine (VM/snapshot).

.DESCRIPTION
Preconditions:
1. Run from an ELEVATED PowerShell (admin).
2. Run on a disposable VM / restore-point snapshot — the tests install and delete driver
packages in the real driver store.
3. Provide a TEST driver package: a directory whose INF (+ catalog) is test-signed or
otherwise approved for this machine. Unsigned packages will be rejected by pnputil
with 0x800B0100. For a self-made package enable test signing first:
bcdedit /set testsigning on (then reboot)
and sign the package with your own catalog (Inf2Cat + Signtool from the WDK).
4. dotnet SDK available on PATH (tests are built and run with `dotnet test`).

What it runs:
- Acceptance_Install_ThenRollback_RoundTrip : fresh install -> installed inventory contains
the package -> rollback deletes exactly the package recorded in install_state.json.
- Acceptance_InstalledBackupHook_ExportsStorePackage : second install must back up the
previously installed package via `pnputil /export-driver` (manifest Source=installed).

All other Drivelution tests (unit + non-destructive smoke) run as well.

Exit codes:
0 the gate was exercised and passed
1 a test failed, or the gate could not be exercised although -InfPath was given
2 only the non-destructive tests ran (-InfPath omitted): they passed, but the gate was
NOT evaluated and is not cleared

.PARAMETER InfPath
Path to the test package INF (inside its package directory). Optional; when omitted only
the non-destructive tests run, the destructive ones are reported as skipped, and the script
exits with code 2.

.EXAMPLE
.\run-windows-acceptance.ps1 -InfPath C:\testpkg\sample.inf
#>
[CmdletBinding()]
param(
[string]$InfPath = "",
[string]$RepoRoot = ""
)

$ErrorActionPreference = "Stop"

# ── Preconditions ─────────────────────────────────────────────────────
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Error "Must run elevated (administrator). Aborting."
exit 1
}

if ([string]::IsNullOrEmpty($RepoRoot)) {
$RepoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) # scripts/acceptance -> repo root
}
$testProject = Join-Path $RepoRoot "tests/DrivelutionTest/DrivelutionTest.csproj"
if (-not (Test-Path $testProject)) {
Write-Error "Test project not found: $testProject"
exit 1
}

Write-Host "== Drivelution Windows acceptance gate ==" -ForegroundColor Cyan
Write-Host "Machine : $env:COMPUTERNAME ($([Environment]::OSVersion.VersionString))"
Write-Host "Elevated : yes"
Write-Host "Test signing: $((bcdedit /enum '{current}' | Select-String 'testsigning') -join ' ')"
Write-Host ""

# The destructive tests need a package; whether one was given decides what this run can certify.
$destructive = -not [string]::IsNullOrEmpty($InfPath)
if ($destructive) {
if (-not (Test-Path $InfPath)) { Write-Error "INF not found: $InfPath"; exit 1 }
$InfPath = (Resolve-Path $InfPath).Path
if (-not (Test-Path (Join-Path (Split-Path -Parent $InfPath) '*.cat'))) {
Write-Warning "No .cat file next to the INF — pnputil may reject an unsigned package (0x800B0100)."
}
$env:DRIVELUTION_ACCEPTANCE_INF = $InfPath
Write-Host "Test INF : $InfPath"
}
else {
# An INF inherited from the environment would arm the destructive tests, although this
# branch announces that they skip.
Remove-Item Env:DRIVELUTION_ACCEPTANCE_INF -ErrorAction SilentlyContinue
Write-Host "Test INF : (none) — destructive acceptance tests are reported as skipped"
}

$env:DRIVELUTION_ACCEPTANCE = "1"

# ── Build & run ───────────────────────────────────────────────────────
Push-Location $RepoRoot
$testOutput = @()
$exit = 1
try {
Write-Host "`n== Building test project ==" -ForegroundColor Cyan
dotnet build $testProject -f net10.0 -c Release --nologo
if ($LASTEXITCODE -ne 0) { Write-Error "Build failed"; exit 1 }

Write-Host "`n== Running acceptance + smoke + unit tests ==" -ForegroundColor Cyan
$testOutput = @(dotnet test $testProject -f net10.0 -c Release --no-build --nologo `
--filter "FullyQualifiedName~DrivelutionTest")
$exit = $LASTEXITCODE
$testOutput | ForEach-Object { Write-Host $_ }
}
finally {
Remove-Item Env:DRIVELUTION_ACCEPTANCE -ErrorAction SilentlyContinue
Remove-Item Env:DRIVELUTION_ACCEPTANCE_INF -ErrorAction SilentlyContinue
Pop-Location
}

if ($exit -ne 0) {
Write-Host "`nRESULT: FAILED — do not release." -ForegroundColor Red
exit $exit
}

# The destructive tests report themselves as skipped when they could not run. A skipped gate
# test is a green run, but not a passed gate.
$skippedGate = @($testOutput | Select-String -Pattern 'Skipped\s+DrivelutionTest\.Acceptance\.')
if ($destructive) {
if ($skippedGate.Count -gt 0) {
Write-Host "`nRESULT: NOT CLEARED — the install/rollback acceptance tests were skipped although a test INF was given:" -ForegroundColor Red
$skippedGate | ForEach-Object { Write-Host " $($_.Line.Trim())" -ForegroundColor Red }
Write-Host "Do not release: the acceptance gate was not exercised." -ForegroundColor Red
exit 1
}

Write-Host "`nRESULT: PASSED — Windows install/rollback gate cleared." -ForegroundColor Green
exit 0
}

Write-Host "`nRESULT: PASSED (non-destructive) — the unit and smoke tests passed, but the install/rollback acceptance gate was NOT evaluated: no -InfPath was given." -ForegroundColor Yellow
Write-Host "Run again with -InfPath on a disposable machine to clear the gate. Exit code 2 means: not cleared." -ForegroundColor Yellow
exit 2
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,20 @@ namespace GeneralUpdate.Drivelution.Abstractions.Configuration;
public class DrivelutionOptions
{
/// <summary>
/// 默认备份路径
/// Default backup path
/// 默认备份路径(UpdateStrategy.BackupPath 为空时使用)
/// Default backup root (used when UpdateStrategy.BackupPath is empty)
/// </summary>
public string DefaultBackupPath { get; set; } = "./DriverBackups";


/// <summary>
/// 下载保存目录(Download 步骤将驱动包下载到这里)
/// Download directory (the Download step stores driver packages here)
/// </summary>
public string DownloadDirectory { get; set; } = "./DriverDownloads";

/// <summary>
/// 默认重试次数
/// Default retry count
/// 默认重试次数(UpdateStrategy.RetryCount 为 0 时使用)
/// Default retry count (used when UpdateStrategy.RetryCount is 0)
/// </summary>
public int DefaultRetryCount { get; set; } = 3;

Expand All @@ -33,26 +37,38 @@ public class DrivelutionOptions
public int DefaultTimeoutSeconds { get; set; } = 300;

/// <summary>
/// 是否在调试模式下跳过签名验证
/// Skip signature validation in debug mode
/// 重试时是否使用指数退避(每次重试延迟翻倍)
/// Whether to use exponential backoff for retries (doubles delay each retry)
/// </summary>
public bool UseExponentialBackoff { get; set; } = false;

/// <summary>
/// 指数退避时是否叠加随机抖动(避免重试风暴;仅 UseExponentialBackoff=true 时生效)
/// Whether to add random jitter to exponential backoff (only effective with UseExponentialBackoff=true)
/// </summary>
public bool UseRetryJitter { get; set; } = false;

/// <summary>
/// 允许在调试会话中跳过签名验证(需同时满足:策略 SkipSignatureValidation=true 且当前处于调试器下,否则忽略并记录警告)
/// Allows skipping signature validation in a debug session (requires strategy.SkipSignatureValidation AND an attached debugger; otherwise ignored with a warning)
/// </summary>
public bool DebugModeSkipSignature { get; set; } = false;

/// <summary>
/// 是否在调试模式下跳过哈希验证
/// Skip hash validation in debug mode
/// 允许在调试会话中跳过哈希验证(需同时满足:策略 SkipHashValidation=true 且当前处于调试器下,否则忽略并记录警告)
/// Allows skipping hash validation in a debug session (requires strategy.SkipHashValidation AND an attached debugger; otherwise ignored with a warning)
/// </summary>
public bool DebugModeSkipHash { get; set; } = false;

/// <summary>
/// 权限校验失败时是否强制终止
/// Force terminate on permission check failure
/// 权限校验失败时是否强制终止(true=管道失败;false=记录警告并继续尝试,由安装阶段给出最终结果)
/// Force terminate on permission check failure (true=pipe fails; false=warn and continue, install stage gives the final verdict)
/// </summary>
public bool ForceTerminateOnPermissionFailure { get; set; } = true;

/// <summary>
/// 是否自动清理旧备份(保留最近N个)
/// Auto cleanup old backups (keep recent N)
/// 更新成功后是否自动清理旧备份(保留最近 BackupsToKeep 个)
/// Auto cleanup old backups after a successful update (keep the most recent BackupsToKeep)
/// </summary>
public bool AutoCleanupBackups { get; set; } = true;

Expand All @@ -63,20 +79,32 @@ public class DrivelutionOptions
public int BackupsToKeep { get; set; } = 5;

/// <summary>
/// 重试时是否使用指数退避(每次重试延迟翻倍)
/// Whether to use exponential backoff for retries (doubles delay each retry)
/// 信任的证书指纹列表(Windows 签名验证时除发布者外额外接受这些指纹)
/// Trusted certificate thumbprints (Windows signature validation additionally accepts these)
/// </summary>
public bool UseExponentialBackoff { get; set; } = false;
public List<string> TrustedCertificateThumbprints { get; set; } = new();

/// <summary>
/// 信任的证书指纹列表(用于签名验证)
/// Trusted certificate thumbprints (for signature validation)
/// 信任的 GPG 公钥指纹或公钥文件路径(Linux 签名验证;40/16 位十六进制视为指纹做强校验)
/// Trusted GPG key fingerprints or key file paths (Linux signature validation; 40/16-char hex values are treated as fingerprints for strict validation)
/// </summary>
public List<string> TrustedCertificateThumbprints { get; set; } = new();
public List<string> TrustedGpgKeys { get; set; } = new();

/// <summary>
/// 信任的GPG公钥列表(Linux用)
/// Trusted GPG public keys (for Linux)
/// 网络代理(下载用;如 http://127.0.0.1:1080、socks5://127.0.0.1:10808、socks5h://...;空=直连)
/// Network proxy for downloads (e.g. http://127.0.0.1:1080, socks5://127.0.0.1:10808, socks5h://...; empty = direct)
/// </summary>
public List<string> TrustedGpgKeys { get; set; } = new();
public string NetworkProxy { get; set; } = string.Empty;

/// <summary>
/// 重启回调:执行系统重启(参数为延迟秒数;返回是否已发起重启)。Immediate/Delayed 重启模式必须提供。
/// Restart callback: performs the system restart (parameter = delay seconds; returns whether restart was initiated). Required for Immediate/Delayed restart modes.
/// </summary>
public Func<int, CancellationToken, Task<bool>>? RestartCallback { get; set; }

/// <summary>
/// 重启询问回调:询问用户是否重启(参数为提示消息;返回用户选择)。Prompt 重启模式使用;未配置时仅记录 RestartRequired。
/// Restart prompt callback: asks the user whether to restart (parameter = prompt message; returns the user's choice). Used by Prompt restart mode; when absent only RestartRequired is recorded.
/// </summary>
public Func<string, Task<bool>>? RestartPromptCallback { get; set; }
}
26 changes: 21 additions & 5 deletions src/GeneralUpdate.Drivelution/Abstractions/IDriverBackup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,39 @@ namespace GeneralUpdate.Drivelution.Abstractions;
public interface IDriverBackup
{
/// <summary>
/// 异步备份驱动
/// Backs up driver asynchronously
/// 异步备份驱动包。备份的单位是驱动包:源路径是目录时为该目录,是驱动文件(INF、内核模块等)时为它所在的目录,
/// 整棵目录树被复制到备份目录中(Linux 的 .deb/.rpm 是自包含的,按单文件复制)。备份目录不能与驱动包目录相互包含。
/// Backs up the driver package. The unit is the package: the directory <paramref name="sourcePath"/>
/// names, or — for a driver file such as an INF or a kernel module — the directory holding it.
/// The whole tree is copied into <paramref name="backupPath"/>, which must not overlap the
/// package (a Linux .deb/.rpm file is self-contained and is copied as that single file).
/// </summary>
/// <param name="sourcePath">源路径 / Source path</param>
/// <param name="backupPath">备份路径 / Backup path</param>
/// <param name="backupPath">备份路径(目录)/ Backup directory</param>
/// <param name="cancellationToken">取消令牌 / Cancellation token</param>
/// <returns>备份结果 / Backup result</returns>
/// <exception cref="Exceptions.DriverBackupException">
/// 源不存在,或备份目录与驱动包目录重叠时抛出(两者均不可重试)/ The source is missing, or the
/// backup directory overlaps the package (neither is retryable).
/// </exception>
Task<bool> BackupAsync(string sourcePath, string backupPath, CancellationToken cancellationToken = default);

/// <summary>
/// 异步恢复驱动
/// Restores driver asynchronously
/// 异步恢复驱动。备份目录中的内容被放回目标:目标是目录时恢复整棵包树;目标是文件时恢复该文件的备份副本。
/// 旧版本产生的单文件备份按文件恢复。确定要写什么之前不会改动目标;目标文件被移到“.old”后若复制失败,会放回原处。
/// Restores a backup to <paramref name="targetPath"/>: a directory target receives the package
/// tree, a file target receives the backup's copy of that file, and a single-file backup made
/// by an older version is restored as a file. Nothing at the target is touched before it is
/// established what goes there, and a target moved aside as ".old" is put back when the copy fails.
/// </summary>
/// <param name="backupPath">备份路径 / Backup path</param>
/// <param name="targetPath">目标路径 / Target path</param>
/// <param name="cancellationToken">取消令牌 / Cancellation token</param>
/// <returns>恢复结果 / Restore result</returns>
/// <exception cref="Exceptions.DriverRollbackException">
/// 备份不存在、没有可恢复的文件,或恢复失败时抛出 / The backup is missing, holds nothing to
/// restore, or the restore failed.
/// </exception>
Task<bool> RestoreAsync(string backupPath, string targetPath, CancellationToken cancellationToken = default);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,14 @@ public interface IDriverValidator
/// </summary>
/// <param name="filePath">文件路径 / File path</param>
/// <param name="trustedPublishers">信任的发布者列表 / Trusted publishers list</param>
/// <param name="trustedThumbprints">信任的证书指纹列表(匹配任一即通过)/ Trusted certificate thumbprints (any match passes)</param>
/// <param name="cancellationToken">取消令牌 / Cancellation token</param>
/// <returns>验证是否通过 / Validation result</returns>
Task<bool> ValidateSignatureAsync(string filePath, IEnumerable<string> trustedPublishers, CancellationToken cancellationToken = default);
Task<bool> ValidateSignatureAsync(
string filePath,
IEnumerable<string> trustedPublishers,
IEnumerable<string>? trustedThumbprints = null,
CancellationToken cancellationToken = default);

/// <summary>
/// 异步验证驱动兼容性
Expand Down
Loading
Loading