Fail closed on malformed local auth

This commit is contained in:
2026-04-11 16:29:53 +02:00
parent 6a223a4b70
commit 09e96ce381
6 changed files with 90 additions and 19 deletions
@@ -0,0 +1,52 @@
using System.Security.Claims;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace JobTrackerApi.Tests;
public sealed class LocalAuthIdentityTests
{
[Fact]
public void GetRequiredUserId_returns_null_when_subject_claim_is_missing()
{
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, "ghost@example.com")
}, "local"));
var userId = LocalAuthIdentity.GetRequiredUserId(principal);
Assert.Null(userId);
}
[Fact]
public void GetRequiredUserId_returns_nameidentifier_when_present()
{
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, "user-123")
}, "local"));
var userId = LocalAuthIdentity.GetRequiredUserId(principal);
Assert.Equal("user-123", userId);
}
[Fact]
public async Task Owner_scoped_query_filters_fail_closed_when_current_user_is_missing()
{
await using var db = TestHostFactory.CreateInMemoryDb(null);
db.Companies.Add(new Company { Name = "Secret Co", OwnerUserId = "user-1" });
db.JobApplications.Add(new JobApplication { JobTitle = "Secret Job", Status = "Applied", OwnerUserId = "user-1" });
db.UserRuleSettings.Add(new UserRuleSettings { OwnerUserId = "user-1", AppliedFollowUpDays = 5 });
await db.SaveChangesAsync();
Assert.Empty(await db.Companies.ToListAsync());
Assert.Empty(await db.JobApplications.ToListAsync());
Assert.Empty(await db.UserRuleSettings.ToListAsync());
}
}
@@ -13,7 +13,7 @@ public static class TestHostFactory
{
// Keep the EF-backed controller tests on the same minimal setup so they fail for product
// reasons, not because each file drifted into a slightly different fake host configuration.
public static JobTrackerContext CreateInMemoryDb(string userId = "user-1")
public static JobTrackerContext CreateInMemoryDb(string? userId = "user-1")
{
var options = new DbContextOptionsBuilder<JobTrackerContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())