feat(auth): 0.5.0 passwordless group lookup ILdapGroupLookup (ScadaBridge#46)
ILdapGroupLookup.GetUserGroupsAsync(username, ct) re-reads a known user's groups with the service account: same extraction, canonicalisation, endpoint walk (FallbackServers), timeouts and TLS policy as AuthenticateAsync, via one shared WalkEndpoints<T>. Explicit statuses: Found, UserNotFound, UserDisabled (AD userAccountControl), AmbiguousUser, DirectoryUnavailable, NotSupported (BindMode=User / no service account / foreign ILdapAuthService), ProviderDisabled. AddZbLdapAuth registers it as the same singleton. 0.5.0 is the first published version carrying 0.4.2-0.4.4; scadaproj#51 was live-verified against the NAM AD (24/24, identity check mutation-proven). Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
+44
@@ -161,3 +161,47 @@ public class ServiceCollectionExtensionsTests
|
||||
Assert.False(options.AcceptDomainQualifiedNames);
|
||||
}
|
||||
}
|
||||
|
||||
public class LdapGroupLookupRegistrationTests
|
||||
{
|
||||
private static IConfiguration Config() =>
|
||||
new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Auth:Ldap:Server"] = "ldap.example.com",
|
||||
["Auth:Ldap:SearchBase"] = "dc=example,dc=com",
|
||||
["Auth:Ldap:ServiceAccountDn"] = "cn=svc,dc=example,dc=com",
|
||||
})
|
||||
.Build();
|
||||
|
||||
[Fact]
|
||||
public void AddZbLdapAuth_ResolvesGroupLookup_AsTheSameInstanceAsTheAuthService()
|
||||
{
|
||||
var services = new ServiceCollection().AddZbLdapAuth(Config(), "Auth:Ldap");
|
||||
using var provider = services.BuildServiceProvider();
|
||||
|
||||
var lookup = provider.GetRequiredService<ILdapGroupLookup>();
|
||||
|
||||
Assert.IsType<LdapAuthService>(lookup);
|
||||
Assert.Same(provider.GetRequiredService<ILdapAuthService>(), lookup);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddZbLdapAuth_WithAForeignAuthService_ResolvesANotSupportedLookup()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<ILdapAuthService, StubAuth>();
|
||||
services.AddZbLdapAuth(Config(), "Auth:Ldap");
|
||||
using var provider = services.BuildServiceProvider();
|
||||
|
||||
var result = await provider.GetRequiredService<ILdapGroupLookup>().GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
|
||||
}
|
||||
|
||||
private sealed class StubAuth : ILdapAuthService
|
||||
{
|
||||
public Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct)
|
||||
=> Task.FromResult(LdapAuthResult.Fail(LdapAuthFailure.Disabled));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// GLAuth integration tests for the 0.5.0 passwordless group lookup — opt-in only.
|
||||
//
|
||||
// Same gate and variables as GLAuthIntegrationTests (ZB_LDAP_IT=1, ZB_LDAP_SERVER/PORT/BASE,
|
||||
// ZB_LDAP_SVC_DN/PW, ZB_LDAP_USER/PW, ZB_LDAP_USERATTR). ZB_LDAP_FALLBACK (optional, "host:port")
|
||||
// names a second live directory for the two-live-endpoint failover case — e.g. the redundant local
|
||||
// pair in scadaproj/infra/glauth-redundant (primary :3893, backup :3894):
|
||||
//
|
||||
// ZB_LDAP_IT=1 ZB_LDAP_SERVER=localhost ZB_LDAP_PORT=3893 ZB_LDAP_FALLBACK=localhost:3894 \
|
||||
// ZB_LDAP_BASE=dc=zb,dc=local ZB_LDAP_SVC_DN=cn=serviceaccount,dc=zb,dc=local ZB_LDAP_SVC_PW=... \
|
||||
// ZB_LDAP_USER=multi-role ZB_LDAP_PW=... \
|
||||
// dotnet test tests/ZB.MOM.WW.Auth.Ldap.Tests --filter "FullyQualifiedName~GLAuthGroupLookupTests"
|
||||
|
||||
using System.Net.Sockets;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests.Integration;
|
||||
|
||||
public sealed class GLAuthGroupLookupTests
|
||||
{
|
||||
private sealed record Env(string Server, int Port, string BaseDn, string SvcDn, string SvcPw,
|
||||
string User, string Pw, string UserAttr, string? Fallback);
|
||||
|
||||
private static Env Require()
|
||||
{
|
||||
Skip.IfNot(Environment.GetEnvironmentVariable("ZB_LDAP_IT") == "1", "Set ZB_LDAP_IT=1 and a reachable GLAuth to run.");
|
||||
var env = new Env(
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_SERVER") ?? "localhost",
|
||||
int.TryParse(Environment.GetEnvironmentVariable("ZB_LDAP_PORT"), out var p) ? p : 3893,
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_BASE") ?? "dc=lmxopcua,dc=local",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_SVC_DN") ?? "",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_SVC_PW") ?? "",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_USER") ?? "",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_PW") ?? "",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_USERATTR") ?? "cn",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_FALLBACK"));
|
||||
try
|
||||
{
|
||||
using var tcp = new TcpClient();
|
||||
if (!tcp.ConnectAsync(env.Server, env.Port).Wait(TimeSpan.FromSeconds(3)))
|
||||
Skip.If(true, $"GLAuth not reachable at {env.Server}:{env.Port} (connect timed out).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Skip.If(true, $"GLAuth not reachable at {env.Server}:{env.Port}: {ex.Message}");
|
||||
}
|
||||
|
||||
return env;
|
||||
}
|
||||
|
||||
private static LdapOptions Options(Env env) => new()
|
||||
{
|
||||
Enabled = true,
|
||||
Server = env.Server,
|
||||
Port = env.Port,
|
||||
Transport = LdapTransport.None,
|
||||
AllowInsecure = true,
|
||||
SearchBase = env.BaseDn,
|
||||
ServiceAccountDn = env.SvcDn,
|
||||
ServiceAccountPassword = env.SvcPw,
|
||||
UserNameAttribute = env.UserAttr,
|
||||
GroupAttribute = "memberOf",
|
||||
ConnectionTimeoutMs = 3000,
|
||||
};
|
||||
|
||||
/// <summary>The lookup returns exactly the group set, username and display name a real sign-in does.</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_ReturnsTheSameGroupsAsSignIn()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env));
|
||||
|
||||
var login = await svc.AuthenticateAsync(env.User, env.Pw, CancellationToken.None);
|
||||
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.True(login.Succeeded, $"sign-in failed: {login.Failure}");
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, lookup.Status);
|
||||
Assert.NotEmpty(lookup.Groups);
|
||||
Assert.Equal(login.Groups.OrderBy(g => g, StringComparer.Ordinal), lookup.Groups.OrderBy(g => g, StringComparer.Ordinal));
|
||||
Assert.Equal(login.Username, lookup.Username);
|
||||
Assert.Equal(login.DisplayName, lookup.DisplayName);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Lookup_OfAnUnknownName_IsUserNotFound()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env));
|
||||
|
||||
var lookup = await svc.GetUserGroupsAsync("no-such-user-" + Guid.NewGuid().ToString("N")[..8], CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserNotFound, lookup.Status);
|
||||
}
|
||||
|
||||
/// <summary>A wrong service-account password is the directory refusing US, not the user: DirectoryUnavailable.</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_WithAWrongServiceAccountPassword_IsDirectoryUnavailable()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env) with { ServiceAccountPassword = "definitely-wrong" });
|
||||
|
||||
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, lookup.Status);
|
||||
}
|
||||
|
||||
/// <summary>Dead primary (closed local port) fails over to the live directory, twice (sticky).</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_FailsOverFromADeadPrimary()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env) with
|
||||
{
|
||||
Server = "127.0.0.1",
|
||||
Port = 39999,
|
||||
FallbackServers = new[] { $"{env.Server}:{env.Port}" },
|
||||
});
|
||||
|
||||
var first = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
var second = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, first.Status);
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, second.Status);
|
||||
}
|
||||
|
||||
/// <summary>Every endpoint dead: DirectoryUnavailable, never UserNotFound (which would revoke a session).</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_WithEveryEndpointDead_IsDirectoryUnavailable()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env) with
|
||||
{
|
||||
Server = "127.0.0.1",
|
||||
Port = 39999,
|
||||
FallbackServers = new[] { "127.0.0.1:39998" },
|
||||
});
|
||||
|
||||
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, lookup.Status);
|
||||
}
|
||||
|
||||
/// <summary>Two LIVE directories (ZB_LDAP_FALLBACK): primary answers first; a dead primary port walks to the backup.</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_AcrossTwoLiveDirectories_AnswersFromEither()
|
||||
{
|
||||
var env = Require();
|
||||
Skip.If(string.IsNullOrWhiteSpace(env.Fallback), "Set ZB_LDAP_FALLBACK=host:port to a second live directory.");
|
||||
|
||||
var both = new LdapAuthService(Options(env) with { FallbackServers = new[] { env.Fallback! } });
|
||||
var backupOnly = new LdapAuthService(Options(env) with { Port = 39999, Server = "127.0.0.1", FallbackServers = new[] { env.Fallback! } });
|
||||
|
||||
var viaPrimary = await both.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
var viaBackup = await backupOnly.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, viaPrimary.Status);
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, viaBackup.Status);
|
||||
Assert.Equal(viaPrimary.Groups.OrderBy(g => g), viaBackup.Groups.OrderBy(g => g));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 0.5.0 passwordless group lookup (<see cref="ILdapGroupLookup"/>): statuses, parity with
|
||||
/// <see cref="LdapAuthService.AuthenticateAsync"/>'s group set, the shared failover walk, and the
|
||||
/// configurations that cannot search without a password.
|
||||
/// </summary>
|
||||
public class LdapGroupLookupTests
|
||||
{
|
||||
private static LdapOptions Opts(params string[] fallbacks) => new()
|
||||
{
|
||||
Enabled = true,
|
||||
Server = "dc1",
|
||||
Port = 636,
|
||||
Transport = LdapTransport.Ldaps,
|
||||
SearchBase = "dc=x",
|
||||
ServiceAccountDn = "cn=svc,dc=x",
|
||||
ServiceAccountPassword = "svcpw",
|
||||
UserNameAttribute = "sAMAccountName",
|
||||
DisplayNameAttribute = "displayName",
|
||||
FallbackServers = fallbacks,
|
||||
};
|
||||
|
||||
private static FakeLdapConnection Alice(string? userAccountControl = null)
|
||||
{
|
||||
var extra = new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "Alice" } };
|
||||
if (userAccountControl is not null)
|
||||
extra["userAccountControl"] = new[] { userAccountControl };
|
||||
return new FakeLdapConnection().WithUserEntry(
|
||||
"cn=Alice,ou=people,dc=x",
|
||||
new[] { "cn=Operators,ou=g,dc=x", @"cn=Eng\,ineers,ou=g,dc=x" },
|
||||
displayName: "Alice Smith",
|
||||
extraAttributes: extra);
|
||||
}
|
||||
|
||||
// ---- the happy path and parity with AuthenticateAsync ----
|
||||
|
||||
[Fact]
|
||||
public async Task Found_ReturnsCanonicalNameDisplayNameAndGroups_WithServiceAccountOnly()
|
||||
{
|
||||
var fake = Alice();
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync(" alice ", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
Assert.True(result.IsFound);
|
||||
Assert.Equal("Alice", result.Username); // directory spelling, not the typed one
|
||||
Assert.Equal("Alice Smith", result.DisplayName);
|
||||
Assert.Equal(new[] { "Operators", "Eng,ineers" }, result.Groups);
|
||||
// Exactly one bind, as the service account — never a bind as the user.
|
||||
Assert.Equal(new[] { "cn=svc,dc=x" }, fake.BoundDns);
|
||||
Assert.Equal(1, fake.BindAttempts);
|
||||
Assert.Contains("search:(sAMAccountName=alice)", fake.Calls);
|
||||
Assert.Contains("userAccountControl", fake.SearchAttributes!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Found_MatchesTheGroupSetAuthenticateAsyncReturns()
|
||||
{
|
||||
var lookup = await new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()))
|
||||
.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
var login = await new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()))
|
||||
.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.True(login.Succeeded);
|
||||
Assert.Equal(login.Groups, lookup.Groups);
|
||||
Assert.Equal(login.Username, lookup.Username);
|
||||
Assert.Equal(login.DisplayName, lookup.DisplayName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Found_WithZeroGroups_IsFoundWithAnEmptySet()
|
||||
{
|
||||
var fake = new FakeLdapConnection().WithUserEntry("cn=bob,dc=x", Array.Empty<string>());
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("bob", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
Assert.Empty(result.Groups);
|
||||
}
|
||||
|
||||
// ---- directory answers ----
|
||||
|
||||
[Fact]
|
||||
public async Task NoEntry_IsUserNotFound()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().WithNoMatch()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("ghost", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
|
||||
Assert.Empty(result.Groups);
|
||||
Assert.Equal("", result.Username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TwoEntries_IsAmbiguousUser()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().WithDuplicateMatch()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("dup", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.AmbiguousUser, result.Status);
|
||||
Assert.Empty(result.Groups);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("514")] // NORMAL_ACCOUNT | ACCOUNTDISABLE
|
||||
[InlineData("66050")] // + DONT_EXPIRE_PASSWORD
|
||||
[InlineData("2")]
|
||||
public async Task AccountDisableFlag_IsUserDisabled_AndReturnsNoGroups(string uac)
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice(uac)));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserDisabled, result.Status);
|
||||
Assert.Empty(result.Groups);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("512")] // NORMAL_ACCOUNT
|
||||
[InlineData("66048")] // + DONT_EXPIRE_PASSWORD
|
||||
[InlineData("garbage")] // unparseable is "not disabled", never a fault
|
||||
public async Task EnabledOrUnparseableAccountControl_IsFound(string uac)
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice(uac)));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
}
|
||||
|
||||
// ---- system-side faults and failover ----
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectFailure_OnOnlyEndpoint_IsDirectoryUnavailable()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().ThrowOnConnect()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ServiceBindFailure_IsDirectoryUnavailable_NotUserNotFound()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice().ThrowOnServiceBind()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchFailure_IsDirectoryUnavailable()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice().ThrowOnSearch()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectFailure_FailsOverToFallback_AndFindsTheUser()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().ThrowOnConnect(), Alice());
|
||||
var svc = new LdapAuthService(Opts("dc2:3894"), factory);
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
Assert.Equal(("dc2", 3894), (factory.Created[1].ConnectArgs!.Value.Host, factory.Created[1].ConnectArgs!.Value.Port));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchFailure_FailsOverToFallback()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Alice().ThrowOnSearch(), Alice());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UserNotFound_IsFinal_AndDoesNotFailOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection(), Alice());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AllEndpointsDown_IsDirectoryUnavailable_AfterTryingEach()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), new FakeLdapConnection().ThrowOnServiceBind());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StickyPreference_IsSharedWithAuthentication()
|
||||
{
|
||||
// A lookup that fails over to dc2 makes dc2 preferred for the next sign-in too.
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), Alice(), Alice());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
var login = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.True(login.Succeeded);
|
||||
Assert.Equal(3, factory.Created.Count);
|
||||
Assert.Equal("dc2", factory.Created[2].ConnectArgs!.Value.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UsesConfiguredTransportTimeoutAndCertificatePolicy()
|
||||
{
|
||||
System.Net.Security.RemoteCertificateValidationCallback callback = (_, _, _, _) => true;
|
||||
var fake = Alice();
|
||||
var options = Opts() with { Transport = LdapTransport.StartTls, ConnectionTimeoutMs = 1234, ServerCertificateValidationCallback = callback };
|
||||
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapTransport.StartTls, fake.ConnectArgs!.Value.Transport);
|
||||
Assert.Equal(1234, fake.ConnectArgs!.Value.TimeoutMs);
|
||||
Assert.Same(callback, fake.ConnectCertCallback);
|
||||
}
|
||||
|
||||
// ---- configurations that cannot look up ----
|
||||
|
||||
[Fact]
|
||||
public async Task UserBindMode_IsNotSupported_WithoutTouchingTheNetwork()
|
||||
{
|
||||
var fake = Alice();
|
||||
var options = Opts() with { BindMode = LdapBindMode.User, UserBindTemplate = @"X\{0}", ServiceAccountDn = "" };
|
||||
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UserBindMode_IsNotSupported_EvenWithAServiceAccountConfigured()
|
||||
{
|
||||
var fake = Alice();
|
||||
var options = Opts() with { BindMode = LdapBindMode.User, UserBindTemplate = @"X\{0}" };
|
||||
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BlankServiceAccount_IsNotSupported_NeverAnAnonymousBind()
|
||||
{
|
||||
var fake = Alice();
|
||||
var svc = new LdapAuthService(Opts() with { ServiceAccountDn = " " }, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisabledProvider_IsProviderDisabled_WithoutTouchingTheNetwork()
|
||||
{
|
||||
var fake = Alice();
|
||||
var svc = new LdapAuthService(Opts() with { Enabled = false }, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.ProviderDisabled, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task BlankUsername_IsUserNotFound_WithoutTouchingTheNetwork(string? username)
|
||||
{
|
||||
var fake = Alice();
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync(username!, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FilterMetacharacters_AreEscaped()
|
||||
{
|
||||
var fake = new FakeLdapConnection();
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
await svc.GetUserGroupsAsync("*)(cn=*", CancellationToken.None);
|
||||
|
||||
Assert.Contains(@"search:(sAMAccountName=\2a\29\28cn=\2a)", fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelledToken_Throws()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()));
|
||||
using var cts = new CancellationTokenSource();
|
||||
cts.Cancel();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => svc.GetUserGroupsAsync("alice", cts.Token));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Of_RefusesFound()
|
||||
=> Assert.Throws<ArgumentException>(() => LdapGroupLookupResult.Of(LdapGroupLookupStatus.Found));
|
||||
}
|
||||
Reference in New Issue
Block a user