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;
///
/// 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 + the singleton proxy live), it forwards to
/// the same the "Deploy current
/// configuration" button calls.
///
/// Auth is a single configured secret (Security:DeployApiKey) checked from the
/// X-Api-Key header in fixed time — deliberately orthogonal to the cookie-only web
/// auth so automation needs no LDAP login round-trip. The endpoint is AllowAnonymous
/// (so the global RequireAuthenticatedUser 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.
///
///
public static class DeployApiEndpoints
{
/// Header carrying the deploy API key.
public const string ApiKeyHeader = "X-Api-Key";
/// Configuration key holding the deploy API secret.
public const string ConfigKey = "Security:DeployApiKey";
/// Maps POST /api/deployments — the headless deploy trigger — and
/// GET /api/deployments/{id}, the status resource its 202 Location points at. No-op-safe to call
/// on any admin-role node; the handler self-disables (503) until Security:DeployApiKey is set.
/// The endpoint route builder.
/// Application configuration (read for the deploy API key).
/// The same for chaining.
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 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;
}
/// Reads one deployment and its per-node apply states, or null when the id is unknown.
/// The config DB context.
/// The deployment id from the POST's response / Location.
/// Cancellation token.
/// The status body, or null.
public static async Task 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);
}
/// Fixed-time compare of the supplied key against the configured secret. False when
/// either is empty (so an unconfigured key never authorizes).
/// The caller-supplied key (from the X-Api-Key header).
/// The configured secret.
/// only when both are non-empty and equal.
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));
}
/// Map a to its HTTP result: Accepted → 202 (with a
/// Location), NoChanges → 200, AnotherDeploymentInFlight → 409, Rejected → 422, anything else → 500.
/// The deployment outcome from the admin-operations singleton.
/// The corresponding HTTP result.
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),
};
/// Reads the POST's optional JSON body. No body (absent or zero-length) is the documented
/// headless form and yields (null, null); 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.
/// The incoming request.
/// Request cancellation.
/// The parsed body (or null), or the error result to return instead.
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(ct), null);
}
catch (System.Text.Json.JsonException)
{
return (null, Results.Problem("The request body is not valid JSON.",
statusCode: StatusCodes.Status400BadRequest));
}
}
/// Optional request body. CreatedBy is recorded as the deployment's initiator
/// (audit); defaults to "rest-api" when absent.
/// Who/what initiated the deploy (for the audit trail).
public sealed record DeployRequest(string? CreatedBy);
/// Response body for a deploy trigger.
/// The name.
/// The new deployment id when one was created; otherwise null.
/// The config revision hash, when known.
public sealed record DeployResponse(string Outcome, Guid? DeploymentId, string? RevisionHash);
/// Response body for GET /api/deployments/{id}.
/// The deployment id.
/// The config revision hash the deployment carries.
/// The deployment's DeploymentStatus name.
/// Who/what initiated it.
/// When it was created.
/// When it sealed; null while still dispatching/applying.
/// The deployment-level failure reason, when any.
/// Per-node apply states, ordered by node id.
public sealed record DeploymentStatusResponse(
Guid DeploymentId, string RevisionHash, string Status, string CreatedBy, DateTime CreatedAtUtc,
DateTime? SealedAtUtc, string? FailureReason, IReadOnlyList Nodes);
/// One node's apply state within a .
/// The cluster node id.
/// The node's NodeDeploymentStatus name.
/// When the node started applying.
/// When the node acked; null while applying.
/// The node's failure (or "Applied degraded: …") reason, when any.
public sealed record NodeDeploymentStatusResponse(
string NodeId, string Status, DateTime StartedAtUtc, DateTime? AppliedAtUtc, string? FailureReason);
}