using Microsoft.Extensions.Configuration;
namespace ZB.MOM.WW.MxGateway.Server.Security.Tls;
///
/// Inspects the Kestrel configuration to decide whether the gateway must supply
/// a generated default certificate (an HTTPS endpoint exists with no certificate
/// of its own).
///
public static class KestrelTlsInspector
{
///
/// Returns when at least one HTTPS endpoint in
/// Kestrel:Endpoints has no certificate of its own (no
/// Certificate:Path, Certificate:Subject, or
/// Certificate:Thumbprint), meaning the gateway must supply a
/// generated fallback certificate.
///
/// The application configuration to inspect for Kestrel certificate settings.
/// if the gateway must supply a generated fallback certificate; otherwise .
public static bool RequiresGeneratedCertificate(IConfiguration configuration)
{
// A Kestrel default certificate applies to every endpoint that lacks its own.
// If the operator configured one, the gateway must not override it.
if (HasConfiguredCertificate(configuration.GetSection("Kestrel:Certificates:Default")))
{
return false;
}
IConfigurationSection endpoints = configuration.GetSection("Kestrel:Endpoints");
foreach (IConfigurationSection endpoint in endpoints.GetChildren())
{
string? url = endpoint["Url"];
if (string.IsNullOrWhiteSpace(url) ||
!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (!HasConfiguredCertificate(endpoint.GetSection("Certificate")))
{
return true;
}
}
return false;
}
private static bool HasConfiguredCertificate(IConfigurationSection certificate)
=> !string.IsNullOrWhiteSpace(certificate["Path"]) ||
!string.IsNullOrWhiteSpace(certificate["Subject"]) ||
!string.IsNullOrWhiteSpace(certificate["Thumbprint"]);
}