Files
WatchedTogether/Jellyfin.Plugin.WatchedTogether.Tests/AuthenticationTests.cs
T
dtourolleandClaude Opus 5 bd08629fff Support Jellyfin 12 alongside 10.11
Jellyfin 12 moved to .NET 10 and changed the IUserManager surface the
plugin relies on: Users/UsersIds became GetUsers()/GetUsersIds(),
ChangePassword takes a user id, HasPassword left the provider contract,
and the user cache is gone, so every lookup is a detached copy.

The plugin now multi-targets net9.0 (against 10.11.5) and net10.0
(against 12.0.0). The differences sit behind a JELLYFIN_12 constant in
Compat/UserManagerCompat.cs, whose ChangePasswordAsync also carries the
stored hash back onto the caller's instance: on 12 the UpdateUserAsync
that claims the account would otherwise write the stale null password
back over the one provisioning just set.

Each release ships one package per generation, with the fourth version
segment naming the target (x.y.z.11 and x.y.z.12) so a 12 server picks
the 12 package over the 10.11 one. scripts/package.sh wraps jprm for a
single generation and the workflows call it twice. The builder image
moves to the .NET 10 SDK, which builds both targets; the net9.0 test run
rolls forward onto the .NET 10 runtime.

CA1873 is a .NET 10 analyzer that flags the same log calls CA1848 does;
it is set to Info, as in the upstream Jellyfin 12 tree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 19:25:16 +02:00

