aisop/tests/D3Startup.Smoke/LicenseTests.cs

219 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.Licensing;
using Microsoft.Win32;
/// <summary>离线授权回归:使用临时签名密钥和内存状态,不触碰发行方私钥或本机正式试用记录。</summary>
internal static class LicenseTests
{
public static void Run()
{
using var issuer = RSA.Create(2048);
var machine = LicenseService.MachineCode("test-board-1");
var store = new MemoryStore();
var now = new DateTimeOffset(2026, 1, 31, 12, 0, 0, TimeSpan.Zero);
LicenseService Create(string? board = null) => new(board ?? machine, store, issuer.ExportSubjectPublicKeyInfoPem(), () => now);
var service = Create();
void Check(bool ok, string message) { if (!ok) throw new Exception(message); Console.WriteLine("PASS: " + message); }
void Reject(Action action, string message)
{
try { action(); } catch (Exception e) when (e is InvalidOperationException or IOException) { Console.WriteLine("PASS: " + message); return; }
throw new Exception(message);
}
string Code(string kind = "Month", string? board = null, string? id = null, int version = 1, RSA? signer = null)
{
var payload = JsonSerializer.SerializeToUtf8Bytes(new LicenseGrant(version, id ?? Guid.NewGuid().ToString("N"), board ?? machine, kind, now));
return "AISOP1." + Convert.ToBase64String(payload) + "." + Convert.ToBase64String((signer ?? issuer).SignData(payload, HashAlgorithmName.SHA256, RSASignaturePadding.Pss));
}
var trial = service.Check();
Check(trial.Allowed && trial.ExpiresUtc == now.AddMonths(1), "首次试用按自然月计算,1月31日到2月28日");
now = now.AddDays(3);
Check(Create().Check().ExpiresUtc == trial.ExpiresUtc, "重启不会重新计算试用起点");
var shortCode = Code();
var renewed = service.Activate(" \n" + shortCode + "\n");
Check(renewed.Allowed && renewed.ExpiresUtc == trial.ExpiresUtc!.Value.AddMonths(1), "提前激活保留剩余期限并增加一个月");
Reject(() => Create().Activate(shortCode), "重启后仍拒绝重复兑换同一码");
Reject(() => service.Activate(Code(board: LicenseService.MachineCode("other"))), "拒绝其他硬件的授权码");
using var stranger = RSA.Create(2048);
Reject(() => service.Activate(Code(signer: stranger)), "拒绝非发行方签名");
Reject(() => service.Activate(Code(kind: "Unknown")), "拒绝未知授权类型");
Reject(() => service.Activate(Code(version: 2)), "拒绝未知协议版本");
Reject(() => service.Activate("AISOP1.a.b"), "拒绝格式错误的授权码");
var parts = Code().Split('.');
var bytes = Convert.FromBase64String(parts[1]); bytes[5] ^= 1; parts[1] = Convert.ToBase64String(bytes);
Reject(() => service.Activate(string.Join('.', parts)), "拒绝被篡改的签名内容");
Check(!Create(LicenseService.MachineCode("replacement")).Check().Allowed, "更换硬件后原记录不可使用");
// 机器码算法升级(主板固件序列号 → 磁盘固件序列号)后,老记录必须继续有效,只改写机器码字段。
var legacyMachine = LicenseService.MachineCode("vendor|model|BSS-00000001");
var usedId = "0123456789abcdef0123456789abcdef";
var upgradeStore = new MemoryStore();
var upgradedService = new LicenseService(machine, upgradeStore, issuer.ExportSubjectPublicKeyInfoPem(), () => now, [legacyMachine]);
upgradeStore.Data = JsonSerializer.SerializeToUtf8Bytes(new
{
Machine = legacyMachine, StartedUtc = now.AddDays(-10), LastUtc = now, ExpiresUtc = now.AddDays(20),
Permanent = false, UsedIds = new List<string> { usedId }
});
var upgraded = upgradedService.Check();
Check(upgraded.Allowed && upgraded.ExpiresUtc == now.AddDays(20), "机器码算法升级后老授权记录继续有效");
var migratedJson = JsonDocument.Parse(Encoding.UTF8.GetString(upgradeStore.Data!)).RootElement;
Check(migratedJson.GetProperty("Machine").GetString() == machine && migratedJson.GetProperty("UsedIds")[0].GetString() == usedId,
"迁移只改写机器码字段,保留试用起点和已兑换授权码");
Check(new LicenseService(machine, new MemoryStore { Data = upgradeStore.Data }, issuer.ExportSubjectPublicKeyInfoPem(), () => now, []).Check().Allowed,
"迁移完成后不再依赖历史硬件标识");
var foreignStore = new MemoryStore();
foreignStore.Data = JsonSerializer.SerializeToUtf8Bytes(new
{
Machine = LicenseService.MachineCode("other-vendor|other-model|BSS-00000001"), StartedUtc = now.AddDays(-10),
LastUtc = now, ExpiresUtc = now.AddDays(20), Permanent = false, UsedIds = new List<string>()
});
Check(!new LicenseService(machine, foreignStore, issuer.ExportSubjectPublicKeyInfoPem(), () => now, [legacyMachine]).Check().Allowed,
"他机主板机器码记录不能借算法升级迁移");
var noLegacyStore = new MemoryStore();
noLegacyStore.Data = JsonSerializer.SerializeToUtf8Bytes(new
{
Machine = legacyMachine, StartedUtc = now.AddDays(-10), LastUtc = now, ExpiresUtc = now.AddDays(20),
Permanent = false, UsedIds = new List<string>()
});
Check(!new LicenseService(machine, noLegacyStore, issuer.ExportSubjectPublicKeyInfoPem(), () => now, []).Check().Allowed,
"本机没有对应历史硬件时拒绝老记录");
now = renewed.ExpiresUtc!.Value;
Check(!service.Check().Allowed, "到期时刻立即失效");
now = now.AddDays(5);
var afterExpiry = service.Activate(Code());
Check(afterExpiry.ExpiresUtc == now.AddMonths(1), "过期续费从激活时刻延长一个月");
var watermark = now;
now = now.AddHours(-1);
Check(!service.Check().Allowed, "运行中时间回拨禁止继续使用");
Reject(() => service.Activate(Code()), "时间回拨时不能兑换短期码");
now = watermark;
Check(service.Check().Allowed, "校准时间后恢复使用");
var future = now.AddDays(1); now = future;
var futureCode = Code(); now = watermark;
Reject(() => service.Activate(futureCode), "拒绝未来签发的授权码");
var permanent = service.Activate(Code("Permanent"));
Check(permanent.Allowed && permanent.Permanent && permanent.ExpiresUtc is null, "长期码切换永久授权");
now = now.AddYears(30);
Check(Create().Check().Allowed && Create().Check().Permanent, "永久授权多年后仍有效");
Reject(() => service.Activate(Code()), "永久授权不再消耗短期码");
store.Data = "broken"u8.ToArray();
Check(!service.Check().Allowed, "记录损坏时禁止重置试用");
store.Fail = true;
Check(!service.Check().Allowed, "读取存储失败时禁止放行");
store.Fail = false; store.Data = null; store.FailWrite = true;
Check(!service.Check().Allowed, "试用记录写盘失败时禁止放行");
Reject(() => service.Activate(Code()), "激活写盘失败不返回成功");
using var publicKey = RSA.Create(); publicKey.ImportFromPem(LicenseService.ReadIssuerPublicKey());
Check(publicKey.KeySize >= 3072, "生产验签公钥已嵌入程序集");
if (OperatingSystem.IsWindows())
{
// 磁盘硬件码必须能稳定读取:两次读取结果一致且为标准 64 位十六进制散列。
var first = DiskIdentity.ReadMachineCode();
Check(first.Length == 64 && first == DiskIdentity.ReadMachineCode(), "本机磁盘序列号读取成功且结果稳定");
}
CheckProtectedStore(machine);
// 可选验收发行脚本真实输出,仍只写入内存,不激活当前电脑的正式记录。
var integrationPath = Environment.GetEnvironmentVariable("AISOP_TEST_LICENSE_FILE");
if (integrationPath is not null)
{
var integration = new LicenseService(machine, new MemoryStore(), LicenseService.ReadIssuerPublicKey());
Check(integration.Activate(File.ReadAllText(integrationPath)).Allowed, "PowerShell 发行工具与客户端验签兼容");
}
}
/// <summary>
/// 现场排障:按真实磁盘机器码读取本机正式授权记录,打印机器码、历史主板机器码与授权状态。
/// 调用 <see cref="LicenseService.Check"/> 与软件启动时的检查完全一致,会把主板绑定时期的旧记录
/// 迁移为磁盘绑定记录;不签发也不兑换授权码,因此不会消耗客户的码。
/// </summary>
public static string RealStoreCheck()
{
var machine = DiskIdentity.ReadMachineCode();
var legacy = LegacyHardwareIdentity.BoardMachineCodes();
// 与生产 ProtectedLicenseStore 相同的正式记录位置,便于支持人员核对文件和注册表镜像。
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Bellwether", "AISOP", "license.dat");
var service = new LicenseService(machine, new ProtectedLicenseStore(machine), LicenseService.ReadIssuerPublicKey());
var status = service.Check();
return string.Join(Environment.NewLine,
[
"当前磁盘机器码:" + machine,
"历史主板机器码:" + (legacy.Count == 0 ? "本机读不到有效主板序列号,旧记录无法迁移" : string.Join(",", legacy)),
"授权文件:" + path + (File.Exists(path) ? "(存在)" : "(缺失)"),
"注册表镜像:HKCU\\Software\\Bellwether\\AISOP\\Licensing" + (OperatingSystem.IsWindows() ? "" : "(非 Windows 不使用)"),
(status.Allowed ? "允许使用:" : "当前不可用:") + status.Message
]);
}
/// <summary>在固定测试文件与测试专用注册表项验证真实加密、镜像恢复及篡改拒绝,最终只清理这两个测试资源。</summary>
private static void CheckProtectedStore(string machine)
{
if (!OperatingSystem.IsWindows()) return;
var path = Path.GetFullPath("../scratch/test-results/license-store.dat");
const string registryPath = @"Software\Bellwether\AISOP\LicenseSmokeTest";
void Check(bool ok, string message) { if (!ok) throw new Exception(message); Console.WriteLine("PASS: " + message); }
bool Refused(ILicenseStore target)
{
try { target.Read(); return false; }
catch (Exception error) when (error is IOException or InvalidDataException or System.ComponentModel.Win32Exception) { return true; }
}
try
{
File.Delete(path); File.Delete(path + ".tmp");
Registry.CurrentUser.DeleteSubKey(registryPath, false);
var target = new ProtectedLicenseStore(machine, path, registryPath);
Check(target.Read() is null, "无记录时存储返回首次运行");
var clear = "license-state-roundtrip"u8.ToArray();
target.Write(clear);
Check(target.Read()!.SequenceEqual(clear) && !File.ReadAllBytes(path).SequenceEqual(clear), "Windows DPAPI 加密存储往返成功");
File.Delete(path);
Check(target.Read()!.SequenceEqual(clear), "删除授权文件后仍从注册表镜像恢复记录");
target.Write(clear);
using (var key = Registry.CurrentUser.OpenSubKey(registryPath, true)!) key.DeleteValue("State");
Check(target.Read()!.SequenceEqual(clear), "镜像缺失时仍保留文件中的原始授权");
Check(Refused(new ProtectedLicenseStore(LicenseService.MachineCode("different-board"), path, registryPath)), "不同硬件无法解密复制的授权记录");
// 机器码算法升级:老记录由历史主板机器码封装,升级后要能读出并按当前机器码重新封装文件和镜像。
var legacyMachine = LicenseService.MachineCode("legacy-vendor|legacy-model|LEGACY0001");
File.Delete(path);
Registry.CurrentUser.DeleteSubKey(registryPath, false);
new ProtectedLicenseStore(legacyMachine, path, registryPath, []).Write(clear);
Check(new ProtectedLicenseStore(machine, path, registryPath, [legacyMachine]).Read()!.SequenceEqual(clear),
"主板绑定时期的旧授权记录可迁移到磁盘绑定机器码");
Check(new ProtectedLicenseStore(machine, path, registryPath, []).Read()!.SequenceEqual(clear),
"迁移后文件与注册表镜像均按当前机器码重新封装");
File.Delete(path);
Check(new ProtectedLicenseStore(machine, path, registryPath, []).Read()!.SequenceEqual(clear),
"注册表镜像同步迁移,删除文件后仍可用当前机器码读取");
var foreignMachine = LicenseService.MachineCode("foreign-vendor|foreign-model|FOREIGN0001");
File.Delete(path);
Registry.CurrentUser.DeleteSubKey(registryPath, false);
new ProtectedLicenseStore(foreignMachine, path, registryPath, []).Write(clear);
// 生产环境的历史密钥集合只能由本机硬件算出,绝不会包含签发记录的那台机器的机器码。
Check(Refused(new ProtectedLicenseStore(machine, path, registryPath, [legacyMachine])),
"他机记录不能借历史密钥迁移");
target.Write(clear);
File.WriteAllBytes(path, [1, 2, 3]);
Check(Refused(target), "授权文件与镜像不同则拒绝加载");
using (var key = Registry.CurrentUser.OpenSubKey(registryPath, true)!) key.SetValue("State", "invalid", RegistryValueKind.String);
File.Delete(path);
Check(Refused(target), "损坏的镜像类型不能被当作首次试用");
}
finally
{
File.Delete(path); File.Delete(path + ".tmp");
Registry.CurrentUser.DeleteSubKey(registryPath, false);
}
}
private sealed class MemoryStore : ILicenseStore
{
public byte[]? Data;
public bool Fail, FailWrite;
public byte[]? Read() => Fail ? throw new IOException("test read failure") : Data;
public void Write(byte[] value) { if (FailWrite) throw new IOException("test write failure"); Data = value; }
}
}