Fix CI build/deploy/smoke pipeline for the self-hosted qa runner (#3)
## Summary - Fix a chain of QA CI issues: Docker build/health-check flakiness, NuGet vuln pins, then adds the post-deploy integration + Playwright smoke suite and works through everything needed to make it actually run on the self-hosted `qa` runner (musl/Alpine job container, no node/dotnet/curl preinstalled, docker-outside-of-docker networking). - Adds a fixed dev/QA seed admin user + fixed Development environment API key so integration tests and e2e specs have a stable target. - Pins Aspire's `AppHost.cs` ports/credentials to match the docker-compose local dev defaults. - Adds `tests/api/MicCheck.Api.Tests.Integration` coverage for disabled flags, environment-document bootstrap, identity override precedence, auth login, and unauthorized access; adds a Playwright e2e suite under `src/admin/e2e` (login, nav, context selection, features CRUD/toggle). - Adds a `smoke-qa` CI job that runs both suites against the just-deployed QA stack, working around: no curl/node/dotnet on the bare runner, musl vs glibc (Playwright browsers run via the official `mcr.microsoft.com/playwright` image instead), and the runner's job-container network isolation (reach the QA stack via the docker bridge gateway IP; `docker cp` instead of a bind mount to get files into the playwright container, since paths don't cross the docker-outside-of-docker boundary). ## Test plan - [x] Unit tests pass (dotnet test tests/api/MicCheck.Api.Tests.Unit, 243 passed) - [x] API integration suite passes against the real QA stack in CI - [x] Playwright e2e suite passes against the real QA stack in CI (verified 3/3 locally against a real dev API + vite server for the flakiest spec) - [x] Full CI pipeline (build → deploy-qa → smoke-qa) green end to end on the qa runner Reviewed-on: #3
This commit was merged in pull request #3.
This commit is contained in:
55
tests/api/MicCheck.Api.Tests.Integration/Auth/AuthSeed.cs
Normal file
55
tests/api/MicCheck.Api.Tests.Integration/Auth/AuthSeed.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using MicCheck.Api.Tests.Integration.Common;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace MicCheck.Api.Tests.Integration.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// A stand-in for the real API's <c>User</c> type: <see cref="PasswordHasher{TUser}"/> only uses
|
||||
/// it as a type parameter (it doesn't inspect the instance), so any reference type works. Keeps
|
||||
/// this project a true black box with no <c>ProjectReference</c> to the API.
|
||||
/// </summary>
|
||||
public class HashedUser;
|
||||
|
||||
public sealed record AuthSeed(int OrganizationId, int UserId, string Email, string Password)
|
||||
{
|
||||
public static async Task<AuthSeed> InsertAsync(TestDatabase db, string testRunTag, string password)
|
||||
{
|
||||
var rawUnique = $"{testRunTag}-{Guid.NewGuid():N}";
|
||||
var unique = rawUnique[..Math.Min(rawUnique.Length, 40)];
|
||||
var email = $"{unique}@integration.test";
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
var passwordHash = new PasswordHasher<HashedUser>().HashPassword(new HashedUser(), password);
|
||||
|
||||
var organizationId = await db.ExecuteScalarAsync<int>(
|
||||
"INSERT INTO \"Organizations\" (\"Name\", \"CreatedAt\") VALUES (@name, @createdAt) RETURNING \"Id\"",
|
||||
("name", $"org_{unique}"),
|
||||
("createdAt", now));
|
||||
|
||||
var userId = await db.ExecuteScalarAsync<int>(
|
||||
"""
|
||||
INSERT INTO "Users" ("Email", "PasswordHash", "FirstName", "LastName", "IsActive", "IsTwoFactorEnabled", "CreatedAt")
|
||||
VALUES (@email, @passwordHash, 'Integration', 'Test', true, false, @createdAt)
|
||||
RETURNING "Id"
|
||||
""",
|
||||
("email", email),
|
||||
("passwordHash", passwordHash),
|
||||
("createdAt", now));
|
||||
|
||||
await db.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO "OrganizationUsers" ("OrganizationId", "UserId", "Role", "IsPrimary")
|
||||
VALUES (@orgId, @userId, 1, true)
|
||||
""",
|
||||
("orgId", organizationId),
|
||||
("userId", userId));
|
||||
|
||||
return new AuthSeed(organizationId, userId, email, password);
|
||||
}
|
||||
|
||||
public async Task CleanupAsync(TestDatabase db)
|
||||
{
|
||||
await db.ExecuteAsync("DELETE FROM \"Users\" WHERE \"Id\" = @userId", ("userId", UserId));
|
||||
await db.ExecuteAsync("DELETE FROM \"Organizations\" WHERE \"Id\" = @orgId", ("orgId", OrganizationId));
|
||||
}
|
||||
}
|
||||
95
tests/api/MicCheck.Api.Tests.Integration/Auth/AuthTests.cs
Normal file
95
tests/api/MicCheck.Api.Tests.Integration/Auth/AuthTests.cs
Normal file
@@ -0,0 +1,95 @@
|
||||
using System.Text.Json;
|
||||
using MicCheck.Api.Tests.Integration.Common;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MicCheck.Api.Tests.Integration.Auth;
|
||||
|
||||
[TestFixture]
|
||||
public class AuthTests
|
||||
{
|
||||
private const string Password = "Integration!Test123";
|
||||
|
||||
private IntegrationTestSettings settings = null!;
|
||||
private TestDatabase db = null!;
|
||||
private FlagApiHttpClient client = null!;
|
||||
private AuthSeed? seed;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
settings = IntegrationTestSettings.Load();
|
||||
db = new TestDatabase(settings.DbConnectionString);
|
||||
client = new FlagApiHttpClient(settings);
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown() => client.Dispose();
|
||||
|
||||
[SetUp]
|
||||
public async Task SetUp()
|
||||
=> seed = await AuthSeed.InsertAsync(db, testRunTag: "Auth", password: Password);
|
||||
|
||||
[TearDown]
|
||||
public async Task TearDown()
|
||||
{
|
||||
if (seed is not null)
|
||||
{
|
||||
await seed.CleanupAsync(db);
|
||||
seed = null;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenValidCredentialsAreSubmitted_ThenLoginReturnsAnAccessToken()
|
||||
{
|
||||
var current = seed!;
|
||||
|
||||
using var response = await client.SendAsync(
|
||||
httpFile: "Auth.http",
|
||||
requestName: "Login",
|
||||
variables: new Dictionary<string, string>
|
||||
{
|
||||
["baseUrl"] = settings.BaseUrl,
|
||||
["email"] = current.Email,
|
||||
["password"] = current.Password
|
||||
});
|
||||
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Assert.That(
|
||||
response.IsSuccessStatusCode,
|
||||
Is.True,
|
||||
$"POST /api/v1/auth/login returned {(int)response.StatusCode} {response.ReasonPhrase} for a valid seeded user. Body: {body}");
|
||||
|
||||
var login = JsonSerializer.Deserialize<LoginResponseDto>(body, JsonOptions)
|
||||
?? throw new InvalidOperationException("Response body was not the expected login shape.");
|
||||
|
||||
Assert.That(login.AccessToken, Is.Not.Null.And.Not.Empty);
|
||||
Assert.That(login.RefreshToken, Is.Not.Null.And.Not.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenAnIncorrectPasswordIsSubmitted_ThenLoginIsUnauthorized()
|
||||
{
|
||||
var current = seed!;
|
||||
|
||||
using var response = await client.SendAsync(
|
||||
httpFile: "Auth.http",
|
||||
requestName: "Login",
|
||||
variables: new Dictionary<string, string>
|
||||
{
|
||||
["baseUrl"] = settings.BaseUrl,
|
||||
["email"] = current.Email,
|
||||
["password"] = "definitely-the-wrong-password"
|
||||
});
|
||||
|
||||
Assert.That(
|
||||
(int)response.StatusCode,
|
||||
Is.EqualTo(401),
|
||||
$"Expected 401 for an incorrect password, got {(int)response.StatusCode} {response.ReasonPhrase}.");
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private sealed record LoginResponseDto(string AccessToken, string RefreshToken, DateTime ExpiresAt);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Text.Json;
|
||||
using MicCheck.Api.Tests.Integration.Common;
|
||||
using MicCheck.Api.Tests.Integration.Flags;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MicCheck.Api.Tests.Integration.Environments;
|
||||
|
||||
[TestFixture]
|
||||
public class EnvironmentDocumentTests
|
||||
{
|
||||
private IntegrationTestSettings settings = null!;
|
||||
private TestDatabase db = null!;
|
||||
private FlagApiHttpClient client = null!;
|
||||
private FlagSeed? seed;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
settings = IntegrationTestSettings.Load();
|
||||
db = new TestDatabase(settings.DbConnectionString);
|
||||
client = new FlagApiHttpClient(settings);
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown() => client.Dispose();
|
||||
|
||||
[SetUp]
|
||||
public async Task SetUp()
|
||||
=> seed = await FlagSeed.InsertEnabledFlagAsync(db, testRunTag: "EnvDocument", enabled: true, value: null);
|
||||
|
||||
[TearDown]
|
||||
public async Task TearDown()
|
||||
{
|
||||
if (seed is not null)
|
||||
{
|
||||
await seed.CleanupAsync(db);
|
||||
seed = null;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenAnEnvironmentHasFeatureStates_ThenTheEnvironmentDocumentIncludesThem()
|
||||
{
|
||||
var current = seed!;
|
||||
|
||||
using var response = await client.SendAsync(
|
||||
httpFile: "EnvironmentDocument.http",
|
||||
requestName: "GetEnvironmentDocument",
|
||||
variables: new Dictionary<string, string>
|
||||
{
|
||||
["baseUrl"] = settings.BaseUrl,
|
||||
["environmentKey"] = current.EnvironmentApiKey
|
||||
});
|
||||
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Assert.That(
|
||||
response.IsSuccessStatusCode,
|
||||
Is.True,
|
||||
$"GET /api/v1/environment-document returned {(int)response.StatusCode} {response.ReasonPhrase}. Body: {body}. DB state:\n{await current.DescribeAsync(db)}");
|
||||
|
||||
var document = JsonSerializer.Deserialize<EnvironmentDocumentDto>(body, JsonOptions)
|
||||
?? throw new InvalidOperationException("Response body was not the expected environment document shape.");
|
||||
|
||||
Assert.That(
|
||||
document.Id,
|
||||
Is.EqualTo(current.EnvironmentId),
|
||||
$"Environment document Id did not match the seeded environment. DB state:\n{await current.DescribeAsync(db)}");
|
||||
|
||||
var match = document.FeatureStates.SingleOrDefault(f => f.Feature.Name == current.FeatureName);
|
||||
|
||||
Assert.That(
|
||||
match,
|
||||
Is.Not.Null,
|
||||
$"Feature '{current.FeatureName}' was not present in the environment document. Returned features: [{string.Join(", ", document.FeatureStates.Select(f => f.Feature.Name))}]. DB state:\n{await current.DescribeAsync(db)}");
|
||||
|
||||
Assert.That(match!.Enabled, Is.True);
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private sealed record EnvironmentDocumentDto(int Id, string ApiKey, List<FlagResponseDto> FeatureStates, EnvironmentProjectDto Project);
|
||||
private sealed record EnvironmentProjectDto(int Id, string Name, List<object> Segments);
|
||||
private sealed record FlagResponseDto(int Id, FeatureSummaryDto Feature, bool Enabled, string? FeatureStateValue);
|
||||
private sealed record FeatureSummaryDto(int Id, string Name);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Text.Json;
|
||||
using MicCheck.Api.Tests.Integration.Common;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MicCheck.Api.Tests.Integration.Flags;
|
||||
|
||||
[TestFixture]
|
||||
public class FlagDisabledTests
|
||||
{
|
||||
private IntegrationTestSettings settings = null!;
|
||||
private TestDatabase db = null!;
|
||||
private FlagApiHttpClient client = null!;
|
||||
private FlagSeed? seed;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
settings = IntegrationTestSettings.Load();
|
||||
db = new TestDatabase(settings.DbConnectionString);
|
||||
client = new FlagApiHttpClient(settings);
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown() => client.Dispose();
|
||||
|
||||
[SetUp]
|
||||
public async Task SetUp()
|
||||
=> seed = await FlagSeed.InsertEnabledFlagAsync(db, testRunTag: "FlagDisabled", enabled: false, value: null);
|
||||
|
||||
[TearDown]
|
||||
public async Task TearDown()
|
||||
{
|
||||
if (seed is not null)
|
||||
{
|
||||
await seed.CleanupAsync(db);
|
||||
seed = null;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenAFeatureIsDisabledInEnvironment_ThenTheFlagApiReportsItDisabled()
|
||||
{
|
||||
var current = seed!;
|
||||
|
||||
using var response = await client.SendAsync(
|
||||
httpFile: "Flags.http",
|
||||
requestName: "GetFlags",
|
||||
variables: new Dictionary<string, string>
|
||||
{
|
||||
["baseUrl"] = settings.BaseUrl,
|
||||
["environmentKey"] = current.EnvironmentApiKey
|
||||
});
|
||||
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Assert.That(
|
||||
response.IsSuccessStatusCode,
|
||||
Is.True,
|
||||
$"GET /api/v1/flags returned {(int)response.StatusCode} {response.ReasonPhrase}. Body: {body}. DB state:\n{await current.DescribeAsync(db)}");
|
||||
|
||||
var flags = JsonSerializer.Deserialize<List<FlagResponseDto>>(body, JsonOptions)
|
||||
?? throw new InvalidOperationException("Response body was not a JSON array.");
|
||||
|
||||
var match = flags.SingleOrDefault(f => f.Feature.Name == current.FeatureName);
|
||||
|
||||
Assert.That(
|
||||
match,
|
||||
Is.Not.Null,
|
||||
$"Feature '{current.FeatureName}' was not present in the flags response. Returned features: [{string.Join(", ", flags.Select(f => f.Feature.Name))}]. DB state:\n{await current.DescribeAsync(db)}");
|
||||
|
||||
Assert.That(
|
||||
match!.Enabled,
|
||||
Is.False,
|
||||
$"Feature '{current.FeatureName}' was reported as enabled, but the seeded FeatureState has Enabled=false. DB state:\n{await current.DescribeAsync(db)}");
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private sealed record FlagResponseDto(int Id, FeatureSummaryDto Feature, bool Enabled, string? FeatureStateValue);
|
||||
private sealed record FeatureSummaryDto(int Id, string Name);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using MicCheck.Api.Tests.Integration.Common;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MicCheck.Api.Tests.Integration.Flags;
|
||||
|
||||
[TestFixture]
|
||||
public class FlagsApiAuthorizationTests
|
||||
{
|
||||
private IntegrationTestSettings settings = null!;
|
||||
private FlagApiHttpClient client = null!;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
settings = IntegrationTestSettings.Load();
|
||||
client = new FlagApiHttpClient(settings);
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown() => client.Dispose();
|
||||
|
||||
[Test]
|
||||
public async Task WhenNoEnvironmentKeyIsProvided_ThenTheFlagsApiReturnsUnauthorized()
|
||||
{
|
||||
using var response = await client.SendAsync(
|
||||
httpFile: "Flags.http",
|
||||
requestName: "GetFlags",
|
||||
variables: new Dictionary<string, string>
|
||||
{
|
||||
["baseUrl"] = settings.BaseUrl,
|
||||
["environmentKey"] = string.Empty
|
||||
});
|
||||
|
||||
Assert.That(
|
||||
(int)response.StatusCode,
|
||||
Is.EqualTo(401),
|
||||
$"Expected 401 for a missing environment key, got {(int)response.StatusCode} {response.ReasonPhrase}.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenAnUnknownEnvironmentKeyIsProvided_ThenTheFlagsApiReturnsUnauthorized()
|
||||
{
|
||||
using var response = await client.SendAsync(
|
||||
httpFile: "Flags.http",
|
||||
requestName: "GetFlags",
|
||||
variables: new Dictionary<string, string>
|
||||
{
|
||||
["baseUrl"] = settings.BaseUrl,
|
||||
["environmentKey"] = $"unknown_{Guid.NewGuid():N}"
|
||||
});
|
||||
|
||||
Assert.That(
|
||||
(int)response.StatusCode,
|
||||
Is.EqualTo(401),
|
||||
$"Expected 401 for an unrecognized environment key, got {(int)response.StatusCode} {response.ReasonPhrase}.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
### Login
|
||||
POST {{baseUrl}}/api/v1/auth/login
|
||||
Content-Type: application/json
|
||||
Accept: application/json
|
||||
|
||||
{
|
||||
"email": "{{email}}",
|
||||
"password": "{{password}}"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
### GetEnvironmentDocument
|
||||
GET {{baseUrl}}/api/v1/environment-document
|
||||
X-Environment-Key: {{environmentKey}}
|
||||
Accept: application/json
|
||||
@@ -0,0 +1,4 @@
|
||||
### GetIdentity
|
||||
GET {{baseUrl}}/api/v1/identity?identifier={{identifier}}
|
||||
X-Environment-Key: {{environmentKey}}
|
||||
Accept: application/json
|
||||
@@ -0,0 +1,103 @@
|
||||
using MicCheck.Api.Tests.Integration.Common;
|
||||
|
||||
namespace MicCheck.Api.Tests.Integration.Identities;
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an environment-default FeatureState plus an identity-level override for the same
|
||||
/// feature, so a test can assert that identity overrides take precedence over the environment
|
||||
/// default when evaluating <c>/api/v1/identity</c>.
|
||||
/// </summary>
|
||||
public sealed record IdentityOverrideSeed(
|
||||
int OrganizationId,
|
||||
int EnvironmentId,
|
||||
int FeatureId,
|
||||
string EnvironmentApiKey,
|
||||
string FeatureName,
|
||||
string Identifier)
|
||||
{
|
||||
public static async Task<IdentityOverrideSeed> InsertAsync(
|
||||
TestDatabase db,
|
||||
string testRunTag,
|
||||
bool environmentDefaultEnabled,
|
||||
bool identityOverrideEnabled)
|
||||
{
|
||||
var rawUnique = $"{testRunTag}-{Guid.NewGuid():N}";
|
||||
var unique = rawUnique[..Math.Min(rawUnique.Length, 40)];
|
||||
var environmentApiKey = $"envkey_{Guid.NewGuid():N}";
|
||||
var featureName = $"feature_{unique}";
|
||||
var identifier = $"identity_{unique}";
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
var organizationId = await db.ExecuteScalarAsync<int>(
|
||||
"INSERT INTO \"Organizations\" (\"Name\", \"CreatedAt\") VALUES (@name, @createdAt) RETURNING \"Id\"",
|
||||
("name", $"org_{unique}"),
|
||||
("createdAt", now));
|
||||
|
||||
var projectId = await db.ExecuteScalarAsync<int>(
|
||||
"INSERT INTO \"Projects\" (\"Name\", \"OrganizationId\", \"CreatedAt\", \"HideDisabledFlags\") VALUES (@name, @orgId, @createdAt, false) RETURNING \"Id\"",
|
||||
("name", $"project_{unique}"),
|
||||
("orgId", organizationId),
|
||||
("createdAt", now));
|
||||
|
||||
var environmentId = await db.ExecuteScalarAsync<int>(
|
||||
"INSERT INTO \"Environments\" (\"Name\", \"ApiKey\", \"ProjectId\", \"CreatedAt\") VALUES (@name, @apiKey, @projectId, @createdAt) RETURNING \"Id\"",
|
||||
("name", $"env_{unique}"),
|
||||
("apiKey", environmentApiKey),
|
||||
("projectId", projectId),
|
||||
("createdAt", now));
|
||||
|
||||
var featureId = await db.ExecuteScalarAsync<int>(
|
||||
"INSERT INTO \"Features\" (\"Name\", \"Type\", \"DefaultEnabled\", \"ProjectId\", \"CreatedAt\") VALUES (@name, 0, @defaultEnabled, @projectId, @createdAt) RETURNING \"Id\"",
|
||||
("name", featureName),
|
||||
("defaultEnabled", environmentDefaultEnabled),
|
||||
("projectId", projectId),
|
||||
("createdAt", now));
|
||||
|
||||
await db.ExecuteScalarAsync<int>(
|
||||
"""
|
||||
INSERT INTO "FeatureStates" ("FeatureId", "EnvironmentId", "Enabled", "Value", "CreatedAt", "UpdatedAt", "Version")
|
||||
VALUES (@featureId, @environmentId, @enabled, NULL, @createdAt, @updatedAt, 1)
|
||||
RETURNING "Id"
|
||||
""",
|
||||
("featureId", featureId),
|
||||
("environmentId", environmentId),
|
||||
("enabled", environmentDefaultEnabled),
|
||||
("createdAt", now),
|
||||
("updatedAt", now));
|
||||
|
||||
var identityId = await db.ExecuteScalarAsync<int>(
|
||||
"INSERT INTO \"Identities\" (\"Identifier\", \"EnvironmentId\", \"CreatedAt\") VALUES (@identifier, @environmentId, @createdAt) RETURNING \"Id\"",
|
||||
("identifier", identifier),
|
||||
("environmentId", environmentId),
|
||||
("createdAt", now));
|
||||
|
||||
await db.ExecuteScalarAsync<int>(
|
||||
"""
|
||||
INSERT INTO "FeatureStates" ("FeatureId", "EnvironmentId", "IdentityId", "Enabled", "Value", "CreatedAt", "UpdatedAt", "Version")
|
||||
VALUES (@featureId, @environmentId, @identityId, @enabled, NULL, @createdAt, @updatedAt, 1)
|
||||
RETURNING "Id"
|
||||
""",
|
||||
("featureId", featureId),
|
||||
("environmentId", environmentId),
|
||||
("identityId", identityId),
|
||||
("enabled", identityOverrideEnabled),
|
||||
("createdAt", now),
|
||||
("updatedAt", now));
|
||||
|
||||
return new IdentityOverrideSeed(organizationId, environmentId, featureId, environmentApiKey, featureName, identifier);
|
||||
}
|
||||
|
||||
public async Task CleanupAsync(TestDatabase db)
|
||||
=> await db.ExecuteAsync(
|
||||
"DELETE FROM \"Organizations\" WHERE \"Id\" = @orgId",
|
||||
("orgId", OrganizationId));
|
||||
|
||||
public async Task<string> DescribeAsync(TestDatabase db)
|
||||
=> await db.SnapshotRowsAsync(
|
||||
"""
|
||||
SELECT fs."Id" AS "FeatureStateId", fs."Enabled", fs."IdentityId", fs."FeatureSegmentId"
|
||||
FROM "FeatureStates" fs
|
||||
WHERE fs."FeatureId" = @featureId
|
||||
""",
|
||||
("featureId", FeatureId));
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System.Text.Json;
|
||||
using MicCheck.Api.Tests.Integration.Common;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MicCheck.Api.Tests.Integration.Identities;
|
||||
|
||||
[TestFixture]
|
||||
public class IdentityOverrideTests
|
||||
{
|
||||
private IntegrationTestSettings settings = null!;
|
||||
private TestDatabase db = null!;
|
||||
private FlagApiHttpClient client = null!;
|
||||
private IdentityOverrideSeed? seed;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
settings = IntegrationTestSettings.Load();
|
||||
db = new TestDatabase(settings.DbConnectionString);
|
||||
client = new FlagApiHttpClient(settings);
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown() => client.Dispose();
|
||||
|
||||
[SetUp]
|
||||
public async Task SetUp()
|
||||
=> seed = await IdentityOverrideSeed.InsertAsync(
|
||||
db,
|
||||
testRunTag: "IdentityOverride",
|
||||
environmentDefaultEnabled: false,
|
||||
identityOverrideEnabled: true);
|
||||
|
||||
[TearDown]
|
||||
public async Task TearDown()
|
||||
{
|
||||
if (seed is not null)
|
||||
{
|
||||
await seed.CleanupAsync(db);
|
||||
seed = null;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenAnIdentityHasAFeatureOverride_ThenItTakesPrecedenceOverTheEnvironmentDefault()
|
||||
{
|
||||
var current = seed!;
|
||||
|
||||
using var response = await client.SendAsync(
|
||||
httpFile: "Identity.http",
|
||||
requestName: "GetIdentity",
|
||||
variables: new Dictionary<string, string>
|
||||
{
|
||||
["baseUrl"] = settings.BaseUrl,
|
||||
["environmentKey"] = current.EnvironmentApiKey,
|
||||
["identifier"] = current.Identifier
|
||||
});
|
||||
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Assert.That(
|
||||
response.IsSuccessStatusCode,
|
||||
Is.True,
|
||||
$"GET /api/v1/identity returned {(int)response.StatusCode} {response.ReasonPhrase}. Body: {body}. DB state:\n{await current.DescribeAsync(db)}");
|
||||
|
||||
var identity = JsonSerializer.Deserialize<IdentityResponseDto>(body, JsonOptions)
|
||||
?? throw new InvalidOperationException("Response body was not the expected identity shape.");
|
||||
|
||||
var match = identity.Flags.SingleOrDefault(f => f.Feature.Name == current.FeatureName);
|
||||
|
||||
Assert.That(
|
||||
match,
|
||||
Is.Not.Null,
|
||||
$"Feature '{current.FeatureName}' was not present in the identity response. DB state:\n{await current.DescribeAsync(db)}");
|
||||
|
||||
Assert.That(
|
||||
match!.Enabled,
|
||||
Is.True,
|
||||
$"Expected the identity override (Enabled=true) to win over the environment default (Enabled=false). DB state:\n{await current.DescribeAsync(db)}");
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private sealed record IdentityResponseDto(List<object> Traits, List<FlagResponseDto> Flags);
|
||||
private sealed record FlagResponseDto(int Id, FeatureSummaryDto Feature, bool Enabled, string? FeatureStateValue);
|
||||
private sealed record FeatureSummaryDto(int Id, string Name);
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
||||
<PackageReference Include="Npgsql" Version="10.0.1" />
|
||||
<PackageReference Include="NUnit" Version="4.5.1" />
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
using MicCheck.Api.Data;
|
||||
using MicCheck.Api.Organizations;
|
||||
using MicCheck.Api.Users;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MicCheck.Api.Tests.Unit.Data;
|
||||
|
||||
[TestFixture]
|
||||
public class DatabaseSeederTests
|
||||
{
|
||||
private MicCheckDbContext _db = null!;
|
||||
private DatabaseSeeder _seeder = null!;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<MicCheckDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
_db = new MicCheckDbContext(options);
|
||||
_seeder = new DatabaseSeeder(_db, new PasswordHasher<User>());
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown() => _db.Dispose();
|
||||
|
||||
[Test]
|
||||
public async Task WhenTheDatabaseIsEmpty_ThenSeedingCreatesADeterministicAdminUser()
|
||||
{
|
||||
await _seeder.SeedAsync();
|
||||
|
||||
var admin = await _db.Users.SingleOrDefaultAsync(u => u.Email == DatabaseSeeder.SeedAdminEmail);
|
||||
|
||||
Assert.That(admin, Is.Not.Null);
|
||||
Assert.That(admin!.IsActive, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenTheDatabaseIsEmpty_ThenTheSeededAdminPasswordVerifiesAgainstTheKnownCredential()
|
||||
{
|
||||
await _seeder.SeedAsync();
|
||||
|
||||
var admin = await _db.Users.SingleAsync(u => u.Email == DatabaseSeeder.SeedAdminEmail);
|
||||
var hasher = new PasswordHasher<User>();
|
||||
|
||||
var result = hasher.VerifyHashedPassword(admin, admin.PasswordHash, DatabaseSeeder.SeedAdminPassword);
|
||||
|
||||
Assert.That(result, Is.Not.EqualTo(PasswordVerificationResult.Failed));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenTheDatabaseIsEmpty_ThenTheSeededAdminIsAnAdminOfTheDefaultOrganization()
|
||||
{
|
||||
await _seeder.SeedAsync();
|
||||
|
||||
var organization = await _db.Organizations.SingleAsync(o => o.Name == "Default");
|
||||
var admin = await _db.Users.SingleAsync(u => u.Email == DatabaseSeeder.SeedAdminEmail);
|
||||
var membership = await _db.OrganizationUsers
|
||||
.SingleAsync(ou => ou.OrganizationId == organization.Id && ou.UserId == admin.Id);
|
||||
|
||||
Assert.That(membership.Role, Is.EqualTo(OrganizationRole.Admin));
|
||||
Assert.That(membership.IsPrimary, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenTheDatabaseIsEmpty_ThenTheSeededDevelopmentEnvironmentHasTheFixedApiKey()
|
||||
{
|
||||
await _seeder.SeedAsync();
|
||||
|
||||
var development = await _db.Environments.SingleAsync(e => e.Name == "Development");
|
||||
var staging = await _db.Environments.SingleAsync(e => e.Name == "Staging");
|
||||
var production = await _db.Environments.SingleAsync(e => e.Name == "Production");
|
||||
|
||||
Assert.That(development.ApiKey, Is.EqualTo(DatabaseSeeder.SeedDevelopmentEnvironmentKey));
|
||||
Assert.That(staging.ApiKey, Is.Not.EqualTo(DatabaseSeeder.SeedDevelopmentEnvironmentKey));
|
||||
Assert.That(production.ApiKey, Is.Not.EqualTo(DatabaseSeeder.SeedDevelopmentEnvironmentKey));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenSeedingRunsTwice_ThenItDoesNotCreateDuplicateOrganizationsOrUsers()
|
||||
{
|
||||
await _seeder.SeedAsync();
|
||||
await _seeder.SeedAsync();
|
||||
|
||||
Assert.That(await _db.Organizations.CountAsync(), Is.EqualTo(1));
|
||||
Assert.That(await _db.Users.CountAsync(u => u.Email == DatabaseSeeder.SeedAdminEmail), Is.EqualTo(1));
|
||||
Assert.That(await _db.Environments.CountAsync(), Is.EqualTo(3));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user