Skip to content

Commit f57c79f

Browse files
net0wellclaude
andcommitted
feat(dashboard): painel embutível com API interna, tempo real e acesso configurável (spec 007)
- AddDashboard + MapPythonScriptRunnerDashboard(prefixo): API em {prefixo}/api, hub SignalR em {prefixo}/hubs/runs e página provisória com <base href> e CSP. - Modos de acesso (ADR-0021): login fixo (hash PBKDF2, cookie psr.session 8 h/24 h, bloqueio 5 falhas/15 min, 10 tentativas/min por IP, recarga sem reinício, chaves em psr.dashboard_keys), filtro próprio, autenticação do host e somente local (Development). - Papéis cumulativos por política, 401/403 em JSON só nos endpoints do painel, CSRF por X-PSR-Request, ETag/If-Match, ProblemDetails com code. - Disparos e testes por multipart (50 MB por arquivo, 200 MB por requisição, 413) ou JSON; auditoria de disparos e logins; visão geral; OpenAPI interno só em Development. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0ac8d74 commit f57c79f

24 files changed

Lines changed: 3052 additions & 0 deletions

‎Directory.Packages.props‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@
55
<ItemGroup>
66
<PackageVersion Include="Cronos" Version="0.13.0" />
77
<PackageVersion Include="JsonSchema.Net" Version="9.4.1" />
8+
<PackageVersion Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.13" />
89
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.13" />
10+
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.13" />
11+
<PackageVersion Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.13" />
912
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.13" />
1013
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.13" />
1114
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="10.0.13" />
@@ -15,8 +18,10 @@
1518
<PackageVersion Include="Microsoft.Extensions.Diagnostics" Version="10.0.13" />
1619
<PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="10.0.13" />
1720
<PackageVersion Include="Microsoft.Extensions.Diagnostics.Testing" Version="10.11.0" />
21+
<PackageVersion Include="Microsoft.Extensions.FileProviders.Embedded" Version="10.0.13" />
1822
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.13" />
1923
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.13" />
24+
<PackageVersion Include="Microsoft.Extensions.Identity.Core" Version="10.0.13" />
2025
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.13" />
2126
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.13" />
2227
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.11.0" />

