Files
ersatztv/ErsatzTV.Tests/Application/Jellyfin/UpdateJellyfinPathReplacementsHandlerTests.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

137 lines
5.4 KiB
C#

using ErsatzTV.Application.Jellyfin;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using LanguageExt;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Unit = LanguageExt.Unit;
namespace ErsatzTV.Tests.Application.Jellyfin;
[TestFixture]
public class UpdateJellyfinPathReplacementsHandlerTests
{
private IMediaSourceRepository _mediaSourceRepository = null!;
private UpdateJellyfinPathReplacementsHandler _handler = null!;
[SetUp]
public void SetUp()
{
_mediaSourceRepository = Substitute.For<IMediaSourceRepository>();
_handler = new UpdateJellyfinPathReplacementsHandler(_mediaSourceRepository);
}
[Test]
public async Task Handle_Should_Return_422_When_Source_Does_Not_Exist()
{
_mediaSourceRepository.GetJellyfin(99).Returns(Option<JellyfinMediaSource>.None);
Either<BaseError, Unit> result = await _handler.Handle(
new UpdateJellyfinPathReplacements(99, [new JellyfinPathReplacementItem(0, "/jf", "/local")]),
CancellationToken.None);
result.IsLeft.ShouldBeTrue();
await _mediaSourceRepository.DidNotReceive().UpdatePathReplacements(
Arg.Any<int>(),
Arg.Any<List<JellyfinPathReplacement>>(),
Arg.Any<List<JellyfinPathReplacement>>(),
Arg.Any<List<JellyfinPathReplacement>>());
}
[Test]
public async Task Handle_Should_Return_422_For_Cross_Source_Id_And_Perform_No_Mutation()
{
var source = new JellyfinMediaSource
{
Id = 1,
PathReplacements = [new JellyfinPathReplacement { Id = 1, JellyfinPath = "/jf1", LocalPath = "/l1" }]
};
_mediaSourceRepository.GetJellyfin(1).Returns(Option<JellyfinMediaSource>.Some(source));
// id 999 belongs to some other source, not this one
Either<BaseError, Unit> result = await _handler.Handle(
new UpdateJellyfinPathReplacements(1, [new JellyfinPathReplacementItem(999, "/jf", "/local")]),
CancellationToken.None);
result.IsLeft.ShouldBeTrue();
await _mediaSourceRepository.DidNotReceive().UpdatePathReplacements(
Arg.Any<int>(),
Arg.Any<List<JellyfinPathReplacement>>(),
Arg.Any<List<JellyfinPathReplacement>>(),
Arg.Any<List<JellyfinPathReplacement>>());
}
[TestCase("", "/local")]
[TestCase("/jf", "")]
[TestCase(" ", " ")]
public async Task Handle_Should_Return_422_For_Blank_Paths(string jellyfinPath, string localPath)
{
var source = new JellyfinMediaSource { Id = 1, PathReplacements = [] };
_mediaSourceRepository.GetJellyfin(1).Returns(Option<JellyfinMediaSource>.Some(source));
Either<BaseError, Unit> result = await _handler.Handle(
new UpdateJellyfinPathReplacements(1, [new JellyfinPathReplacementItem(0, jellyfinPath, localPath)]),
CancellationToken.None);
result.IsLeft.ShouldBeTrue();
await _mediaSourceRepository.DidNotReceive().UpdatePathReplacements(
Arg.Any<int>(),
Arg.Any<List<JellyfinPathReplacement>>(),
Arg.Any<List<JellyfinPathReplacement>>(),
Arg.Any<List<JellyfinPathReplacement>>());
}
[Test]
public async Task Handle_Should_Return_422_For_Null_Items_List_Defense()
{
var source = new JellyfinMediaSource { Id = 1, PathReplacements = [] };
_mediaSourceRepository.GetJellyfin(1).Returns(Option<JellyfinMediaSource>.Some(source));
Either<BaseError, Unit> result = await _handler.Handle(
new UpdateJellyfinPathReplacements(1, [null!]),
CancellationToken.None);
result.IsLeft.ShouldBeTrue();
}
[Test]
public async Task Handle_Should_Merge_Add_Update_Delete_On_Valid_Request()
{
var source = new JellyfinMediaSource
{
Id = 1,
PathReplacements =
[
new JellyfinPathReplacement { Id = 1, JellyfinPath = "/old", LocalPath = "/old-local" },
new JellyfinPathReplacement { Id = 2, JellyfinPath = "/gone", LocalPath = "/gone-local" }
]
};
_mediaSourceRepository.GetJellyfin(1).Returns(Option<JellyfinMediaSource>.Some(source));
_mediaSourceRepository.UpdatePathReplacements(
Arg.Any<int>(),
Arg.Any<List<JellyfinPathReplacement>>(),
Arg.Any<List<JellyfinPathReplacement>>(),
Arg.Any<List<JellyfinPathReplacement>>())
.Returns(Unit.Default);
Either<BaseError, Unit> result = await _handler.Handle(
new UpdateJellyfinPathReplacements(
1,
[
new JellyfinPathReplacementItem(1, "/updated", "/updated-local"), // update
new JellyfinPathReplacementItem(0, "/new", "/new-local") // add
// id 2 is absent -> delete
]),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
await _mediaSourceRepository.Received(1).UpdatePathReplacements(
1,
Arg.Is<List<JellyfinPathReplacement>>(l => l.Count == 1 && l[0].JellyfinPath == "/new"),
Arg.Is<List<JellyfinPathReplacement>>(l => l.Count == 1 && l[0].Id == 1 && l[0].JellyfinPath == "/updated"),
Arg.Is<List<JellyfinPathReplacement>>(l => l.Count == 1 && l[0].Id == 2));
}
}