Skip to content

Commit 14e25fe

Browse files
net0wellclaude
andcommitted
feat(hosts,tool): DashboardHost com login fixo ou OIDC e psr hash-password (spec 009)
- DashboardHost: login fixo por padrão com usuários por variáveis de ambiente; OIDC opcional (Oidc__Authority/ClientId/ClientSecret, cookie + PKCE, papéis por Dashboard__RoleClaim e Dashboard__Roles__*); a SPA é desafiada e a API responde 401. Sem usuários e sem OIDC a inicialização falha com mensagem clara. Dashboard__PathPrefix, health checks de banco e broker, PSR_AUTO_MIGRATE. - PythonScriptRunner.Tool (7º pacote): dotnet tool `psr`; `psr hash-password` lê a senha sem eco (duas vezes) ou de --stdin e imprime o hash PBKDF2 do ASP.NET Identity v3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f57c79f commit 14e25fe

4 files changed

Lines changed: 303 additions & 0 deletions

File tree

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
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;
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<RootNamespace>PythonScriptRunner.DashboardHost</RootNamespace>
5+
</PropertyGroup>
6+
7+
<ItemGroup>
8+
<ProjectReference Include="..\..\src\PythonScriptRunner.Dashboard\PythonScriptRunner.Dashboard.csproj" />
9+
<ProjectReference Include="..\PythonScriptRunner.ServiceDefaults\PythonScriptRunner.ServiceDefaults.csproj" />
10+
</ItemGroup>
11+
12+
<ItemGroup>
13+
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
14+
</ItemGroup>
15+
16+
</Project>
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
using System.Reflection;
2+
using System.Text;
3+
using Microsoft.AspNetCore.Identity;
4+
5+
namespace PythonScriptRunner.Tool;
6+
7+
/// <summary>The <c>psr</c> command (spec 009; D-124, D-130). Today: <c>psr hash-password</c>.</summary>
8+
public static class PsrTool
9+
{
10+
/// <summary>Entry point.</summary>
11+
/// <param name="args">Command line.</param>
12+
/// <returns>0 on success.</returns>
13+
public static int Main(string[] args) => Run(args, ToolConsole.System);
14+
15+
internal static int Run(IReadOnlyList<string> args, ToolConsole console)
16+
{
17+
ArgumentNullException.ThrowIfNull(args);
18+
ArgumentNullException.ThrowIfNull(console);
19+
switch (args.Count == 0 ? null : args[0])
20+
{
21+
case "hash-password":
22+
return HashPassword([.. args.Skip(1)], console);
23+
case "-h" or "--help" or "help":
24+
Usage(console.Out);
25+
return 0;
26+
case "--version":
27+
console.Out.WriteLine(typeof(PsrTool).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion);
28+
return 0;
29+
case null:
30+
Usage(console.Error);
31+
return 1;
32+
default:
33+
console.Error.WriteLine($"Unknown command '{args[0]}'.");
34+
Usage(console.Error);
35+
return 1;
36+
}
37+
}
38+
39+
/// <summary>
40+
/// Prints the PBKDF2 hash (ASP.NET Identity v3 format) of a password for <c>PasswordHash</c> of a fixed login user (D-121).
41+
/// The password is typed twice without echo, or read from the first line of the standard input with <c>--stdin</c>; it is
42+
/// never printed.
43+
/// </summary>
44+
private static int HashPassword(IReadOnlyList<string> options, ToolConsole console)
45+
{
46+
var unknown = options.Where(o => o != "--stdin").ToList();
47+
if (unknown.Count > 0)
48+
{
49+
console.Error.WriteLine($"Unknown option '{unknown[0]}'. The password is never an argument: type it or pipe it with --stdin.");
50+
return 1;
51+
}
52+
53+
string? password;
54+
if (options.Contains("--stdin"))
55+
{
56+
password = console.In.ReadLine();
57+
}
58+
else if (console.IsInputRedirected)
59+
{
60+
console.Error.WriteLine("The input is redirected: use 'psr hash-password --stdin' to read the password from it.");
61+
return 1;
62+
}
63+
else
64+
{
65+
console.Error.Write("Password: ");
66+
password = console.ReadSecret();
67+
console.Error.Write("Repeat the password: ");
68+
if (console.ReadSecret() != password)
69+
{
70+
console.Error.WriteLine("The passwords do not match.");
71+
return 1;
72+
}
73+
}
74+
75+
if (string.IsNullOrEmpty(password))
76+
{
77+
console.Error.WriteLine("The password is empty.");
78+
return 1;
79+
}
80+
81+
console.Out.WriteLine(new PasswordHasher<object>().HashPassword(new object(), password));
82+
return 0;
83+
}
84+
85+
private static void Usage(TextWriter writer)
86+
{
87+
writer.WriteLine("Usage: psr <command>");
88+
writer.WriteLine();
89+
writer.WriteLine("Commands:");
90+
writer.WriteLine(" hash-password [--stdin] Prints the hash of a password for PythonScriptRunner__Dashboard__Login__Users__N__PasswordHash.");
91+
writer.WriteLine(" The password is typed twice without echo, or read from the first line of the input with --stdin.");
92+
}
93+
}
94+
95+
/// <summary>Console of the tool (replaced in tests).</summary>
96+
/// <param name="In">Standard input.</param>
97+
/// <param name="Out">Standard output (only results).</param>
98+
/// <param name="Error">Prompts and errors.</param>
99+
/// <param name="IsInputRedirected">Whether the input is not a terminal.</param>
100+
/// <param name="ReadSecret">Reads a line without echo.</param>
101+
internal sealed record ToolConsole(TextReader In, TextWriter Out, TextWriter Error, bool IsInputRedirected, Func<string> ReadSecret)
102+
{
103+
public static ToolConsole System { get; } = new(Console.In, Console.Out, Console.Error, Console.IsInputRedirected, ReadWithoutEcho);
104+
105+
private static string ReadWithoutEcho()
106+
{
107+
var text = new StringBuilder();
108+
while (true)
109+
{
110+
var key = Console.ReadKey(intercept: true);
111+
switch (key.Key)
112+
{
113+
case ConsoleKey.Enter:
114+
Console.Error.WriteLine();
115+
return text.ToString();
116+
case ConsoleKey.Backspace:
117+
if (text.Length > 0)
118+
{
119+
text.Length--;
120+
}
121+
122+
break;
123+
default:
124+
if (!char.IsControl(key.KeyChar))
125+
{
126+
text.Append(key.KeyChar);
127+
}
128+
129+
break;
130+
}
131+
}
132+
}
133+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<RootNamespace>PythonScriptRunner.Tool</RootNamespace>
6+
<Description>Command line utilities of PythonScriptRunner (dotnet tool 'psr'): psr hash-password generates the password hash of a dashboard fixed login user.</Description>
7+
<PackAsTool>true</PackAsTool>
8+
<ToolCommandName>psr</ToolCommandName>
9+
<StartupObject>PythonScriptRunner.Tool.PsrTool</StartupObject>
10+
</PropertyGroup>
11+
12+
<ItemGroup>
13+
<InternalsVisibleTo Include="PythonScriptRunner.Dashboard.Tests" />
14+
</ItemGroup>
15+
16+
<ItemGroup>
17+
<PackageReference Include="Microsoft.Extensions.Identity.Core" />
18+
</ItemGroup>
19+
20+
</Project>

0 commit comments

Comments
 (0)