diff --git a/src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs b/src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs index ecc2a4db..1591761b 100644 --- a/src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs +++ b/src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs @@ -133,19 +133,13 @@ private async Task OpenBackup() if (files.Count == 0) { return; } using var file = files[0]; await using var stream = await file.OpenReadAsync(); - using var buffer = new MemoryStream(); - var chunk = new byte[8192]; - int count; - while ((count = await stream.ReadAsync(chunk)) > 0) - { - if (buffer.Length + count > BackupArchive.MaximumFileSize) { throw new InvalidDataException(); } - buffer.Write(chunk, 0, count); - } + // One bounded buffer, handed to the session without another copy (issue #394). + var archive = await BackupArchive.ReadFileAsync(stream); var password = BackupPassword; var lifetime = Services.ShutdownToken; var opened = await Task.Run(() => { - var session = BackupArchive.OpenImport(buffer.ToArray(), password); + var session = BackupArchive.OpenImportOwned(archive, password); // Register on the worker too: shutdown can stop the UI dispatcher before // this await resumes and transfers ownership to the ViewModel. try { return (Session: session, Shutdown: lifetime.Register(session.Dispose)); } diff --git a/src/Bydlo.Core/Backup/BackupArchive.cs b/src/Bydlo.Core/Backup/BackupArchive.cs index c20a3173..91a231ce 100644 --- a/src/Bydlo.Core/Backup/BackupArchive.cs +++ b/src/Bydlo.Core/Backup/BackupArchive.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Security.Cryptography; using System.Text.Json; using Bydlo.Core.Models; @@ -32,52 +33,147 @@ public static class BackupArchive public const int MaximumFileSize = 32 * 1024 * 1024; internal const int Overhead = 8 + 16 + 12 + 16; - public static BackupImportSession OpenImport(byte[] file, string password) => BackupImportSession.Open(file, password); + public static BackupImportSession OpenImport(byte[] file, string password) => BackupImportSession.Open(file, password, copy: true); + + /// + /// Opens an archive read with . Ownership of + /// moves to the session: it is not copied again and is cleared when the session is disposed (issue #394). + /// + public static BackupImportSession OpenImportOwned(byte[] file, string password) => BackupImportSession.Open(file, password, copy: false); + + /// + /// Reads an archive with a hard size limit (issue #394). A stream with a known length gets one + /// exactly sized buffer after the limit check; an unknown length grows geometrically but never + /// past + 1 bytes. + /// + public static async Task ReadFileAsync(Stream stream, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + long? known = null; + try { if (stream.CanSeek) { known = stream.Length - stream.Position; } } + catch (NotSupportedException) { } + if (known is { } length) + { + if (length > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); } + var exact = new byte[length]; + try { await stream.ReadExactlyAsync(exact, ct).ConfigureAwait(false); } + catch (EndOfStreamException ex) { throw new InvalidDataException("Backup changed while reading.", ex); } + var probe = new byte[1]; + if (await stream.ReadAsync(probe, ct).ConfigureAwait(false) != 0) + { throw new InvalidDataException("Backup changed while reading."); } + return exact; + } + var buffer = new byte[Math.Min(64 * 1024, MaximumFileSize + 1)]; + var count = 0; + while (true) + { + if (count == buffer.Length) + { + if (buffer.Length > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); } + Array.Resize(ref buffer, (int)Math.Min((long)buffer.Length * 2, MaximumFileSize + 1L)); + } + var read = await stream.ReadAsync(buffer.AsMemory(count), ct).ConfigureAwait(false); + if (read == 0) { break; } + count += read; + if (count > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); } + } + return count == buffer.Length ? buffer : buffer.AsSpan(0, count).ToArray(); + } public static byte[] Encrypt(BackupData data, string password) { ArgumentException.ThrowIfNullOrWhiteSpace(password); Validate(data); - var plaintext = JsonSerializer.SerializeToUtf8Bytes(data, JsonDefaults.Options.Info()); + // Cheap lower bound first: large raw configs fail before any buffer is allocated. + if (MinimumPayloadSize(data) > MaximumFileSize - Overhead) { throw new InvalidDataException("Backup is too large."); } + // Serialize straight after the header into one pooled buffer, enforcing the limit while + // writing, then encrypt in place (issue #394). The buffer holds plaintext until encrypted, + // so it is always cleared before it returns to the pool. + using var buffer = new BoundedBuffer(Overhead, MaximumFileSize); byte[]? key = null; try { - if (plaintext.Length > MaximumFileSize - Overhead) { throw new InvalidDataException("Backup is too large."); } - var output = new byte[Overhead + plaintext.Length]; + using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Encoder = JsonDefaults.Options.Encoder, Indented = JsonDefaults.Options.WriteIndented })) + { + JsonSerializer.Serialize(writer, data, JsonDefaults.Options.Info()); + } + var total = buffer.WrittenCount; + var output = buffer.Array.AsSpan(0, total); Header.CopyTo(output); - RandomNumberGenerator.Fill(output.AsSpan(8, 16)); - RandomNumberGenerator.Fill(output.AsSpan(24, 12)); - key = Rfc2898DeriveBytes.Pbkdf2(password, output.AsSpan(8, 16), Iterations, HashAlgorithmName.SHA256, 32); + RandomNumberGenerator.Fill(output.Slice(8, 16)); + RandomNumberGenerator.Fill(output.Slice(24, 12)); + key = Rfc2898DeriveBytes.Pbkdf2(password, output.Slice(8, 16), Iterations, HashAlgorithmName.SHA256, 32); using var aes = new AesGcm(key, 16); - aes.Encrypt(output.AsSpan(24, 12), plaintext, output.AsSpan(Overhead), output.AsSpan(36, 16), output.AsSpan(0, 24)); - return output; + var body = output[Overhead..]; + aes.Encrypt(output.Slice(24, 12), body, body, output.Slice(36, 16), output[..24]); + return output.ToArray(); } finally { - CryptographicOperations.ZeroMemory(plaintext); if (key is not null) { CryptographicOperations.ZeroMemory(key); } } } + /// + /// Lower bound of the serialized size: every string value appears at least once in UTF-8. + /// Escaping and property names only add bytes, so exceeding the limit here is conclusive. + /// + internal static long MinimumPayloadSize(BackupData data) + { + long total = 0; + static long Bytes(string? value) => value is null ? 0 : System.Text.Encoding.UTF8.GetByteCount(value); + static long Dictionary(Dictionary? values) => + values?.Sum(entry => Bytes(entry.Key) + Bytes(entry.Value)) ?? 0; + foreach (var item in data.Profiles) + { + total += Dictionary(item.Secrets.Values) + Dictionary(item.Profile.Options) + + Bytes(item.Profile.Name) + Bytes(item.Profile.Host); + } + foreach (var sub in data.Subscriptions) + { + total += Bytes(sub.Url) + Bytes(sub.Subscription.Name) + + (sub.Subscription.SourceOptions?.Values.Sum(Dictionary) ?? 0); + } + return total + Dictionary(data.ToolSecrets.Values); + } + public static BackupData Decrypt(byte[] file, string password) { ArgumentException.ThrowIfNullOrWhiteSpace(password); if (file.Length < Overhead || file.Length > MaximumFileSize || !file.AsSpan(0, 8).SequenceEqual(Header)) { throw new InvalidDataException("Unsupported backup."); } var key = Rfc2898DeriveBytes.Pbkdf2(password, file.AsSpan(8, 16), Iterations, HashAlgorithmName.SHA256, 32); - var plaintext = new byte[file.Length - Overhead]; + try + { + return DecryptWith(key, file, plaintext => + { + var data = JsonSerializer.Deserialize(plaintext.Span, JsonDefaults.Options.Info()) ?? throw new InvalidDataException("Invalid backup."); + Validate(data); + return data; + }); + } + finally { CryptographicOperations.ZeroMemory(key); } + } + + /// + /// Authenticates and decrypts into a pooled buffer that is cleared on every path. The reader only + /// sees plaintext after the tag has been verified and must not retain the span. + /// + internal static T DecryptWith(byte[] key, byte[] archive, Func, T> read) + { + var length = archive.Length - Overhead; + var rented = ArrayPool.Shared.Rent(Math.Max(length, 1)); + var plaintext = rented.AsMemory(0, length); try { using var aes = new AesGcm(key, 16); - aes.Decrypt(file.AsSpan(24, 12), file.AsSpan(Overhead), file.AsSpan(36, 16), plaintext, file.AsSpan(0, 24)); - var data = JsonSerializer.Deserialize(plaintext, JsonDefaults.Options.Info()) ?? throw new InvalidDataException("Invalid backup."); - Validate(data); - return data; + aes.Decrypt(archive.AsSpan(24, 12), archive.AsSpan(Overhead), archive.AsSpan(36, 16), plaintext.Span, archive.AsSpan(0, 24)); + return read(plaintext); } finally { - CryptographicOperations.ZeroMemory(key); - CryptographicOperations.ZeroMemory(plaintext); + CryptographicOperations.ZeroMemory(plaintext.Span); + ArrayPool.Shared.Return(rented); } } diff --git a/src/Bydlo.Core/Backup/BackupImportSession.cs b/src/Bydlo.Core/Backup/BackupImportSession.cs index 152f4803..f2d68dda 100644 --- a/src/Bydlo.Core/Backup/BackupImportSession.cs +++ b/src/Bydlo.Core/Backup/BackupImportSession.cs @@ -26,14 +26,15 @@ public sealed class BackupImportSession : IDisposable private BackupImportSession(byte[] archive, byte[] key) { _archive = archive; _key = key; } - internal static BackupImportSession Open(byte[] file, string password) + internal static BackupImportSession Open(byte[] file, string password, bool copy) { ArgumentException.ThrowIfNullOrWhiteSpace(password); if (file.Length < BackupArchive.Overhead || file.Length > BackupArchive.MaximumFileSize || !file.AsSpan(0, 8).SequenceEqual(BackupArchive.Header)) { throw new InvalidDataException("Unsupported backup."); } - // Never retain a caller-owned array that can change after authentication. - var archive = file.ToArray(); + // Never retain a caller-owned array that can change after authentication; an owned + // array (OpenImportOwned) is already exclusive to the session. + var archive = copy ? file.ToArray() : file; var key = Rfc2898DeriveBytes.Pbkdf2(password, archive.AsSpan(8, 16), BackupArchive.Iterations, HashAlgorithmName.SHA256, 32); var session = new BackupImportSession(archive, key); try @@ -78,7 +79,7 @@ public BackupData Materialize() ObjectDisposedException.ThrowIf(_disposed, this); return ReadPlaintext(plaintext => { - var data = JsonSerializer.Deserialize(plaintext, JsonDefaults.Options.Info()) + var data = JsonSerializer.Deserialize(plaintext.Span, JsonDefaults.Options.Info()) ?? throw new InvalidDataException("Invalid backup."); BackupArchive.Validate(data); return data; @@ -86,25 +87,14 @@ public BackupData Materialize() } } - private T ReadPlaintext(Func read) - { - var plaintext = new byte[_archive.Length - BackupArchive.Overhead]; - try - { - using var aes = new AesGcm(_key, 16); - aes.Decrypt(_archive.AsSpan(24, 12), _archive.AsSpan(BackupArchive.Overhead), - _archive.AsSpan(36, 16), plaintext, _archive.AsSpan(0, 24)); - return read(plaintext); - } - finally { CryptographicOperations.ZeroMemory(plaintext); } - } + private T ReadPlaintext(Func, T> read) => BackupArchive.DecryptWith(_key, _archive, read); - private static BackupData ReadMetadata(byte[] plaintext) + private static BackupData ReadMetadata(ReadOnlyMemory plaintext) { using var sanitized = new MemoryStream(); using (var writer = new Utf8JsonWriter(sanitized)) { - var reader = new Utf8JsonReader(plaintext); + var reader = new Utf8JsonReader(plaintext.Span); if (!reader.Read()) { throw new InvalidDataException("Invalid backup."); } CopyValue(ref reader, writer, false, false); if (reader.Read()) { throw new InvalidDataException("Invalid backup."); } diff --git a/src/Bydlo.Core/Backup/BoundedBuffer.cs b/src/Bydlo.Core/Backup/BoundedBuffer.cs new file mode 100644 index 00000000..08a1f6a6 --- /dev/null +++ b/src/Bydlo.Core/Backup/BoundedBuffer.cs @@ -0,0 +1,69 @@ +using System.Buffers; +using System.Security.Cryptography; + +namespace Bydlo.Core.Backup; + +/// +/// Pooled with a reserved prefix and a hard size limit (issue #394). +/// The limit is enforced while writing, so an oversized export fails before the result grows +/// without bound. Every buffer is cleared before it returns to the pool because it may hold plaintext. +/// +internal sealed class BoundedBuffer : IBufferWriter, IDisposable +{ + private readonly int _limit; + private byte[] _buffer; + private int _written; + + public BoundedBuffer(int prefix, int limit) + { + ArgumentOutOfRangeException.ThrowIfNegative(prefix); + ArgumentOutOfRangeException.ThrowIfLessThan(limit, prefix); + _limit = limit; + _buffer = ArrayPool.Shared.Rent(Math.Min(Math.Max(prefix + 4096, 64 * 1024), limit)); + _written = prefix; + } + + /// Prefix plus everything written so far. + public int WrittenCount => _written; + + /// Backing array; only the first bytes are meaningful. + public byte[] Array => _buffer; + + public void Advance(int count) + { + ArgumentOutOfRangeException.ThrowIfNegative(count); + if ((long)_written + count > _buffer.Length) { throw new InvalidOperationException("Advanced past the buffer."); } + if ((long)_written + count > _limit) { throw new InvalidDataException("Backup is too large."); } + _written += count; + } + + public Memory GetMemory(int sizeHint = 0) { Ensure(sizeHint); return _buffer.AsMemory(_written); } + + public Span GetSpan(int sizeHint = 0) { Ensure(sizeHint); return _buffer.AsSpan(_written); } + + private void Ensure(int sizeHint) + { + if (_written >= _limit) { throw new InvalidDataException("Backup is too large."); } + var needed = (long)_written + Math.Max(sizeHint, 1); + if (needed <= _buffer.Length) { return; } + // Writers over-request for worst-case escaping, so the buffer may exceed the limit by one + // hint; Advance still rejects any data past the limit. The hint itself stays bounded. + if (needed > (long)_limit * 8) { throw new InvalidDataException("Backup is too large."); } + var size = (int)Math.Min(Math.Max(needed, (long)_buffer.Length * 2), Math.Max(needed, _limit)); + var next = ArrayPool.Shared.Rent(size); + _buffer.AsSpan(0, _written).CopyTo(next); + CryptographicOperations.ZeroMemory(_buffer); + ArrayPool.Shared.Return(_buffer); + _buffer = next; + } + + public void Dispose() + { + if (_buffer.Length == 0) { return; } + // Clear the whole array: a writer may have produced bytes it never advanced over. + CryptographicOperations.ZeroMemory(_buffer); + ArrayPool.Shared.Return(_buffer); + _buffer = []; + _written = 0; + } +} diff --git a/tests/Bydlo.Tests/BackupBufferTests.cs b/tests/Bydlo.Tests/BackupBufferTests.cs new file mode 100644 index 00000000..86861c1f --- /dev/null +++ b/tests/Bydlo.Tests/BackupBufferTests.cs @@ -0,0 +1,194 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Bydlo.Core.Backup; +using Bydlo.Core.Models; +using Bydlo.Core.Serialization; +using Bydlo.Core.Storage; + +namespace Bydlo.Tests; + +/// Bounded backup buffers (issue #394): same format, fewer copies, limits enforced early. +public sealed class BackupBufferTests +{ + private const string Password = "a long backup password for buffers"; + + private sealed class UnknownLengthStream(byte[] data) : Stream + { + private int _position; + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override int Read(byte[] buffer, int offset, int count) + { + // Short reads exercise fragmented accumulation. + var n = Math.Min(Math.Min(count, 7919), data.Length - _position); + Array.Copy(data, _position, buffer, offset, n); + _position += n; + return n; + } + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + /// Reports a length that does not match its content (file changed while reading). + private sealed class LyingLengthStream(byte[] data, long reported) : MemoryStream(data) + { + public override long Length => reported; + } + + private static BackupData Data() => new() + { + Profiles = [new(new Profile { Name = "Buffer server", Protocol = ProtocolKind.Vless, Host = "h.example", Port = 443 }, + new ProfileSecrets { Values = { [Keys.Uuid] = "buffer-uuid" } })], + ToolSecrets = new ProfileSecrets { Values = { ["secret"] = "buffer-tool-secret" } }, + }; + + [Theory] + [InlineData(true, 0)] + [InlineData(true, 1)] + [InlineData(true, BackupArchive.MaximumFileSize)] + [InlineData(false, 0)] + [InlineData(false, 100_000)] + [InlineData(false, BackupArchive.MaximumFileSize)] + public async Task Reads_up_to_the_exact_limit(bool seekable, int size) + { + var bytes = new byte[size]; + Random.Shared.NextBytes(bytes); + Stream stream = seekable ? new MemoryStream(bytes) : new UnknownLengthStream(bytes); + var read = await BackupArchive.ReadFileAsync(stream); + Assert.Equal(bytes, read); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Rejects_one_byte_over_the_limit(bool seekable) + { + var bytes = new byte[BackupArchive.MaximumFileSize + 1]; + Stream stream = seekable ? new MemoryStream(bytes) : new UnknownLengthStream(bytes); + await Assert.ThrowsAsync(() => BackupArchive.ReadFileAsync(stream)); + } + + [Theory] + [InlineData(10, 5)] + [InlineData(10, 20)] + public async Task Rejects_streams_whose_length_changes_while_reading(int actual, long reported) + { + await Assert.ThrowsAsync(() => + BackupArchive.ReadFileAsync(new LyingLengthStream(new byte[actual], reported))); + } + + [Fact] + public async Task New_archives_are_read_by_the_previous_format_and_vice_versa() + { + var data = Data(); + var current = BackupArchive.Encrypt(data, Password); + var legacyRead = JsonSerializer.Deserialize(LegacyDecrypt(current, Password), JsonDefaults.Options.Info())!; + Assert.Equal("buffer-uuid", legacyRead.Profiles[0].Secrets[Keys.Uuid]); + + var legacy = LegacyEncrypt(data, Password); + Assert.Equal("buffer-tool-secret", BackupArchive.Decrypt(legacy, Password).ToolSecrets["secret"]); + var file = await BackupArchive.ReadFileAsync(new UnknownLengthStream(legacy)); + using var session = BackupArchive.OpenImportOwned(file, Password); + Assert.Equal("Buffer server", Assert.Single(session.Profiles).Name); + } + + [Fact] + public void Owned_session_rejects_wrong_password_tampering_and_truncation() + { + var archive = BackupArchive.Encrypt(Data(), Password); + Assert.ThrowsAny(() => BackupArchive.OpenImportOwned(archive.ToArray(), "a different long password")); + var tampered = archive.ToArray(); + tampered[^1] ^= 1; + Assert.ThrowsAny(() => BackupArchive.OpenImportOwned(tampered, Password)); + Assert.Throws(() => BackupArchive.OpenImportOwned(archive[..(BackupArchive.Overhead - 1)], Password)); + } + + [Fact] + public void Owned_archive_is_cleared_when_the_session_is_disposed() + { + var archive = BackupArchive.Encrypt(Data(), Password); + var session = BackupArchive.OpenImportOwned(archive, Password); + session.Dispose(); + Assert.All(archive, b => Assert.Equal(0, b)); + } + + [Fact] + public void Bounded_buffer_accepts_the_limit_and_rejects_one_more_byte() + { + using var buffer = new BoundedBuffer(52, 1000); + buffer.GetSpan(948); + buffer.Advance(948); + Assert.Equal(1000, buffer.WrittenCount); + Assert.Throws(() => buffer.GetSpan(1)); + } + + [Fact] + public void Oversized_export_fails_while_serializing() + { + var data = new BackupData(); + var config = new string('x', 1024 * 1024); + for (var i = 0; i < 40; i++) + { + data.Profiles.Add(new(new Profile { Name = "p" + i, Protocol = ProtocolKind.WireGuard, Host = "h", Port = 1 }, + new ProfileSecrets { Values = { [Keys.RawConfig] = config } })); + } + Assert.Throws(() => BackupArchive.Encrypt(data, Password)); // warm the pool + var start = GC.GetAllocatedBytesForCurrentThread(); + Assert.Throws(() => BackupArchive.Encrypt(data, Password)); + var current = GC.GetAllocatedBytesForCurrentThread() - start; + start = GC.GetAllocatedBytesForCurrentThread(); + // The previous implementation serialized the whole payload before checking the limit. + JsonSerializer.SerializeToUtf8Bytes(data, JsonDefaults.Options.Info()); + var legacy = GC.GetAllocatedBytesForCurrentThread() - start; + Assert.True(current * 2 < legacy, $"current={current} legacy={legacy}"); + } + + [Fact] + public void Export_allocates_less_than_the_previous_implementation() + { + var data = new BackupData(); + var config = new string('x', 128 * 1024); + for (var i = 0; i < 200; i++) + { + data.Profiles.Add(new(new Profile { Name = "p" + i, Protocol = ProtocolKind.WireGuard, Host = "h", Port = 1 }, + new ProfileSecrets { Values = { [Keys.RawConfig] = config + i } })); + } + BackupArchive.Encrypt(data, Password); // warm the pool + var start = GC.GetAllocatedBytesForCurrentThread(); + BackupArchive.Encrypt(data, Password); + var current = GC.GetAllocatedBytesForCurrentThread() - start; + start = GC.GetAllocatedBytesForCurrentThread(); + LegacyEncrypt(data, Password); + var legacy = GC.GetAllocatedBytesForCurrentThread() - start; + Assert.True(current * 3 < legacy * 2, $"current={current} legacy={legacy}"); + } + + // Verbatim copies of the v1 implementation before issue #394, used as the compatibility oracle. + private static byte[] LegacyEncrypt(BackupData data, string password) + { + var plaintext = JsonSerializer.SerializeToUtf8Bytes(data, JsonDefaults.Options.Info()); + var output = new byte[BackupArchive.Overhead + plaintext.Length]; + "BYDLOBK\x01"u8.CopyTo(output); + RandomNumberGenerator.Fill(output.AsSpan(8, 16)); + RandomNumberGenerator.Fill(output.AsSpan(24, 12)); + var key = Rfc2898DeriveBytes.Pbkdf2(password, output.AsSpan(8, 16), 600_000, HashAlgorithmName.SHA256, 32); + using var aes = new AesGcm(key, 16); + aes.Encrypt(output.AsSpan(24, 12), plaintext, output.AsSpan(BackupArchive.Overhead), output.AsSpan(36, 16), output.AsSpan(0, 24)); + return output; + } + + private static byte[] LegacyDecrypt(byte[] file, string password) + { + Assert.True(file.AsSpan(0, 8).SequenceEqual("BYDLOBK\x01"u8)); + var key = Rfc2898DeriveBytes.Pbkdf2(password, file.AsSpan(8, 16), 600_000, HashAlgorithmName.SHA256, 32); + var plaintext = new byte[file.Length - BackupArchive.Overhead]; + using var aes = new AesGcm(key, 16); + aes.Decrypt(file.AsSpan(24, 12), file.AsSpan(BackupArchive.Overhead), file.AsSpan(36, 16), plaintext, file.AsSpan(0, 24)); + return plaintext; + } +} diff --git a/tests/Bydlo.Tests/BackupImportSessionTests.cs b/tests/Bydlo.Tests/BackupImportSessionTests.cs index 41bb8af6..ad88c3cb 100644 --- a/tests/Bydlo.Tests/BackupImportSessionTests.cs +++ b/tests/Bydlo.Tests/BackupImportSessionTests.cs @@ -48,13 +48,13 @@ public void Metadata_contains_only_ids_names_relationships_and_caller_cannot_cha public void Dispose_is_idempotent_and_clears_owned_arrays_and_failed_read_plaintext() { var session = BackupArchive.OpenImport(BackupArchive.Encrypt(Data(), Password), Password); - byte[]? plaintext = null; + ReadOnlyMemory? plaintext = null; var read = typeof(BackupImportSession).GetMethod("ReadPlaintext", BindingFlags.Instance | BindingFlags.NonPublic)!.MakeGenericMethod(typeof(bool)); - var error = Assert.Throws(() => read.Invoke(session, [new Func(bytes => + var error = Assert.Throws(() => read.Invoke(session, [new Func, bool>(bytes => { plaintext = bytes; throw new IOException("Synthetic read failure"); })])); Assert.IsType(error.InnerException); Assert.NotNull(plaintext); - Assert.All(plaintext, value => Assert.Equal(0, value)); + Assert.All(plaintext.Value.ToArray(), value => Assert.Equal(0, value)); var key = Buffer(session, "_key"); var archive = Buffer(session, "_archive"); Assert.Contains(key, value => value != 0); @@ -97,7 +97,7 @@ public void Sanitizer_removes_escaped_secret_values_and_legacy_headers_before_de try { var method = typeof(BackupImportSession).GetMethod("ReadMetadata", BindingFlags.NonPublic | BindingFlags.Static)!; - var sanitized = (BackupData)method.Invoke(null, [plaintext])!; + var sanitized = (BackupData)method.Invoke(null, [new ReadOnlyMemory(plaintext)])!; Assert.Equal("x", sanitized.Profiles[0].Secrets[Keys.Password]); Assert.Equal("x", sanitized.Profiles[0].Secrets[Keys.RawConfig]); Assert.Equal("x", sanitized.Profiles[0].Profile.Options[Keys.XhttpHeaders]);