docs(secrets-ui): verify exact published package delivery
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Akka.Actor;
|
||||
using Akka.Configuration;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using SecretsCompatibility;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
using ZB.MOM.WW.Secrets.Crypto;
|
||||
using ZB.MOM.WW.Secrets.Sqlite;
|
||||
using ZB.MOM.WW.Secrets.Replicator.SqlServer;
|
||||
using ZB.MOM.WW.Secrets.Replicator.AkkaDotNet;
|
||||
using ZB.MOM.WW.Secrets.Replicator.AkkaDotNet.Protocol;
|
||||
using ZB.MOM.WW.Secrets.Ui;
|
||||
using ZB.MOM.WW.Theme;
|
||||
|
||||
string coreVersion = args[0];
|
||||
string revision = args[1];
|
||||
string reportPath = args[2];
|
||||
var checks = new List<object>();
|
||||
void Check(string name, bool passed)
|
||||
{
|
||||
checks.Add(new { name, passed });
|
||||
if (!passed) throw new InvalidOperationException("Compatibility check failed: " + name);
|
||||
}
|
||||
void Refuses<T>(string name, Action operation) where T : Exception
|
||||
{
|
||||
try { operation(); }
|
||||
catch (T) { Check(name, true); return; }
|
||||
Check(name, false);
|
||||
}
|
||||
|
||||
Check("Actual older Core assembly", typeof(AesGcmEnvelopeCipher).Assembly.GetName().Version!.ToString() == coreVersion + ".0");
|
||||
Check("New contracts runtime", typeof(ISecretStore).Assembly.GetName().Version!.ToString() == "0.6.6.0");
|
||||
Check("UI package runtime", typeof(SecretsList).Assembly.GetName().Version!.ToString() == "1.0.0.0");
|
||||
Check("Exact shared Theme runtime", typeof(ThemeHead).Assembly.GetName().Version!.ToString() == "1.0.1.0");
|
||||
Check("UI frozen revision metadata", typeof(SecretsList).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!.InformationalVersion.EndsWith("+" + revision, StringComparison.Ordinal));
|
||||
Check("Contracts frozen revision metadata", typeof(ISecretStore).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!.InformationalVersion.EndsWith("+" + revision, StringComparison.Ordinal));
|
||||
Check("Old compiled provider references 0.6.2", typeof(LegacyProvider).Assembly.GetReferencedAssemblies().Single(a => a.Name == "ZB.MOM.WW.Secrets.Abstractions").Version!.ToString() == "0.6.2.0");
|
||||
IMasterKeyProvider oldProvider = new LegacyProvider("synthetic-old-key", 7);
|
||||
IMasterKeyProvider nextProvider = new LegacyProvider("synthetic-next-key", 19);
|
||||
Check("Old provider has no new concrete member", oldProvider.GetType().GetMethod(nameof(IMasterKeyProvider.GetSnapshot)) is null);
|
||||
ReadOnlyMemory<byte> owned;
|
||||
using (MasterKeySnapshot snapshot = oldProvider.GetSnapshot())
|
||||
{
|
||||
owned = snapshot.Key;
|
||||
Check("Default snapshot dispatch on old compiled provider", snapshot.KekId == oldProvider.KekId && snapshot.Key.Span.SequenceEqual(oldProvider.GetMasterKey().Span));
|
||||
}
|
||||
Check("Owned snapshot zeroed on disposal", owned.Span.IndexOfAnyExcept((byte)0) < 0);
|
||||
Check("Legacy provider original buffer remains usable", oldProvider.GetMasterKey().Span[0] == 7);
|
||||
Check("Name normalization", new SecretName(" COMPAT/One ").Value == "compat/one");
|
||||
Check("450 character validation boundary", SecretName.MaxLength == 450 && new SecretName(new string('a', 450)).Value.Length == 450);
|
||||
Refuses<ArgumentException>("451 characters rejected explicitly", () => _ = new SecretName(new string('a', 451)));
|
||||
|
||||
ISecretCipher cipher = new AesGcmEnvelopeCipher(oldProvider);
|
||||
const string value = "synthetic-compatibility-value-only";
|
||||
var name = new SecretName("compat/one");
|
||||
StoredSecret row = cipher.Encrypt(name, value, SecretContentType.Text) with { Description = "Synthetic local metadata", CreatedBy = "synthetic-reviewer", UpdatedBy = "synthetic-reviewer" };
|
||||
Check("Old cipher encrypt/decrypt with new contracts", cipher.Decrypt(row) == value && !Encoding.UTF8.GetString(row.Ciphertext).Contains(value, StringComparison.Ordinal));
|
||||
Check("Longest valid name encrypts under old binary", cipher.Decrypt(cipher.Encrypt(new SecretName(new string('a', 450)), value, SecretContentType.Text)) == value);
|
||||
var badTag = row.Tag.ToArray(); badTag[0] ^= 1;
|
||||
Refuses<SecretDecryptionException>("Tampered ciphertext fails closed", () => cipher.Decrypt(row with { Tag = badTag }));
|
||||
Refuses<SecretDecryptionException>("Name AAD prevents relocation", () => cipher.Decrypt(row with { Name = new SecretName("compat/another") }));
|
||||
StoredSecret rewrapped = cipher.Rewrap(row, oldProvider, nextProvider);
|
||||
Check("Old binary rewrap preserves body and new KEK decrypts", rewrapped.Ciphertext.SequenceEqual(row.Ciphertext) && rewrapped.KekId == nextProvider.KekId && new AesGcmEnvelopeCipher(nextProvider).Decrypt(rewrapped) == value);
|
||||
|
||||
string directory = Path.Combine(Path.GetTempPath(), "secrets-package-compat-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
var factory = new SecretsSqliteConnectionFactory(Path.Combine(directory, "synthetic.db"));
|
||||
await new SqliteSecretsStoreMigrator(factory).MigrateAsync(CancellationToken.None);
|
||||
ISecretStore store = new SqliteSecretStore(factory);
|
||||
await store.UpsertAsync(row, CancellationToken.None);
|
||||
StoredSecret stored = (await store.GetAsync(name, CancellationToken.None))!;
|
||||
Check("Published SQLite store real persistence", stored is not null && stored.Revision == 0 && cipher.Decrypt(stored) == value);
|
||||
const string secondValue = "synthetic-second-compatibility-value-only";
|
||||
await store.UpsertAsync(cipher.Encrypt(name, secondValue, SecretContentType.Text) with { CreatedBy = "must-not-replace-original", UpdatedBy = "synthetic-second-actor" }, CancellationToken.None);
|
||||
StoredSecret updated = (await store.GetAsync(name, CancellationToken.None))!;
|
||||
Check("Published upsert increments revision and preserves creation", updated.Revision == stored!.Revision + 1 && updated.CreatedBy == stored.CreatedBy && updated.CreatedUtc == stored.CreatedUtc && updated.UpdatedBy == "synthetic-second-actor" && cipher.Decrypt(updated) == secondValue);
|
||||
await store.UpsertAsync(cipher.Encrypt(new SecretName(new string('a', 450)), value, SecretContentType.Text), CancellationToken.None);
|
||||
var metadata = await store.ListAsync(false, CancellationToken.None);
|
||||
Check("Metadata projection with valid long name", metadata.Count == 2 && metadata.Any(m => m.Name.Value.Length == 450) && typeof(SecretMetadata).GetProperties().All(p => p.Name is not ("Ciphertext" or "Value" or "Plaintext")));
|
||||
Check("Published delete commits a tombstone", await store.DeleteAsync(name, "synthetic-reviewer", CancellationToken.None));
|
||||
Check("Tombstone is retained and excluded from active list", (await store.GetAsync(name, CancellationToken.None))!.IsDeleted && (await store.ListAsync(false, CancellationToken.None)).Count == 1 && (await store.ListAsync(true, CancellationToken.None)).Count == 2);
|
||||
Check("Stored SQLite bytes do not include plaintext", !Encoding.UTF8.GetString(File.ReadAllBytes(Path.Combine(directory, "synthetic.db"))).Contains(value, StringComparison.Ordinal) && !Encoding.UTF8.GetString(File.ReadAllBytes(Path.Combine(directory, "synthetic.db"))).Contains(secondValue, StringComparison.Ordinal));
|
||||
}
|
||||
finally
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
|
||||
var hub = new RecordingHub();
|
||||
ISecretReplicator sqlReplicator = new SqlServerSecretReplicator(hub);
|
||||
await sqlReplicator.PublishAsync(row, CancellationToken.None);
|
||||
Check("Published SQL replicator forwards encrypted row verbatim", ReferenceEquals(hub.Row, row));
|
||||
Check("Published SQL store interface maps against new contracts", typeof(SqlServerSecretStore).GetInterfaceMap(typeof(ISecretStore)).TargetMethods.Length > 0);
|
||||
var dto = SecretRowDto.FromStoredSecret(row);
|
||||
string wire = JsonSerializer.Serialize(dto);
|
||||
StoredSecret roundtrip = JsonSerializer.Deserialize<SecretRowDto>(wire)!.ToStoredSecret();
|
||||
Check("Published Akka DTO preserves encrypted row", roundtrip.Name == row.Name && roundtrip.Ciphertext.SequenceEqual(row.Ciphertext) && roundtrip.WrappedDek.SequenceEqual(row.WrappedDek) && !wire.Contains(value, StringComparison.Ordinal));
|
||||
var received = new TaskCompletionSource<StoredSecret>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var system = ActorSystem.Create("secrets-compat-" + Guid.NewGuid().ToString("N"), ConfigurationFactory.ParseString("akka.actor.provider=local\nakka.loglevel=OFF\nakka.stdout-loglevel=OFF"));
|
||||
try
|
||||
{
|
||||
var sink = system.ActorOf(Props.Create(() => new Sink(received)));
|
||||
ISecretReplicator akkaReplicator = new AkkaSecretReplicator(sink);
|
||||
await akkaReplicator.PublishAsync(row, CancellationToken.None);
|
||||
Check("Published Akka replicator local mailbox binary path", ReferenceEquals(await received.Task.WaitAsync(TimeSpan.FromSeconds(10)), row));
|
||||
}
|
||||
finally { await system.Terminate().WaitAsync(TimeSpan.FromSeconds(10)); }
|
||||
|
||||
foreach (var assembly in new[] { typeof(AesGcmEnvelopeCipher).Assembly, typeof(SqlServerSecretReplicator).Assembly, typeof(AkkaSecretReplicator).Assembly, typeof(SecretsList).Assembly })
|
||||
Check("Exported types load: " + assembly.GetName().Name, assembly.GetExportedTypes().Length > 0);
|
||||
var report = new
|
||||
{
|
||||
coreVersion, revision, passed = checks.Count,
|
||||
assemblies = new[] { typeof(AesGcmEnvelopeCipher).Assembly, typeof(ISecretStore).Assembly, typeof(SqlServerSecretReplicator).Assembly, typeof(AkkaSecretReplicator).Assembly, typeof(SecretsList).Assembly, typeof(ThemeHead).Assembly, typeof(LegacyProvider).Assembly }
|
||||
.Select(a => new { name = a.GetName().Name, version = a.GetName().Version!.ToString(), information = a.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion, path = a.Location, sha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(a.Location))).ToLowerInvariant() }),
|
||||
scope = "Actual published binaries; synthetic fixed keys, ephemeral SQLite and local-only Akka. No SQL connection, remote cluster, deployment or production data.", checks
|
||||
};
|
||||
File.WriteAllText(reportPath, JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }) + "\n");
|
||||
Console.WriteLine(JsonSerializer.Serialize(new { coreVersion, passed = checks.Count }));
|
||||
|
||||
sealed class RecordingHub : ISecretReplicationHub
|
||||
{
|
||||
public StoredSecret? Row { get; private set; }
|
||||
public Task<IReadOnlyList<SecretManifestEntry>> GetManifestAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<SecretManifestEntry>>([]);
|
||||
public Task<IReadOnlyList<StoredSecret>> GetManyAsync(IReadOnlyList<SecretName> names, CancellationToken ct) => Task.FromResult<IReadOnlyList<StoredSecret>>([]);
|
||||
public Task ApplyReplicatedAsync(StoredSecret row, CancellationToken ct) { Row = row; return Task.CompletedTask; }
|
||||
}
|
||||
sealed class Sink : ReceiveActor
|
||||
{
|
||||
public Sink(TaskCompletionSource<StoredSecret> received) => Receive<SecretReplicationActor.PublishLocalWrite>(message => received.TrySetResult(message.Row));
|
||||
}
|
||||
Reference in New Issue
Block a user