| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using ProjectTemplate.Infrastructure.Data.Entities; |
| | | 3 | | |
| | | 4 | | namespace ProjectTemplate.Infrastructure.Data.Auditing; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Verifies retained application audit records against a canonical mutation manifest digest. |
| | | 8 | | /// </summary> |
| | 20 | 9 | | public sealed class ApplicationMutationManifestVerifier( |
| | 20 | 10 | | IApplicationMutationManifestBuilder manifestBuilder, |
| | 20 | 11 | | IApplicationMutationManifestHasher manifestHasher) |
| | | 12 | | : IApplicationMutationManifestVerifier |
| | | 13 | | { |
| | 20 | 14 | | private readonly IApplicationMutationManifestBuilder _manifestBuilder = |
| | 20 | 15 | | manifestBuilder ?? throw new ArgumentNullException(nameof(manifestBuilder)); |
| | 20 | 16 | | private readonly IApplicationMutationManifestHasher _manifestHasher = |
| | 20 | 17 | | manifestHasher ?? throw new ArgumentNullException(nameof(manifestHasher)); |
| | | 18 | | |
| | | 19 | | /// <inheritdoc /> |
| | | 20 | | public bool Verify( |
| | | 21 | | ApplicationMutationAuditReceipt receipt, |
| | | 22 | | IReadOnlyCollection<AuditRecord> auditRecords) |
| | | 23 | | { |
| | 18 | 24 | | ArgumentNullException.ThrowIfNull(receipt); |
| | 18 | 25 | | ArgumentNullException.ThrowIfNull(auditRecords); |
| | | 26 | | |
| | 18 | 27 | | if (!string.Equals(receipt.MutationManifestAlgorithm, _manifestHasher.Algorithm, StringComparison.Ordinal) || |
| | 18 | 28 | | auditRecords.Count != receipt.AuditRecordCount || |
| | 38 | 29 | | auditRecords.Any(record => !string.Equals(record.MutationBatchId, receipt.MutationBatchId, StringComparison. |
| | | 30 | | { |
| | 2 | 31 | | return false; |
| | | 32 | | } |
| | | 33 | | |
| | 16 | 34 | | ApplicationMutationManifest manifest = _manifestBuilder.Build(auditRecords); |
| | 16 | 35 | | string actualHash = _manifestHasher.ComputeHash(manifest); |
| | | 36 | | |
| | | 37 | | byte[] expectedBytes; |
| | | 38 | | byte[] actualBytes; |
| | | 39 | | |
| | | 40 | | try |
| | | 41 | | { |
| | 16 | 42 | | expectedBytes = Convert.FromHexString(receipt.MutationManifestHash); |
| | 16 | 43 | | actualBytes = Convert.FromHexString(actualHash); |
| | 16 | 44 | | } |
| | 0 | 45 | | catch (FormatException) |
| | | 46 | | { |
| | 0 | 47 | | return false; |
| | | 48 | | } |
| | | 49 | | |
| | 16 | 50 | | return CryptographicOperations.FixedTimeEquals(expectedBytes, actualBytes); |
| | 0 | 51 | | } |
| | | 52 | | } |