5100* tests strengthtenen work
This commit is contained in:
@@ -3,7 +3,11 @@ namespace StellaOps.Gateway.WebService.Middleware;
|
||||
public static class GatewayContextKeys
|
||||
{
|
||||
public const string TenantId = "Gateway.TenantId";
|
||||
public const string ProjectId = "Gateway.ProjectId";
|
||||
public const string Actor = "Gateway.Actor";
|
||||
public const string Scopes = "Gateway.Scopes";
|
||||
public const string DpopThumbprint = "Gateway.DpopThumbprint";
|
||||
public const string MtlsThumbprint = "Gateway.MtlsThumbprint";
|
||||
public const string CnfJson = "Gateway.CnfJson";
|
||||
public const string IsAnonymous = "Gateway.IsAnonymous";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using StellaOps.Auth.Abstractions;
|
||||
|
||||
namespace StellaOps.Gateway.WebService.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware that enforces the Gateway identity header policy:
|
||||
/// 1. Strips all reserved identity headers from incoming requests (prevents spoofing)
|
||||
/// 2. Computes effective identity from validated principal claims
|
||||
/// 3. Writes downstream identity headers for microservice consumption
|
||||
/// 4. Stores normalized identity context in HttpContext.Items
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This middleware replaces the legacy ClaimsPropagationMiddleware and TenantMiddleware
|
||||
/// which used "set-if-missing" semantics that allowed client header spoofing.
|
||||
/// </remarks>
|
||||
public sealed class IdentityHeaderPolicyMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<IdentityHeaderPolicyMiddleware> _logger;
|
||||
private readonly IdentityHeaderPolicyOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Reserved identity headers that must never be trusted from external clients.
|
||||
/// These are stripped from incoming requests and overwritten from validated claims.
|
||||
/// </summary>
|
||||
private static readonly string[] ReservedHeaders =
|
||||
[
|
||||
// StellaOps canonical headers
|
||||
"X-StellaOps-Tenant",
|
||||
"X-StellaOps-Project",
|
||||
"X-StellaOps-Actor",
|
||||
"X-StellaOps-Scopes",
|
||||
"X-StellaOps-Client",
|
||||
// Legacy Stella headers (compatibility)
|
||||
"X-Stella-Tenant",
|
||||
"X-Stella-Project",
|
||||
"X-Stella-Actor",
|
||||
"X-Stella-Scopes",
|
||||
// Raw claim headers (internal/legacy pass-through)
|
||||
"sub",
|
||||
"tid",
|
||||
"scope",
|
||||
"scp",
|
||||
"cnf",
|
||||
"cnf.jkt"
|
||||
];
|
||||
|
||||
public IdentityHeaderPolicyMiddleware(
|
||||
RequestDelegate next,
|
||||
ILogger<IdentityHeaderPolicyMiddleware> logger,
|
||||
IdentityHeaderPolicyOptions options)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
_options = options;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
// Skip processing for system paths (health, metrics, openapi, etc.)
|
||||
if (GatewayRoutes.IsSystemPath(context.Request.Path))
|
||||
{
|
||||
await _next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 1: Strip all reserved identity headers from incoming request
|
||||
StripReservedHeaders(context);
|
||||
|
||||
// Step 2: Extract identity from validated principal
|
||||
var identity = ExtractIdentity(context);
|
||||
|
||||
// Step 3: Store normalized identity in HttpContext.Items
|
||||
StoreIdentityContext(context, identity);
|
||||
|
||||
// Step 4: Write downstream identity headers
|
||||
WriteDownstreamHeaders(context, identity);
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
|
||||
private void StripReservedHeaders(HttpContext context)
|
||||
{
|
||||
foreach (var header in ReservedHeaders)
|
||||
{
|
||||
if (context.Request.Headers.ContainsKey(header))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Stripped reserved identity header {Header} from request {TraceId}",
|
||||
header,
|
||||
context.TraceIdentifier);
|
||||
context.Request.Headers.Remove(header);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IdentityContext ExtractIdentity(HttpContext context)
|
||||
{
|
||||
var principal = context.User;
|
||||
var isAuthenticated = principal.Identity?.IsAuthenticated == true;
|
||||
|
||||
if (!isAuthenticated)
|
||||
{
|
||||
return new IdentityContext
|
||||
{
|
||||
IsAnonymous = true,
|
||||
Actor = "anonymous",
|
||||
Scopes = _options.AnonymousScopes ?? []
|
||||
};
|
||||
}
|
||||
|
||||
// Extract subject (actor)
|
||||
var actor = principal.FindFirstValue(StellaOpsClaimTypes.Subject);
|
||||
|
||||
// Extract tenant - try canonical claim first, then legacy 'tid'
|
||||
var tenant = principal.FindFirstValue(StellaOpsClaimTypes.Tenant)
|
||||
?? principal.FindFirstValue("tid");
|
||||
|
||||
// Extract project (optional)
|
||||
var project = principal.FindFirstValue(StellaOpsClaimTypes.Project);
|
||||
|
||||
// Extract scopes - try 'scp' claims first (individual items), then 'scope' (space-separated)
|
||||
var scopes = ExtractScopes(principal);
|
||||
|
||||
// Extract cnf (confirmation claim) for DPoP/sender constraint
|
||||
var cnfJson = principal.FindFirstValue("cnf");
|
||||
string? dpopThumbprint = null;
|
||||
if (!string.IsNullOrWhiteSpace(cnfJson))
|
||||
{
|
||||
TryParseCnfThumbprint(cnfJson, out dpopThumbprint);
|
||||
}
|
||||
|
||||
return new IdentityContext
|
||||
{
|
||||
IsAnonymous = false,
|
||||
Actor = actor,
|
||||
Tenant = tenant,
|
||||
Project = project,
|
||||
Scopes = scopes,
|
||||
CnfJson = cnfJson,
|
||||
DpopThumbprint = dpopThumbprint
|
||||
};
|
||||
}
|
||||
|
||||
private static HashSet<string> ExtractScopes(ClaimsPrincipal principal)
|
||||
{
|
||||
var scopes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// First try individual scope claims (scp)
|
||||
var scpClaims = principal.FindAll(StellaOpsClaimTypes.ScopeItem);
|
||||
foreach (var claim in scpClaims)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(claim.Value))
|
||||
{
|
||||
scopes.Add(claim.Value.Trim());
|
||||
}
|
||||
}
|
||||
|
||||
// If no scp claims, try space-separated scope claim
|
||||
if (scopes.Count == 0)
|
||||
{
|
||||
var scopeClaims = principal.FindAll(StellaOpsClaimTypes.Scope);
|
||||
foreach (var claim in scopeClaims)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(claim.Value))
|
||||
{
|
||||
var parts = claim.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
foreach (var part in parts)
|
||||
{
|
||||
scopes.Add(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return scopes;
|
||||
}
|
||||
|
||||
private void StoreIdentityContext(HttpContext context, IdentityContext identity)
|
||||
{
|
||||
context.Items[GatewayContextKeys.IsAnonymous] = identity.IsAnonymous;
|
||||
|
||||
if (!string.IsNullOrEmpty(identity.Actor))
|
||||
{
|
||||
context.Items[GatewayContextKeys.Actor] = identity.Actor;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(identity.Tenant))
|
||||
{
|
||||
context.Items[GatewayContextKeys.TenantId] = identity.Tenant;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(identity.Project))
|
||||
{
|
||||
context.Items[GatewayContextKeys.ProjectId] = identity.Project;
|
||||
}
|
||||
|
||||
if (identity.Scopes.Count > 0)
|
||||
{
|
||||
context.Items[GatewayContextKeys.Scopes] = identity.Scopes;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(identity.CnfJson))
|
||||
{
|
||||
context.Items[GatewayContextKeys.CnfJson] = identity.CnfJson;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(identity.DpopThumbprint))
|
||||
{
|
||||
context.Items[GatewayContextKeys.DpopThumbprint] = identity.DpopThumbprint;
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteDownstreamHeaders(HttpContext context, IdentityContext identity)
|
||||
{
|
||||
var headers = context.Request.Headers;
|
||||
|
||||
// Actor header
|
||||
if (!string.IsNullOrEmpty(identity.Actor))
|
||||
{
|
||||
headers["X-StellaOps-Actor"] = identity.Actor;
|
||||
if (_options.EnableLegacyHeaders)
|
||||
{
|
||||
headers["X-Stella-Actor"] = identity.Actor;
|
||||
}
|
||||
}
|
||||
|
||||
// Tenant header
|
||||
if (!string.IsNullOrEmpty(identity.Tenant))
|
||||
{
|
||||
headers["X-StellaOps-Tenant"] = identity.Tenant;
|
||||
if (_options.EnableLegacyHeaders)
|
||||
{
|
||||
headers["X-Stella-Tenant"] = identity.Tenant;
|
||||
}
|
||||
}
|
||||
|
||||
// Project header (optional)
|
||||
if (!string.IsNullOrEmpty(identity.Project))
|
||||
{
|
||||
headers["X-StellaOps-Project"] = identity.Project;
|
||||
if (_options.EnableLegacyHeaders)
|
||||
{
|
||||
headers["X-Stella-Project"] = identity.Project;
|
||||
}
|
||||
}
|
||||
|
||||
// Scopes header (space-delimited, sorted for determinism)
|
||||
if (identity.Scopes.Count > 0)
|
||||
{
|
||||
var sortedScopes = identity.Scopes.OrderBy(s => s, StringComparer.Ordinal);
|
||||
var scopesValue = string.Join(" ", sortedScopes);
|
||||
headers["X-StellaOps-Scopes"] = scopesValue;
|
||||
if (_options.EnableLegacyHeaders)
|
||||
{
|
||||
headers["X-Stella-Scopes"] = scopesValue;
|
||||
}
|
||||
}
|
||||
else if (identity.IsAnonymous)
|
||||
{
|
||||
// Explicit empty scopes for anonymous to prevent ambiguity
|
||||
headers["X-StellaOps-Scopes"] = string.Empty;
|
||||
if (_options.EnableLegacyHeaders)
|
||||
{
|
||||
headers["X-Stella-Scopes"] = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
// DPoP thumbprint (if present)
|
||||
if (!string.IsNullOrEmpty(identity.DpopThumbprint))
|
||||
{
|
||||
headers["cnf.jkt"] = identity.DpopThumbprint;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryParseCnfThumbprint(string json, out string? jkt)
|
||||
{
|
||||
jkt = null;
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
if (document.RootElement.TryGetProperty("jkt", out var jktElement) &&
|
||||
jktElement.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
jkt = jktElement.GetString();
|
||||
}
|
||||
|
||||
return !string.IsNullOrWhiteSpace(jkt);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class IdentityContext
|
||||
{
|
||||
public bool IsAnonymous { get; init; }
|
||||
public string? Actor { get; init; }
|
||||
public string? Tenant { get; init; }
|
||||
public string? Project { get; init; }
|
||||
public HashSet<string> Scopes { get; init; } = [];
|
||||
public string? CnfJson { get; init; }
|
||||
public string? DpopThumbprint { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configuration options for the identity header policy middleware.
|
||||
/// </summary>
|
||||
public sealed class IdentityHeaderPolicyOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Enable legacy X-Stella-* headers in addition to X-StellaOps-* headers.
|
||||
/// Default: true (for migration compatibility).
|
||||
/// </summary>
|
||||
public bool EnableLegacyHeaders { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Scopes to assign to anonymous requests.
|
||||
/// Default: empty (no scopes).
|
||||
/// </summary>
|
||||
public HashSet<string>? AnonymousScopes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Allow client-provided scope headers in offline/pre-prod mode.
|
||||
/// Default: false (forbidden for security).
|
||||
/// </summary>
|
||||
public bool AllowScopeHeaderOverride { get; set; } = false;
|
||||
}
|
||||
Reference in New Issue
Block a user