|
| 1 | +using Microsoft.AspNetCore.Authentication; |
| 2 | +using Microsoft.AspNetCore.Authentication.Cookies; |
| 3 | +using Microsoft.AspNetCore.Authentication.OpenIdConnect; |
| 4 | +using Microsoft.IdentityModel.Protocols.OpenIdConnect; |
| 5 | + |
| 6 | +// Standalone dashboard of PythonScriptRunner (spec 009): API, real-time updates and panel of spec 007, plus the outbox relay. |
| 7 | +// Fixed login by default, with users from environment variables (PythonScriptRunner__Dashboard__Login__Users__0__Name, __Role, |
| 8 | +// __PasswordHash); OIDC when Oidc__Authority is set (D-125). Also: ConnectionStrings__psr, ConnectionStrings__rabbitmq, |
| 9 | +// Dashboard__PathPrefix (default /psr), PSR_AUTO_MIGRATE and ASPNETCORE_FORWARDEDHEADERS_ENABLED behind a proxy. |
| 10 | +var builder = WebApplication.CreateBuilder(args); |
| 11 | +builder.AddServiceDefaults("psr-dashboard"); |
| 12 | + |
| 13 | +var configuration = builder.Configuration; |
| 14 | +var prefix = configuration["Dashboard:PathPrefix"] is { Length: > 0 } path ? "/" + path.Trim('/') : "/psr"; |
| 15 | +var oidc = configuration.GetSection("Oidc"); |
| 16 | +var useOidc = !string.IsNullOrWhiteSpace(oidc["Authority"]); |
| 17 | +if (!useOidc && !configuration.GetSection("PythonScriptRunner:Dashboard:Login:Users").GetChildren().Any()) |
| 18 | +{ |
| 19 | + throw new InvalidOperationException( |
| 20 | + "The dashboard has no way to sign in: set the fixed login users (PythonScriptRunner__Dashboard__Login__Users__0__Name, __Role and " |
| 21 | + + "__PasswordHash, with the hash from 'psr hash-password') or enable OIDC (Oidc__Authority, Oidc__ClientId and Oidc__ClientSecret)."); |
| 22 | +} |
| 23 | + |
| 24 | +var roleClaim = configuration["Dashboard:RoleClaim"] ?? "roles"; |
| 25 | +if (useOidc) |
| 26 | +{ |
| 27 | + // Host authentication (BFF): the cookie keeps the session, OpenID Connect signs in; tokens never reach the browser. |
| 28 | + builder.Services.AddAuthentication(o => |
| 29 | + { |
| 30 | + o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; |
| 31 | + o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; |
| 32 | + }) |
| 33 | + .AddCookie(o => |
| 34 | + { |
| 35 | + o.Cookie.Name = "psr.host"; |
| 36 | + o.Cookie.HttpOnly = true; |
| 37 | + o.Cookie.SameSite = SameSiteMode.Lax; |
| 38 | + o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; |
| 39 | + o.ExpireTimeSpan = TimeSpan.FromHours(8); |
| 40 | + o.SlidingExpiration = true; |
| 41 | + }) |
| 42 | + .AddOpenIdConnect(o => |
| 43 | + { |
| 44 | + o.Authority = oidc["Authority"]; |
| 45 | + o.ClientId = oidc["ClientId"]; |
| 46 | + o.ClientSecret = oidc["ClientSecret"]; |
| 47 | + o.RequireHttpsMetadata = oidc.GetValue("RequireHttpsMetadata", true); |
| 48 | + o.ResponseType = OpenIdConnectResponseType.Code; |
| 49 | + o.UsePkce = true; |
| 50 | + o.SaveTokens = false; |
| 51 | + o.GetClaimsFromUserInfoEndpoint = true; |
| 52 | + o.MapInboundClaims = false; |
| 53 | + o.Scope.Add("profile"); |
| 54 | + o.TokenValidationParameters.NameClaimType = "name"; |
| 55 | + o.TokenValidationParameters.RoleClaimType = roleClaim; |
| 56 | + }); |
| 57 | +} |
| 58 | + |
| 59 | +builder.Services |
| 60 | + .AddPythonScriptRunner(o => configuration.GetSection("PythonScriptRunner").Bind(o)) |
| 61 | + .AddEntityFrameworkCore(o => |
| 62 | + { |
| 63 | + configuration.GetSection("PythonScriptRunner:EntityFrameworkCore").Bind(o); |
| 64 | + o.UseNpgsql(configuration.GetConnectionString("psr") |
| 65 | + ?? throw new InvalidOperationException("Set the PostgreSQL connection string ConnectionStrings__psr.")); |
| 66 | + }) |
| 67 | + .AddRabbitMq(o => |
| 68 | + { |
| 69 | + configuration.GetSection("PythonScriptRunner:RabbitMQ").Bind(o); |
| 70 | + o.ConnectionString = configuration.GetConnectionString("rabbitmq") |
| 71 | + ?? throw new InvalidOperationException("Set the RabbitMQ connection string ConnectionStrings__rabbitmq."); |
| 72 | + }) |
| 73 | + .AddDashboard(o => |
| 74 | + { |
| 75 | + if (!useOidc) |
| 76 | + { |
| 77 | + o.UseFixedLogin(login => login.BindConfiguration()); |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + // Each role needs its own claim value (Dashboard__Roles__Reader...); the highest one the user has wins. |
| 82 | + string Role(string name, string fallback) => configuration[$"Dashboard:Roles:{name}"] ?? fallback; |
| 83 | + o.UseHostAuthentication(roles => |
| 84 | + { |
| 85 | + roles.Reader = p => p.RequireAuthenticatedUser().RequireClaim(roleClaim, Role("Reader", "psr-leitor")); |
| 86 | + roles.Executor = p => p.RequireAuthenticatedUser().RequireClaim(roleClaim, Role("Executor", "psr-executor")); |
| 87 | + roles.Author = p => p.RequireAuthenticatedUser().RequireClaim(roleClaim, Role("Author", "psr-autor")); |
| 88 | + roles.Admin = p => p.RequireAuthenticatedUser().RequireClaim(roleClaim, Role("Admin", "psr-admin")); |
| 89 | + roles.LoginUrl = "/account/login?returnUrl={returnUrl}"; |
| 90 | + roles.LogoutUrl = "/account/logout"; |
| 91 | + }); |
| 92 | + }); |
| 93 | +string[] ready = [ServiceDefaultsExtensions.ReadyTag]; |
| 94 | +builder.Services.AddHealthChecks().AddPythonScriptRunnerDatabase(tags: ready).AddPythonScriptRunnerBroker(tags: ready); |
| 95 | + |
| 96 | +var app = builder.Build(); |
| 97 | +if (configuration.GetValue<bool>("PSR_AUTO_MIGRATE")) |
| 98 | +{ |
| 99 | + await app.Services.MigratePythonScriptRunnerAsync(); |
| 100 | +} |
| 101 | + |
| 102 | +app.UseAuthentication(); |
| 103 | +app.UseAuthorization(); |
| 104 | +if (useOidc) |
| 105 | +{ |
| 106 | + // The panel itself is challenged (redirect to the provider); the API answers 401 JSON and the hub refuses (spec 009, AC-10). |
| 107 | + app.Use(async (context, next) => |
| 108 | + { |
| 109 | + if (context.Request.Path.StartsWithSegments(prefix, out var rest) |
| 110 | + && !rest.StartsWithSegments("/api") && !rest.StartsWithSegments("/hubs") |
| 111 | + && context.User.Identity?.IsAuthenticated != true) |
| 112 | + { |
| 113 | + await context.ChallengeAsync(new AuthenticationProperties { RedirectUri = context.Request.PathBase + context.Request.Path + context.Request.QueryString }); |
| 114 | + return; |
| 115 | + } |
| 116 | + |
| 117 | + await next(context); |
| 118 | + }); |
| 119 | + app.MapGet("/account/login", (string? returnUrl) => |
| 120 | + TypedResults.Challenge(new AuthenticationProperties { RedirectUri = IsLocal(returnUrl) ? returnUrl : prefix + "/" })); |
| 121 | + app.MapGet("/account/logout", () => TypedResults.SignOut(new AuthenticationProperties { RedirectUri = prefix + "/" }, |
| 122 | + [CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme])); |
| 123 | +} |
| 124 | + |
| 125 | +app.MapDefaultEndpoints(); |
| 126 | +app.MapPythonScriptRunnerDashboard(prefix); |
| 127 | +await app.RunAsync(); |
| 128 | + |
| 129 | +// Only paths of this site are accepted as return addresses (no open redirect). |
| 130 | +static bool IsLocal(string? url) => |
| 131 | + url is { Length: > 0 } && url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\')); |
| 132 | + |
| 133 | +/// <summary>Entry point (public for the integration tests).</summary> |
| 134 | +public partial class Program; |
0 commit comments