Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.IntegrationTests/SecurityHardeningTests.cs
T
Joseph Doherty 1b3928a0a2 fix(security): finish the bearer-token design and cache role mappings (review 2026-10-21 05/U1, 05/P1)
- ManagementAuthenticator accepts Authorization: Bearer <jwt> alongside Basic on
  /management, the audit REST endpoints and the debug-stream hub. Tokens are
  validated locally (HS256 only, alg=none rejected, issuer/audience, lifetime with
  30 s skew); roles and site scope inside a valid token are authoritative for its
  lifetime, so a bearer call costs no LDAP bind and no role re-map.
- /auth/token returns expires_in + management_bearer:true, carries username, display
  name, roles and permitted sites, and answers 404 under DisableLogin.
- CLI exchanges credentials once per process (in-memory CliTokenStore), sends Bearer,
  re-exchanges once on 401 then falls back to Basic; older/login-disabled servers are
  Basic-only; bad credentials are not retried with Basic. Debug stream uses the token
  via AccessTokenProvider. SCADABRIDGE_AUTH_MODE=basic opts out.
- StartupValidator fails a Central boot on a JwtSigningKey under 32 UTF-8 bytes;
  fixed the false 'fail-fast at construction' comment. Removed the dead
  RefreshToken/RecordActivity/ShouldRefresh/IsIdleTimedOut members and the inert
  JwtRefreshThresholdMinutes; JwtExpiryMinutes now documented as the bearer lifetime
  (validated > 0).
- RoleMapper reads through a process-wide RoleMappingCache (RoleMappingCacheSeconds,
  default 30 s): one refresh loads the table plus every Deployer mapping's scope
  rules, Invalidate() drops it (generation-guarded against in-flight refreshes).
- Component-Security.md / Component-CLI.md / CLI README describe the real model
  (cookie claims ticket, bearer for CLI) instead of a cookie-embedded JWT.
2026-10-22 08:25:35 -04:00

174 lines
6.5 KiB
C#

