fix(security): enforce resource isolation across API and hubs
This commit is contained in:
1 parent
21f0530b6c
commit
1cd4e2b4b5
39 files changed
+1081
-497
No files matched your search
@@ -0,0 +1,84 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Heimdall.Api.Controllers;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Application.Cameras.Queries.GetCamera;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Security;
|
||||
|
||||
public sealed class HttpIsolationTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(AppRoles.Admin, "none")]
|
||||
[InlineData(AppRoles.Supervisor, "group")]
|
||||
[InlineData(AppRoles.Viewer, "direct")]
|
||||
[InlineData(AppRoles.Viewer, "none")]
|
||||
public async Task Real_http_pipeline_combines_permissions_and_resource_scope(string role, string grant)
|
||||
{
|
||||
using var f = new AccessFixture();
|
||||
var user = f.User(role, grant);
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Testing" });
|
||||
builder.Logging.ClearProviders();
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
builder.Services.AddSingleton<IApplicationDbContext>(f.Db);
|
||||
builder.Services.AddSingleton(f.Db);
|
||||
builder.Services.AddSingleton<ICameraAccessService>(f.Cameras);
|
||||
builder.Services.AddScoped<ResourceAccess>();
|
||||
builder.Services.AddMediatR(c => c.RegisterServicesFromAssemblyContaining<GetCameraQuery>());
|
||||
builder.Services.AddControllers(o => o.Filters.Add<ResourceAccessFilter>()).AddApplicationPart(typeof(CamerasController).Assembly);
|
||||
builder.Services.AddAuthentication("JwtBearer")
|
||||
.AddScheme<AuthenticationSchemeOptions, TestHumanHandler>("JwtBearer", _ => { })
|
||||
.AddScheme<AuthenticationSchemeOptions, TestHumanHandler>("Cookies", _ => { })
|
||||
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", _ => { });
|
||||
builder.Services.AddAuthorization(o =>
|
||||
{
|
||||
foreach (var permission in AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct())
|
||||
o.AddPolicy(permission, p => p.RequireClaim("permission", permission));
|
||||
});
|
||||
builder.Services.AddRateLimiter(o => o.AddPolicy("Api", _ => System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("tests")));
|
||||
await using var app = builder.Build();
|
||||
app.UseRouting(); app.UseRateLimiter(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers();
|
||||
await app.StartAsync();
|
||||
using var client = new HttpClient { BaseAddress = new(app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single()) };
|
||||
client.DefaultRequestHeaders.Add("X-Test-User", user.Id.ToString());
|
||||
client.DefaultRequestHeaders.Add("X-Test-Role", role);
|
||||
var canReadA = role == AppRoles.Admin || grant != "none";
|
||||
(await client.GetAsync($"api/cameras/{f.A1.Id}")).StatusCode.ShouldBe(canReadA ? HttpStatusCode.OK : HttpStatusCode.Forbidden);
|
||||
(await client.GetAsync($"api/cameras/{f.B1.Id}")).StatusCode.ShouldBe(role == AppRoles.Admin ? HttpStatusCode.OK : HttpStatusCode.Forbidden);
|
||||
var mutation = await client.PostAsync($"api/cameras/{f.A1.Id}/toggle-status", null);
|
||||
mutation.StatusCode.ShouldBe(canReadA && role != AppRoles.Viewer ? HttpStatusCode.OK : HttpStatusCode.Forbidden);
|
||||
client.DefaultRequestHeaders.Remove("X-Test-User");
|
||||
(await client.GetAsync($"api/cameras/{f.A1.Id}")).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
// Only the credential verification step is replaced. MVC, policies, resource filter,
|
||||
// database and query/command handlers are exercised through an actual HTTP listener.
|
||||
public sealed class TestHumanHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (Scheme.Name != "JwtBearer" || !Guid.TryParse(Request.Headers["X-Test-User"], out var id))
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
var role = Request.Headers["X-Test-Role"].ToString();
|
||||
var claims = new List<Claim> { new(ClaimTypes.NameIdentifier, id.ToString()) };
|
||||
claims.AddRange(AppPermissions.RolePermissions[role].Select(p => new Claim("permission", p)));
|
||||
return Task.FromResult(AuthenticateResult.Success(new(new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name)), Scheme.Name)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user