Files
admin/e2e/Azaion.E2E/Tests/ResourceTests.cs
T
Oleksandr Bezdieniezhnykh 5e90512987 [AZ-197] Remove hardware ID binding from resource flow
Sealed-Jetson + SaaS architecture eliminates the credential-reuse-across-
machines threat that motivated hardware fingerprint binding. The binding's
only remaining effect was a real production failure mode on legitimate
hardware events.

Production:
- Drop PUT /users/hardware/set and POST /resources/check.
- Simplify POST /resources/get/{dataFolder?} (no Hardware field).
- Remove CheckHardwareHash, UpdateHardware, Security.GetHWHash.
- GetApiEncryptionKey signature: (email, password) — no hardwareHash.
- Drop SetHWRequest DTO and Hardware property from GetResourceRequest.
- Remove HardwareIdMismatch (40) and BadHardware (45) ExceptionEnum
  entries; numeric codes left as a gap, not for reuse.

Wire-compat policy: drop entirely (no Loader; no in-flight legacy
clients). Stale callers will see 404s, which is the right loud failure.

Tombstones:
- User.Hardware DB column kept (nullable, unused) — separate cleanup
  ticket for the migration per workspace "no rename without confirmation".
- User.LastLogin is now never written by app code (only writer was inside
  the deleted CheckHardwareHash); flagged in batch_06_review for a future
  ticket.

Tests:
- Delete e2e HardwareBindingTests (165 lines) and Azaion.Test
  UserServiceTest (sole test was CheckHardwareHashTest).
- Drop Hardware payloads + /resources/check preconditions from e2e
  ResourceTests, SecurityTests, ResilienceTests; drop hardwareId arg
  from Azaion.Test SecurityTest.
- Add SecurityTests.Hardware_endpoints_are_removed_AZ_197 (AC-2 regression
  asserting both removed routes return 404).

Docs:
- architecture.md: System Context note, ADR-003 new key formula, ADR-004
  retired with rationale.
- diagrams/flows/flow_hardware_check.md: tombstoned.

Also archives the four batch-1+batch-2 task files into _docs/02_tasks/done/
(file moves were missed by the batch_05 commit).

Code review: PASS — see _docs/03_implementation/reviews/batch_06_review.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 04:46:39 +03:00

