mirror of
https://github.com/azaion/annotations.git
synced 2026-06-21 13:41:07 +00:00
docs+src: complete Steps 1-3 outcomes + auth re-sync baseline
This commit captures everything produced during autodev existing-code Steps 1 (Document), 2 (Architecture Baseline Scan), and 3 (Test Spec), together with the targeted auth + CORS re-sync triggered on 2026-05-14 when codebase drift was detected at Step 4 entry. None of this work was previously committed. Step 1 (Document) — 50+ _docs/02_document/ files: problem, solution, architecture, system flows, glossary, module-layout, per-component specs (01..06), modules, deployment, diagrams, data model, FINAL report, verification log, discovery. Step 2 (Architecture Baseline) — architecture_compliance_baseline.md. Verdict PASS_WITH_WARNINGS (0 Critical, 0 High, 1 Medium, 2 Low). No High/Critical findings; auto-chained to Step 3 per existing-code flow. Step 3 (Test Spec) — _docs/02_document/tests/* (67 scenarios across blackbox, security, resilience, resource-limit, performance), plus e2e/docker-compose.test.yml, e2e/seed/run.sh, scripts/run-tests.sh, scripts/run-performance-tests.sh. Coverage 88% over the active scope (40 of 45 items covered, 6 RB-deferred, 5 documented-as-uncovered). Targeted auth + CORS re-sync — replaces the deleted in-house token issuer with a JWKS-verifier model. AuthController and TokenService removed; JwtExtensions switched from HS256 symmetric to ES256 over admin's JWKS. ConfigurationResolver and CorsConfigurationValidator added under src/Infrastructure/. ADR-002 and ADR-006 retired; SEC-01, SEC-02, SEC-03 marked Closed. One new testability risk recorded in architecture.md Open Risks Section 6 (JWKS HTTPS gating). Source changes: - src/Auth/JwtExtensions.cs (modified) — ES256, JWKS, alg pinning - src/Program.cs (modified) — DI wiring for ConfigurationResolver and CorsConfigurationValidator - src/Controllers/AuthController.cs (deleted) — no in-service issuance - src/Services/TokenService.cs (deleted) — same - src/Infrastructure/ConfigurationResolver.cs (new) - src/Infrastructure/CorsConfigurationValidator.cs (new) - .env.example (new) — required env var documentation - .gitignore (updated) Cross-repo coordination: _docs/cross-repo/flights_h1_h2_h3_change_spec captures the change-spec for downstream services that consumed the now deleted /auth endpoints. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,32 +1,89 @@
|
||||
using System.Text;
|
||||
using Azaion.Annotations.Infrastructure;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Protocols;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Azaion.Annotations.Auth;
|
||||
|
||||
public static class JwtExtensions
|
||||
{
|
||||
public static IServiceCollection AddJwtAuth(this IServiceCollection services, string jwtSecret)
|
||||
public const string JwtIssuerEnvVar = "JWT_ISSUER";
|
||||
public const string JwtIssuerConfigKey = "Jwt:Issuer";
|
||||
public const string JwtAudienceEnvVar = "JWT_AUDIENCE";
|
||||
public const string JwtAudienceConfigKey = "Jwt:Audience";
|
||||
public const string JwtJwksUrlEnvVar = "JWT_JWKS_URL";
|
||||
public const string JwtJwksUrlConfigKey = "Jwt:JwksUrl";
|
||||
|
||||
public static IServiceCollection AddJwtAuth(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(configuration);
|
||||
|
||||
var issuer = ConfigurationResolver.ResolveRequiredOrThrow(configuration, JwtIssuerEnvVar, JwtIssuerConfigKey, "JWT issuer");
|
||||
var audience = ConfigurationResolver.ResolveRequiredOrThrow(configuration, JwtAudienceEnvVar, JwtAudienceConfigKey, "JWT audience");
|
||||
var jwksUrl = ConfigurationResolver.ResolveRequiredOrThrow(configuration, JwtJwksUrlEnvVar, JwtJwksUrlConfigKey, "JWKS URL");
|
||||
|
||||
// JwtBearer's stock ConfigurationManager targets the full OIDC discovery
|
||||
// document; admin only exposes JWKS, so we wire a JWKS-only retriever.
|
||||
// The manager caches the document and refreshes on the default schedule
|
||||
// (matches admin's Cache-Control: public, max-age=3600 on /.well-known/jwks.json).
|
||||
var jwksConfigManager = new ConfigurationManager<JsonWebKeySet>(
|
||||
jwksUrl,
|
||||
new JwksRetriever(),
|
||||
new HttpDocumentRetriever { RequireHttps = true });
|
||||
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = audience,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)),
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
// Pin algorithms so a token forged with alg=HS256 using the
|
||||
// public key as the HMAC secret cannot pass validation.
|
||||
ValidAlgorithms = [SecurityAlgorithms.EcdsaSha256],
|
||||
RequireSignedTokens = true,
|
||||
RequireExpirationTime = true,
|
||||
ClockSkew = TimeSpan.FromSeconds(30),
|
||||
IssuerSigningKeyResolver = (_, _, kid, _) =>
|
||||
{
|
||||
var jwks = jwksConfigManager
|
||||
.GetConfigurationAsync(CancellationToken.None)
|
||||
.GetAwaiter()
|
||||
.GetResult();
|
||||
|
||||
if (string.IsNullOrEmpty(kid))
|
||||
return jwks.GetSigningKeys();
|
||||
|
||||
return jwks.GetSigningKeys().Where(k => k.KeyId == kid);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
services.AddAuthorizationBuilder()
|
||||
.AddPolicy("ANN", p => p.RequireClaim("permissions", "ANN"))
|
||||
.AddPolicy("ANN", p => p.RequireClaim("permissions", "ANN"))
|
||||
.AddPolicy("DATASET", p => p.RequireClaim("permissions", "DATASET"))
|
||||
.AddPolicy("ADM", p => p.RequireClaim("permissions", "ADM"));
|
||||
.AddPolicy("ADM", p => p.RequireClaim("permissions", "ADM"));
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
// ConfigurationManager<JsonWebKeySet> needs an IConfigurationRetriever<JsonWebKeySet>.
|
||||
// Microsoft ships OpenIdConnectConfigurationRetriever (full discovery doc) but
|
||||
// no JWKS-only equivalent, so we implement the minimal version here.
|
||||
private sealed class JwksRetriever : IConfigurationRetriever<JsonWebKeySet>
|
||||
{
|
||||
public async Task<JsonWebKeySet> GetConfigurationAsync(string address, IDocumentRetriever retriever, CancellationToken cancel)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(address);
|
||||
ArgumentNullException.ThrowIfNull(retriever);
|
||||
|
||||
var document = await retriever.GetDocumentAsync(address, cancel).ConfigureAwait(false);
|
||||
return new JsonWebKeySet(document);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Azaion.Annotations.Services;
|
||||
|
||||
namespace Azaion.Annotations.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("auth")]
|
||||
public class AuthController(TokenService tokenService) : ControllerBase
|
||||
{
|
||||
[HttpPost("refresh")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Refresh([FromBody] RefreshRequest request)
|
||||
{
|
||||
var newToken = tokenService.RefreshAccessToken(request.RefreshToken);
|
||||
if (newToken == null)
|
||||
return Unauthorized(new { message = "Invalid or expired refresh token" });
|
||||
|
||||
return Ok(new { Token = newToken });
|
||||
}
|
||||
}
|
||||
|
||||
public record RefreshRequest(string RefreshToken);
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace Azaion.Annotations.Infrastructure;
|
||||
|
||||
public static class ConfigurationResolver
|
||||
{
|
||||
// Fail-fast contract: missing or whitespace-only values throw at startup so a
|
||||
// production deploy without the operator-confirmed values cannot silently
|
||||
// accept an insecure default (e.g. a development JWT secret, a localhost DB).
|
||||
public static string ResolveRequiredOrThrow(
|
||||
IConfiguration configuration,
|
||||
string envVar,
|
||||
string configKey,
|
||||
string humanLabel)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(configuration);
|
||||
|
||||
var value = Environment.GetEnvironmentVariable(envVar);
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
value = configuration[configKey];
|
||||
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
throw new InvalidOperationException(
|
||||
$"{humanLabel} is not configured. Set the {envVar} environment variable " +
|
||||
$"or the {configKey} configuration key.");
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace Azaion.Annotations.Infrastructure;
|
||||
|
||||
public static class CorsConfigurationValidator
|
||||
{
|
||||
public const string MissingOriginsMessage =
|
||||
"CORS is misconfigured: CorsConfig:AllowedOrigins is empty and CorsConfig:AllowAnyOrigin is not true. " +
|
||||
"Refusing to start in Production with a permissive CORS policy. " +
|
||||
"Set CorsConfig:AllowedOrigins to a non-empty array, or set CorsConfig:AllowAnyOrigin=true to opt in.";
|
||||
|
||||
public const string PermissiveDefaultWarning =
|
||||
"CorsConfig:AllowedOrigins is empty and CorsConfig:AllowAnyOrigin is not true. " +
|
||||
"Permissive CORS is being applied for environment {Environment}; do not run with this configuration in Production.";
|
||||
|
||||
public static void EnsureSafeForEnvironment(
|
||||
string[] allowedOrigins,
|
||||
bool allowAnyOrigin,
|
||||
string environmentName)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(allowedOrigins);
|
||||
ArgumentNullException.ThrowIfNull(environmentName);
|
||||
|
||||
if (allowedOrigins.Length == 0
|
||||
&& !allowAnyOrigin
|
||||
&& string.Equals(environmentName, "Production", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new InvalidOperationException(MissingOriginsMessage);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool ShouldUsePermissivePolicy(string[] allowedOrigins, bool allowAnyOrigin)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(allowedOrigins);
|
||||
return allowAnyOrigin || allowedOrigins.Length == 0;
|
||||
}
|
||||
|
||||
public static bool ShouldWarnAboutPermissiveDefault(string[] allowedOrigins, bool allowAnyOrigin)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(allowedOrigins);
|
||||
return allowedOrigins.Length == 0 && !allowAnyOrigin;
|
||||
}
|
||||
}
|
||||
+34
-14
@@ -2,23 +2,25 @@ using LinqToDB;
|
||||
using LinqToDB.Data;
|
||||
using Azaion.Annotations.Auth;
|
||||
using Azaion.Annotations.Database;
|
||||
using Azaion.Annotations.Infrastructure;
|
||||
using Azaion.Annotations.Middleware;
|
||||
using Azaion.Annotations.Services;
|
||||
|
||||
const string DatabaseUrlEnvVar = "DATABASE_URL";
|
||||
const string DatabaseUrlConfigKey = "Database:Url";
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
var databaseUrl = builder.Configuration["DATABASE_URL"]
|
||||
?? Environment.GetEnvironmentVariable("DATABASE_URL")
|
||||
?? "Host=localhost;Database=azaion;Username=postgres;Password=changeme";
|
||||
var databaseUrl = ConfigurationResolver.ResolveRequiredOrThrow(
|
||||
builder.Configuration,
|
||||
DatabaseUrlEnvVar,
|
||||
DatabaseUrlConfigKey,
|
||||
"Database connection string");
|
||||
|
||||
var connectionString = databaseUrl.StartsWith("postgresql://")
|
||||
? ConvertPostgresUrl(databaseUrl)
|
||||
: databaseUrl;
|
||||
|
||||
var jwtSecret = builder.Configuration["JWT_SECRET"]
|
||||
?? Environment.GetEnvironmentVariable("JWT_SECRET")
|
||||
?? "development-secret-key-min-32-chars!!";
|
||||
|
||||
builder.Services.AddScoped(_ =>
|
||||
{
|
||||
var options = new DataOptions()
|
||||
@@ -32,23 +34,34 @@ builder.Services.AddScoped<DatasetService>();
|
||||
builder.Services.AddScoped<SettingsService>();
|
||||
builder.Services.AddScoped<PathResolver>();
|
||||
builder.Services.AddSingleton<AnnotationEventService>();
|
||||
builder.Services.AddSingleton(new TokenService(jwtSecret));
|
||||
|
||||
var rabbitMqConfig = new RabbitMqConfig
|
||||
{
|
||||
Host = Environment.GetEnvironmentVariable("RABBITMQ_HOST") ?? "127.0.0.1",
|
||||
Port = int.TryParse(Environment.GetEnvironmentVariable("RABBITMQ_STREAM_PORT"), out var rmqPort) ? rmqPort : 5552,
|
||||
Username = Environment.GetEnvironmentVariable("RABBITMQ_PRODUCER_USER") ?? "azaion_producer",
|
||||
Password = Environment.GetEnvironmentVariable("RABBITMQ_PRODUCER_PASS") ?? "producer_pass",
|
||||
Host = Environment.GetEnvironmentVariable("RABBITMQ_HOST") ?? "127.0.0.1",
|
||||
Port = int.TryParse(Environment.GetEnvironmentVariable("RABBITMQ_STREAM_PORT"), out var rmqPort) ? rmqPort : 5552,
|
||||
Username = Environment.GetEnvironmentVariable("RABBITMQ_PRODUCER_USER") ?? "azaion_producer",
|
||||
Password = Environment.GetEnvironmentVariable("RABBITMQ_PRODUCER_PASS") ?? "producer_pass",
|
||||
StreamName = Environment.GetEnvironmentVariable("RABBITMQ_STREAM_NAME") ?? "azaion-annotations"
|
||||
};
|
||||
builder.Services.AddSingleton(rabbitMqConfig);
|
||||
builder.Services.AddHostedService<FailsafeProducer>();
|
||||
|
||||
builder.Services.AddJwtAuth(jwtSecret);
|
||||
builder.Services.AddJwtAuth(builder.Configuration);
|
||||
|
||||
var allowedOrigins = builder.Configuration.GetSection("CorsConfig:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
|
||||
var allowAnyOrigin = builder.Configuration.GetValue<bool>("CorsConfig:AllowAnyOrigin");
|
||||
CorsConfigurationValidator.EnsureSafeForEnvironment(allowedOrigins, allowAnyOrigin, builder.Environment.EnvironmentName);
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddDefaultPolicy(policy =>
|
||||
policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
|
||||
{
|
||||
if (CorsConfigurationValidator.ShouldUsePermissivePolicy(allowedOrigins, allowAnyOrigin))
|
||||
policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
|
||||
else
|
||||
policy.WithOrigins(allowedOrigins).AllowAnyHeader().AllowAnyMethod();
|
||||
});
|
||||
});
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
@@ -56,6 +69,13 @@ builder.Services.AddSwaggerGen();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (CorsConfigurationValidator.ShouldWarnAboutPermissiveDefault(allowedOrigins, allowAnyOrigin))
|
||||
{
|
||||
app.Services
|
||||
.GetRequiredService<ILogger<Program>>()
|
||||
.LogWarning(CorsConfigurationValidator.PermissiveDefaultWarning, app.Environment.EnvironmentName);
|
||||
}
|
||||
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDataConnection>();
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Azaion.Annotations.Services;
|
||||
|
||||
public class TokenService
|
||||
{
|
||||
private readonly string _jwtSecret;
|
||||
private readonly double _accessTokenHours;
|
||||
|
||||
public TokenService(string jwtSecret, double accessTokenHours = 4)
|
||||
{
|
||||
_jwtSecret = jwtSecret;
|
||||
_accessTokenHours = accessTokenHours;
|
||||
}
|
||||
|
||||
public string? RefreshAccessToken(string refreshToken)
|
||||
{
|
||||
var principal = ValidateToken(refreshToken);
|
||||
if (principal == null)
|
||||
return null;
|
||||
|
||||
var tokenType = principal.FindFirstValue("token_type");
|
||||
if (tokenType != "refresh")
|
||||
return null;
|
||||
|
||||
var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
var email = principal.FindFirstValue(ClaimTypes.Name);
|
||||
var role = principal.FindFirstValue(ClaimTypes.Role);
|
||||
|
||||
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email))
|
||||
return null;
|
||||
|
||||
return CreateAccessToken(userId, email, role);
|
||||
}
|
||||
|
||||
private string CreateAccessToken(string userId, string email, string? role)
|
||||
{
|
||||
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecret));
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, userId),
|
||||
new(ClaimTypes.Name, email),
|
||||
new("token_type", "access")
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(role))
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(claims),
|
||||
Expires = DateTime.UtcNow.AddHours(_accessTokenHours),
|
||||
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature)
|
||||
};
|
||||
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
return tokenHandler.WriteToken(token);
|
||||
}
|
||||
|
||||
private ClaimsPrincipal? ValidateToken(string token)
|
||||
{
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var validationParams = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecret)),
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
return tokenHandler.ValidateToken(token, validationParams, out _);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user