Files
ersatztv/ErsatzTV.Tests/Controllers/JellyfinMediaSourcesControllerTests.cs
T
timothyandClaude Opus 4.8 c617a01e83 feat(api): add Jellyfin/Emby media-source write API (#202 slice S3)
New JellyfinMediaSourcesController (/api/media-sources/jellyfin, J1-J9) and
EmbyMediaSourcesController (/api/media-sources/emby, E1-E9), wrapping the
existing Jellyfin/Emby MediatR commands per the #202 design doc §A.3/§A.4.

Secure connection contract (§C3/§B, finding 1): the connection GET returns
only { address, hasApiKey } — the API key never crosses the wire. The PUT
retains the existing key when the incoming key is blank, sets a new one when
non-blank, and 422s "API key is required" on a blank first connect.

Finding 7 (lock-release discipline): DisconnectJellyfinHandler and
DisconnectEmbyHandler now wrap their work in try/finally so a throw from any
awaited dependency (repo delete, search-index commit, secret store) still
releases the family lock instead of wedging every future disconnect at 409.

Findings 2c/8 (path-replacement cross-source guard): UpdateJellyfinPathReplacementsHandler
and UpdateEmbyPathReplacementsHandler now reject, before any write, an incoming
positive Id that isn't owned by the route's media source, a null item, or a
blank RemotePath/LocalPath — all 422 with no partial mutation. Defense-in-depth
repo fix: the Jellyfin/Emby path-replacement UPDATE SQL in MediaSourceRepository
now scopes by {Jellyfin,Emby}MediaSourceId (was previously unscoped by Id alone,
allowing a PUT to one source to silently overwrite another source's row). The
Plex path-replacement method (~line 397) is untouched — that's slice S2's file.

Library preferences (§C4a): the controller validates the incoming id set
against the source's known libraries (reject foreign ids, require full
coverage, no Id=0) before dispatch, then — for §C7 — LockLibrary + enqueues
the SynchronizeXLibraries/SynchronizeXLibraryByIdIfNeeded pair per enabled
library (compensating unlock if the enqueue throws), and returns the reloaded
list (ids are not stable across a disable).

404s on id-taking endpoints come from a controller pre-check (GetXMediaSourceById
is None), not a handler NotFoundError, since Either.Apply/ToEitherAsync join any
NotFoundError into a flat 422 (finding 9).

Tests: controller route/404/409/422 tests for both families; disconnect
fault-injection tests proving the lock releases even when a dependency throws;
path-replacement handler tests for cross-source-id/blank/null-item rejection
and correct add/update/delete merge; a repository-level test proving the SQL
fix stops a same-family cross-source path-replacement overwrite.

No new commands, no DB migration, no OpenAPI regen (gated until S1-S3 merge
per the design doc's build-slice plan).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 15:47:42 +02:00

427 lines
19 KiB
C#

using System.Reflection;
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.Jellyfin;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.MediaSources;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Locking;
using ErsatzTV.Core.Jellyfin;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using static LanguageExt.Prelude;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class JellyfinMediaSourcesControllerTests
{
private IMediator _mediator = null!;
private IEntityLocker _entityLocker = null!;
private Channel<IScannerBackgroundServiceRequest> _scannerChannel = null!;
private JellyfinMediaSourcesController _controller = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_entityLocker = Substitute.For<IEntityLocker>();
_scannerChannel = System.Threading.Channels.Channel.CreateUnbounded<IScannerBackgroundServiceRequest>();
_controller = new JellyfinMediaSourcesController(_mediator, _entityLocker, _scannerChannel.Writer);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Routes()
{
ShouldHaveActionRoute(nameof(JellyfinMediaSourcesController.GetState), "GET", "/api/media-sources/jellyfin");
ShouldHaveActionRoute(
nameof(JellyfinMediaSourcesController.GetConnection),
"GET",
"/api/media-sources/jellyfin/connection");
ShouldHaveActionRoute(
nameof(JellyfinMediaSourcesController.SaveConnection),
"PUT",
"/api/media-sources/jellyfin/connection");
ShouldHaveActionRoute(
nameof(JellyfinMediaSourcesController.Disconnect),
"POST",
"/api/media-sources/jellyfin/disconnect");
ShouldHaveActionRoute(
nameof(JellyfinMediaSourcesController.GetLibraries),
"GET",
"/api/media-sources/jellyfin/{id:int}/libraries");
ShouldHaveActionRoute(
nameof(JellyfinMediaSourcesController.ReplaceLibraryPreferences),
"PUT",
"/api/media-sources/jellyfin/{id:int}/libraries");
ShouldHaveActionRoute(
nameof(JellyfinMediaSourcesController.GetPathReplacements),
"GET",
"/api/media-sources/jellyfin/{id:int}/path-replacements");
ShouldHaveActionRoute(
nameof(JellyfinMediaSourcesController.ReplacePathReplacements),
"PUT",
"/api/media-sources/jellyfin/{id:int}/path-replacements");
ShouldHaveActionRoute(
nameof(JellyfinMediaSourcesController.RefreshLibraries),
"POST",
"/api/media-sources/jellyfin/{id:int}/refresh-libraries");
}
[Test]
public async Task GetState_Should_Report_Authorized_And_Locked()
{
_mediator.Send(Arg.Any<GetAllJellyfinMediaSources>(), Arg.Any<CancellationToken>())
.Returns([new JellyfinMediaSourceViewModel(1, "My Server", "http://jf.local")]);
_mediator.Send(Arg.Any<GetJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(new JellyfinSecrets { Address = "http://jf.local", ApiKey = "secret" });
_entityLocker.IsRemoteMediaSourceLocked<JellyfinMediaSource>().Returns(true);
RemoteMediaSourceStateResponseModel result = await _controller.GetState(CancellationToken.None);
result.IsAuthorized.ShouldBeTrue();
result.IsLocked.ShouldBeTrue();
result.Servers.ShouldBe([new RemoteMediaSourceItemResponseModel(1, "My Server", "http://jf.local")]);
}
[Test]
public async Task GetState_Should_Report_Unauthorized_When_ApiKey_Blank()
{
_mediator.Send(Arg.Any<GetAllJellyfinMediaSources>(), Arg.Any<CancellationToken>())
.Returns(new List<JellyfinMediaSourceViewModel>());
_mediator.Send(Arg.Any<GetJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(new JellyfinSecrets { Address = "http://jf.local", ApiKey = "" });
RemoteMediaSourceStateResponseModel result = await _controller.GetState(CancellationToken.None);
result.IsAuthorized.ShouldBeFalse();
}
[Test]
public async Task GetConnection_Should_Never_Return_The_Api_Key()
{
_mediator.Send(Arg.Any<GetJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(new JellyfinSecrets { Address = "http://jf.local", ApiKey = "super-secret" });
RemoteConnectionResponseModel result = await _controller.GetConnection(CancellationToken.None);
result.Address.ShouldBe("http://jf.local");
result.HasApiKey.ShouldBeTrue();
result.ToString().ShouldNotContain("super-secret");
}
[Test]
public async Task GetConnection_Should_Report_No_Key_When_Not_Configured()
{
_mediator.Send(Arg.Any<GetJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(new JellyfinSecrets { Address = "", ApiKey = "" });
RemoteConnectionResponseModel result = await _controller.GetConnection(CancellationToken.None);
result.HasApiKey.ShouldBeFalse();
}
[Test]
public async Task SaveConnection_Should_Return_409_When_Locked()
{
_entityLocker.IsRemoteMediaSourceLocked<JellyfinMediaSource>().Returns(true);
IActionResult result = await _controller.SaveConnection(
new SaveRemoteConnectionRequest("http://jf.local", "key"),
CancellationToken.None);
result.ShouldBeOfType<ConflictObjectResult>().StatusCode.ShouldBe(409);
await _mediator.DidNotReceive().Send(Arg.Any<SaveJellyfinSecrets>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task SaveConnection_Should_Return_422_For_Non_Absolute_Address()
{
IActionResult result = await _controller.SaveConnection(
new SaveRemoteConnectionRequest("not-a-uri", "key"),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>().StatusCode.ShouldBe(422);
await _mediator.DidNotReceive().Send(Arg.Any<SaveJellyfinSecrets>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task SaveConnection_Should_Return_422_When_Key_Blank_On_First_Connect()
{
_mediator.Send(Arg.Any<GetJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(new JellyfinSecrets { Address = "", ApiKey = "" });
IActionResult result = await _controller.SaveConnection(
new SaveRemoteConnectionRequest("http://jf.local", ""),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>().StatusCode.ShouldBe(422);
await _mediator.DidNotReceive().Send(Arg.Any<SaveJellyfinSecrets>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task SaveConnection_Should_Retain_Existing_Key_When_Blank()
{
_mediator.Send(Arg.Any<GetJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(
new JellyfinSecrets { Address = "http://old.local", ApiKey = "existing-key" },
new JellyfinSecrets { Address = "http://jf.local", ApiKey = "existing-key" });
_mediator.Send(Arg.Any<SaveJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.SaveConnection(
new SaveRemoteConnectionRequest("http://jf.local", " "),
CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value
.ShouldBeOfType<RemoteConnectionResponseModel>()
.HasApiKey.ShouldBeTrue();
await _mediator.Received(1).Send(
Arg.Is<SaveJellyfinSecrets>(c => c.Secrets.ApiKey == "existing-key" && c.Secrets.Address == "http://jf.local"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task SaveConnection_Should_Set_New_Key_When_NonBlank()
{
_mediator.Send(Arg.Any<GetJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(
new JellyfinSecrets { Address = "http://old.local", ApiKey = "existing-key" },
new JellyfinSecrets { Address = "http://jf.local", ApiKey = "new-key" });
_mediator.Send(Arg.Any<SaveJellyfinSecrets>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.SaveConnection(
new SaveRemoteConnectionRequest("http://jf.local", "new-key"),
CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>();
await _mediator.Received(1).Send(
Arg.Is<SaveJellyfinSecrets>(c => c.Secrets.ApiKey == "new-key"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task Disconnect_Should_Return_409_When_Lock_Fails()
{
_entityLocker.LockRemoteMediaSource<JellyfinMediaSource>().Returns(false);
IActionResult result = await _controller.Disconnect(CancellationToken.None);
result.ShouldBeOfType<ConflictObjectResult>().StatusCode.ShouldBe(409);
await _mediator.DidNotReceive().Send(Arg.Any<DisconnectJellyfin>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task Disconnect_Should_Return_204_On_Success()
{
_entityLocker.LockRemoteMediaSource<JellyfinMediaSource>().Returns(true);
_mediator.Send(Arg.Any<DisconnectJellyfin>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
IActionResult result = await _controller.Disconnect(CancellationToken.None);
result.ShouldBeOfType<NoContentResult>();
}
[Test]
public async Task GetLibraries_Should_Return_404_When_Source_Missing()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.None);
IActionResult result = await _controller.GetLibraries(99, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task ReplaceLibraryPreferences_Should_Return_422_For_Foreign_Id()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.Some(new JellyfinMediaSourceViewModel(1, "s", "a")));
_mediator.Send(Arg.Any<GetJellyfinLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns([new JellyfinLibraryViewModel(1, "Movies", LibraryMediaKind.Movies, true, 1)]);
IActionResult result = await _controller.ReplaceLibraryPreferences(
1,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(999, true)]),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>().StatusCode.ShouldBe(422);
await _mediator.DidNotReceive().Send(Arg.Any<UpdateJellyfinLibraryPreferences>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task ReplaceLibraryPreferences_Should_Return_422_When_Not_Covering_All_Libraries()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.Some(new JellyfinMediaSourceViewModel(1, "s", "a")));
_mediator.Send(Arg.Any<GetJellyfinLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(
[
new JellyfinLibraryViewModel(1, "Movies", LibraryMediaKind.Movies, true, 1),
new JellyfinLibraryViewModel(2, "Shows", LibraryMediaKind.Shows, true, 1)
]);
IActionResult result = await _controller.ReplaceLibraryPreferences(
1,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(1, true)]),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>().StatusCode.ShouldBe(422);
}
[Test]
public async Task ReplaceLibraryPreferences_Should_Enqueue_Sync_Pair_For_Enabled_Libraries_And_Return_Reloaded()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.Some(new JellyfinMediaSourceViewModel(1, "s", "a")));
_mediator.Send(Arg.Any<GetJellyfinLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(
[new JellyfinLibraryViewModel(1, "Movies", LibraryMediaKind.Movies, true, 1)],
[new JellyfinLibraryViewModel(1, "Movies", LibraryMediaKind.Movies, true, 1)]);
_mediator.Send(Arg.Any<UpdateJellyfinLibraryPreferences>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
_entityLocker.LockLibrary(1).Returns(true);
IActionResult result = await _controller.ReplaceLibraryPreferences(
1,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(1, true)]),
CancellationToken.None);
result.ShouldBeOfType<OkObjectResult>().Value
.ShouldBeOfType<List<RemoteLibraryResponseModel>>()
.Single().Id.ShouldBe(1);
_scannerChannel.Reader.TryRead(out IScannerBackgroundServiceRequest? first).ShouldBeTrue();
first.ShouldBeOfType<SynchronizeJellyfinLibraries>().JellyfinMediaSourceId.ShouldBe(1);
_scannerChannel.Reader.TryRead(out IScannerBackgroundServiceRequest? second).ShouldBeTrue();
second.ShouldBeOfType<SynchronizeJellyfinLibraryByIdIfNeeded>().JellyfinLibraryId.ShouldBe(1);
}
[Test]
public async Task ReplaceLibraryPreferences_Should_Skip_Enqueue_When_Library_Locked()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.Some(new JellyfinMediaSourceViewModel(1, "s", "a")));
_mediator.Send(Arg.Any<GetJellyfinLibrariesBySourceId>(), Arg.Any<CancellationToken>())
.Returns(
[new JellyfinLibraryViewModel(1, "Movies", LibraryMediaKind.Movies, true, 1)],
[new JellyfinLibraryViewModel(1, "Movies", LibraryMediaKind.Movies, true, 1)]);
_mediator.Send(Arg.Any<UpdateJellyfinLibraryPreferences>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
_entityLocker.LockLibrary(1).Returns(false);
await _controller.ReplaceLibraryPreferences(
1,
new ReplaceRemoteLibraryPreferencesRequest([new RemoteLibraryPreferenceRequest(1, true)]),
CancellationToken.None);
_scannerChannel.Reader.TryRead(out _).ShouldBeFalse();
}
[Test]
public async Task GetPathReplacements_Should_Return_404_When_Source_Missing()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.None);
IActionResult result = await _controller.GetPathReplacements(99, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task ReplacePathReplacements_Should_Return_200_With_Reloaded_List()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.Some(new JellyfinMediaSourceViewModel(1, "s", "a")));
_mediator.Send(Arg.Any<UpdateJellyfinPathReplacements>(), Arg.Any<CancellationToken>())
.Returns(Right<BaseError, Unit>(Unit.Default));
_mediator.Send(Arg.Any<GetJellyfinPathReplacementsBySourceId>(), Arg.Any<CancellationToken>())
.Returns([new JellyfinPathReplacementViewModel(1, "/jellyfin", "/local")]);
IActionResult result = await _controller.ReplacePathReplacements(
1,
new ReplacePathReplacementsRequest([new PathReplacementItemRequest(1, "/jellyfin", "/local")]),
CancellationToken.None);
List<PathReplacementResponseModel> body = result.ShouldBeOfType<OkObjectResult>().Value
.ShouldBeOfType<List<PathReplacementResponseModel>>();
body.Single().ShouldBe(new PathReplacementResponseModel(1, "/jellyfin", "/local"));
}
[Test]
public async Task ReplacePathReplacements_Should_Map_Handler_Error_To_422()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.Some(new JellyfinMediaSourceViewModel(1, "s", "a")));
_mediator.Send(Arg.Any<UpdateJellyfinPathReplacements>(), Arg.Any<CancellationToken>())
.Returns(Left<BaseError, Unit>(BaseError.New("bad row")));
IActionResult result = await _controller.ReplacePathReplacements(
1,
new ReplacePathReplacementsRequest([new PathReplacementItemRequest(999, "", "")]),
CancellationToken.None);
result.ShouldBeOfType<UnprocessableEntityObjectResult>().StatusCode.ShouldBe(422);
}
[Test]
public async Task RefreshLibraries_Should_Return_404_When_Source_Missing()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.None);
IActionResult result = await _controller.RefreshLibraries(99, CancellationToken.None);
result.ShouldBeOfType<NotFoundObjectResult>();
}
[Test]
public async Task RefreshLibraries_Should_Return_409_When_Locked()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.Some(new JellyfinMediaSourceViewModel(1, "s", "a")));
_entityLocker.IsRemoteMediaSourceLocked<JellyfinMediaSource>().Returns(true);
IActionResult result = await _controller.RefreshLibraries(1, CancellationToken.None);
result.ShouldBeOfType<ConflictObjectResult>().StatusCode.ShouldBe(409);
}
[Test]
public async Task RefreshLibraries_Should_Enqueue_And_Return_202()
{
_mediator.Send(Arg.Any<GetJellyfinMediaSourceById>(), Arg.Any<CancellationToken>())
.Returns(Option<JellyfinMediaSourceViewModel>.Some(new JellyfinMediaSourceViewModel(1, "s", "a")));
_entityLocker.IsRemoteMediaSourceLocked<JellyfinMediaSource>().Returns(false);
IActionResult result = await _controller.RefreshLibraries(1, CancellationToken.None);
result.ShouldBeOfType<AcceptedResult>();
_scannerChannel.Reader.TryRead(out IScannerBackgroundServiceRequest? request).ShouldBeTrue();
request.ShouldBeOfType<SynchronizeJellyfinLibraries>().JellyfinMediaSourceId.ShouldBe(1);
}
private static void ShouldHaveActionRoute(string actionName, string httpMethod, string route)
{
MethodInfo action = typeof(JellyfinMediaSourcesController).GetMethod(actionName)
?? throw new AssertionException($"Missing action {actionName}");
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
attribute.HttpMethods.ShouldContain(httpMethod);
attribute.Template.ShouldBe(route);
}
}