feat(restaurant-admin): enforce bff session auth
Why: protect admin endpoints with thalos session validation. What: add edge auth guard call to thalos session/me, preserve anonymous health endpoints, and add auth enforcement docs. Rule: keep identity ownership in thalos and standardize edge auth behavior.
This commit is contained in:
parent
4f77aaa37f
commit
9ae20bc441
45
docs/security/auth-enforcement.md
Normal file
45
docs/security/auth-enforcement.md
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
# Auth Enforcement
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This BFF enforces authenticated access on business endpoints using Thalos session validation.
|
||||||
|
|
||||||
|
## Protected Endpoints
|
||||||
|
|
||||||
|
- `/api/restaurant/admin/config`
|
||||||
|
- `/api/restaurant/admin/service-window`
|
||||||
|
|
||||||
|
## Anonymous Endpoints
|
||||||
|
|
||||||
|
- `/health`
|
||||||
|
- `/healthz`
|
||||||
|
|
||||||
|
## Session Validation Contract
|
||||||
|
|
||||||
|
- BFF requires at least one session cookie:
|
||||||
|
- `thalos_session`
|
||||||
|
- `thalos_refresh`
|
||||||
|
- BFF calls Thalos session introspection endpoint:
|
||||||
|
- `GET /api/identity/session/me`
|
||||||
|
- Base address configured by:
|
||||||
|
- `ThalosAuth:BaseAddress`
|
||||||
|
|
||||||
|
## Error Semantics
|
||||||
|
|
||||||
|
Standard auth error payload:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "unauthorized|forbidden|session_missing|session_invalid",
|
||||||
|
"message": "human-readable message",
|
||||||
|
"correlationId": "request correlation id"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `401`: missing or invalid session
|
||||||
|
- `403`: permission denied by identity service
|
||||||
|
|
||||||
|
## Correlation
|
||||||
|
|
||||||
|
- Incoming/outgoing correlation header: `x-correlation-id`
|
||||||
|
- Correlation ID is forwarded to Thalos session validation call.
|
||||||
@ -1,22 +1,62 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Microsoft.Extensions.Primitives;
|
||||||
using Restaurant.Admin.Bff.Application.Adapters;
|
using Restaurant.Admin.Bff.Application.Adapters;
|
||||||
using Restaurant.Admin.Bff.Application.Handlers;
|
using Restaurant.Admin.Bff.Application.Handlers;
|
||||||
using Restaurant.Admin.Bff.Contracts.Requests;
|
using Restaurant.Admin.Bff.Contracts.Requests;
|
||||||
|
|
||||||
|
const string CorrelationHeaderName = "x-correlation-id";
|
||||||
|
const string SessionAccessCookieName = "thalos_session";
|
||||||
|
const string SessionRefreshCookieName = "thalos_refresh";
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
builder.Services.AddSingleton<IRestaurantAdminServiceClient, DefaultRestaurantAdminServiceClient>();
|
builder.Services.AddSingleton<IRestaurantAdminServiceClient, DefaultRestaurantAdminServiceClient>();
|
||||||
builder.Services.AddSingleton<IGetRestaurantAdminConfigHandler, GetRestaurantAdminConfigHandler>();
|
builder.Services.AddSingleton<IGetRestaurantAdminConfigHandler, GetRestaurantAdminConfigHandler>();
|
||||||
builder.Services.AddSingleton<ISetServiceWindowHandler, SetServiceWindowHandler>();
|
builder.Services.AddSingleton<ISetServiceWindowHandler, SetServiceWindowHandler>();
|
||||||
|
builder.Services.AddHttpClient("ThalosAuth");
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
app.MapGet("/api/restaurant/admin/config", async (string contextId, IGetRestaurantAdminConfigHandler handler, CancellationToken ct) =>
|
app.Use(async (context, next) =>
|
||||||
{
|
{
|
||||||
|
var correlationId = ResolveCorrelationId(context);
|
||||||
|
context.Items[CorrelationHeaderName] = correlationId;
|
||||||
|
context.Request.Headers[CorrelationHeaderName] = correlationId;
|
||||||
|
context.Response.Headers[CorrelationHeaderName] = correlationId;
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapGet("/api/restaurant/admin/config", async (
|
||||||
|
string contextId,
|
||||||
|
HttpContext context,
|
||||||
|
IHttpClientFactory httpClientFactory,
|
||||||
|
IConfiguration configuration,
|
||||||
|
IGetRestaurantAdminConfigHandler handler,
|
||||||
|
CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var authError = await EnforceSessionAsync(context, httpClientFactory, configuration, ct);
|
||||||
|
if (authError is not null)
|
||||||
|
{
|
||||||
|
return authError;
|
||||||
|
}
|
||||||
|
|
||||||
var request = new GetRestaurantAdminConfigRequest(contextId);
|
var request = new GetRestaurantAdminConfigRequest(contextId);
|
||||||
return Results.Ok(await handler.HandleAsync(request, ct));
|
return Results.Ok(await handler.HandleAsync(request, ct));
|
||||||
});
|
});
|
||||||
|
|
||||||
app.MapPost("/api/restaurant/admin/service-window", async (SetServiceWindowRequest request, ISetServiceWindowHandler handler, CancellationToken ct) =>
|
app.MapPost("/api/restaurant/admin/service-window", async (
|
||||||
|
SetServiceWindowRequest request,
|
||||||
|
HttpContext context,
|
||||||
|
IHttpClientFactory httpClientFactory,
|
||||||
|
IConfiguration configuration,
|
||||||
|
ISetServiceWindowHandler handler,
|
||||||
|
CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
|
var authError = await EnforceSessionAsync(context, httpClientFactory, configuration, ct);
|
||||||
|
if (authError is not null)
|
||||||
|
{
|
||||||
|
return authError;
|
||||||
|
}
|
||||||
|
|
||||||
return Results.Ok(await handler.HandleAsync(request, ct));
|
return Results.Ok(await handler.HandleAsync(request, ct));
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -24,3 +64,93 @@ app.MapGet("/health", () => Results.Ok(new { status = "ok", service = "restauran
|
|||||||
app.MapGet("/healthz", () => Results.Ok(new { status = "ok", service = "restaurant-admin-bff" }));
|
app.MapGet("/healthz", () => Results.Ok(new { status = "ok", service = "restaurant-admin-bff" }));
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|
||||||
|
string ResolveCorrelationId(HttpContext context)
|
||||||
|
{
|
||||||
|
if (context.Items.TryGetValue(CorrelationHeaderName, out var itemValue) &&
|
||||||
|
itemValue is string itemCorrelationId &&
|
||||||
|
!string.IsNullOrWhiteSpace(itemCorrelationId))
|
||||||
|
{
|
||||||
|
return itemCorrelationId;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (context.Request.Headers.TryGetValue(CorrelationHeaderName, out var headerValue) &&
|
||||||
|
!StringValues.IsNullOrEmpty(headerValue))
|
||||||
|
{
|
||||||
|
return headerValue.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.TraceIdentifier;
|
||||||
|
}
|
||||||
|
|
||||||
|
async Task<IResult?> EnforceSessionAsync(
|
||||||
|
HttpContext context,
|
||||||
|
IHttpClientFactory httpClientFactory,
|
||||||
|
IConfiguration configuration,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
var correlationId = ResolveCorrelationId(context);
|
||||||
|
|
||||||
|
if (!context.Request.Cookies.ContainsKey(SessionAccessCookieName) &&
|
||||||
|
!context.Request.Cookies.ContainsKey(SessionRefreshCookieName))
|
||||||
|
{
|
||||||
|
return ErrorResponse(StatusCodes.Status401Unauthorized, "session_missing", "No active session.", correlationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
var thalosBaseAddress = configuration["ThalosAuth:BaseAddress"] ?? "http://thalos-bff:8080";
|
||||||
|
using var request = new HttpRequestMessage(
|
||||||
|
HttpMethod.Get,
|
||||||
|
$"{thalosBaseAddress.TrimEnd('/')}/api/identity/session/me");
|
||||||
|
|
||||||
|
request.Headers.TryAddWithoutValidation(CorrelationHeaderName, correlationId);
|
||||||
|
var cookieHeader = BuildForwardCookieHeader(context);
|
||||||
|
if (!string.IsNullOrWhiteSpace(cookieHeader))
|
||||||
|
{
|
||||||
|
request.Headers.TryAddWithoutValidation("Cookie", cookieHeader);
|
||||||
|
}
|
||||||
|
|
||||||
|
using var response = await httpClientFactory.CreateClient("ThalosAuth").SendAsync(request, ct);
|
||||||
|
|
||||||
|
if (response.StatusCode == HttpStatusCode.Forbidden)
|
||||||
|
{
|
||||||
|
return ErrorResponse(StatusCodes.Status403Forbidden, "forbidden", "Permission denied.", correlationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||||
|
{
|
||||||
|
return ErrorResponse(StatusCodes.Status401Unauthorized, "unauthorized", "Unauthorized request.", correlationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
return ErrorResponse(StatusCodes.Status401Unauthorized, "session_invalid", "Session validation failed.", correlationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static string BuildForwardCookieHeader(HttpContext context)
|
||||||
|
{
|
||||||
|
var cookies = new List<string>();
|
||||||
|
|
||||||
|
if (context.Request.Cookies.TryGetValue(SessionAccessCookieName, out var accessCookie) &&
|
||||||
|
!string.IsNullOrWhiteSpace(accessCookie))
|
||||||
|
{
|
||||||
|
cookies.Add($"{SessionAccessCookieName}={accessCookie}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (context.Request.Cookies.TryGetValue(SessionRefreshCookieName, out var refreshCookie) &&
|
||||||
|
!string.IsNullOrWhiteSpace(refreshCookie))
|
||||||
|
{
|
||||||
|
cookies.Add($"{SessionRefreshCookieName}={refreshCookie}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return string.Join("; ", cookies);
|
||||||
|
}
|
||||||
|
|
||||||
|
static IResult ErrorResponse(int statusCode, string code, string message, string correlationId)
|
||||||
|
{
|
||||||
|
return Results.Json(new AuthErrorResponse(code, message, correlationId), statusCode: statusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed record AuthErrorResponse(string Code, string Message, string CorrelationId);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user