‎PythonScriptRunner.slnx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
11
<Solution>
22
<Folder Name="/hosts/">
3+
<Project Path="hosts/PythonScriptRunner.DashboardHost/PythonScriptRunner.DashboardHost.csproj" />
34
<Project Path="hosts/PythonScriptRunner.ServiceDefaults/PythonScriptRunner.ServiceDefaults.csproj" />
45
<Project Path="hosts/PythonScriptRunner.WorkerHost/PythonScriptRunner.WorkerHost.csproj" />
56
</Folder>
67
<Folder Name="/src/">
78
<Project Path="src/PythonScriptRunner.Abstractions/PythonScriptRunner.Abstractions.csproj" />
89
<Project Path="src/PythonScriptRunner.Core/PythonScriptRunner.Core.csproj" />
10+
<Project Path="src/PythonScriptRunner.Dashboard/PythonScriptRunner.Dashboard.csproj" />
911
<Project Path="src/PythonScriptRunner.EntityFrameworkCore/PythonScriptRunner.EntityFrameworkCore.csproj" />
1012
<Project Path="src/PythonScriptRunner.RabbitMQ/PythonScriptRunner.RabbitMQ.csproj" />
13+
<Project Path="src/PythonScriptRunner.Tool/PythonScriptRunner.Tool.csproj" />
1114
<Project Path="src/PythonScriptRunner.Worker/PythonScriptRunner.Worker.csproj" />
1215
</Folder>
1316
<Folder Name="/tests/">
1417
<Project Path="tests/PythonScriptRunner.Core.Tests/PythonScriptRunner.Core.Tests.csproj" />
18+
<Project Path="tests/PythonScriptRunner.Dashboard.Tests/PythonScriptRunner.Dashboard.Tests.csproj" />
1519
<Project Path="tests/PythonScriptRunner.EntityFrameworkCore.Tests/PythonScriptRunner.EntityFrameworkCore.Tests.csproj" />
1620
<Project Path="tests/PythonScriptRunner.RabbitMQ.Tests/PythonScriptRunner.RabbitMQ.Tests.csproj" />
1721
<Project Path="tests/PythonScriptRunner.Worker.Tests/PythonScriptRunner.Worker.Tests.csproj" />
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
using System.Diagnostics;
2+
using System.Text.Json;
3+
using Microsoft.AspNetCore.Http;
4+
using Microsoft.AspNetCore.Mvc;
5+
6+
namespace PythonScriptRunner.Dashboard;
7+
8+
/// <summary>Errors of the API as <c>ProblemDetails</c> (RFC 9457) with the extensions <c>code</c>, <c>errors</c>, <c>current</c> and <c>traceId</c>.</summary>
9+
internal static class ApiProblems
10+
{
11+
public static ProblemDetails Create(HttpContext context, int status, string code, string title, string? detail = null)
12+
{
13+
var problem = new ProblemDetails
14+
{
15+
Status = status,
16+
Title = title,
17+
Detail = detail,
18+
Type = $"https://httpstatuses.io/{status}",
19+
};
20+
problem.Extensions["code"] = code;
21+
problem.Extensions["traceId"] = Activity.Current?.TraceId.ToHexString() ?? context.TraceIdentifier;
22+
return problem;
23+
}
24+
25+
public static IResult Result(HttpContext context, int status, string code, string title, string? detail = null, Action<ProblemDetails>? extend = null)
26+
{
27+
var problem = Create(context, status, code, title, detail);
28+
extend?.Invoke(problem);
29+
return TypedResults.Problem(problem);
30+
}
31+
32+
public static IResult NotFound(HttpContext context, string detail) =>
33+
Result(context, StatusCodes.Status404NotFound, "NOT_FOUND", "The resource was not found.", detail);
34+
35+
public static Task WriteAsync(HttpContext context, int status, string code, string title, string? detail = null)
36+
{
37+
context.Response.StatusCode = status;
38+
return context.Response.WriteAsJsonAsync(Create(context, status, code, title, detail), options: null, contentType: "application/problem+json");
39+
}
40+
41+
/// <summary>Maps a domain exception to its status (spec 007); <c>null</c> for unexpected exceptions.</summary>
42+
public static IResult? FromException(HttpContext context, Exception exception) => exception switch
43+
{
44+
InputValidationException invalid => Result(context, StatusCodes.Status400BadRequest, "INPUT_INVALID", "The inputs do not match the contract.",
45+
invalid.Message, p => p.Extensions["errors"] = invalid.Errors
46+
.GroupBy(e => e.Field)
47+
.ToDictionary(g => g.Key, g => g.Select(e => new { e.Code, e.Message }).ToArray())),
48+
ConcurrencyConflictException conflict => Result(context, StatusCodes.Status412PreconditionFailed, conflict.Code, "The resource was changed by someone else.",
49+
conflict.Message, p => p.Extensions["current"] = conflict.Current),
50+
ScriptSyntaxException syntax => Result(context, StatusCodes.Status422UnprocessableEntity, syntax.Code, "The script does not compile.",
51+
syntax.Message, p =>
52+
{
53+
p.Extensions["line"] = syntax.Line;
54+
p.Extensions["column"] = syntax.Column;
55+
}),
56+
DefinitionInvalidException definition => Result(context,
57+
definition.Code == PsrErrorCodes.ImportInvalid ? StatusCodes.Status400BadRequest : StatusCodes.Status422UnprocessableEntity,
58+
definition.Code, "The definition is not valid.", definition.Message, p => p.Extensions["report"] = definition.Report),
59+
VersionReferencedException referenced => Result(context, StatusCodes.Status409Conflict, referenced.Code, "The version is in use.",
60+
referenced.Message, p => p.Extensions["pipelines"] = referenced.Pipelines),
61+
PsrDomainException domain => Result(context, StatusOf(domain.Code), domain.Code, Title(domain.Code), domain.Message),
62+
StageNotFoundException or PipelineNotFoundException or VersionNotFoundException or RunNotFoundException or ArtifactNotFoundException =>
63+
Result(context, StatusCodes.Status404NotFound, "NOT_FOUND", "The resource was not found.", exception.Message),
64+
VersionNotRunnableException => Result(context, StatusCodes.Status409Conflict, "VERSION_NOT_RUNNABLE", "The version cannot run.", exception.Message),
65+
PayloadTooLargeException or BadHttpRequestException { StatusCode: StatusCodes.Status413PayloadTooLarge } =>
66+
Result(context, StatusCodes.Status413PayloadTooLarge, "PAYLOAD_TOO_LARGE", "The upload is larger than allowed.", exception.Message),
67+
BadHttpRequestException bad => Result(context, bad.StatusCode, "BAD_REQUEST", "The request is not valid.", exception.Message),
68+
ArgumentException or JsonException or InvalidDataException =>
69+
Result(context, StatusCodes.Status400BadRequest, "INVALID_ARGUMENT", "The request is not valid.", exception.Message),
70+
_ => null,
71+
};
72+
73+
private static int StatusOf(string code) => code switch
74+
{
75+
PsrErrorCodes.ConcurrencyConflict => StatusCodes.Status412PreconditionFailed,
76+
PsrErrorCodes.ArtifactExpired => StatusCodes.Status410Gone,
77+
PsrErrorCodes.ScheduleNotFound => StatusCodes.Status404NotFound,
78+
PsrErrorCodes.ScriptSyntaxError or PsrErrorCodes.DependencyResolutionFailed or PsrErrorCodes.StageInvalid or PsrErrorCodes.PipelineInvalid
79+
=> StatusCodes.Status422UnprocessableEntity,
80+
PsrErrorCodes.RetentionExceedsGlobal or PsrErrorCodes.ScheduleFileInput or PsrErrorCodes.InvalidCron or PsrErrorCodes.InvalidTimeZone
81+
or PsrErrorCodes.ScheduleInvalid or PsrErrorCodes.ImportInvalid or PsrErrorCodes.FileInputNotAllowed => StatusCodes.Status400BadRequest,
82+
_ => StatusCodes.Status409Conflict,
83+
};
84+
85+
private static string Title(string code) => code switch
86+
{
87+
PsrErrorCodes.ArtifactExpired => "The file is beyond the retention.",
88+
PsrErrorCodes.ScheduleNotFound => "The schedule was not found.",
89+
_ => "The operation is not allowed in the current state.",
90+
};
91+
}
92+
93+
/// <summary>
94+
/// Endpoint filter of the API: requires <c>X-PSR-Request: 1</c> on mutating requests (CSRF; QA-007-3) and turns domain
95+
/// exceptions into <c>ProblemDetails</c>.
96+
/// </summary>
97+
internal sealed class ApiFilter : IEndpointFilter
98+
{
99+
public const string CsrfHeader = "X-PSR-Request";
100+
101+
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
102+
{
103+
ArgumentNullException.ThrowIfNull(context);
104+
ArgumentNullException.ThrowIfNull(next);
105+
var http = context.HttpContext;
106+
if (!HttpMethods.IsGet(http.Request.Method) && !HttpMethods.IsHead(http.Request.Method) && !HttpMethods.IsOptions(http.Request.Method)
107+
&& http.Request.Headers[CsrfHeader] != "1")
108+
{
109+
return ApiProblems.Result(http, StatusCodes.Status400BadRequest, "CSRF_HEADER_MISSING",
110+
$"Mutating requests must send the header {CsrfHeader}: 1.");
111+
}
112+
113+
try
114+
{
115+
return await next(context).ConfigureAwait(false);
116+
}
117+
catch (Exception ex) when (ApiProblems.FromException(http, ex) is { } problem)
118+
{
119+
return problem;
120+
}
121+
}
122+
}
123+
124+
/// <summary>An uploaded file or the whole upload exceeds the limits (413 before any run is created).</summary>
125+
internal sealed class PayloadTooLargeException(string message) : Exception(message);
126+
127+
/// <summary>Optimistic concurrency with <c>ETag</c> = row version (<c>xmin</c>) and <c>If-Match</c>.</summary>
128+
internal static class ETags
129+
{
130+
public static string Of(uint rowVersion) => $"\"{rowVersion}\"";
131+
132+
public static void Set(HttpContext context, uint rowVersion) => context.Response.Headers.ETag = Of(rowVersion);
133+
134+
/// <summary>The row version sent in <c>If-Match</c>; <c>null</c> when missing or malformed.</summary>
135+
public static uint? IfMatch(HttpContext context) =>
136+
context.Request.Headers.IfMatch.ToString().Trim().Trim('"') is { Length: > 0 } text && uint.TryParse(text, out var version) ? version : null;
137+
138+
public static IResult Required(HttpContext context) =>
139+
ApiProblems.Result(context, StatusCodes.Status428PreconditionRequired, "IF_MATCH_REQUIRED", "Send the ETag read before in If-Match.");
140+
}
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
using System.Net;
2+
using System.Security.Claims;
3+
using Microsoft.AspNetCore.Authentication;
4+
using Microsoft.AspNetCore.Authorization;
5+
using Microsoft.AspNetCore.Http;
6+
using Microsoft.Extensions.DependencyInjection;
7+
8+
namespace PythonScriptRunner.Dashboard.Access;
9+
10+
/// <summary>The user of a dashboard request.</summary>
11+
/// <param name="Subject">Recorded in the audit and on the runs: <c>login:&lt;name&gt;</c>, <c>filter:&lt;name&gt;</c>, <c>local</c> or the host <c>sub</c>.</param>
12+
/// <param name="Name">Display name.</param>
13+
/// <param name="Role">Role, or <c>null</c> when authenticated by the host without any dashboard role (403).</param>
14+
/// <param name="Mode">How the user was identified.</param>
15+
internal sealed record DashboardPrincipal(string Subject, string Name, DashboardRole? Role, DashboardAccessMode Mode)
16+
{
17+
/// <summary>The user as the author of changes (the subject fits the 200 chars of the audit and authorship columns).</summary>
18+
public Actor Actor => Actor.User(Subject.Length <= 200 ? Subject : Subject[..200]);
19+
20+
/// <summary>The roles the user has (cumulative).</summary>
21+
public IReadOnlyList<DashboardRole> Roles => Role is { } role ? [.. Enum.GetValues<DashboardRole>().Where(r => r <= role)] : [];
22+
}
23+
24+
/// <summary>Resolved access settings (validated by <c>AddDashboard</c>).</summary>
25+
/// <param name="Mode">Main mode, or <c>null</c> when only local requests are allowed.</param>
26+
/// <param name="AllowLocalRequests">Local requests enter as Admin.</param>
27+
/// <param name="FilterType">Filter of the filter mode.</param>
28+
/// <param name="RolePolicies">Policies of the roles in the host mode.</param>
29+
/// <param name="HostSchemes">Schemes that read the host user.</param>
30+
/// <param name="LoginUrl">Host login page.</param>
31+
/// <param name="LogoutUrl">Host logout page.</param>
32+
internal sealed record DashboardAccessSettings(
33+
DashboardAccessMode? Mode,
34+
bool AllowLocalRequests,
35+
Type? FilterType,
36+
IReadOnlyDictionary<DashboardRole, AuthorizationPolicy> RolePolicies,
37+
IReadOnlyList<string> HostSchemes,
38+
string? LoginUrl,
39+
string? LogoutUrl)
40+
{
41+
/// <summary>The mode reported to the panel.</summary>
42+
public DashboardAccessMode EffectiveMode => Mode ?? DashboardAccessMode.Localhost;
43+
}
44+
45+
/// <summary>Identifies the user of a request in the configured mode (ADR-0021). The result is cached for the request.</summary>
46+
internal sealed class DashboardAccess(DashboardAccessSettings settings)
47+
{
48+
public const string SessionScheme = "PythonScriptRunner.Dashboard.Session";
49+
public const string RoleClaim = "psr:role";
50+
public const string StampClaim = "psr:stamp";
51+
52+
private static readonly object CacheKey = new();
53+
54+
public async ValueTask<DashboardPrincipal?> ResolveAsync(HttpContext http)
55+
{
56+
ArgumentNullException.ThrowIfNull(http);
57+
if (http.Items.TryGetValue(CacheKey, out var cached))
58+
{
59+
return (DashboardPrincipal?)cached;
60+
}
61+
62+
var principal = await ResolveCoreAsync(http).ConfigureAwait(false);
63+
http.Items[CacheKey] = principal;
64+
return principal;
65+
}
66+
67+
/// <summary>Whether the request comes from this machine (the real address, after the host ForwardedHeaders).</summary>
68+
public static bool IsLocal(HttpContext http)
69+
{
70+
var remote = http.Connection.RemoteIpAddress;
71+
return remote is not null && (IPAddress.IsLoopback(remote) || remote.Equals(http.Connection.LocalIpAddress));
72+
}
73+
74+
private async ValueTask<DashboardPrincipal?> ResolveCoreAsync(HttpContext http)
75+
{
76+
if (settings.AllowLocalRequests && IsLocal(http))
77+
{
78+
return new DashboardPrincipal("local", "local", DashboardRole.Admin, DashboardAccessMode.Localhost);
79+
}
80+
81+
switch (settings.Mode)
82+
{
83+
case DashboardAccessMode.FixedLogin:
84+
{
85+
var result = await http.AuthenticateAsync(SessionScheme).ConfigureAwait(false);
86+
if (!result.Succeeded || result.Principal.Identity?.Name is not { } name
87+
|| !Enum.TryParse<DashboardRole>(result.Principal.FindFirstValue(RoleClaim), out var role))
88+
{
89+
return null;
90+
}
91+
92+
return new DashboardPrincipal($"login:{name}", name, role, DashboardAccessMode.FixedLogin);
93+
}
94+
95+
case DashboardAccessMode.Filter:
96+
{
97+
var filter = (IDashboardAuthorizationFilter)http.RequestServices.GetRequiredService(settings.FilterType!);
98+
var user = await filter.AuthorizeAsync(http).ConfigureAwait(false);
99+
return user is null || string.IsNullOrWhiteSpace(user.Name)
100+
? null
101+
: new DashboardPrincipal($"filter:{user.Name}", user.Name, user.Role, DashboardAccessMode.Filter);
102+
}
103+
104+
case DashboardAccessMode.Host:
105+
return await ResolveHostAsync(http).ConfigureAwait(false);
106+
107+
default:
108+
return null;
109+
}
110+
}
111+
112+
private async ValueTask<DashboardPrincipal?> ResolveHostAsync(HttpContext http)
113+
{
114+
var user = http.User;
115+
foreach (var scheme in settings.HostSchemes)
116+
{
117+
var result = await http.AuthenticateAsync(scheme).ConfigureAwait(false);
118+
if (result.Succeeded)
119+
{
120+
user = result.Principal;
121+
break;
122+
}
123+
}
124+
125+
if (user.Identity?.IsAuthenticated != true)
126+
{
127+
return null;
128+
}
129+
130+
var subject = user.FindFirstValue("sub") ?? user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.Identity.Name ?? "unknown";
131+
var name = user.Identity.Name ?? user.FindFirstValue("name") ?? subject;
132+
// Resolved per request: host handlers may be scoped.
133+
var authorization = http.RequestServices.GetRequiredService<IAuthorizationService>();
134+
foreach (var role in (DashboardRole[])[DashboardRole.Admin, DashboardRole.Author, DashboardRole.Executor, DashboardRole.Reader])
135+
{
136+
if ((await authorization.AuthorizeAsync(user, http, settings.RolePolicies[role]).ConfigureAwait(false)).Succeeded)
137+
{
138+
return new DashboardPrincipal(subject, name, role, DashboardAccessMode.Host);
139+
}
140+
}
141+
142+
return new DashboardPrincipal(subject, name, null, DashboardAccessMode.Host);
143+
}
144+
}
145+
146+
/// <summary>Requires at least <see cref="Minimum"/> (roles are cumulative; D-28), or only an identified user when <c>null</c>.</summary>
147+
/// <param name="Minimum">Lowest role allowed.</param>
148+
internal sealed record DashboardRoleRequirement(DashboardRole? Minimum) : IAuthorizationRequirement
149+
{
150+
/// <summary>Policy of any identified user, even without a role (<c>/me</c>, logout).</summary>
151+
public const string UserPolicy = "psr:user";
152+
153+
/// <summary>Name of the policy of a role (<c>psr:reader</c>, <c>psr:executor</c>, <c>psr:author</c>, <c>psr:admin</c>).</summary>
154+
public static string PolicyName(DashboardRole role) => $"psr:{role.ToString().ToLowerInvariant()}";
155+
}
156+
157+
/// <summary>Evaluates <see cref="DashboardRoleRequirement"/> with the dashboard user of the request.</summary>
158+
internal sealed class DashboardRoleHandler(DashboardAccess access) : AuthorizationHandler<DashboardRoleRequirement>
159+
{
160+
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, DashboardRoleRequirement requirement)
161+
{
162+
if (context.Resource is HttpContext http && await access.ResolveAsync(http).ConfigureAwait(false) is { } user
163+
&& (requirement.Minimum is not { } minimum || user.Role >= minimum))
164+
{
165+
context.Succeed(requirement);
166+
}
167+
}
168+
}
169+
170+
/// <summary>Marks the endpoints of the dashboard (API and hub): their failures become JSON 401/403 instead of host challenges.</summary>
171+
internal sealed class DashboardEndpointMetadata;

0 commit comments

Comments
 (0)