"jane+john" and "john+jane" name the same group, but they did not behave that way. Jellyfin only routes a login here when no account matches the typed name, so logging in with the reversed spelling of an existing group found nothing and quietly created a second shared account for the same two people - each with its own watched state. Group identity is now order-independent: - Member names are sorted alphabetically when building an account name, so a given set of members always produces the same name. - Before creating anything, the login path looks for an existing group whose members are exactly the named set, compared as a set rather than a sequence, and logs into that account if it finds one. - Stored member lists are kept in the same canonical order on create and update, so a group's stored order does not depend on the order an admin happened to select members in. Passing no name through to provisioning lets it generate the canonical name, rather than preserving whatever order was typed. Members are also now checked in the order they were typed, stopping at the first match, so whoever puts their own name first is verified first. Verification is a deliberately slow hash comparison, so the ordering is worth having; it is only a preference, and any member's password still unlocks the group.
227 lines
8.6 KiB
C#
227 lines
8.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Jellyfin.Data;
|
|
using Jellyfin.Database.Implementations.Entities;
|
|
using Jellyfin.Database.Implementations.Enums;
|
|
using Jellyfin.Plugin.WatchedTogether.Configuration;
|
|
using MediaBrowser.Controller.Library;
|
|
using MediaBrowser.Model.Cryptography;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Jellyfin.Plugin.WatchedTogether.Services;
|
|
|
|
/// <summary>
|
|
/// Creates a shared account the first time someone logs in as "alice+bob".
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Jellyfin only routes a login to the providers with a null resolved user when <em>no</em> local
|
|
/// user matches the typed name. A real account named "alice+bob" therefore always wins, and this
|
|
/// code never sees it - the ambiguity between a group and a same-named user resolves in favour of
|
|
/// the real user automatically.
|
|
/// </para>
|
|
/// <para>
|
|
/// Every named member must exist and none may be a shared account, so an unrelated username
|
|
/// containing the separator simply fails to resolve and is rejected.
|
|
/// </para>
|
|
/// </remarks>
|
|
public class DynamicGroupService : IDynamicGroupService
|
|
{
|
|
private readonly IUserManager _userManager;
|
|
private readonly IProvisioningService _provisioningService;
|
|
private readonly ICryptoProvider _cryptoProvider;
|
|
private readonly ILogger<DynamicGroupService> _logger;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="DynamicGroupService"/> class.
|
|
/// </summary>
|
|
/// <param name="userManager">The user manager.</param>
|
|
/// <param name="provisioningService">The provisioning service.</param>
|
|
/// <param name="cryptoProvider">The crypto provider.</param>
|
|
/// <param name="logger">The logger.</param>
|
|
public DynamicGroupService(
|
|
IUserManager userManager,
|
|
IProvisioningService provisioningService,
|
|
ICryptoProvider cryptoProvider,
|
|
ILogger<DynamicGroupService> logger)
|
|
{
|
|
_userManager = userManager;
|
|
_provisioningService = provisioningService;
|
|
_cryptoProvider = cryptoProvider;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<DynamicGroupResult?> TryCreateFromLoginAsync(string enteredUsername, string password)
|
|
{
|
|
var config = Plugin.Instance?.Configuration;
|
|
if (config is null || !config.EnableDynamicGroups)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(enteredUsername))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var separator = string.IsNullOrEmpty(config.NameSeparator) ? "+" : config.NameSeparator;
|
|
|
|
var parts = enteredUsername
|
|
.Split(separator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
|
|
.ToList();
|
|
|
|
// Needs at least two names to be a group at all.
|
|
if (parts.Count < 2)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
// Every part must name a real, non-shared, enabled user. Anything else means this is not a
|
|
// group login, so fall through and let the attempt fail normally.
|
|
var members = new List<User>(parts.Count);
|
|
foreach (var part in parts)
|
|
{
|
|
var member = _userManager.GetUserByName(part);
|
|
if (member is null)
|
|
{
|
|
_logger.LogDebug("Dynamic group login rejected: no user named {Part}", part);
|
|
return null;
|
|
}
|
|
|
|
if (config.Groups.Any(g => g.SharedUserId == member.Id))
|
|
{
|
|
_logger.LogWarning(
|
|
"Dynamic group login rejected: {Part} is itself a shared account",
|
|
part);
|
|
return null;
|
|
}
|
|
|
|
if (member.HasPermission(PermissionKind.IsDisabled))
|
|
{
|
|
_logger.LogWarning("Dynamic group login rejected: {Part} is disabled", part);
|
|
return null;
|
|
}
|
|
|
|
if (members.Any(m => m.Id == member.Id))
|
|
{
|
|
_logger.LogWarning("Dynamic group login rejected: {Part} named more than once", part);
|
|
return null;
|
|
}
|
|
|
|
members.Add(member);
|
|
}
|
|
|
|
// The password must belong to one of the named members. Without this any visitor could
|
|
// conjure a shared account out of two usernames they happened to know.
|
|
//
|
|
// Members are tried in the order they were typed and the loop stops at the first match, so
|
|
// whoever types their own name first has their password checked first. Verification is a
|
|
// deliberately slow hash comparison, so the ordering is worth having.
|
|
var matched = members.FirstOrDefault(m => VerifyPassword(m, password));
|
|
if (matched is null)
|
|
{
|
|
_logger.LogWarning(
|
|
"Dynamic group login for {Username} rejected: no named member's password matched",
|
|
enteredUsername);
|
|
return null;
|
|
}
|
|
|
|
var memberIds = members.Select(m => m.Id).ToList();
|
|
|
|
// The same people in a different order are the same group: someone typing "john+jane" must
|
|
// land on the existing "jane+john" account rather than creating a second one. Jellyfin only
|
|
// reaches this code when no account matches the typed name, so without this check every
|
|
// ordering would spawn its own account.
|
|
var existing = FindGroupWithSameMembers(config, memberIds);
|
|
if (existing is not null)
|
|
{
|
|
if (existing.IsDisabled)
|
|
{
|
|
_logger.LogWarning(
|
|
"Login for {Username} rejected: the matching group is disabled",
|
|
enteredUsername);
|
|
return null;
|
|
}
|
|
|
|
var existingUser = _userManager.GetUserById(existing.SharedUserId);
|
|
if (existingUser is null)
|
|
{
|
|
_logger.LogWarning(
|
|
"Group for {Username} references a shared account that no longer exists",
|
|
enteredUsername);
|
|
return null;
|
|
}
|
|
|
|
_logger.LogInformation(
|
|
"Login as {Entered} resolved to the existing shared account {Username}",
|
|
enteredUsername,
|
|
existingUser.Username);
|
|
|
|
return new DynamicGroupResult(existing, existingUser.Username);
|
|
}
|
|
|
|
// Passing no name lets provisioning generate the canonical alphabetically-sorted one, so
|
|
// the account is named the same whichever order the members were typed in.
|
|
// The account is limited to the libraries all named members share, so creating one at the
|
|
// login screen cannot grant anybody access they did not already have.
|
|
var group = await _provisioningService.CreateGroupAsync(memberIds, null).ConfigureAwait(false);
|
|
|
|
var sharedUser = _userManager.GetUserById(group.SharedUserId);
|
|
if (sharedUser is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
_logger.LogInformation(
|
|
"Created shared account {Username} on demand for {MemberCount} members",
|
|
sharedUser.Username,
|
|
members.Count);
|
|
|
|
return new DynamicGroupResult(group, sharedUser.Username);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Finds a configured group whose members are exactly the given set, ignoring order.
|
|
/// </summary>
|
|
/// <param name="config">The plugin configuration to search.</param>
|
|
/// <param name="memberIds">The member identifiers to match.</param>
|
|
/// <returns>The matching group, or <c>null</c> if no group has that membership.</returns>
|
|
private static SharedGroup? FindGroupWithSameMembers(
|
|
PluginConfiguration config,
|
|
IReadOnlyList<Guid> memberIds)
|
|
{
|
|
var wanted = memberIds.ToHashSet();
|
|
|
|
return config.Groups.FirstOrDefault(g =>
|
|
g.MemberUserIds.Count == wanted.Count && wanted.SetEquals(g.MemberUserIds));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifies a submitted password against a member's live stored hash.
|
|
/// </summary>
|
|
/// <param name="member">The member to check.</param>
|
|
/// <param name="password">The submitted password.</param>
|
|
/// <returns><c>true</c> if the password matches.</returns>
|
|
private bool VerifyPassword(User member, string password)
|
|
{
|
|
if (string.IsNullOrEmpty(member.Password))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
return _cryptoProvider.Verify(PasswordHash.Parse(member.Password), password);
|
|
}
|
|
catch (Exception ex) when (ex is FormatException or ArgumentException)
|
|
{
|
|
// Never log the hash or the submitted password.
|
|
_logger.LogError(ex, "Could not parse the stored password hash for member {MemberId}", member.Id);
|
|
return false;
|
|
}
|
|
}
|
|
}
|