Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Api/DeployApiEndpoints.cs
T
Joseph Doherty fa8c3d1a1a fix(adminui): bodyless POST /api/deployments answered 404 on fused admin+driver nodes (#761)
Found on the docker-dev rig during the #761 Wave-4 gate run (2026-11-12): the documented
bodyless headless deploy (docker-dev/deploy.sh, README "Headless deploy") returned 404 on
both centrals, while the same POST with a JSON body was accepted.

Cause: the optional body was an inferred `DeployRequest?` parameter, which stamps
Accepts(application/json) metadata on the endpoint. For a request with no Content-Type the
routing AcceptsMatcherPolicy prefers endpoints that declare no consumes metadata, and on a
fused admin+driver host MapOtOpcUaMeshGrpcServices has mapped grpc-dotnet's
`{unimplementedService}/{unimplementedMethod}` catch-all, so the request was routed away
from the deploy handler and 404'd. The deploy API on its own does not reproduce it.

The handler now reads the optional body itself: no body (absent or zero-length) is the
headless form, a non-JSON body answers 415 and malformed JSON 400, as the framework's
binding did. New DeployApiBodylessPostTests compose the deploy API with the mesh gRPC
services and drive real HTTP; with the fix reverted the two bodyless cases fail with 404.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-12 22:44:29 -05:00

224 lines
13 KiB
C#

using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Api;
/// <summary>
/// Headless REST gateway over the admin-operations cluster singleton, for CI / scripts that
/// need to trigger a deployment without driving the Blazor AdminUI. Mounted on admin-role nodes
/// only (where <see cref="IAdminOperationsClient"/> + the singleton proxy live), it forwards to
/// the same <see cref="IAdminOperationsClient.StartDeploymentAsync"/> the "Deploy current
/// configuration" button calls.
/// <para>
/// Auth is a single configured secret (<c>Security:DeployApiKey</c>) checked from the
/// <c>X-Api-Key</c> header in fixed time — deliberately orthogonal to the cookie-only web
/// auth so automation needs no LDAP login round-trip. The endpoint is <c>AllowAnonymous</c>
/// (so the global <c>RequireAuthenticatedUser</c> fallback doesn't 401 it) and enforces the
/// key itself; when the key is unconfigured the endpoint is disabled (503), so it is never
/// open.
/// </para>
/// </summary>
public static class DeployApiEndpoints
{
/// <summary>Header carrying the deploy API key.</summary>
public const string ApiKeyHeader = "X-Api-Key";
/// <summary>Configuration key holding the deploy API secret.</summary>
public const string ConfigKey = "Security:DeployApiKey";
/// <summary>Maps <c>POST /api/deployments</c> — the headless deploy trigger — and
/// <c>GET /api/deployments/{id}</c>, the status resource its 202 <c>Location</c> points at. No-op-safe to call
/// on any admin-role node; the handler self-disables (503) until <c>Security:DeployApiKey</c> is set.</summary>
/// <param name="app">The endpoint route builder.</param>
/// <param name="config">Application configuration (read for the deploy API key).</param>
/// <returns>The same <paramref name="app"/> for chaining.</returns>
public static IEndpointRouteBuilder MapOtOpcUaDeployApi(this IEndpointRouteBuilder app, IConfiguration config)
{
var configuredKey = config[ConfigKey];
// The optional body is read in the handler, NOT bound as an inferred `DeployRequest?` parameter
// (lmxopcua#761 gate run, 2026-11-12). An inferred JSON body stamps Accepts(application/json)
// metadata on the endpoint, and for a request with NO Content-Type the routing AcceptsMatcherPolicy
// prefers endpoints without consumes metadata — on a fused admin+driver host that is grpc-dotnet's
// `{unimplementedService}/{unimplementedMethod}` catch-all (mapped by MapOtOpcUaMeshGrpcServices),
// so the documented bodyless POST (docker-dev/deploy.sh) answered 404 and never reached this handler.
app.MapPost("/api/deployments", async (
HttpContext http,
IAdminOperationsClient adminOps,
CancellationToken ct) =>
{
if (string.IsNullOrEmpty(configuredKey))
return Results.Problem(
"Deploy API is disabled. Set Security:DeployApiKey to enable it.",
statusCode: StatusCodes.Status503ServiceUnavailable);
if (!IsAuthorized(http.Request.Headers[ApiKeyHeader].ToString(), configuredKey))
return Results.Unauthorized();
var (body, bodyError) = await ReadOptionalBodyAsync(http.Request, ct);
if (bodyError is not null)
return bodyError;
var createdBy = string.IsNullOrWhiteSpace(body?.CreatedBy) ? "rest-api" : body!.CreatedBy!.Trim();
var result = await adminOps.StartDeploymentAsync(createdBy, ct);
return ToResult(result);
})
.AllowAnonymous() // gated by the API key, not the cookie auth fallback
.DisableAntiforgery() // machine endpoint, not a browser form post
.WithName("StartDeployment");
// The status resource the POST's 202 Location points at (R04 S5). Same gate as the POST: the
// client that follows the Location is the automation holding the deploy key, not a browser
// session, so it is API-key gated (AllowAnonymous + the key check) rather than cookie-policy
// gated, and disabled (503) while the key is unconfigured.
app.MapGet("/api/deployments/{deploymentId:guid}", async (
HttpContext http,
Guid deploymentId,
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
CancellationToken ct) =>
{
if (string.IsNullOrEmpty(configuredKey))
return Results.Problem(
"Deploy API is disabled. Set Security:DeployApiKey to enable it.",
statusCode: StatusCodes.Status503ServiceUnavailable);
if (!IsAuthorized(http.Request.Headers[ApiKeyHeader].ToString(), configuredKey))
return Results.Unauthorized();
await using var db = await dbFactory.CreateDbContextAsync(ct);
var status = await GetDeploymentStatusAsync(db, deploymentId, ct);
return status is null ? Results.NotFound() : Results.Ok(status);
})
.AllowAnonymous() // gated by the API key, not the cookie auth fallback
.WithName("GetDeployment");
return app;
}
/// <summary>Reads one deployment and its per-node apply states, or null when the id is unknown.</summary>
/// <param name="db">The config DB context.</param>
/// <param name="deploymentId">The deployment id from the POST's response / Location.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The status body, or null.</returns>
public static async Task<DeploymentStatusResponse?> GetDeploymentStatusAsync(
OtOpcUaConfigDbContext db, Guid deploymentId, CancellationToken ct = default)
{
// Projected: the deployment row also carries the (large) artifact blob, which a status poll never needs.
var deployment = await db.Deployments.AsNoTracking()
.Where(d => d.DeploymentId == deploymentId)
.Select(d => new { d.DeploymentId, d.RevisionHash, d.Status, d.CreatedBy, d.CreatedAtUtc, d.SealedAtUtc, d.FailureReason })
.FirstOrDefaultAsync(ct);
if (deployment is null) return null;
var nodes = await db.NodeDeploymentStates.AsNoTracking()
.Where(n => n.DeploymentId == deploymentId)
.OrderBy(n => n.NodeId)
.Select(n => new NodeDeploymentStatusResponse(
n.NodeId, n.Status.ToString(), n.StartedAtUtc, n.AppliedAtUtc, n.FailureReason))
.ToListAsync(ct);
return new DeploymentStatusResponse(
deployment.DeploymentId, deployment.RevisionHash, deployment.Status.ToString(), deployment.CreatedBy,
deployment.CreatedAtUtc, deployment.SealedAtUtc, deployment.FailureReason, nodes);
}
/// <summary>Fixed-time compare of the supplied key against the configured secret. False when
/// either is empty (so an unconfigured key never authorizes).</summary>
/// <param name="provided">The caller-supplied key (from the <c>X-Api-Key</c> header).</param>
/// <param name="configuredKey">The configured secret.</param>
/// <returns><see langword="true"/> only when both are non-empty and equal.</returns>
public static bool IsAuthorized(string? provided, string? configuredKey)
{
if (string.IsNullOrEmpty(configuredKey) || string.IsNullOrEmpty(provided)) return false;
return CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(provided), Encoding.UTF8.GetBytes(configuredKey));
}
/// <summary>Map a <see cref="StartDeploymentResult"/> to its HTTP result: Accepted → 202 (with a
/// Location), NoChanges → 200, AnotherDeploymentInFlight → 409, Rejected → 422, anything else → 500.</summary>
/// <param name="r">The deployment outcome from the admin-operations singleton.</param>
/// <returns>The corresponding HTTP result.</returns>
public static IResult ToResult(StartDeploymentResult r) => r.Outcome switch
{
StartDeploymentOutcome.Accepted => Results.Accepted(
$"/api/deployments/{r.DeploymentId?.Value}",
new DeployResponse(r.Outcome.ToString(), r.DeploymentId?.Value, r.RevisionHash?.Value)),
StartDeploymentOutcome.NoChanges => Results.Ok(
new DeployResponse(r.Outcome.ToString(), r.DeploymentId?.Value, r.RevisionHash?.Value)),
StartDeploymentOutcome.AnotherDeploymentInFlight => Results.Conflict(
new DeployResponse(r.Outcome.ToString(), DeploymentId: null, RevisionHash: null)),
StartDeploymentOutcome.Rejected => Results.Problem(
r.Message ?? "Deployment rejected.", statusCode: StatusCodes.Status422UnprocessableEntity),
_ => Results.Problem($"Unexpected deployment outcome: {r.Outcome}",
statusCode: StatusCodes.Status500InternalServerError),
};
/// <summary>Reads the POST's optional JSON body. No body (absent or zero-length) is the documented
/// headless form and yields <c>(null, null)</c>; a non-JSON body answers 415 and malformed JSON 400, as
/// the framework's own body binding did before the body stopped being an inferred parameter.</summary>
/// <param name="request">The incoming request.</param>
/// <param name="ct">Request cancellation.</param>
/// <returns>The parsed body (or null), or the error result to return instead.</returns>
internal static async Task<(DeployRequest? Body, IResult? Error)> ReadOptionalBodyAsync(
HttpRequest request, CancellationToken ct)
{
var hasBody = request.ContentLength is > 0
|| (request.ContentLength is null && request.Headers.TransferEncoding.Count > 0);
if (!hasBody)
return (null, null);
if (!request.HasJsonContentType())
return (null, Results.StatusCode(StatusCodes.Status415UnsupportedMediaType));
try
{
return (await request.ReadFromJsonAsync<DeployRequest>(ct), null);
}
catch (System.Text.Json.JsonException)
{
return (null, Results.Problem("The request body is not valid JSON.",
statusCode: StatusCodes.Status400BadRequest));
}
}
/// <summary>Optional request body. <c>CreatedBy</c> is recorded as the deployment's initiator
/// (audit); defaults to <c>"rest-api"</c> when absent.</summary>
/// <param name="CreatedBy">Who/what initiated the deploy (for the audit trail).</param>
public sealed record DeployRequest(string? CreatedBy);
/// <summary>Response body for a deploy trigger.</summary>
/// <param name="Outcome">The <see cref="StartDeploymentOutcome"/> name.</param>
/// <param name="DeploymentId">The new deployment id when one was created; otherwise null.</param>
/// <param name="RevisionHash">The config revision hash, when known.</param>
public sealed record DeployResponse(string Outcome, Guid? DeploymentId, string? RevisionHash);
/// <summary>Response body for <c>GET /api/deployments/{id}</c>.</summary>
/// <param name="DeploymentId">The deployment id.</param>
/// <param name="RevisionHash">The config revision hash the deployment carries.</param>
/// <param name="Status">The deployment's <c>DeploymentStatus</c> name.</param>
/// <param name="CreatedBy">Who/what initiated it.</param>
/// <param name="CreatedAtUtc">When it was created.</param>
/// <param name="SealedAtUtc">When it sealed; null while still dispatching/applying.</param>
/// <param name="FailureReason">The deployment-level failure reason, when any.</param>
/// <param name="Nodes">Per-node apply states, ordered by node id.</param>
public sealed record DeploymentStatusResponse(
Guid DeploymentId, string RevisionHash, string Status, string CreatedBy, DateTime CreatedAtUtc,
DateTime? SealedAtUtc, string? FailureReason, IReadOnlyList<NodeDeploymentStatusResponse> Nodes);
/// <summary>One node's apply state within a <see cref="DeploymentStatusResponse"/>.</summary>
/// <param name="NodeId">The cluster node id.</param>
/// <param name="Status">The node's <c>NodeDeploymentStatus</c> name.</param>
/// <param name="StartedAtUtc">When the node started applying.</param>
/// <param name="AppliedAtUtc">When the node acked; null while applying.</param>
/// <param name="FailureReason">The node's failure (or "Applied degraded: …") reason, when any.</param>
public sealed record NodeDeploymentStatusResponse(
string NodeId, string Status, DateTime StartedAtUtc, DateTime? AppliedAtUtc, string? FailureReason);
}