fix(host): central https URLs get TLS from a node certificate or refuse to boot (ScadaBridge#108)
Central re-bound its HTTP surface from ASPNETCORE_URLS keeping only the port, so https://+:443 silently served plaintext HTTP. The parser now keeps the scheme (ParseHttpBindEndpoints); an https entry binds UseHttps with the node certificate from the new ScadaBridge:Node:Tls section (CertificatePath + CertificatePassword, or CertificateThumbprint + StoreName + StoreLocation; default unset) and the node refuses to boot, with a clear error, when https is requested without a certificate. http entries bind exactly as before. Tests: scheme parsing, refuse-to-boot, http endpoint config identical to the legacy inline binding (reflected effective Kestrel listen options), and a real Kestrel HTTPS listener with a generated .pfx serving h2 and HTTP/1.1 by ALPN while plaintext to the TLS port fails. Reverting the fix turns the refuse-to-boot and real-listener tests red. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Host;
|
||||
|
||||
/// <summary>One endpoint of central's HTTP surface, parsed from <c>ASPNETCORE_URLS</c>.</summary>
|
||||
/// <param name="Port">The TCP port.</param>
|
||||
/// <param name="IsHttps">True when the URL scheme was <c>https</c>.</param>
|
||||
internal readonly record struct HttpBindEndpoint(int Port, bool IsHttps);
|
||||
|
||||
/// <summary>
|
||||
/// Central's re-declared HTTP/1.1+HTTP/2 Kestrel listeners (ScadaBridge#108). http entries bind
|
||||
/// exactly as they always did; https entries bind TLS with the node certificate, and refuse to
|
||||
/// boot when none is configured.
|
||||
/// </summary>
|
||||
internal static class CentralHttpBinding
|
||||
{
|
||||
/// <summary>
|
||||
/// Loads the node certificate when any endpoint is https. Returns null when none is (the
|
||||
/// certificate settings are then ignored). Throws when https is requested without a usable certificate.
|
||||
/// </summary>
|
||||
internal static X509Certificate2? LoadCertificateIfNeeded(IReadOnlyList<HttpBindEndpoint> endpoints, NodeTlsOptions? tls)
|
||||
{
|
||||
var httpsPorts = endpoints.Where(e => e.IsHttps).Select(e => e.Port).ToList();
|
||||
if (httpsPorts.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (tls is null || !tls.IsConfigured)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"ASPNETCORE_URLS requests https on port(s) {string.Join(", ", httpsPorts)} but no node certificate is " +
|
||||
"configured. Set ScadaBridge:Node:Tls:CertificatePath (+ CertificatePassword) or " +
|
||||
"ScadaBridge:Node:Tls:CertificateThumbprint, or use an http:// URL. Refusing to boot rather than " +
|
||||
"serve plaintext on an https port.");
|
||||
}
|
||||
|
||||
return Load(tls);
|
||||
}
|
||||
|
||||
/// <summary>Loads the certificate from the configured .pfx or store thumbprint (exactly one).</summary>
|
||||
internal static X509Certificate2 Load(NodeTlsOptions tls)
|
||||
{
|
||||
var hasPath = !string.IsNullOrWhiteSpace(tls.CertificatePath);
|
||||
var hasThumb = !string.IsNullOrWhiteSpace(tls.CertificateThumbprint);
|
||||
if (hasPath == hasThumb)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"ScadaBridge:Node:Tls must set exactly one of CertificatePath or CertificateThumbprint.");
|
||||
}
|
||||
|
||||
if (hasPath)
|
||||
{
|
||||
if (!File.Exists(tls.CertificatePath))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"ScadaBridge:Node:Tls:CertificatePath '{tls.CertificatePath}' does not exist.");
|
||||
}
|
||||
|
||||
return X509CertificateLoader.LoadPkcs12FromFile(
|
||||
tls.CertificatePath!, string.IsNullOrEmpty(tls.CertificatePassword) ? null : tls.CertificatePassword);
|
||||
}
|
||||
|
||||
if (!Enum.TryParse<StoreName>(tls.StoreName, ignoreCase: true, out var storeName))
|
||||
{
|
||||
throw new InvalidOperationException($"ScadaBridge:Node:Tls:StoreName '{tls.StoreName}' is not a valid store name.");
|
||||
}
|
||||
|
||||
var location = tls.StoreLocation?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"local-machine" or "localmachine" => StoreLocation.LocalMachine,
|
||||
"current-user" or "currentuser" => StoreLocation.CurrentUser,
|
||||
_ => throw new InvalidOperationException(
|
||||
$"ScadaBridge:Node:Tls:StoreLocation '{tls.StoreLocation}' must be 'local-machine' or 'current-user'."),
|
||||
};
|
||||
|
||||
using var store = new X509Store(storeName, location);
|
||||
store.Open(OpenFlags.ReadOnly);
|
||||
var thumbprint = new string(tls.CertificateThumbprint!.Where(char.IsLetterOrDigit).ToArray());
|
||||
var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false);
|
||||
if (found.Count == 0 || !found[0].HasPrivateKey)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"ScadaBridge:Node:Tls certificate with thumbprint {thumbprint} not found (with a private key) in {location}\\{storeName}.");
|
||||
}
|
||||
|
||||
return found[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binds each endpoint with <c>ListenAnyIP</c>, <c>Http1AndHttp2</c>; https endpoints also
|
||||
/// <c>UseHttps(certificate)</c>. http endpoints are bound exactly as before ScadaBridge#108.
|
||||
/// </summary>
|
||||
internal static void BindHttpSurface(
|
||||
KestrelServerOptions options, IReadOnlyList<HttpBindEndpoint> endpoints, X509Certificate2? certificate)
|
||||
{
|
||||
foreach (var endpoint in endpoints)
|
||||
{
|
||||
options.ListenAnyIP(endpoint.Port, listenOptions =>
|
||||
{
|
||||
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
|
||||
if (endpoint.IsHttps)
|
||||
{
|
||||
listenOptions.UseHttps(certificate
|
||||
?? throw new InvalidOperationException("https endpoint without a certificate."));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,4 +36,38 @@ public class NodeOptions
|
||||
/// with the Akka remoting port a site node binds.
|
||||
/// </summary>
|
||||
public int MetricsPort { get; set; } = 8084;
|
||||
|
||||
/// <summary>
|
||||
/// This node's own TLS certificate for the Kestrel HTTP surface (ScadaBridge#108, design
|
||||
/// 2026-11-09-tls-production-profile stage 1). Default: nothing set. Required if (and only if)
|
||||
/// <c>ASPNETCORE_URLS</c> contains an <c>https://</c> entry; central then refuses to boot
|
||||
/// without it. Applies to central's HTTP/1.1+HTTP/2 surface only; the gRPC listener is unchanged.
|
||||
/// </summary>
|
||||
public NodeTlsOptions Tls { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Certificate source for <see cref="NodeOptions.Tls"/>: a .pfx path plus password, OR a
|
||||
/// certificate-store thumbprint. Same shape as the cluster's <c>RemotingTls</c> certificate fields.
|
||||
/// </summary>
|
||||
public sealed class NodeTlsOptions
|
||||
{
|
||||
/// <summary>Path to a PKCS#12 (.pfx) file with the private key. Set this OR <see cref="CertificateThumbprint"/>.</summary>
|
||||
public string? CertificatePath { get; set; }
|
||||
|
||||
/// <summary>Password for <see cref="CertificatePath"/>; write it as <c>${secret:NAME}</c>, never a literal.</summary>
|
||||
public string? CertificatePassword { get; set; }
|
||||
|
||||
/// <summary>Thumbprint of a certificate in the OS store. Set this OR <see cref="CertificatePath"/>.</summary>
|
||||
public string? CertificateThumbprint { get; set; }
|
||||
|
||||
/// <summary>Store name for <see cref="CertificateThumbprint"/>. Default <c>My</c>.</summary>
|
||||
public string StoreName { get; set; } = "My";
|
||||
|
||||
/// <summary>Store location for <see cref="CertificateThumbprint"/>: <c>local-machine</c> (default) or <c>current-user</c>.</summary>
|
||||
public string StoreLocation { get; set; } = "local-machine";
|
||||
|
||||
/// <summary>Whether any certificate source field is set.</summary>
|
||||
public bool IsConfigured =>
|
||||
!string.IsNullOrWhiteSpace(CertificatePath) || !string.IsNullOrWhiteSpace(CertificateThumbprint);
|
||||
}
|
||||
|
||||
@@ -205,7 +205,11 @@ try
|
||||
var httpUrls = configuration["ASPNETCORE_URLS"]
|
||||
?? builder.WebHost.GetSetting("urls")
|
||||
?? "http://+:5000";
|
||||
var httpPorts = ParseHttpBindPorts(httpUrls);
|
||||
var httpEndpoints = ParseHttpBindEndpoints(httpUrls);
|
||||
var httpPorts = httpEndpoints.Select(e => e.Port).ToList();
|
||||
// ScadaBridge#108: an https URL needs a configured node certificate; without one the
|
||||
// node refuses to boot rather than silently serving plaintext on that port.
|
||||
var httpsCertificate = CentralHttpBinding.LoadCertificateIfNeeded(httpEndpoints, nodeOptions.Tls);
|
||||
|
||||
// Register row 56: central's dedicated Prometheus listener, OPT-IN.
|
||||
//
|
||||
@@ -233,13 +237,7 @@ try
|
||||
options.Limits.Http2.KeepAlivePingTimeout = SiteKestrelSetup.Http2KeepAlivePingTimeout;
|
||||
// The HTTP/1.1 (+ HTTP/2) surface from the configured URLs, re-declared so it
|
||||
// survives the explicit-endpoints switch above.
|
||||
foreach (var httpPort in httpPorts)
|
||||
{
|
||||
options.ListenAnyIP(httpPort, listenOptions =>
|
||||
{
|
||||
listenOptions.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2;
|
||||
});
|
||||
}
|
||||
CentralHttpBinding.BindHttpSurface(options, httpEndpoints, httpsCertificate);
|
||||
|
||||
// The gRPC control plane, HTTP/2 h2c only, on its own port.
|
||||
options.ListenAnyIP(centralGrpcPort, listenOptions =>
|
||||
@@ -942,29 +940,41 @@ public partial class Program
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the distinct TCP ports from an ASP.NET Core server-URLs string (the
|
||||
/// <c>ASPNETCORE_URLS</c> / <c>--urls</c> value, e.g. <c>"http://+:5000"</c> or a
|
||||
/// <c>ASPNETCORE_URLS</c> / <c>--urls</c> value). Port-only view of
|
||||
/// <see cref="ParseHttpBindEndpoints"/>; kept for callers that only need the ports.
|
||||
/// </summary>
|
||||
/// <param name="serverUrls">The server-URLs string; may be null/empty.</param>
|
||||
/// <returns>The distinct ports, in first-seen order.</returns>
|
||||
internal static IReadOnlyList<int> ParseHttpBindPorts(string? serverUrls) =>
|
||||
ParseHttpBindEndpoints(serverUrls).Select(e => e.Port).ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the distinct (port, scheme) endpoints from an ASP.NET Core server-URLs string
|
||||
/// (the <c>ASPNETCORE_URLS</c> / <c>--urls</c> value, e.g. <c>"http://+:5000"</c> or a
|
||||
/// semicolon-separated list). Used to re-declare central's HTTP surface after the gRPC
|
||||
/// listener switches Kestrel into explicit-endpoints mode — see the call site's warning.
|
||||
/// listener switches Kestrel into explicit-endpoints mode - see the call site's warning.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Bind hosts (<c>+</c>, <c>*</c>, <c>0.0.0.0</c>, <c>[::]</c>, a hostname) are irrelevant
|
||||
/// here because the caller re-binds via <c>ListenAnyIP</c>; only the port matters. A URL
|
||||
/// with no explicit port falls back to the scheme default (80/443). Unparseable entries
|
||||
/// are skipped rather than throwing — a bad URL should not take the node down at boot.
|
||||
/// here because the caller re-binds via <c>ListenAnyIP</c>. The scheme IS kept (ScadaBridge#108):
|
||||
/// dropping it used to make <c>https://+:443</c> serve plaintext. A URL with no explicit port
|
||||
/// falls back to the scheme default (80/443). Unparseable entries are skipped rather than
|
||||
/// throwing. The same port listed with two schemes is a configuration error and throws.
|
||||
/// </remarks>
|
||||
/// <param name="serverUrls">The server-URLs string; may be null/empty.</param>
|
||||
/// <returns>The distinct ports, in first-seen order.</returns>
|
||||
internal static IReadOnlyList<int> ParseHttpBindPorts(string? serverUrls)
|
||||
/// <returns>The distinct endpoints, in first-seen order.</returns>
|
||||
internal static IReadOnlyList<HttpBindEndpoint> ParseHttpBindEndpoints(string? serverUrls)
|
||||
{
|
||||
var ports = new List<int>();
|
||||
var endpoints = new List<HttpBindEndpoint>();
|
||||
if (string.IsNullOrWhiteSpace(serverUrls))
|
||||
{
|
||||
return ports;
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
foreach (var raw in serverUrls.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
int port;
|
||||
var isHttps = raw.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
|
||||
// Uri can't parse the wildcard hosts Kestrel accepts (+, *), so normalize them
|
||||
// to a placeholder host before parsing; the host is discarded anyway.
|
||||
var normalized = raw.Replace("://+", "://placeholder").Replace("://*", "://placeholder");
|
||||
@@ -982,12 +992,21 @@ public partial class Program
|
||||
}
|
||||
}
|
||||
|
||||
if (port is > 0 and <= 65535 && !ports.Contains(port))
|
||||
if (port is > 0 and <= 65535)
|
||||
{
|
||||
ports.Add(port);
|
||||
var existing = endpoints.FindIndex(e => e.Port == port);
|
||||
if (existing < 0)
|
||||
{
|
||||
endpoints.Add(new HttpBindEndpoint(port, isHttps));
|
||||
}
|
||||
else if (endpoints[existing].IsHttps != isHttps)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"ASPNETCORE_URLS lists port {port} with both http and https schemes; a port is one or the other.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ports;
|
||||
return endpoints;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user