Files
scadaproj/ZB.MOM.WW.Secrets/tests/ZB.MOM.WW.Secrets.Tests/Crypto/AesGcmEnvelopeCipherTests.cs
T
Joseph Doherty d82d3451e7 feat(secrets): build G-8 KEK rotation (RewrapAll); design+plan G-7 clustered replication
G-8 (KEK rotation) — built in ZB.MOM.WW.Secrets, lib 0.1.2->0.1.3:
- ISecretCipher.Rewrap(row, oldKek, newKek): re-wraps the per-secret DEK only
  (bodies never re-encrypted; revision/timestamps preserved -> invisible to
  cluster LWW). Fail-closed on wrong old-KEK id, wrong key bytes, and malformed
  wraps; DEK zeroed on all paths.
- ISecretStore.ApplyRewrapAsync(rewrappedRow, expectedCurrentWrappedDek):
  updates only the 4 wrap columns + kek_id, compare-and-swap on the current
  wrapped DEK so a concurrent set/rotate cannot corrupt a row (closes a
  review-caught TOCTOU).
- KekRotationService.RewrapAllAsync + RewrapReport: enumerate all rows incl.
  tombstones, idempotent/resumable skip-already-current, bounded CAS-retry,
  fail-closed on unknown/identical KEK.
- `secret rewrap-all` CLI verb: key material only via env-var name / file path,
  JSON counts report; README section + operator runbook.

Verified: full offline suite green (82 core + 15 UI, 0 regressions) + end-to-end
CLI smoke + adversarial crypto review (all 7 categories PASS; TOCTOU fixed).

G-7 (clustered replication) — designed + planned, no code:
- Fork resolved to build Option A (shared SQL-Server ISecretStore); Akka
  replicator ZB.MOM.WW.Secrets.Akka is a deferred phase-2. Design doc +
  executable plan + .tasks.json under docs/plans/2026-07-17-secrets-g7-*.

Tracking: components/secrets/GAPS.md + CLAUDE.md secrets row updated.
2026-07-17 02:55:43 -04:00

217 lines
8.4 KiB
C#