204 lines
7.6 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Azaion.E2E.Helpers;
using FluentAssertions;
using Xunit;
namespace Azaion.E2E.Tests;
[Collection("E2E")]
public sealed class ResourceTests
{
private static readonly JsonSerializerOptions ResponseJsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private const string TestUserPassword = "TestPass1234";
private sealed record ErrorResponse(int ErrorCode, string Message);
private readonly TestFixture _fixture;
public ResourceTests(TestFixture fixture) => _fixture = fixture;
[Fact]
public async Task File_upload_succeeds()
{
// Arrange
var folder = $"restest-{Guid.NewGuid():N}";
var fileBytes = Encoding.UTF8.GetBytes(new string('a', 100));
try
{
using var admin = _fixture.CreateAuthenticatedClient(_fixture.AdminToken);
// Act
using var response = await admin.UploadFileAsync($"/resources/{folder}", fileBytes, "upload.txt");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
finally
{
using var adminCleanup = _fixture.CreateAuthenticatedClient(_fixture.AdminToken);
using var clear = await adminCleanup.PostAsync($"/resources/clear/{folder}", new { });
clear.EnsureSuccessStatusCode();
}
}
[Fact]
public async Task Encrypted_download_returns_octet_stream_and_non_empty_body()
{
// Arrange
var folder = $"restest-{Guid.NewGuid():N}";
const string fileName = "secure.bin";
var fileBytes = Encoding.UTF8.GetBytes("download-test-payload");
string? email = null;
try
{
using (var admin = _fixture.CreateAuthenticatedClient(_fixture.AdminToken))
{
using var upload = await admin.UploadFileAsync($"/resources/{folder}", fileBytes, fileName);
upload.EnsureSuccessStatusCode();
}
var candidateEmail = $"restest-{Guid.NewGuid():N}@azaion.com";
using (var admin = _fixture.CreateAuthenticatedClient(_fixture.AdminToken))
{
using var createResp = await admin.PostAsync("/users",
new { Email = candidateEmail, Password = TestUserPassword, Role = 10 });
createResp.EnsureSuccessStatusCode();
}
email = candidateEmail;
using var loginClient = _fixture.CreateApiClient();
var userToken = await loginClient.LoginAsync(email, TestUserPassword);
using var userClient = _fixture.CreateAuthenticatedClient(userToken);
// Act
using var response = await userClient.PostAsync($"/resources/get/{folder}",
new { Password = TestUserPassword, FileName = fileName });
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/octet-stream");
var body = await response.Content.ReadAsByteArrayAsync();
body.Should().NotBeEmpty();
}
finally
{
if (email is not null)
{
using var adminCleanup = _fixture.CreateAuthenticatedClient(_fixture.AdminToken);
using var del = await adminCleanup.DeleteAsync($"/users/{Uri.EscapeDataString(email)}");
del.EnsureSuccessStatusCode();
}
using var adminClear = _fixture.CreateAuthenticatedClient(_fixture.AdminToken);
using var clear = await adminClear.PostAsync($"/resources/clear/{folder}", new { });
clear.EnsureSuccessStatusCode();
}
}
[Fact]
public async Task Encryption_round_trip_decrypt_matches_original_bytes()
{
// Arrange
var folder = $"restest-{Guid.NewGuid():N}";
const string fileName = "roundtrip.bin";
var original = Enumerable.Range(0, 128).Select(i => (byte)i).ToArray();
const string password = "RoundTrip123";
string? email = null;
try
{
using (var admin = _fixture.CreateAuthenticatedClient(_fixture.AdminToken))
{
using var upload = await admin.UploadFileAsync($"/resources/{folder}", original, fileName);
upload.EnsureSuccessStatusCode();
}
var candidateEmail = $"roundtrip-{Guid.NewGuid():N}@azaion.com";
using (var admin = _fixture.CreateAuthenticatedClient(_fixture.AdminToken))
{
using var createResp = await admin.PostAsync("/users",
new { Email = candidateEmail, Password = password, Role = 10 });
createResp.EnsureSuccessStatusCode();
}
email = candidateEmail;
using var loginClient = _fixture.CreateApiClient();
var userToken = await loginClient.LoginAsync(email, password);
using var userClient = _fixture.CreateAuthenticatedClient(userToken);
// Act
using var download = await userClient.PostAsync($"/resources/get/{folder}",
new { Password = password, FileName = fileName });
download.EnsureSuccessStatusCode();
var encrypted = await download.Content.ReadAsByteArrayAsync();
var decrypted = DecryptResourcePayload(encrypted, email!, password);
// Assert
decrypted.Should().Equal(original);
}
finally
{
if (email is not null)
{
using var adminCleanup = _fixture.CreateAuthenticatedClient(_fixture.AdminToken);
using var del = await adminCleanup.DeleteAsync($"/users/{Uri.EscapeDataString(email)}");
del.EnsureSuccessStatusCode();
}
using var adminClear = _fixture.CreateAuthenticatedClient(_fixture.AdminToken);
using var clear = await adminClear.PostAsync($"/resources/clear/{folder}", new { });
clear.EnsureSuccessStatusCode();
}
}
[Fact]
public async Task Upload_without_file_is_rejected_with_400_or_409_and_60_on_conflict()
{
// Arrange
var folder = $"restest-{Guid.NewGuid():N}";
using var content = new MultipartFormDataContent();
// Act
using var response = await _fixture.HttpClient.PostAsync($"/resources/{folder}", content);
// Assert
response.StatusCode.Should().BeOneOf(HttpStatusCode.BadRequest, HttpStatusCode.Conflict);
if (response.StatusCode == HttpStatusCode.Conflict)
{
var err = await response.Content.ReadFromJsonAsync<ErrorResponse>(ResponseJsonOptions);
err.Should().NotBeNull();
err!.ErrorCode.Should().Be(60);
}
}
private static byte[] DecryptResourcePayload(byte[] encrypted, string email, string password)
{
var apiKey = Convert.ToBase64String(SHA384.HashData(
Encoding.UTF8.GetBytes($"{email}-{password}-#%@AzaionKey@%#---")));
var aesKey = SHA256.HashData(Encoding.UTF8.GetBytes(apiKey));
if (encrypted.Length <= 16)
throw new InvalidOperationException("Encrypted payload too short.");
using var aes = Aes.Create();
aes.Key = aesKey;
aes.IV = encrypted.AsSpan(0, 16).ToArray();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using var decryptor = aes.CreateDecryptor();
return decryptor.TransformFinalBlock(encrypted, 16, encrypted.Length - 16);
}
}