using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
using ZB.MOM.WW.ScadaBridge.Security;
namespace ZB.MOM.WW.ScadaBridge.IntegrationTests;
/// <summary>
/// Security hardening tests.
/// Verifies LDAPS enforcement, JWT key length, secret scrubbing, and API key protection.
/// </summary>
public class SecurityHardeningTests
{
private static JwtTokenService CreateJwtService(string signingKey = "integration-test-signing-key-must-be-at-least-32-chars-long")
{
var options = Options.Create(new SecurityOptions
{
JwtSigningKey = signingKey,
JwtExpiryMinutes = 15,
IdleTimeoutMinutes = 30
});
return new JwtTokenService(options, NullLogger<JwtTokenService>.Instance);
}
/// <summary>Verifies the case: ldap Options, transport, defaults To Ldaps.</summary>
[Fact]
public void LdapOptions_Transport_DefaultsToLdaps()
{
// Production requires encrypted transport. The shared LdapOptions defaults to
// LDAPS (secure-by-default), preserving the donor's LdapUseTls=true default.
var options = new LdapOptions();
Assert.Equal(LdapTransport.Ldaps, options.Transport);
}
/// <summary>Verifies the case: ldap Options, allow Insecure, defaults To False.</summary>
[Fact]
public void LdapOptions_AllowInsecure_DefaultsToFalse()
{
var options = new LdapOptions();
Assert.False(options.AllowInsecure);
}
/// <summary>Verifies the case: jwt Signing Key, minimum Length, enforced.</summary>
[Fact]
public void JwtSigningKey_MinimumLength_Enforced()
{
// HMAC-SHA256 requires a key of at least 32 bytes (256 bits).
var jwtService = CreateJwtService();
var token = jwtService.GenerateToken(
displayName: "Test",
username: "test",
roles: new[] { "Administrator" },
permittedSiteIds: null);
Assert.NotNull(token);
Assert.True(token.Length > 0);
}
/// <summary>Verifies the case: jwt Signing Key, short Key, fails Validation.</summary>
[Fact]
public void JwtSigningKey_ShortKey_FailsValidation()
{
var shortKey = "tooshort";
Assert.True(shortKey.Length < 32,
"Test key must be shorter than 32 chars to verify minimum length enforcement");
}
/// <summary>Verifies the case: log Output Template, does Not Contain Secrets.</summary>
[Fact]
public void LogOutputTemplate_DoesNotContainSecrets()
{
// Verify the Serilog output template does not include secret-bearing properties.
var template = "[{Timestamp:HH:mm:ss} {Level:u3}] [{NodeRole}/{NodeHostname}] {Message:lj}{NewLine}{Exception}";
Assert.DoesNotContain("Password", template, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("ApiKey", template, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Secret", template, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SigningKey", template, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("ConnectionString", template, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Verifies the case: log Enrichment, contains Expected Properties.</summary>
[Fact]
public void LogEnrichment_ContainsExpectedProperties()
{
var enrichmentProperties = new[] { "SiteId", "NodeHostname", "NodeRole" };
foreach (var prop in enrichmentProperties)
{
Assert.DoesNotContain("Password", prop, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Key", prop, StringComparison.OrdinalIgnoreCase);
}
}
/// <summary>Verifies the case: jwt Token, does Not Contain Signing Key.</summary>
[Fact]
public void JwtToken_DoesNotContainSigningKey()
{
var jwtService = CreateJwtService();
var token = jwtService.GenerateToken(
displayName: "Test",
username: "test",
roles: new[] { "Administrator" },
permittedSiteIds: null);
// JWT tokens are base64-encoded; the signing key should not appear in the payload
Assert.DoesNotContain("signing-key", token, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Verifies the case: security Options, jwt Expiry Defaults, are Secure.</summary>
[Fact]
public void SecurityOptions_JwtExpiryDefaults_AreSecure()
{
var options = new SecurityOptions();
Assert.Equal(15, options.JwtExpiryMinutes);
Assert.Equal(30, options.IdleTimeoutMinutes);
}
/// <summary>Verifies the case: jwt Token, tampered Payload, fails Validation.</summary>
[Fact]
public void JwtToken_TamperedPayload_FailsValidation()
{
var jwtService = CreateJwtService();
var token = jwtService.GenerateToken(
displayName: "User",
username: "user",
roles: new[] { "Administrator" },
permittedSiteIds: null);
// Tamper with the token payload (second segment)
var parts = token.Split('.');
Assert.Equal(3, parts.Length);
// Flip a character in the payload
var tamperedPayload = parts[1];
if (tamperedPayload.Length > 5)
{
var chars = tamperedPayload.ToCharArray();
chars[5] = chars[5] == 'A' ? 'B' : 'A';
tamperedPayload = new string(chars);
}
var tamperedToken = $"{parts[0]}.{tamperedPayload}.{parts[2]}";
var principal = jwtService.ValidateToken(tamperedToken);
Assert.Null(principal);
}
/// <summary>Verifies the case: startup Validator, rejects Insecure Ldap In Production.</summary>
[Fact]
public void StartupValidator_RejectsInsecureLdapInProduction()
{
// The shared LdapOptionsValidator (registered with ValidateOnStart by AddZbLdapAuth)
// rejects plaintext transport (Transport=None) unless AllowInsecure is explicitly set,
// preserving the donor's production LDAPS-enforcement guarantee.
var insecure = new LdapOptions
{
Server = "ldap.example.com",
SearchBase = "dc=example,dc=com",
ServiceAccountDn = "cn=admin,dc=example,dc=com",
Transport = LdapTransport.None,
AllowInsecure = false,
};
var result = new ZB.MOM.WW.Auth.Ldap.LdapOptionsValidator().Validate(name: null, insecure);
Assert.True(result.Failed);
Assert.Contains(nameof(LdapOptions.AllowInsecure), result.FailureMessage);
}
}