220 lines
8.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Plugin.WatchedTogether.Auth;
using Jellyfin.Plugin.WatchedTogether.Configuration;
using Jellyfin.Plugin.WatchedTogether.Services;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Model.Cryptography;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace Jellyfin.Plugin.WatchedTogether.Tests;
/// <summary>
/// Covers the rule that makes this plugin work: any member's password unlocks the shared account,
/// and nothing else does.
/// </summary>
public class AuthenticationTests
{
// PasswordHash.Parse requires hex-encoded salt and hash segments, so these fixtures use real
// hex rather than readable placeholders.
private const string AliceHash = "$PBKDF2-SHA512$iterations=210000$A1A1A1A1$AAAAAAAABBBBBBBB";
private const string BobHash = "$PBKDF2-SHA512$iterations=210000$B2B2B2B2$CCCCCCCCDDDDDDDD";
private static User MakeUser(string name, string? password)
{
var user = new User(name, "Prov", "ResetProv") { Password = password! };
return user;
}
/// <summary>
/// Builds a provider whose crypto accepts exactly the (hash, password) pairs given.
/// </summary>
private static SharedAccountAuthenticationProvider MakeProvider(
SharedGroup? group,
IReadOnlyList<User> members,
params (string Hash, string Password)[] validPairs)
=> MakeProvider(group, members, null, validPairs);
/// <summary>
/// Builds a provider, optionally with a dynamic-group service that returns
/// <paramref name="dynamicResult"/> for an unresolved username.
/// </summary>
private static SharedAccountAuthenticationProvider MakeProvider(
SharedGroup? group,
IReadOnlyList<User> members,
DynamicGroupResult? dynamicResult,
params (string Hash, string Password)[] validPairs)
{
// ICryptoProvider.Verify takes a ReadOnlySpan<char>, which Moq cannot express as a generic
// argument, so the crypto provider is stubbed by hand.
var crypto = new StubCryptoProvider(validPairs);
var groups = new Mock<IGroupService>();
groups.Setup(g => g.GetGroupForSharedUser(It.IsAny<Guid>())).Returns(group);
groups.Setup(g => g.GetEligibleMembers(It.IsAny<SharedGroup>())).Returns(members);
var dynamic = new Mock<IDynamicGroupService>();
dynamic.Setup(d => d.TryCreateFromLoginAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(dynamicResult);
return new SharedAccountAuthenticationProvider(
crypto,
new Lazy<IGroupService>(() => groups.Object),
new Lazy<IDynamicGroupService>(() => dynamic.Object),
NullLogger<SharedAccountAuthenticationProvider>.Instance);
}
[Fact]
public async Task Authenticate_WithFirstMemberPassword_Succeeds()
{
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var shared = MakeUser("alice+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] };
var provider = MakeProvider(group, [alice, bob], (AliceHash, "alice-pw"));
var result = await provider.Authenticate("alice+bob", "alice-pw", shared);
Assert.Equal("alice+bob", result.Username);
}
[Fact]
public async Task Authenticate_WithLaterMemberPassword_Succeeds()
{
// The second member's password must work even though the first member's check failed
// first - that loop is the whole point of the plugin.
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var shared = MakeUser("alice+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] };
var provider = MakeProvider(group, [alice, bob], (BobHash, "bob-pw"));
var result = await provider.Authenticate("alice+bob", "bob-pw", shared);
Assert.Equal("alice+bob", result.Username);
}
[Fact]
public async Task Authenticate_WithWrongPassword_Throws()
{
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var shared = MakeUser("alice+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] };
var provider = MakeProvider(group, [alice, bob], (AliceHash, "alice-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("alice+bob", "not-the-password", shared));
}
[Fact]
public async Task Authenticate_WhenGroupDisabledOrUnknown_Throws()
{
// GetGroupForSharedUser returns null both for accounts we do not manage and for groups an
// admin has suspended. Neither may be unlocked.
var shared = MakeUser("alice+bob", null);
var provider = MakeProvider(null, [], (AliceHash, "alice-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("alice+bob", "alice-pw", shared));
}
[Fact]
public async Task Authenticate_WhenNoEligibleMembers_Throws()
{
// Every member disabled or deleted: a correct password for a now-disabled member must not
// still open the account.
var shared = MakeUser("alice+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [Guid.NewGuid()] };
var provider = MakeProvider(group, [], (AliceHash, "alice-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("alice+bob", "alice-pw", shared));
}
[Fact]
public async Task Authenticate_MemberWithNoPassword_IsSkipped()
{
// A passwordless member contributes no credential; an empty submitted password must not
// match them and unlock the account.
var ghost = MakeUser("ghost", null);
var bob = MakeUser("bob", BobHash);
var shared = MakeUser("ghost+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [ghost.Id, bob.Id] };
var provider = MakeProvider(group, [ghost, bob], (BobHash, "bob-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("ghost+bob", string.Empty, shared));
}
[Fact]
public async Task Authenticate_WithNullResolvedUser_AndNoDynamicMatch_Throws()
{
// Nothing resolved and the name is not a valid member combination.
var provider = MakeProvider(null, [], dynamicResult: null, (AliceHash, "alice-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("whoever", "alice-pw", null));
}
[Fact]
public async Task Authenticate_WithNullResolvedUser_CreatesGroupOnDemand()
{
// Typing "alice+bob" with a member's password provisions the shared account and logs in.
var group = new SharedGroup { SharedUserId = Guid.NewGuid() };
var provider = MakeProvider(
null,
[],
new DynamicGroupResult(group, "alice+bob"),
(AliceHash, "alice-pw"));
var result = await provider.Authenticate("alice+bob", "alice-pw", null);
Assert.Equal("alice+bob", result.Username);
}
[Fact]
public async Task Authenticate_TwoArgOverload_AlsoCreatesGroupOnDemand()
{
// The two-argument overload is equivalent to passing a null resolved user.
var group = new SharedGroup { SharedUserId = Guid.NewGuid() };
var provider = MakeProvider(
null,
[],
new DynamicGroupResult(group, "alice+bob"),
(AliceHash, "alice-pw"));
var result = await provider.Authenticate("alice+bob", "alice-pw");
Assert.Equal("alice+bob", result.Username);
}
#if !JELLYFIN_12
[Fact]
public void HasPassword_IsAlwaysTrue()
{
// Returning false would let a client offer a passwordless login for the shared account.
// Jellyfin 12 dropped this hook from the provider contract.
var provider = MakeProvider(null, []);
Assert.True(provider.HasPassword(MakeUser("alice+bob", null)));
}
#endif
[Fact]
public async Task ChangePassword_IsNotSupported()
{
var provider = MakeProvider(null, []);
await Assert.ThrowsAsync<NotSupportedException>(
() => provider.ChangePassword(MakeUser("alice+bob", null), "new-pw"));
}
}