using System.Text;
using ZB.MOM.WW.Secrets.Abstractions;
using ZB.MOM.WW.Secrets.Crypto;
using ZB.MOM.WW.Secrets.Tests.Fakes;
namespace ZB.MOM.WW.Secrets.Tests.Crypto;
public class AesGcmEnvelopeCipherTests
{
[Fact]
public void RoundTrips()
{
var provider = new FakeMasterKeyProvider("k1");
var cipher = new AesGcmEnvelopeCipher(provider);
var name = new SecretName("sql/foo");
StoredSecret row = cipher.Encrypt(name, "hunter2", SecretContentType.Text);
Assert.Equal("k1", row.KekId);
// Ciphertext must not leak the plaintext in the clear.
byte[] plaintextBytes = Encoding.UTF8.GetBytes("hunter2");
Assert.False(Contains(row.Ciphertext, plaintextBytes));
string decrypted = cipher.Decrypt(row);
Assert.Equal("hunter2", decrypted);
}
[Fact]
public void TwoEncryptsProduceDifferentNonces()
{
var provider = new FakeMasterKeyProvider("k1");
var cipher = new AesGcmEnvelopeCipher(provider);
var name = new SecretName("sql/foo");
// Same plaintext + name encrypted twice must yield a fresh nonce (and therefore a distinct
// ciphertext) each time — the AES-GCM (key, nonce) uniqueness invariant.
StoredSecret first = cipher.Encrypt(name, "hunter2", SecretContentType.Text);
StoredSecret second = cipher.Encrypt(name, "hunter2", SecretContentType.Text);
Assert.False(first.Nonce.AsSpan().SequenceEqual(second.Nonce));
Assert.False(first.Ciphertext.AsSpan().SequenceEqual(second.Ciphertext));
}
[Fact]
public void TamperedCiphertextThrows()
{
var provider = new FakeMasterKeyProvider("k1");
var cipher = new AesGcmEnvelopeCipher(provider);
var name = new SecretName("sql/foo");
StoredSecret row = cipher.Encrypt(name, "hunter2", SecretContentType.Text);
row.Ciphertext[0] ^= 0xFF;
Assert.Throws<SecretDecryptionException>(() => cipher.Decrypt(row));
}
[Fact]
public void AadBindingRejectsRenamedRow()
{
var provider = new FakeMasterKeyProvider("k1");
var cipher = new AesGcmEnvelopeCipher(provider);
StoredSecret row = cipher.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);
var renamed = row with { Name = new SecretName("sql/bar") };
Assert.Throws<SecretDecryptionException>(() => cipher.Decrypt(renamed));
}
[Fact]
public void WrongKekThrows()
{
// Both providers report KekId "k1" but hold different random key bytes.
var providerA = new FakeMasterKeyProvider("k1");
var providerB = new FakeMasterKeyProvider("k1");
var cipherA = new AesGcmEnvelopeCipher(providerA);
var cipherB = new AesGcmEnvelopeCipher(providerB);
StoredSecret row = cipherA.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);
// Matching KekId string but wrong key material must still fail closed (unwrap tag mismatch).
Assert.Throws<SecretDecryptionException>(() => cipherB.Decrypt(row));
}
[Fact]
public void UnknownKekIdThrows()
{
var providerK1 = new FakeMasterKeyProvider("k1");
var providerK2 = new FakeMasterKeyProvider("k2");
var cipherK1 = new AesGcmEnvelopeCipher(providerK1);
var cipherK2 = new AesGcmEnvelopeCipher(providerK2);
StoredSecret row = cipherK1.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);
var ex = Assert.Throws<SecretDecryptionException>(() => cipherK2.Decrypt(row));
Assert.Contains("unknown KEK", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void Rewrap_RewrapsDek_BodyStillDecryptsUnderNewKek()
{
var oldKek = new FakeMasterKeyProvider("kek-old");
var newKek = new FakeMasterKeyProvider("kek-new");
var oldCipher = new AesGcmEnvelopeCipher(oldKek);
var name = new SecretName("sql/foo");
StoredSecret row = oldCipher.Encrypt(name, "hunter2", SecretContentType.Text);
Assert.Equal("kek-old", row.KekId);
// Rewrap is provider-explicit — it can be driven through any cipher instance.
StoredSecret rewrapped = oldCipher.Rewrap(row, oldKek, newKek);
Assert.Equal("kek-new", rewrapped.KekId);
// The DEK-sealed body is untouched; only the KEK-wrap envelope changed.
Assert.True(rewrapped.Ciphertext.AsSpan().SequenceEqual(row.Ciphertext));
Assert.True(rewrapped.Nonce.AsSpan().SequenceEqual(row.Nonce));
Assert.True(rewrapped.Tag.AsSpan().SequenceEqual(row.Tag));
Assert.False(rewrapped.WrappedDek.AsSpan().SequenceEqual(row.WrappedDek));
// The rewrapped row decrypts under the NEW KEK...
var newCipher = new AesGcmEnvelopeCipher(newKek);
Assert.Equal("hunter2", newCipher.Decrypt(rewrapped));
// ...and no longer under the OLD KEK (kek_id now names the new KEK; old cipher fails closed).
Assert.Throws<SecretDecryptionException>(() => oldCipher.Decrypt(rewrapped));
}
[Fact]
public void Rewrap_PreservesRevisionTimestampsTombstoneAndMetadata()
{
var oldKek = new FakeMasterKeyProvider("kek-old");
var newKek = new FakeMasterKeyProvider("kek-new");
var cipher = new AesGcmEnvelopeCipher(oldKek);
StoredSecret row = cipher.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text) with
{
Revision = 7,
IsDeleted = true,
DeletedUtc = DateTimeOffset.UnixEpoch,
CreatedUtc = DateTimeOffset.UnixEpoch,
UpdatedUtc = DateTimeOffset.UnixEpoch.AddMinutes(5),
CreatedBy = "alice",
UpdatedBy = "bob",
Description = "the foo password",
};
StoredSecret rewrapped = cipher.Rewrap(row, oldKek, newKek);
// Only the wrap envelope + kek_id change — a rewrap must be invisible to (updated_utc, revision) LWW.
Assert.Equal(7, rewrapped.Revision);
Assert.True(rewrapped.IsDeleted);
Assert.Equal(row.DeletedUtc, rewrapped.DeletedUtc);
Assert.Equal(row.CreatedUtc, rewrapped.CreatedUtc);
Assert.Equal(row.UpdatedUtc, rewrapped.UpdatedUtc);
Assert.Equal("alice", rewrapped.CreatedBy);
Assert.Equal("bob", rewrapped.UpdatedBy);
Assert.Equal("the foo password", rewrapped.Description);
Assert.Equal(SecretContentType.Text, rewrapped.ContentType);
}
[Fact]
public void Rewrap_WrongOldKekId_FailsClosed()
{
var actualKek = new FakeMasterKeyProvider("kek-old");
var wrongOld = new FakeMasterKeyProvider("kek-somethingelse");
var newKek = new FakeMasterKeyProvider("kek-new");
var cipher = new AesGcmEnvelopeCipher(actualKek);
StoredSecret row = cipher.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);
// Row is wrapped by "kek-old" but the caller claims the old KEK is "kek-somethingelse".
var ex = Assert.Throws<SecretDecryptionException>(() => cipher.Rewrap(row, wrongOld, newKek));
Assert.Contains("kek-old", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void Rewrap_CorrectKekIdButWrongKeyMaterial_FailsClosed()
{
// Same KEK-id string, different key bytes → the unwrap must fail closed (tag mismatch),
// never emitting a garbage DEK.
var realOld = new FakeMasterKeyProvider("kek-old");
var imposterOld = new FakeMasterKeyProvider("kek-old"); // same id, fresh random bytes
var newKek = new FakeMasterKeyProvider("kek-new");
var cipher = new AesGcmEnvelopeCipher(realOld);
StoredSecret row = cipher.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);
Assert.Throws<SecretDecryptionException>(() => cipher.Rewrap(row, imposterOld, newKek));
}
private static bool Contains(byte[] haystack, byte[] needle)
{
if (needle.Length == 0 || haystack.Length < needle.Length)
{
return false;
}
for (int i = 0; i <= haystack.Length - needle.Length; i++)
{
bool match = true;
for (int j = 0; j < needle.Length; j++)
{
if (haystack[i + j] != needle[j])
{
match = false;
break;
}
}
if (match)
{
return true;
}
}
return false;
}
}