diff --git a/ErsatzTV.Application/Troubleshooting/Commands/PrepareTroubleshootingPlaybackHandler.cs b/ErsatzTV.Application/Troubleshooting/Commands/PrepareTroubleshootingPlaybackHandler.cs index b98cd1498..4bbcab92e 100644 --- a/ErsatzTV.Application/Troubleshooting/Commands/PrepareTroubleshootingPlaybackHandler.cs +++ b/ErsatzTV.Application/Troubleshooting/Commands/PrepareTroubleshootingPlaybackHandler.cs @@ -3,6 +3,7 @@ using ErsatzTV.Application.Streaming; using ErsatzTV.Core; using ErsatzTV.Core.Domain; using ErsatzTV.Core.Domain.Filler; +using ErsatzTV.Core.Errors; using ErsatzTV.Core.Extensions; using ErsatzTV.Core.FFmpeg; using ErsatzTV.Core.Interfaces.Emby; @@ -72,7 +73,7 @@ public class PrepareTroubleshootingPlaybackHandler( // already holds it (no check-then-set race, no double-owner) if (!entityLocker.LockTroubleshootingPlayback()) { - return BaseError.New("Troubleshooting playback is locked"); + return new LockedError("Troubleshooting playback is locked"); } lockAcquired = true; @@ -143,7 +144,7 @@ public class PrepareTroubleshootingPlaybackHandler( // report the conflict. Ownership is tracked so the catch never cross-releases. if (!entityLocker.LockTroubleshootingPlayback()) { - return BaseError.New("Troubleshooting playback is locked"); + return new LockedError("Troubleshooting playback is locked"); } lockAcquired = true; diff --git a/ErsatzTV.Core/Api/Troubleshooting/TroubleshootingPlaybackStartedResponseModel.cs b/ErsatzTV.Core/Api/Troubleshooting/TroubleshootingPlaybackStartedResponseModel.cs new file mode 100644 index 000000000..f7f13c413 --- /dev/null +++ b/ErsatzTV.Core/Api/Troubleshooting/TroubleshootingPlaybackStartedResponseModel.cs @@ -0,0 +1,6 @@ +#nullable enable +namespace ErsatzTV.Core.Api.Troubleshooting; + +// Returned once a troubleshooting playback session has started producing segments; Url is the +// rooted /iptv path the SPA feeds straight to hls.js (HlsPlayer never inspects the status code). +public record TroubleshootingPlaybackStartedResponseModel(string Url); diff --git a/ErsatzTV.Core/Errors/LockedError.cs b/ErsatzTV.Core/Errors/LockedError.cs new file mode 100644 index 000000000..6765df728 --- /dev/null +++ b/ErsatzTV.Core/Errors/LockedError.cs @@ -0,0 +1,13 @@ +namespace ErsatzTV.Core.Errors; + +/// +/// A raised when a mutation races another operation that already holds an +/// exclusive lock (e.g. a troubleshooting playback session in flight). REST endpoints map this to +/// HTTP 409 Conflict, distinguishing it from the generic 422 other values get. +/// +public class LockedError : BaseError +{ + public LockedError(string value) : base(value) + { + } +} diff --git a/ErsatzTV.Tests/Application/Troubleshooting/PrepareTroubleshootingPlaybackHandlerTests.cs b/ErsatzTV.Tests/Application/Troubleshooting/PrepareTroubleshootingPlaybackHandlerTests.cs index 7079901a2..68e1febb8 100644 --- a/ErsatzTV.Tests/Application/Troubleshooting/PrepareTroubleshootingPlaybackHandlerTests.cs +++ b/ErsatzTV.Tests/Application/Troubleshooting/PrepareTroubleshootingPlaybackHandlerTests.cs @@ -2,6 +2,7 @@ using System.IO.Abstractions; using ErsatzTV.Application.Troubleshooting; using ErsatzTV.Core; using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Errors; using ErsatzTV.Core.Interfaces.Emby; using ErsatzTV.Core.Interfaces.FFmpeg; using ErsatzTV.Core.Interfaces.Jellyfin; @@ -84,6 +85,43 @@ public class PrepareTroubleshootingPlaybackHandlerTests _entityLocker.Received(1).UnlockTroubleshootingPlayback(); } + [Test] + public async Task Handle_Should_Return_LockedError_When_Lock_Already_Held() + { + await SeedFFmpegConfig(); + int profileId = await SeedFFmpegProfile(); + int movieId = await SeedMovieWithMissingFile(); + + // another session already holds the troubleshooting lock + _entityLocker.LockTroubleshootingPlayback().Returns(false); + + PrepareTroubleshootingPlaybackHandler handler = CreateHandler(); + + var request = new PrepareTroubleshootingPlayback( + Guid.NewGuid(), + StreamingMode.HttpLiveStreamingSegmenter, + movieId, + ChannelId: 0, + profileId, + StreamSelector: string.Empty, + WatermarkIds: [], + GraphicsElementIds: [], + SubtitleId: null, + SeekSeconds: Option.None, + Start: Option.None); + + Either result = await handler.Handle(request, CancellationToken.None); + + result.IsLeft.ShouldBeTrue(); + foreach (BaseError error in result.LeftToSeq()) + { + error.ShouldBeOfType(); + } + + // never acquired, so never releases + _entityLocker.DidNotReceive().UnlockTroubleshootingPlayback(); + } + [Test] public async Task Handle_Should_Not_Release_Lock_It_Never_Acquired() { diff --git a/ErsatzTV.Tests/Controllers/AuthControllerTests.cs b/ErsatzTV.Tests/Controllers/AuthControllerTests.cs index 84d34c320..a669015ea 100644 --- a/ErsatzTV.Tests/Controllers/AuthControllerTests.cs +++ b/ErsatzTV.Tests/Controllers/AuthControllerTests.cs @@ -1,7 +1,9 @@ using System.Collections.Generic; +using System.Security.Claims; using ErsatzTV.Application.Auth; using ErsatzTV.Controllers.Api; using ErsatzTV.Controllers.Api.Requests; +using ErsatzTV.Services; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -23,13 +25,20 @@ public class AuthControllerTests : new Dictionary()) .Build(); + private static IApiKeyProvider ApiKeyProvider(string key = "the-machine-key") + { + var provider = Substitute.For(); + provider.ApiKey.Returns(key); + return provider; + } + [Test] public async Task Config_Reports_Setup_Not_Required_When_Env_Seed_Configured() { var mediator = Substitute.For(); mediator.Send(Arg.Any(), Arg.Any()).Returns(false); - var controller = new AuthController(mediator, Config(envSeed: true)); + var controller = new AuthController(mediator, Config(envSeed: true), ApiKeyProvider()); var result = await controller.Config(CancellationToken.None) as OkObjectResult; var body = result!.Value.ShouldBeOfType(); @@ -44,7 +53,7 @@ public class AuthControllerTests var mediator = Substitute.For(); mediator.Send(Arg.Any(), Arg.Any()).Returns(false); - var controller = new AuthController(mediator, Config(envSeed: false)); + var controller = new AuthController(mediator, Config(envSeed: false), ApiKeyProvider()); var result = await controller.Config(CancellationToken.None) as OkObjectResult; var body = result!.Value.ShouldBeOfType(); @@ -56,7 +65,7 @@ public class AuthControllerTests public async Task Setup_Is_Closed_With_409_When_Env_Seed_Configured() { var mediator = Substitute.For(); - var controller = new AuthController(mediator, Config(envSeed: true)) + var controller = new AuthController(mediator, Config(envSeed: true), ApiKeyProvider()) { ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } }; @@ -68,4 +77,61 @@ public class AuthControllerTests // The claim must never be attempted while the env seed owns the credential. await mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); } + + [Test] + public void MachineKey_Returns_401_When_Anonymous() + { + var mediator = Substitute.For(); + var controller = new AuthController(mediator, Config(envSeed: false), ApiKeyProvider()) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } + }; + + IActionResult result = controller.MachineKey(); + + var unauthorized = result.ShouldBeOfType(); + unauthorized.Value.ShouldBeOfType().Status.ShouldBe(401); + } + + [Test] + public void MachineKey_Returns_The_Key_For_An_Authenticated_Session() + { + var mediator = Substitute.For(); + var controller = new AuthController(mediator, Config(envSeed: false), ApiKeyProvider("the-machine-key")) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext + { + User = new ClaimsPrincipal( + new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], AuthConstants.CookieScheme)) + } + } + }; + + IActionResult result = controller.MachineKey(); + + var ok = result.ShouldBeOfType(); + ok.Value.ShouldBeOfType().ApiKey.ShouldBe("the-machine-key"); + } + + [Test] + public void MachineKey_Sets_CacheControl_NoStore_For_An_Authenticated_Session() + { + var mediator = Substitute.For(); + var httpContext = new DefaultHttpContext + { + User = new ClaimsPrincipal( + new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], AuthConstants.CookieScheme)) + }; + var controller = new AuthController(mediator, Config(envSeed: false), ApiKeyProvider("the-machine-key")) + { + ControllerContext = new ControllerContext { HttpContext = httpContext } + }; + + controller.MachineKey(); + + httpContext.Response.Headers.CacheControl.ToString().ShouldBe("no-store"); + httpContext.Response.Headers.Pragma.ToString().ShouldBe("no-cache"); + } } diff --git a/ErsatzTV.Tests/Controllers/GraphicsElementControllerTests.cs b/ErsatzTV.Tests/Controllers/GraphicsElementControllerTests.cs index 55bdff023..5dfcc6297 100644 --- a/ErsatzTV.Tests/Controllers/GraphicsElementControllerTests.cs +++ b/ErsatzTV.Tests/Controllers/GraphicsElementControllerTests.cs @@ -3,6 +3,7 @@ using ErsatzTV.Application.Graphics; using ErsatzTV.Controllers.Api; using ErsatzTV.Core.Api.Graphics; using MediatR; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; using NSubstitute; using NUnit.Framework; @@ -24,7 +25,7 @@ public class GraphicsElementControllerTests } [Test] - public void Controller_Should_Expose_Idiomatic_Rest_Route() + public void Controller_Should_Expose_Idiomatic_Rest_Route_For_GetAll() { MethodInfo action = typeof(GraphicsElementController).GetMethod(nameof(GraphicsElementController.GetAll)) ?? throw new AssertionException("Missing action GetAll"); @@ -34,6 +35,17 @@ public class GraphicsElementControllerTests attribute.Template.ShouldBe("/api/graphics-elements"); } + [Test] + public void Controller_Should_Expose_Idiomatic_Rest_Route_For_Refresh() + { + MethodInfo action = typeof(GraphicsElementController).GetMethod(nameof(GraphicsElementController.Refresh)) + ?? throw new AssertionException("Missing action Refresh"); + + HttpMethodAttribute attribute = action.GetCustomAttributes(inherit: true).Single(); + attribute.HttpMethods.ShouldContain("POST"); + attribute.Template.ShouldBe("/api/graphics-elements/refresh"); + } + [Test] public async Task GetAll_Should_Return_GraphicsElements() { @@ -45,7 +57,7 @@ public class GraphicsElementControllerTests _mediator.Send(Arg.Any(), Arg.Any()) .Returns(models); - List result = await _controller.GetAll(refresh: false, CancellationToken.None); + List result = await _controller.GetAll(CancellationToken.None); result.ShouldBe(models); } @@ -56,34 +68,29 @@ public class GraphicsElementControllerTests _mediator.Send(Arg.Any(), Arg.Any()) .Returns([]); - List result = await _controller.GetAll(refresh: false, CancellationToken.None); + List result = await _controller.GetAll(CancellationToken.None); result.ShouldBeEmpty(); } [Test] - public async Task GetAll_Should_Not_Refresh_When_Refresh_Is_False() + public async Task GetAll_Should_Never_Trigger_A_Refresh() { + // the GET must be a pure read (CSRF vector when it wrote to the DB — ersatztv#316 review) _mediator.Send(Arg.Any(), Arg.Any()) .Returns([]); - await _controller.GetAll(refresh: false, CancellationToken.None); + await _controller.GetAll(CancellationToken.None); await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); } [Test] - public async Task GetAll_Should_Refresh_Before_Listing_When_Refresh_Is_True() + public async Task Refresh_Should_Send_RefreshGraphicsElements_And_Return_204() { - _mediator.Send(Arg.Any(), Arg.Any()) - .Returns([]); + IActionResult result = await _controller.Refresh(CancellationToken.None); - await _controller.GetAll(refresh: true, CancellationToken.None); - - Received.InOrder(() => - { - _mediator.Send(Arg.Any(), Arg.Any()); - _mediator.Send(Arg.Any(), Arg.Any()); - }); + result.ShouldBeOfType(); + await _mediator.Received(1).Send(Arg.Any(), Arg.Any()); } } diff --git a/ErsatzTV.Tests/Controllers/OpenApiContractHonestyTests.cs b/ErsatzTV.Tests/Controllers/OpenApiContractHonestyTests.cs index da94713c7..124e5ecea 100644 --- a/ErsatzTV.Tests/Controllers/OpenApiContractHonestyTests.cs +++ b/ErsatzTV.Tests/Controllers/OpenApiContractHonestyTests.cs @@ -72,34 +72,37 @@ public class OpenApiContractHonestyTests } [Test] - public void Colliding_Troubleshoot_HeadGet_Pairs_Should_Carry_VerbDerived_OperationIds() + public void Troubleshoot_Playback_Actions_Should_Carry_Stable_Explicit_OperationIds() { - // The 3 Troubleshoot HEAD/GET pairs share a controller+action and differ only by verb. Their - // synthesized operationIds must be verb-suffixed (structural, order-independent) — NOT one bare - // base + one arbitrary suffix that depends on ApiExplorer visitation order. See #197 Bundle C. + // #301 POST-ified these three side-effecting actions (each now a single POST with an explicit + // Name=), which removed the former HEAD/GET collision entirely — so the synthesized verb-suffix + // disambiguation (#197 Bundle C) no longer applies to them. Pin the explicit ids instead, and + // assert the old synthesized/colliding forms are gone. var ids = EnumerateOperations().Select(op => op.Operation.OperationId!).ToHashSet(StringComparer.Ordinal); foreach (string expected in new[] { - "TroubleshootTroubleshootPlaybackGet", - "TroubleshootTroubleshootPlaybackHead", - "TroubleshootTroubleshootPlaybackArchiveGet", - "TroubleshootTroubleshootPlaybackArchiveHead", - "TroubleshootTroubleshootPlaybackSampleGet", - "TroubleshootTroubleshootPlaybackSampleHead" + "StartTroubleshootingPlayback", + "DownloadTroubleshootingArchive", + "DownloadTroubleshootingMediaSample" }) { ids.ShouldContain(expected); } - // The old order-dependent forms (bare base + "...GET" suffix) must be gone. foreach (string stale in new[] { "TroubleshootTroubleshootPlayback", - "TroubleshootTroubleshootPlaybackArchive", - "TroubleshootTroubleshootPlaybackSample", + "TroubleshootTroubleshootPlaybackGet", + "TroubleshootTroubleshootPlaybackHead", "TroubleshootTroubleshootPlaybackGET", + "TroubleshootTroubleshootPlaybackArchive", + "TroubleshootTroubleshootPlaybackArchiveGet", + "TroubleshootTroubleshootPlaybackArchiveHead", "TroubleshootTroubleshootPlaybackArchiveGET", + "TroubleshootTroubleshootPlaybackSample", + "TroubleshootTroubleshootPlaybackSampleGet", + "TroubleshootTroubleshootPlaybackSampleHead", "TroubleshootTroubleshootPlaybackSampleGET" }) { diff --git a/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs b/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs index c4ea019bc..14e03d18e 100644 --- a/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs +++ b/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs @@ -270,8 +270,9 @@ public class OpenApiErrorResponseContractTests [TestCase("/api/trakt/lists/{id}", "put", "404")] [TestCase("/api/trakt/lists/{id}", "put", "422")] [TestCase("/api/troubleshoot/playback/subtitles/{mediaItemId}", "get", "404")] - [TestCase("/api/troubleshoot/playback.m3u8", "get", "409")] - [TestCase("/api/troubleshoot/playback.m3u8", "head", "409")] + [TestCase("/api/troubleshoot/playback/start", "post", "404")] + [TestCase("/api/troubleshoot/playback/start", "post", "409")] + [TestCase("/api/troubleshoot/playback/start", "post", "422")] [TestCase("/api/libraries/{id}/scan-show", "post", "404")] [TestCase("/api/libraries/{id}/scan", "post", "404")] [TestCase("/api/libraries/{id}/scan", "post", "409")] diff --git a/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs b/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs index 31d470256..4f9436ba8 100644 --- a/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs +++ b/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs @@ -20,6 +20,7 @@ using ErsatzTV.Core.Notifications; using ErsatzTV.Core.Troubleshooting; using LanguageExt; using MediatR; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using NSubstitute; using NUnit.Framework; @@ -249,22 +250,64 @@ public class TroubleshootControllerTests attribute.Name.ShouldBe("GetTroubleshootingPlaybackStatus"); } + private static StartTroubleshootingPlaybackRequest DefaultPlaybackRequest(int mediaItem = 1, int channel = 0) => + new( + mediaItem, + channel, + FfmpegProfile: 1, + StreamingMode.HttpLiveStreamingSegmenter, + Watermark: [], + GraphicsElement: [], + StreamSelector: string.Empty, + SubtitleId: null, + SeekSeconds: 0, + Start: null); + + [Test] + public void Controller_Should_Expose_Idiomatic_Rest_Route_For_TroubleshootPlayback() + { + MethodInfo action = typeof(TroubleshootController).GetMethod(nameof(TroubleshootController.TroubleshootPlayback)) + ?? throw new AssertionException("Missing action TroubleshootPlayback"); + + var attribute = action.GetCustomAttributes().Single(); + attribute.Template.ShouldBe("api/troubleshoot/playback/start"); + attribute.Name.ShouldBe("StartTroubleshootingPlayback"); + action.GetParameters()[0].ParameterType.ShouldBe(typeof(StartTroubleshootingPlaybackRequest)); + } + + [Test] + public void Controller_Should_Expose_Idiomatic_Rest_Route_For_PlaybackArchive() + { + MethodInfo action = typeof(TroubleshootController).GetMethod(nameof(TroubleshootController.TroubleshootPlaybackArchive)) + ?? throw new AssertionException("Missing action TroubleshootPlaybackArchive"); + + var attribute = action.GetCustomAttributes().Single(); + attribute.Template.ShouldBe("api/troubleshoot/playback/archive"); + attribute.Name.ShouldBe("DownloadTroubleshootingArchive"); + action.GetCustomAttributes().ShouldBeEmpty(); + action.GetCustomAttributes().ShouldBeEmpty(); + } + + [Test] + public void Controller_Should_Expose_Idiomatic_Rest_Route_For_PlaybackSample() + { + MethodInfo action = typeof(TroubleshootController).GetMethod(nameof(TroubleshootController.TroubleshootPlaybackSample)) + ?? throw new AssertionException("Missing action TroubleshootPlaybackSample"); + + var attribute = action.GetCustomAttributes().Single(); + attribute.Template.ShouldBe("api/troubleshoot/playback/sample/{mediaItemId:int}"); + attribute.Name.ShouldBe("DownloadTroubleshootingMediaSample"); + action.GetCustomAttributes().ShouldBeEmpty(); + action.GetCustomAttributes().ShouldBeEmpty(); + } + [Test] public async Task TroubleshootPlayback_Should_Return_409_When_Already_Locked() { _entityLocker.IsTroubleshootingPlaybackLocked().Returns(true); IActionResult result = await _controller.TroubleshootPlayback( - mediaItem: 1, - channel: 0, - ffmpegProfile: 1, - StreamingMode.HttpLiveStreamingSegmenter, - watermark: [], - graphicsElement: [], - streamSelector: string.Empty, - subtitleId: null, - seekSeconds: 0, - start: null, + DefaultPlaybackRequest(), CancellationToken.None); ConflictObjectResult conflict = result.ShouldBeOfType(); @@ -275,6 +318,24 @@ public class TroubleshootControllerTests .Send(Arg.Any(), Arg.Any()); } + [Test] + public async Task TroubleshootPlayback_Should_Return_409_ProblemDetails_When_Prepare_Loses_Lock_Race() + { + // pre-check passes, but the handler's atomic acquire loses the race to another session + // that grabbed the lock in between -> still a 409, not a 422 (ersatztv#316 review) + _entityLocker.IsTroubleshootingPlaybackLocked().Returns(false); + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Either.Left( + new ErsatzTV.Core.Errors.LockedError("Troubleshooting playback is locked"))); + + IActionResult result = await _controller.TroubleshootPlayback( + DefaultPlaybackRequest(), + CancellationToken.None); + + var conflict = result.ShouldBeOfType(); + conflict.Value.ShouldBeOfType().Status.ShouldBe(409); + } + [Test] public async Task TroubleshootPlayback_Should_Return_404_ProblemDetails_When_Prepare_Not_Found() { @@ -284,16 +345,7 @@ public class TroubleshootControllerTests new ErsatzTV.Core.Errors.NotFoundError("no such media item"))); IActionResult result = await _controller.TroubleshootPlayback( - mediaItem: 999, - channel: 0, - ffmpegProfile: 1, - StreamingMode.HttpLiveStreamingSegmenter, - watermark: [], - graphicsElement: [], - streamSelector: string.Empty, - subtitleId: null, - seekSeconds: 0, - start: null, + DefaultPlaybackRequest(mediaItem: 999), CancellationToken.None); var notFound = result.ShouldBeOfType(); @@ -308,22 +360,94 @@ public class TroubleshootControllerTests .Returns(Either.Left(BaseError.New("unable to prepare"))); IActionResult result = await _controller.TroubleshootPlayback( - mediaItem: 1, - channel: 0, - ffmpegProfile: 1, - StreamingMode.HttpLiveStreamingSegmenter, - watermark: [], - graphicsElement: [], - streamSelector: string.Empty, - subtitleId: null, - seekSeconds: 0, - start: null, + DefaultPlaybackRequest(), CancellationToken.None); var unprocessable = result.ShouldBeOfType(); unprocessable.Value.ShouldBeOfType().Status.ShouldBe(422); } + [Test] + public async Task TroubleshootPlayback_Should_Return_200_With_Rooted_Iptv_Url_On_Success() + { + // The segment-readiness poll shells out to the real filesystem (Directory.GetFiles), not the + // injected IFileSystem abstraction, so this test seeds real files under the troubleshooting + // transcode folder rather than mocking it. + Directory.CreateDirectory(FileSystemLayout.TranscodeTroubleshootingFolder); + string segmentPath = Path.Combine(FileSystemLayout.TranscodeTroubleshootingFolder, "seg-test-0.ts"); + string segmentPath2 = Path.Combine(FileSystemLayout.TranscodeTroubleshootingFolder, "seg-test-1.ts"); + await File.WriteAllTextAsync(segmentPath, string.Empty); + await File.WriteAllTextAsync(segmentPath2, string.Empty); + + try + { + _entityLocker.IsTroubleshootingPlaybackLocked().Returns(false); + + var playoutItemResult = new PlayoutItemResult( + new CliWrap.Command("ffmpeg"), + Option.None, + Option.Some(1)); + + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Either.Right(playoutItemResult)); + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Either.Right(FakeMediaItemInfo())); + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(new TroubleshootingInfo( + "1.2.3", + new Dictionary(), + [], + [], + [], + new ErsatzTV.Application.FFmpegProfiles.FFmpegSettingsViewModel(), + [], + [], + [], + false, + false, + null, + null, + null, + null)); + + var fileSystem = Substitute.For(); + fileSystem.File.Exists(Arg.Any()).Returns(true); + + var configElementRepository = Substitute.For(); + configElementRepository + .GetValue(ConfigElementKey.FFmpegInitialSegmentCount, Arg.Any()) + .Returns(Option.Some(2)); + + var controller = new TroubleshootController( + System.Threading.Channels.Channel.CreateUnbounded().Writer, + fileSystem, + configElementRepository, + Substitute.For(), + _entityLocker, + _statusStore, + _mediator) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext { Request = { PathBase = "/etv" } } + } + }; + + IActionResult result = await controller.TroubleshootPlayback( + DefaultPlaybackRequest(), + CancellationToken.None); + + var ok = result.ShouldBeOfType(); + var body = ok.Value.ShouldBeOfType(); + body.Url.ShouldBe("/etv/iptv/session/.troubleshooting/live.m3u8"); + } + finally + { + File.Delete(segmentPath); + File.Delete(segmentPath2); + } + } + [Test] public async Task GetPlaybackStatus_Should_Report_Idle_When_No_Result_And_Unlocked() { diff --git a/ErsatzTV.Tests/Extensions/ApiResultsTests.cs b/ErsatzTV.Tests/Extensions/ApiResultsTests.cs index 3e37238e4..fc8916dad 100644 --- a/ErsatzTV.Tests/Extensions/ApiResultsTests.cs +++ b/ErsatzTV.Tests/Extensions/ApiResultsTests.cs @@ -38,6 +38,24 @@ public class ApiResultsTests problemDetails.Detail.ShouldBe("missing"); } + [Test] + public void ToErrorResult_Should_Map_LockedError_To_409() + { + IActionResult result = new LockedError("locked").ToErrorResult(); + result.ShouldBeOfType().StatusCode.ShouldBe(409); + } + + [Test] + public void ToErrorResult_Should_Return_ProblemDetails_For_LockedError() + { + IActionResult result = new LockedError("locked").ToErrorResult(); + + var conflict = result.ShouldBeOfType(); + var problemDetails = conflict.Value.ShouldBeOfType(); + problemDetails.Status.ShouldBe(409); + problemDetails.Detail.ShouldBe("locked"); + } + [Test] public void ToErrorResult_Should_Map_Other_Error_To_422() { diff --git a/ErsatzTV/Controllers/Api/AuthController.cs b/ErsatzTV/Controllers/Api/AuthController.cs index cc633a61d..732e6d462 100644 --- a/ErsatzTV/Controllers/Api/AuthController.cs +++ b/ErsatzTV/Controllers/Api/AuthController.cs @@ -4,6 +4,7 @@ using ErsatzTV.Controllers.Api.Requests; using ErsatzTV.Core; using ErsatzTV.Extensions; using ErsatzTV.Filters; +using ErsatzTV.Services; using MediatR; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; @@ -21,7 +22,8 @@ namespace ErsatzTV.Controllers.Api; [ApiController] [ApiExplorerSettings(IgnoreApi = true)] [SkipApiAuthorization] -public class AuthController(IMediator mediator, IConfiguration configuration) : ControllerBase +public class AuthController(IMediator mediator, IConfiguration configuration, IApiKeyProvider apiKeyProvider) + : ControllerBase { // When the operator has set an env seed, the local admin is managed via configuration — the browser // setup-claim is closed. This also eliminates the startup race where an attacker could claim admin in the @@ -48,6 +50,30 @@ public class AuthController(IMediator mediator, IConfiguration configuration) : return Ok(new AuthSessionResponse(true, User.Identity?.Name, User.FindFirst(AuthConstants.AuthMethodClaim)?.Value)); } + /// + /// The effective machine X-Api-Key (issue #301), for the ChicoryTV "API Key" settings screen to + /// display once it moves off session-managed auth. Requires any authenticated session (OIDC or local); + /// 401 otherwise. Never CSRF-gated — it's a GET, and SOP already blocks a cross-site page from reading a + /// credentialed response body. + /// + [HttpGet("/api/auth/machine-key")] + public IActionResult MachineKey() + { + if (User.Identity?.IsAuthenticated != true) + { + return Unauthorized(new ProblemDetails + { + Status = StatusCodes.Status401Unauthorized, + Title = "Unauthorized", + Detail = "An authenticated session is required." + }); + } + + Response.Headers.CacheControl = "no-store"; + Response.Headers.Pragma = "no-cache"; + return Ok(new MachineKeyResponse(apiKeyProvider.ApiKey)); + } + /// First-run setup-claim: create the local admin. Fails 409 if one already exists. [HttpPost("/api/auth/setup")] [EnableRateLimiting("auth")] @@ -232,3 +258,5 @@ public class AuthController(IMediator mediator, IConfiguration configuration) : public record AuthConfigResponse(bool OidcEnabled, bool LocalLoginEnabled, bool SetupRequired); public record AuthSessionResponse(bool Authenticated, string Username, string Method); + +public record MachineKeyResponse(string ApiKey); diff --git a/ErsatzTV/Controllers/Api/GraphicsElementController.cs b/ErsatzTV/Controllers/Api/GraphicsElementController.cs index 3496d7d96..ba63df156 100644 --- a/ErsatzTV/Controllers/Api/GraphicsElementController.cs +++ b/ErsatzTV/Controllers/Api/GraphicsElementController.cs @@ -12,20 +12,23 @@ public class GraphicsElementController(IMediator mediator) : ControllerBase [HttpGet("/api/graphics-elements", Name = "GetGraphicsElements")] [Tags("Graphics Elements")] [EndpointSummary("Get all graphics elements")] - [EndpointDescription( - "Returns all graphics elements. Pass refresh=true to first re-sync the on-disk graphics element " + - "definitions into the database (matching the legacy Blazor behavior) so newly added files appear.")] + [EndpointDescription("Returns all graphics elements.")] [EndpointGroupName("general")] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - public async Task> GetAll( - [FromQuery] bool refresh, - CancellationToken cancellationToken) - { - if (refresh) - { - await mediator.Send(new RefreshGraphicsElements(), cancellationToken); - } + public async Task> GetAll(CancellationToken cancellationToken) => + await mediator.Send(new GetAllGraphicsElementsForApi(), cancellationToken); - return await mediator.Send(new GetAllGraphicsElementsForApi(), cancellationToken); + [HttpPost("/api/graphics-elements/refresh", Name = "RefreshGraphicsElements")] + [Tags("Graphics Elements")] + [EndpointSummary("Re-sync graphics elements from disk")] + [EndpointDescription( + "Re-syncs the on-disk graphics element definitions into the database (matching the legacy Blazor " + + "behavior) so newly added files appear.")] + [EndpointGroupName("general")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Refresh(CancellationToken cancellationToken) + { + await mediator.Send(new RefreshGraphicsElements(), cancellationToken); + return NoContent(); } } diff --git a/ErsatzTV/Controllers/Api/Requests/StartTroubleshootingPlaybackRequest.cs b/ErsatzTV/Controllers/Api/Requests/StartTroubleshootingPlaybackRequest.cs new file mode 100644 index 000000000..2a7374740 --- /dev/null +++ b/ErsatzTV/Controllers/Api/Requests/StartTroubleshootingPlaybackRequest.cs @@ -0,0 +1,15 @@ +using ErsatzTV.Core.Domain; + +namespace ErsatzTV.Controllers.Api.Requests; + +public record StartTroubleshootingPlaybackRequest( + int MediaItem, + int Channel, + int FfmpegProfile, + StreamingMode StreamingMode, + List Watermark, + List GraphicsElement, + string StreamSelector, + int? SubtitleId, + int SeekSeconds, + DateTimeOffset? Start); diff --git a/ErsatzTV/Controllers/Api/TroubleshootController.cs b/ErsatzTV/Controllers/Api/TroubleshootController.cs index f2b2158b0..3fadd189f 100644 --- a/ErsatzTV/Controllers/Api/TroubleshootController.cs +++ b/ErsatzTV/Controllers/Api/TroubleshootController.cs @@ -112,37 +112,30 @@ public class TroubleshootController( new ValidateSequentialScheduleResponseModel(result.IsValid, result.Messages, result.Json)); } - [HttpHead("api/troubleshoot/playback.m3u8")] - [HttpGet("api/troubleshoot/playback.m3u8")] + [HttpPost("api/troubleshoot/playback/start", Name = "StartTroubleshootingPlayback")] [Tags("Troubleshooting")] [EndpointSummary("Start a troubleshooting playback session")] [EndpointGroupName("general")] + [ProducesResponseType(typeof(TroubleshootingPlaybackStartedResponseModel), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)] public async Task TroubleshootPlayback( - [FromQuery] - int mediaItem, - [FromQuery] - int channel, - [FromQuery] - int ffmpegProfile, - [FromQuery] - StreamingMode streamingMode, - [FromQuery] - List watermark, - [FromQuery] - List graphicsElement, - [FromQuery] - string streamSelector, - [FromQuery] - int? subtitleId, - [FromQuery] - int seekSeconds, - [FromQuery] - DateTimeOffset? start, + [FromBody] + StartTroubleshootingPlaybackRequest request, CancellationToken cancellationToken) { + int mediaItem = request.MediaItem; + int channel = request.Channel; + int ffmpegProfile = request.FfmpegProfile; + StreamingMode streamingMode = request.StreamingMode; + List watermark = request.Watermark; + List graphicsElement = request.GraphicsElement; + string streamSelector = request.StreamSelector; + int? subtitleId = request.SubtitleId; + int seekSeconds = request.SeekSeconds; + DateTimeOffset? start = request.Start; + var sessionId = Guid.NewGuid(); using var logContext = LogContext.PushProperty(InMemoryLogService.CorrelationIdKey, sessionId); @@ -261,7 +254,9 @@ public class TroubleshootController( if (!notifier.IsFailed(sessionId)) { - return Redirect("~/iptv/session/.troubleshooting/live.m3u8"); + return Ok( + new TroubleshootingPlaybackStartedResponseModel( + $"{Request.PathBase}/iptv/session/.troubleshooting/live.m3u8")); } } finally @@ -292,8 +287,7 @@ public class TroubleshootController( "Troubleshooting playback did not produce any output. It may have failed to start or been cancelled."); } - [HttpHead("api/troubleshoot/playback/archive")] - [HttpGet("api/troubleshoot/playback/archive")] + [HttpPost("api/troubleshoot/playback/archive", Name = "DownloadTroubleshootingArchive")] [Tags("Troubleshooting")] [EndpointSummary("Download the last troubleshooting playback session archive")] [EndpointGroupName("general")] @@ -318,8 +312,7 @@ public class TroubleshootController( return NotFound(); } - [HttpHead("api/troubleshoot/playback/sample/{mediaItemId:int}")] - [HttpGet("api/troubleshoot/playback/sample/{mediaItemId:int}")] + [HttpPost("api/troubleshoot/playback/sample/{mediaItemId:int}", Name = "DownloadTroubleshootingMediaSample")] [Tags("Troubleshooting")] [EndpointSummary("Download a media sample archive for troubleshooting")] [EndpointGroupName("general")] @@ -357,7 +350,7 @@ public class TroubleshootController( [EndpointSummary("List selectable subtitle streams for a media item")] [EndpointDescription( "Returns the subtitle streams that can be burned in for a troubleshooting playback. Each item's id is the " + - "value to pass back as the playback.m3u8 endpoint's subtitleId query parameter.")] + "value to pass back as the POST /api/troubleshoot/playback/start request body's subtitleId field.")] [EndpointGroupName("general")] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] diff --git a/ErsatzTV/Extensions/ApiResults.cs b/ErsatzTV/Extensions/ApiResults.cs index b520e9ef5..e3d32db3f 100644 --- a/ErsatzTV/Extensions/ApiResults.cs +++ b/ErsatzTV/Extensions/ApiResults.cs @@ -18,7 +18,8 @@ public static class ApiResults /// /// Maps a failure to 404 when it is a , 412 when it is a /// (optimistic-concurrency mismatch, issue #253), - /// otherwise 422. + /// 409 when it is a (a mutation raced another operation's exclusive + /// lock), otherwise 422. /// public static IActionResult ToErrorResult(this BaseError error) => error switch @@ -30,6 +31,8 @@ public static class ApiResults { StatusCode = StatusCodes.Status412PreconditionFailed }, + LockedError => + ConflictProblem("Troubleshooting playback is locked", error.Value), _ => new UnprocessableEntityObjectResult(CreateProblemDetails(422, "Validation failed", error.Value)) }; diff --git a/ErsatzTV/wwwroot/openapi/v1.json b/ErsatzTV/wwwroot/openapi/v1.json index f6abb3756..228df4de5 100644 --- a/ErsatzTV/wwwroot/openapi/v1.json +++ b/ErsatzTV/wwwroot/openapi/v1.json @@ -7532,17 +7532,8 @@ "Graphics Elements" ], "summary": "Get all graphics elements", - "description": "Returns all graphics elements. Pass refresh=true to first re-sync the on-disk graphics element definitions into the database (matching the legacy Blazor behavior) so newly added files appear.", + "description": "Returns all graphics elements.", "operationId": "GetGraphicsElements", - "parameters": [ - { - "name": "refresh", - "in": "query", - "schema": { - "type": "boolean" - } - } - ], "responses": { "200": { "description": "OK", @@ -7582,13 +7573,31 @@ } } } + } + }, + "security": [ + { } + ] + } + }, + "/api/graphics-elements/refresh": { + "post": { + "tags": [ + "Graphics Elements" + ], + "summary": "Re-sync graphics elements from disk", + "description": "Re-syncs the on-disk graphics element definitions into the database (matching the legacy Blazor behavior) so newly added files appear.", + "operationId": "RefreshGraphicsElements", + "responses": { + "204": { + "description": "No Content" }, - "400": { - "description": "Request validation failed (model binding or FluentValidation).", + "401": { + "description": "API key missing or invalid.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ValidationProblemDetails" + "$ref": "#/components/schemas/ProblemDetails" } } } @@ -21113,278 +21122,59 @@ ] } }, - "/api/troubleshoot/playback.m3u8": { - "head": { + "/api/troubleshoot/playback/start": { + "post": { "tags": [ "Troubleshooting" ], "summary": "Start a troubleshooting playback session", - "operationId": "TroubleshootTroubleshootPlaybackHead", - "parameters": [ - { - "name": "mediaItem", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "channel", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "ffmpegProfile", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "streamingMode", - "in": "query", - "schema": { - "$ref": "#/components/schemas/StreamingMode" - } - }, - { - "name": "watermark", - "in": "query", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" + "operationId": "StartTroubleshootingPlayback", + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/StartTroubleshootingPlaybackRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/StartTroubleshootingPlaybackRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/StartTroubleshootingPlaybackRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/StartTroubleshootingPlaybackRequest" } } }, - { - "name": "graphicsElement", - "in": "query", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - } - }, - { - "name": "streamSelector", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "subtitleId", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "seekSeconds", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "start", - "in": "query", - "schema": { - "type": "string", - "format": "date-time" - } - } - ], - "responses": { - "404": { - "description": "Not Found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "409": { - "description": "Conflict", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "422": { - "description": "Unprocessable Entity", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "API key missing or invalid.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "400": { - "description": "Request validation failed (model binding or FluentValidation).", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationProblemDetails" - } - } - } - } + "required": true }, - "security": [ - { } - ] - }, - "get": { - "tags": [ - "Troubleshooting" - ], - "summary": "Start a troubleshooting playback session", - "operationId": "TroubleshootTroubleshootPlaybackGet", - "parameters": [ - { - "name": "mediaItem", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "channel", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "ffmpegProfile", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "streamingMode", - "in": "query", - "schema": { - "$ref": "#/components/schemas/StreamingMode" - } - }, - { - "name": "watermark", - "in": "query", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - } - }, - { - "name": "graphicsElement", - "in": "query", - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - } - }, - { - "name": "streamSelector", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "subtitleId", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "seekSeconds", - "in": "query", - "schema": { - "type": "integer", - "format": "int32" - } - }, - { - "name": "start", - "in": "query", - "schema": { - "type": "string", - "format": "date-time" - } - } - ], "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/TroubleshootingPlaybackStartedResponseModel" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/TroubleshootingPlaybackStartedResponseModel" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/TroubleshootingPlaybackStartedResponseModel" + } + } + } + }, "404": { "description": "Not Found", "content": { @@ -21472,37 +21262,12 @@ } }, "/api/troubleshoot/playback/archive": { - "head": { + "post": { "tags": [ "Troubleshooting" ], "summary": "Download the last troubleshooting playback session archive", - "operationId": "TroubleshootTroubleshootPlaybackArchiveHead", - "responses": { - "200": { - "description": "OK" - }, - "401": { - "description": "API key missing or invalid.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - } - }, - "security": [ - { } - ] - }, - "get": { - "tags": [ - "Troubleshooting" - ], - "summary": "Download the last troubleshooting playback session archive", - "operationId": "TroubleshootTroubleshootPlaybackArchiveGet", + "operationId": "DownloadTroubleshootingArchive", "responses": { "200": { "description": "OK" @@ -21524,58 +21289,12 @@ } }, "/api/troubleshoot/playback/sample/{mediaItemId}": { - "head": { + "post": { "tags": [ "Troubleshooting" ], "summary": "Download a media sample archive for troubleshooting", - "operationId": "TroubleshootTroubleshootPlaybackSampleHead", - "parameters": [ - { - "name": "mediaItemId", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "format": "int32" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "401": { - "description": "API key missing or invalid.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "400": { - "description": "Request validation failed (model binding or FluentValidation).", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationProblemDetails" - } - } - } - } - }, - "security": [ - { } - ] - }, - "get": { - "tags": [ - "Troubleshooting" - ], - "summary": "Download a media sample archive for troubleshooting", - "operationId": "TroubleshootTroubleshootPlaybackSampleGet", + "operationId": "DownloadTroubleshootingMediaSample", "parameters": [ { "name": "mediaItemId", @@ -21676,7 +21395,7 @@ "Troubleshooting" ], "summary": "List selectable subtitle streams for a media item", - "description": "Returns the subtitle streams that can be burned in for a troubleshooting playback. Each item's id is the value to pass back as the playback.m3u8 endpoint's subtitleId query parameter.", + "description": "Returns the subtitle streams that can be burned in for a troubleshooting playback. Each item's id is the value to pass back as the POST /api/troubleshoot/playback/start request body's subtitleId field.", "operationId": "GetTroubleshootingSubtitles", "parameters": [ { @@ -30188,6 +29907,82 @@ } } }, + "StartTroubleshootingPlaybackRequest": { + "required": [ + "mediaItem", + "channel", + "ffmpegProfile", + "streamingMode", + "watermark", + "graphicsElement", + "streamSelector", + "subtitleId", + "seekSeconds", + "start" + ], + "type": "object", + "properties": { + "mediaItem": { + "type": "integer", + "format": "int32" + }, + "channel": { + "type": "integer", + "format": "int32" + }, + "ffmpegProfile": { + "type": "integer", + "format": "int32" + }, + "streamingMode": { + "$ref": "#/components/schemas/StreamingMode" + }, + "watermark": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "graphicsElement": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "streamSelector": { + "type": [ + "null", + "string" + ] + }, + "subtitleId": { + "type": [ + "null", + "integer" + ], + "format": "int32" + }, + "seekSeconds": { + "type": "integer", + "format": "int32" + }, + "start": { + "type": [ + "null", + "string" + ], + "format": "date-time" + } + } + }, "StartType": { "enum": [ "Dynamic", @@ -30427,6 +30222,17 @@ } } }, + "TroubleshootingPlaybackStartedResponseModel": { + "required": [ + "url" + ], + "type": "object", + "properties": { + "url": { + "type": "string" + } + } + }, "TroubleshootingPlaybackStatusResponseModel": { "required": [ "state", diff --git a/docs/api-conventions.md b/docs/api-conventions.md index 68f790d05..4c97516e7 100644 --- a/docs/api-conventions.md +++ b/docs/api-conventions.md @@ -94,7 +94,7 @@ hand-rolling `IActionResult` status codes: | Method | Input | Output | |---|---|---| -| `ToErrorResult()` | `BaseError` | 404 if `NotFoundError`, **412 if `PreconditionFailedError`** (optimistic-concurrency mismatch, §7a), else 422 (`ProblemDetails`) | +| `ToErrorResult()` | `BaseError` | 404 if `NotFoundError`, **412 if `PreconditionFailedError`** (optimistic-concurrency mismatch, §7a), **409 if `LockedError`** (a handler's own lock-acquire lost the race, §3a), else 422 (`ProblemDetails`) | | `ToCreatedResult(location, body)` | `Either` | `Left` → `ToErrorResult()`; `Right` → 201 + `Location` header | | `ToUpdatedResult()` | `Either` | `Left` → `ToErrorResult()`; `Right` → 200 + body | | `ToDeletedResult()` | `Either` | `Left` → `ToErrorResult()`; `Right` → 204 | @@ -142,6 +142,15 @@ action. Precedent for the 409 shape: `TraktController` (its private `ConflictPro contract keys on `Id`, never the user-mutable `Number` (re-keyed in #197 Bundle C; see `docs/decisions.md` 2026-07-12). The broadcast-side lookup (`GetPlayoutIdByChannelNumber`, used by `HlsSessionWorker`) stays number-keyed — a separate contract. Reserve 200 for a synchronous durable result. +- **Handler-side atomic lock loss also maps to 409, via a typed error, not 422** (issue #316 review): + when the *handler itself* is the one that atomically acquires an `IEntityLocker` lock (not just a + controller pre-check) and loses the race, return `new LockedError(...)` (`ErsatzTV.Core/Errors/LockedError.cs`, + sibling of `NotFoundError`/`PreconditionFailedError`) from the handler — `ToErrorResult()` maps it to + 409 automatically. Exemplar: `PrepareTroubleshootingPlaybackHandler` — `TroubleshootController` does a + cheap `IsTroubleshootingPlaybackLocked()` pre-check (advisory, §3a's check-then-act caveat applies), + but the handler's own `LockTroubleshootingPlayback()` is the atomic acquire; if *that* loses the race + it returns `LockedError`, so the 409 survives even when the pre-check passed a moment too early. Don't + let a handler-side lock loss fall through to the generic 422 `BaseError.New(...)`. ### 3b. Map a "queue a background job" outcome to status codes with an enum, not a `bool` @@ -599,7 +608,8 @@ OpenAPI generation, so the spec can't drift). When you add an endpoint: **only** auth-exempt controllers. - **The `/api/auth/*` surface** (`AuthController`, `[ApiExplorerSettings(IgnoreApi = true)]` → excluded from the OpenAPI doc, whose audience is machine clients): `GET config` (what auth options exist + `setupRequired`), - `GET session`, `POST setup` (first-run claim), `POST login`, `POST logout`, `POST password`. The browser-nav + `GET session`, `POST setup` (first-run claim), `POST login`, `POST logout`, `POST password`, `GET machine-key` + (returns the server machine key to an authenticated session — the SPA's machine-key-management screen). The browser-nav OIDC challenge is `GET /auth/oidc/login` (outside `/api`). `login`/`setup`/`password` carry a per-IP rate limit (`[EnableRateLimiting("auth")]`, 10 / 5 min). The local admin is a single credential in `ConfigElement` rows (`AuthLocalAdminUsername`/`AuthLocalAdminPasswordHash` (PBKDF2) / `AuthSecurityStamp`) — **no DB @@ -620,15 +630,19 @@ OpenAPI generation, so the spec can't drift). When you add an endpoint: `KnownProxies`. **Strongly set `KnownProxies`/`:KnownNetworks`** when exposing ErsatzTV behind a proxy — it also gives the #295 login rate limiter an unspoofable client IP and lets the session cookie be marked `Secure` behind TLS. -- **Side-effecting GET endpoints are not CSRF-covered by the filter** (it only checks mutating verbs). A few - `[RequiresAuthentication]` GETs have side effects (e.g. `GET /api/troubleshoot/playback.m3u8` starts playback). - Once a session cookie is a normal SPA credential (PR2), those need POST-ification or an explicit `X-CSRF` gate - — tracked as **#301**, which gates PR2 (latent in PR1: the SPA still uses the machine key, so no session - reaches them in normal use). -- **PR1 scope note (this change is server-only).** The SPA still authenticates with the stored key - (`ctv-api-key`, `X-Api-Key`) until the SPA login flow lands (PR2) — PR1 is backward compatible. The - `ApiKeyScreen` → machine-key-management repurpose, the SPA login/setup screens, and `spa-conventions §5e` - update all land in PR2. +- **Never add a side-effecting GET/HEAD under `/api`.** The filter's CSRF check only covers mutating verbs, so + a side-effecting GET is a CSRF vector the moment a session cookie is a normal credential (a `SameSite=Lax` + cookie rides a cross-site top-level GET navigation). The former `GET /api/troubleshoot/playback.m3u8` (started + an FFmpeg workload) and the archive/sample GETs were **POST-ified for #301** (PR2): `POST + /api/troubleshoot/playback/start` (returns `{ url }` pointing at the open `/iptv` manifest), `POST + /api/troubleshoot/playback/archive`, `POST /api/troubleshoot/playback/sample/{mediaItemId}` — so the standard + session-mutation CSRF gate covers them with no new filter machinery (removing HEAD also fixed a latent + `DeleteOnClose`-on-HEAD artifact-destruction bug). Any new endpoint that *does* something must be a mutating + verb; a GET must be a pure read. +- **The SPA cutover shipped in PR2 (#295 + #301).** The browser now authenticates with the session cookie only — + it no longer sends `X-Api-Key`; the machine key is external/MCP-only, surfaced read-only by the machine-key + screen (`GET /api/auth/machine-key`). See `spa-conventions.md §5e` for the SPA seams (boot gate, central + `X-Csrf` on mutations, fetch-blob downloads). **The OpenAPI "v1" document declares the machine posture by construction (#287).** An `ApiKey` security scheme (`X-Api-Key`, `in: header`) is declared in `components.securitySchemes`, and diff --git a/docs/decisions.md b/docs/decisions.md index 1a595aee3..73d3fb834 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -80,6 +80,7 @@ keep append-only from accreting stale, contradictory, or unreadably-large histor - [2026-07-12 — Formatting-as-you-touch, enforced; rebase-not-merge for PR branches (#311 H11 + format CI)](#2026-07-12--formatting-as-you-touch-enforced-rebase-not-merge-for-pr-branches-311-h11--format-ci) - [2026-07-12 — Merge-consent gate auto-grants when satisfied (no redundant prompt); state IS the consent (#314)](#2026-07-12--merge-consent-gate-auto-grants-when-satisfied-no-redundant-prompt-state-is-the-consent-314) - [2026-07-12 — Release path rehearses migrations on a prod-DB copy before promoting (#315)](#2026-07-12--release-path-rehearses-migrations-on-a-prod-db-copy-before-promoting-315) +- [2026-07-12 — #295 PR2: SPA session cutover + #301 side-effecting-GET POST-ification](#2026-07-12--295-pr2-spa-session-cutover--301-side-effecting-get-post-ification) --- @@ -1574,3 +1575,44 @@ afterwards. Always operates on a copy, never the live DB. Home: the script + doc into the Komodo **pre-deploy** step (which already produces the backup) is a server-management concern. Rationale: data-plane rigor — catch a bad migration on a disposable copy, not on live prod data. See `docs/ci-cd.md` → Migration-on-prod-copy smoke. Cross-repo wiring tracked in server-management. +--- + +## 2026-07-12 — #295 PR2: SPA session cutover + #301 side-effecting-GET POST-ification + +PR1 shipped the server side (previous entry): `/api` accepts a session cookie OR the machine `X-Api-Key`, with +`X-CSRF` required on session-authenticated mutations. **PR2 is the SPA cutover** — the browser now authenticates +with the session only — plus **#301** (a session-cookie CSRF hole in side-effecting GETs). + +**Browser is cookie-only; the machine key is external/MCP-only.** `web/src/api/client.ts` no longer attaches +`X-Api-Key`; it relies on the same-origin session cookie and sets `X-Csrf: '1'` on every mutating verb centrally. +The former "paste your key" `ApiKeyScreen` is repurposed to **machine-key management**: it reads the server key +from the new `GET /api/auth/machine-key` (session-gated; masked with Reveal + Copy) so an operator can hand it to +MCP / external REST clients — the browser itself never sends it again. *Why:* one credential per audience (the +ratified #295 model); leaving a browser key path alive would keep a CSRF-immune bypass around and defeat the +point. + +**Boot gate, not a route** (`web/src/AuthGate.tsx`, wrapping `` in `main.tsx`): on load it calls the public +`GET /api/auth/config` then `GET /api/auth/session` and renders Setup (first-run local-admin claim) / Login +(local form + an OIDC "Sign in with SSO" button when `oidcEnabled`) / the app. Login and Setup mint **no URL** — +the gate renders them at whatever `/app/*` path was requested, so a deep link survives login for free and **no +`blazor-route-parity.md`/`domain-model.md` route rows are added**. It publishes `AuthContext` +(`{ username, method, signOut, requireLogin }`); the 401 signal (`notifyUnauthorized`) now drives re-login via a +passive shell banner (never yanks a dirty draft — it consults the navigation guard first). Auth flows that expect +a 401 inline (login, change-password) pass `suppressUnauthorizedSignal`. + +**#301 — POST-ify, don't gate-the-GET.** A side-effecting GET is a CSRF vector once a `SameSite=Lax` cookie is a +normal credential (it rides a cross-site top-level navigation). The three offenders became mutating verbs so the +existing filter CSRF gate covers them with zero new machinery: `GET /api/troubleshoot/playback.m3u8` → +**`POST /api/troubleshoot/playback/start`** returning `200 { url }` (the open `/iptv` manifest the player then +loads — so hls.js/native-HLS needs no header injection, strictly better than X-CSRF-on-GET); the archive and +sample GETs → **POST** (SPA downloads them via a fetch-blob helper, never `window.open`). Removing the HEAD +variants also fixed a latent bug: a HEAD opened the `DeleteOnClose` stream and destroyed the artifact. Standing +rule added to `api-conventions.md §9`: **never add a side-effecting GET/HEAD under `/api`.** + +**Machine-key GET discloses the key to any authenticated session** — deliberate: the session principal is the +single admin (local or OIDC), same-origin policy blocks a cross-site page from reading the response body, and it +is how the "copy the key for MCP" UX works without a rotation endpoint (rotation is a later PR). **Accepted +residual (OIDC logout):** `POST /api/auth/logout` ends the *app* cookie but not the IdP session, so an OIDC user +who clicks "Sign out" then "Sign in with SSO" returns without re-entering credentials — a `returnUrl`/RP-initiated +logout is a future nicety. Docs: `spa-conventions.md §5e` (SPA seams), `api-conventions.md §9`, `e2e-local.md` +(browser setup/login flow). Refs #295 #301 #197. diff --git a/docs/e2e-local.md b/docs/e2e-local.md index 64c1a6a4c..122c16f6f 100644 --- a/docs/e2e-local.md +++ b/docs/e2e-local.md @@ -76,9 +76,10 @@ skip rubric uses (kickoff workflow lore). may 404/error. The UI and the entire `/api/*` surface are served on the **same port**, 8409 by default (override with `ETV_UI_PORT`). -5. **Seed data** as needed via the API — no API key is required for local mutating requests by - default (`ApiKeyAuthorizationFilter` only enforces the `X-Api-Key` header when - `Api:WriteKey` is configured; it's empty/unset in a fresh local config, so writes are open). +5. **Seed data** as needed via the API. **The `/api` surface is fail-closed since #197** (writes always, + and reads because `Api:RequireKeyForReads` defaults true), so curl seeding must send the machine key the + server generates at startup: `-H "X-Api-Key: $(cat "$CONFIG_DIR/api.key")"`. (Mutations from a *session* + also need `-H 'X-CSRF: 1'`, but for scripted seeding the machine key is simpler and CSRF-immune.) Examples: - Create a channel: `POST /api/channels` — check the current `ErsatzTV/wwwroot/openapi/v1.json` (or `CreateChannelRequest.cs`) for the exact required field @@ -89,6 +90,13 @@ skip rubric uses (kickoff workflow lore). `{"channelId": , "scheduleKind": "Block"}` (or `"Classic"`/`"Scripted"`/`"Sequential"` per `ChannelPlayoutSource`/schedule-kind enums — check `v1.json` for the current set). +5b. **Browser flow (since #295 session auth)**: the first `/app` load hits a **boot gate**. On a fresh + config it shows **Setup** — claim the local admin (pick any username/password); that issues the session + cookie and drops you into the app. On a subsequent run of the *same* config it shows **Login** instead. + (To skip the browser claim in automation, set `Auth:LocalAdmin:Password` before launch — the env seed + provisions the admin and disables the browser setup-claim.) The machine key still works for curl seeding + regardless. Driving this with Playwright: fill the Setup/Login form before asserting any authed screen. + 6. **Tear down**: kill the `dotnet ErsatzTV.dll` process and confirm the port is freed (`lsof -i :8409` should return nothing) before starting another run — a stray process holding the port will make the next run's health check hang or fail confusingly. diff --git a/docs/endpoint-index.md b/docs/endpoint-index.md index 9d1d65709..c64754d74 100644 --- a/docs/endpoint-index.md +++ b/docs/endpoint-index.md @@ -2,7 +2,7 @@ *Generated by `scripts/generate-endpoint-index.py` from `ErsatzTV/wwwroot/openapi/v1.json`. Do not edit by hand -- regenerated by `scripts/update-openapi.sh`.* -159 endpoints, 244 operations. +160 endpoints, 242 operations. ## Artists @@ -150,6 +150,7 @@ | Method | Path | Operation | Summary | |---|---|---|---| | GET | `/api/graphics-elements` | GetGraphicsElements | Get all graphics elements | +| POST | `/api/graphics-elements/refresh` | RefreshGraphicsElements | Re-sync graphics elements from disk | ## Health @@ -416,12 +417,9 @@ | Method | Path | Operation | Summary | |---|---|---|---| | GET | `/api/troubleshoot/info` | GetTroubleshootingInfo | Get troubleshooting diagnostic info | -| GET | `/api/troubleshoot/playback.m3u8` | TroubleshootTroubleshootPlaybackGet | Start a troubleshooting playback session | -| HEAD | `/api/troubleshoot/playback.m3u8` | TroubleshootTroubleshootPlaybackHead | Start a troubleshooting playback session | -| GET | `/api/troubleshoot/playback/archive` | TroubleshootTroubleshootPlaybackArchiveGet | Download the last troubleshooting playback session archive | -| HEAD | `/api/troubleshoot/playback/archive` | TroubleshootTroubleshootPlaybackArchiveHead | Download the last troubleshooting playback session archive | -| GET | `/api/troubleshoot/playback/sample/{mediaItemId}` | TroubleshootTroubleshootPlaybackSampleGet | Download a media sample archive for troubleshooting | -| HEAD | `/api/troubleshoot/playback/sample/{mediaItemId}` | TroubleshootTroubleshootPlaybackSampleHead | Download a media sample archive for troubleshooting | +| POST | `/api/troubleshoot/playback/archive` | DownloadTroubleshootingArchive | Download the last troubleshooting playback session archive | +| POST | `/api/troubleshoot/playback/sample/{mediaItemId}` | DownloadTroubleshootingMediaSample | Download a media sample archive for troubleshooting | +| POST | `/api/troubleshoot/playback/start` | StartTroubleshootingPlayback | Start a troubleshooting playback session | | GET | `/api/troubleshoot/playback/status` | GetTroubleshootingPlaybackStatus | Get the status of the current or last troubleshooting playback session | | GET | `/api/troubleshoot/playback/stream-selectors` | GetTroubleshootingStreamSelectors | List available channel stream selectors | | GET | `/api/troubleshoot/playback/subtitles/{mediaItemId}` | GetTroubleshootingSubtitles | List selectable subtitle streams for a media item | diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md index 8c0789a93..dc8838ce9 100644 --- a/docs/spa-conventions.md +++ b/docs/spa-conventions.md @@ -207,28 +207,43 @@ session — if a preference needs to be shared across devices or is really serve (e.g. Blazor's `ConfigElement`-backed settings), it belongs behind an API endpoint instead; see `docs/decisions.md` 2026-07-11 for the specific reasoning on logs page-size. -## 5e. API key: the one keyless screen + the global 401 signal (#197) +## 5e. Session auth: the boot gate, the machine-key screen + the global 401 signal (#295) -The whole `/api` surface is gated behind an `X-Api-Key` header (server-side #197): writes always -require it and reads require it too (`Api:RequireKeyForReads` defaults true), so a missing/wrong key -yields **401** on every call. Two SPA seams support this: +Since #295 the browser authenticates with a **session cookie**, not an API key. The whole `/api` +surface still answers a missing/expired session with **401**, and mutating verbs additionally require a +CSRF header. The former keyless-bootstrap `ApiKeyScreen` (the `X-Api-Key`/`localStorage` model of #197) +is gone. The SPA seams now are: -- **The request client sends the key on every request** (`web/src/api/client.ts`): whenever - `getStoredApiKey()` returns a value it's attached to `X-Api-Key`, regardless of method (there is no - reads-vs-mutations split — that older guard was removed). The key lives in `localStorage` - (`ctv-api-key`) via `web/src/api/auth.ts` (`get/set/clearStoredApiKey`), per §5d. -- **The API Key screen is the one screen that must render with ZERO successful `/api` calls** - (`web/src/screens/ApiKeyScreen.tsx`, route `/app/api-key`, System nav group). A keyless first load - 401s every read, so this screen reads/writes **only** `localStorage` (the `auth.ts` helpers) and - never fetches from `/api`. It shows a masked "key set / no key" state (never echoes the stored key - in plaintext — a `type="password"` input), Save (`setStoredApiKey`) and Clear (`clearStoredApiKey`), - and copy pointing at the server-generated `/config/api.key`. If you add a keyless bootstrap screen, - keep it `localStorage`-only for the same reason. +- **The request client sends no API key; it relies on the cookie and adds CSRF automatically** + (`web/src/api/client.ts`): the session cookie rides along with every same-origin request, and every + mutating verb (POST/PUT/PATCH/DELETE) gets an `X-Csrf` header set automatically — screens making a + POST get CSRF for free. There is **no** `getStoredApiKey`/`X-Api-Key` path anymore; the only residual + `localStorage` touch is `clearLegacyStoredApiKey()` (`web/src/api/auth.ts`), a one-shot cleanup the + boot gate runs once to purge any stale `ctv-api-key`. +- **The boot gate owns login/setup** (`web/src/AuthGate.tsx`), wrapping `` outside the + shell/router. It asks the PUBLIC `/api/auth/config`, then `/api/auth/session`, and renders Setup / + Login / the app. It also publishes `AuthContext` (`{ username, method, signOut, requireLogin }`) — + read `method` via `useContext(AuthContext)` to branch on the auth kind (e.g. `'local'` vs OIDC). +- **The machine-key screen is a normal authenticated screen** (`web/src/screens/ApiKeyScreen.tsx`, + route `/app/api-key`, System nav group). It loads the server machine key from `/api/auth/machine-key` + (via `getMachineKey()`) and displays it **masked** (a masked `` that never puts the key in the + DOM until Reveal) with Reveal + Copy affordances — the key is for MCP / external REST clients; the + browser no longer uses it. For **local** accounts only (`AuthContext.method === 'local'`) it also + renders a "Local admin password" card that calls `changePassword(current, new)`, mapping a wrong- + current-password **401** to the server ProblemDetails detail inline. +- **File-download endpoints go through a fetch-blob helper, never a browser tab.** Endpoints that + return a binary body (the troubleshooting archive / media-sample POSTs) must **not** go through + `request()` (it JSON-parses) and must **not** be opened with `window.open` (a session-cookie GET in a + new tab can't carry the CSRF header and bypasses error handling). Instead `fetch(path, { method: + 'POST', headers: { 'X-Csrf': '1' } })`, then `response.blob()` → object URL → anchor-click → + revoke, reading the filename from `Content-Disposition`; a non-ok response throws an `ApiError`. See + `downloadTroubleshootingArchive` / `downloadTroubleshootingMediaSample` in `web/src/api/troubleshoot.ts`. - **401 UX is one shell-level banner, not per-screen handling.** Rather than special-casing 401 in every screen's error path, the request client emits a single app-wide signal on 401 (`auth.ts` `notifyUnauthorized` / `subscribeUnauthorized`), and `web/src/UnauthorizedBanner.tsx` - (rendered once in the App shell) subscribes and points the user at `/app/api-key`. This is the DRY - seam for "the server rejected us" — reuse it instead of adding bespoke 401 branches. + (rendered once in the App shell) subscribes and prompts re-login. This is the DRY seam for "the server + rejected us" — reuse it instead of adding bespoke 401 branches. Auth flows that expect a 401 as an + inline answer (login, change-password) pass `suppressUnauthorizedSignal` so they don't trip it. ## 6. Tests diff --git a/scripts/update-openapi.sh b/scripts/update-openapi.sh index dd9edbd42..3be869c49 100755 --- a/scripts/update-openapi.sh +++ b/scripts/update-openapi.sh @@ -5,7 +5,13 @@ REPO_ROOT="$(pwd)" # Only regenerate the endpoint index if the spec build succeeded, so a failed # build can't render docs/endpoint-index.md from a stale/partial v1.json. -(cd ErsatzTV && dotnet build -t:GenerateOpenApiDocuments) || exit +# +# A full `dotnet build` MUST run before the doc-gen target: OpenApiGenerateDocumentsOnBuild +# is false, so `-t:GenerateOpenApiDocuments` alone does NOT compile the project — it invokes +# dotnet-getdocument against ErsatzTV.dll + ErsatzTV.deps.json, which don't exist in a clean +# tree (e.g. the CI api-docs job, which only restores). Without the build the target fails with +# "The specified deps.json … does not exist" (exit 129). Build first, then generate. +(cd ErsatzTV && dotnet build && dotnet build -t:GenerateOpenApiDocuments) || exit cd "$REPO_ROOT" || exit python3 scripts/generate-endpoint-index.py diff --git a/web/src/App.tsx b/web/src/App.tsx index e3302c1d8..7190a5ced 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -84,6 +84,7 @@ import { SearchScreen } from './screens/SearchScreen'; import { SettingsScreen } from './screens/SettingsScreen'; import { ApiKeyScreen } from './screens/ApiKeyScreen'; import { UnauthorizedBanner } from './UnauthorizedBanner'; +import { UserMenu } from './UserMenu'; import { TraktListsScreen } from './screens/TraktListsScreen'; import { TrashScreen } from './screens/TrashScreen'; import { TroubleshootingScreen } from './screens/TroubleshootingScreen'; @@ -900,6 +901,7 @@ function TopBar({ route }: { route: ScreenRoute | null }) {
+ diff --git a/web/src/AuthGate.test.tsx b/web/src/AuthGate.test.tsx new file mode 100644 index 000000000..1173ffe73 --- /dev/null +++ b/web/src/AuthGate.test.tsx @@ -0,0 +1,147 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AuthGate } from './AuthGate'; +import type { AuthConfig, AuthSession } from './api'; + +const APP_MARKER = 'APP CONTENT'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json' }, + status + }); +} + +interface Scenario { + config: AuthConfig | { fail: true }; + session?: AuthSession; + login?: AuthSession; +} + +function mockFetch(scenario: Scenario) { + return vi.spyOn(window, 'fetch').mockImplementation((input, init) => { + const url = typeof input === 'string' ? input : (input as Request).url; + const method = (init?.method ?? 'GET').toUpperCase(); + + if (url.endsWith('/api/auth/config')) { + if ('fail' in scenario.config) { + return Promise.resolve(jsonResponse({ status: 500, title: 'Server error' }, 500)); + } + return Promise.resolve(jsonResponse(scenario.config)); + } + + if (url.endsWith('/api/auth/session')) { + return Promise.resolve(jsonResponse(scenario.session ?? { authenticated: false, username: null, method: null })); + } + + if (url.endsWith('/api/auth/login') && method === 'POST') { + return Promise.resolve(jsonResponse(scenario.login ?? { authenticated: true, username: 'admin', method: 'local' })); + } + + return Promise.resolve(new Response(null, { status: 404 })); + }); +} + +const localConfig: AuthConfig = { oidcEnabled: false, localLoginEnabled: true, setupRequired: false }; + +describe('AuthGate', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('renders the setup screen when setup is required', async () => { + mockFetch({ config: { oidcEnabled: false, localLoginEnabled: true, setupRequired: true } }); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByText('Create the first administrator account')).toBeTruthy(); + expect(screen.queryByText(APP_MARKER)).toBeNull(); + }); + + it('renders the login screen when unauthenticated, with the SSO button only when OIDC is enabled', async () => { + mockFetch({ config: { oidcEnabled: true, localLoginEnabled: true, setupRequired: false } }); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByRole('button', { name: /Sign in with SSO/ })).toBeTruthy(); + expect(screen.queryByText(APP_MARKER)).toBeNull(); + }); + + it('omits the SSO button when OIDC is disabled', async () => { + mockFetch({ config: localConfig }); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByRole('button', { name: 'Sign in' })).toBeTruthy(); + expect(screen.queryByRole('button', { name: /SSO/ })).toBeNull(); + }); + + it('renders children when already authenticated and clears the legacy API key', async () => { + window.localStorage.setItem('ctv-api-key', 'legacy-secret'); + mockFetch({ config: localConfig, session: { authenticated: true, username: 'admin', method: 'local' } }); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByText(APP_MARKER)).toBeTruthy(); + await waitFor(() => expect(window.localStorage.getItem('ctv-api-key')).toBeNull()); + }); + + it('transitions from login to the app after a successful sign-in', async () => { + mockFetch({ config: localConfig, login: { authenticated: true, username: 'admin', method: 'local' } }); + + render( + +
{APP_MARKER}
+
+ ); + + const button = await screen.findByRole('button', { name: 'Sign in' }); + + fireEvent.change(screen.getByPlaceholderText('Username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Password'), { target: { value: 'hunter2' } }); + fireEvent.click(button); + + expect(await screen.findByText(APP_MARKER)).toBeTruthy(); + }); + + it('shows an error state with Retry when the config fetch fails, then recovers', async () => { + const scenario: Scenario = { config: { fail: true } }; + mockFetch(scenario); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByRole('alert')).toBeTruthy(); + const retry = screen.getByRole('button', { name: 'Retry' }); + + // Config now succeeds — Retry should re-run the gate and land on the login screen. + scenario.config = localConfig; + fireEvent.click(retry); + + expect(await screen.findByRole('button', { name: 'Sign in' })).toBeTruthy(); + }); +}); diff --git a/web/src/AuthGate.tsx b/web/src/AuthGate.tsx new file mode 100644 index 000000000..3580e3f64 --- /dev/null +++ b/web/src/AuthGate.tsx @@ -0,0 +1,181 @@ +import { createContext, useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; +import { RefreshCw, TriangleAlert } from 'lucide-react'; +import { Button, Card, Spinner } from './components'; +import { + clearLegacyStoredApiKey, + getAuthConfig, + getAuthSession, + type AuthConfig, + type AuthSession +} from './api'; +import { LoginScreen } from './screens/LoginScreen'; +import { SetupScreen } from './screens/SetupScreen'; + +// The boot gate (#295). It wraps OUTSIDE the shell/router, so Login and Setup mint no URLs and a +// deep link survives an intervening sign-in. On mount it asks the PUBLIC `/api/auth/config`, then (unless +// setup is required) `/api/auth/session`, and renders Setup / Login / the app accordingly. A config-fetch +// failure lands on an explicit error state with Retry — a keyless, sessionless browser must ALWAYS be able +// to reach the login form, never a blank screen. + +export interface AuthContextValue { + username: string | null; + method: string | null; + /** Return to the login screen after the caller has POSTed `/api/auth/logout`. */ + signOut: () => void; + /** Flip the gate to the login screen (e.g. the 401 banner's "Sign in"). */ + requireLogin: () => void; +} + +// A safe default so consumers (App, UserMenu, UnauthorizedBanner) render without a provider — e.g. +// `App.test.tsx` renders directly. AuthGate publishes the real value only in the `ready` state. +// Colocated with the gate that owns it (per the #295 plan); the fast-refresh rule is disabled to allow +// this non-component export alongside AuthGate, matching LocalLibraryEditScreen's established pattern. +// eslint-disable-next-line react-refresh/only-export-components +export const AuthContext = createContext({ + username: null, + method: null, + signOut: () => {}, + requireLogin: () => {} +}); + +type GateState = + | { status: 'checking' } + | { status: 'error' } + | { status: 'setup'; config: AuthConfig } + | { status: 'login'; config: AuthConfig } + | { status: 'ready'; session: AuthSession }; + +export function AuthGate({ children }: { children: ReactNode }) { + const [state, setState] = useState({ status: 'checking' }); + const activeRef = useRef(true); + const seqRef = useRef(0); + const configRef = useRef(null); + const clearedRef = useRef(false); + + useEffect(() => { + // Mount/unmount tracker — guards against the StrictMode double-mount and a slow fetch resolving + // after unmount (spa-conventions §3). Re-arm on (re)mount so the second StrictMode pass is live. + activeRef.current = true; + return () => { + activeRef.current = false; + }; + }, []); + + // Runs the boot fetch, setting state ONLY in the async completions (never synchronously) so it's safe + // to invoke from the mount effect without tripping the react-hooks "no set-state-in-effect" rule (§3): + // the initial `checking` state is the useState default, so the effect path needs no synchronous reset. + const runGate = useCallback(() => { + const seq = ++seqRef.current; + + getAuthConfig() + .then((config) => { + if (!activeRef.current || seq !== seqRef.current) { + return undefined; + } + + configRef.current = config; + + if (config.setupRequired) { + setState({ status: 'setup', config }); + return undefined; + } + + return getAuthSession().then((session) => { + if (!activeRef.current || seq !== seqRef.current) { + return; + } + + if (session.authenticated) { + setState({ status: 'ready', session }); + } else { + setState({ status: 'login', config }); + } + }); + }) + .catch(() => { + if (!activeRef.current || seq !== seqRef.current) { + return; + } + setState({ status: 'error' }); + }); + }, []); + + useEffect(() => { + runGate(); + }, [runGate]); + + // Re-run the gate from an event handler (Retry / recovery), resetting to the checking state first. + const restart = useCallback(() => { + setState({ status: 'checking' }); + runGate(); + }, [runGate]); + + useEffect(() => { + // Reaching the app once means any pre-session `ctv-api-key` is now dead — clear it a single time. + if (state.status === 'ready' && !clearedRef.current) { + clearedRef.current = true; + clearLegacyStoredApiKey(); + } + }, [state.status]); + + const onAuthenticated = useCallback((session: AuthSession) => { + setState({ status: 'ready', session }); + }, []); + + const requireLogin = useCallback(() => { + const config = configRef.current; + if (config) { + setState({ status: 'login', config }); + } else { + // No config cached (shouldn't happen post-boot) — re-run the whole gate to recover safely. + restart(); + } + }, [restart]); + + if (state.status === 'checking') { + return ( +
+ +
+ ); + } + + if (state.status === 'error') { + return ( +
+ +
+
+
+ +
+
+
+ ); + } + + if (state.status === 'setup') { + return ; + } + + if (state.status === 'login') { + return ; + } + + return ( + + {children} + + ); +} diff --git a/web/src/UnauthorizedBanner.test.tsx b/web/src/UnauthorizedBanner.test.tsx index f707b1828..3b6d290a5 100644 --- a/web/src/UnauthorizedBanner.test.tsx +++ b/web/src/UnauthorizedBanner.test.tsx @@ -1,41 +1,68 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { notifyUnauthorized } from './api'; +import { AuthContext, type AuthContextValue } from './AuthGate'; +import { registerNavigationGuard } from './navigationGuard'; import { UnauthorizedBanner } from './UnauthorizedBanner'; -describe('UnauthorizedBanner', () => { - beforeEach(() => { - window.history.pushState(null, '', '/app'); - }); +function renderBanner(overrides: Partial = {}) { + const requireLogin = overrides.requireLogin ?? vi.fn(); + const value: AuthContextValue = { + username: null, + method: null, + signOut: vi.fn(), + requireLogin, + ...overrides + }; + render( + + + + ); + return { requireLogin }; +} +describe('UnauthorizedBanner', () => { afterEach(() => { cleanup(); }); it('stays hidden until a 401 signal fires', () => { - render(); + renderBanner(); expect(screen.queryByRole('alert')).toBeNull(); act(() => notifyUnauthorized()); expect(screen.getByRole('alert')).toBeTruthy(); - expect(screen.getByText(/requires an API key/)).toBeTruthy(); - expect(screen.getByText(/Settings → API Key/)).toBeTruthy(); + expect(screen.getByText(/session has expired or you are signed out/)).toBeTruthy(); }); - it('navigates to the API Key screen from the pointer link', () => { - render(); + it('flips the gate to login via requireLogin when navigation is allowed', () => { + const { requireLogin } = renderBanner(); act(() => notifyUnauthorized()); - fireEvent.click(screen.getByRole('button', { name: 'Open API Key' })); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); - expect(window.location.pathname).toBe('/app/api-key'); + expect(requireLogin).toHaveBeenCalledTimes(1); expect(screen.queryByRole('alert')).toBeNull(); }); + it('respects the unsaved-changes guard — a vetoed leave keeps the banner and skips requireLogin', () => { + const { requireLogin } = renderBanner(); + const unregister = registerNavigationGuard(() => false); + act(() => notifyUnauthorized()); + + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + expect(requireLogin).not.toHaveBeenCalled(); + expect(screen.getByRole('alert')).toBeTruthy(); + + unregister(); + }); + it('can be dismissed', () => { - render(); + renderBanner(); act(() => notifyUnauthorized()); fireEvent.click(screen.getByRole('button', { name: 'Dismiss' })); diff --git a/web/src/UnauthorizedBanner.tsx b/web/src/UnauthorizedBanner.tsx index e5b3cba8b..bfeaaa5c9 100644 --- a/web/src/UnauthorizedBanner.tsx +++ b/web/src/UnauthorizedBanner.tsx @@ -1,15 +1,19 @@ -import { useEffect, useState } from 'react'; -import { KeyRound, X } from 'lucide-react'; +import { useContext, useEffect, useState } from 'react'; +import { LogIn, X } from 'lucide-react'; import { subscribeUnauthorized } from './api'; -import { navigateToPath } from './routing'; +import { AuthContext } from './AuthGate'; +import { canLeaveCurrentScreen } from './navigationGuard'; -const API_KEY_PATH = '/app/api-key'; - -// Shell-level pointer shown when any `/api` request returns 401 (#197). Rather than teach every -// screen's error path to special-case 401, the request client emits one app-wide signal (auth.ts) +// Shell-level pointer shown when any `/api` request returns 401 (#295 session-auth). Rather than teach +// every screen's error path to special-case 401, the request client emits one app-wide signal (auth.ts) // and this single banner subscribes — DRY, and it renders regardless of which screen triggered it. +// +// It stays PASSIVE: a background 401 must not yank the user mid-edit, so it only surfaces the banner. The +// "Sign in" affordance consults the unsaved-changes guard before flipping the gate to the login screen, so +// a dirty draft isn't silently discarded. export function UnauthorizedBanner() { const [visible, setVisible] = useState(false); + const { requireLogin } = useContext(AuthContext); useEffect(() => subscribeUnauthorized(() => setVisible(true)), []); @@ -17,19 +21,20 @@ export function UnauthorizedBanner() { return null; } - const goToApiKey = () => { + const signIn = () => { + if (!canLeaveCurrentScreen()) { + return; + } setVisible(false); - navigateToPath(API_KEY_PATH); + requireLogin(); }; return (
-
+ + )} +
+ ); +} diff --git a/web/src/api/auth.test.ts b/web/src/api/auth.test.ts index f6c9d4eb0..bd243766e 100644 --- a/web/src/api/auth.test.ts +++ b/web/src/api/auth.test.ts @@ -1,46 +1,154 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { clearStoredApiKey, getStoredApiKey, notifyUnauthorized, setStoredApiKey, subscribeUnauthorized } from './auth'; +import { + changePassword, + clearLegacyStoredApiKey, + getAuthConfig, + getAuthSession, + getMachineKey, + login, + logout, + notifyUnauthorized, + setup, + subscribeUnauthorized +} from './auth'; -describe('API key storage', () => { +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json' }, + status + }); +} + +describe('legacy API-key cleanup', () => { beforeEach(() => { window.localStorage.clear(); }); - it('stores and reads the API key from local storage', () => { - setStoredApiKey('write-secret'); + it('removes a leftover ctv-api-key entry', () => { + window.localStorage.setItem('ctv-api-key', 'legacy-secret'); - expect(getStoredApiKey()).toBe('write-secret'); - expect(window.localStorage.getItem('ctv-api-key')).toBe('write-secret'); - }); + clearLegacyStoredApiKey(); - it('trims blank API keys and clears storage', () => { - setStoredApiKey(' '); - - expect(getStoredApiKey()).toBeNull(); expect(window.localStorage.getItem('ctv-api-key')).toBeNull(); }); - it('clears a stored API key', () => { - setStoredApiKey('write-secret'); + it('is a no-op when localStorage is unavailable', () => { + const localStorageGetter = vi.spyOn(window, 'localStorage', 'get').mockImplementation(() => { + throw new Error('localStorage unavailable'); + }); - clearStoredApiKey(); - - expect(getStoredApiKey()).toBeNull(); - }); - - it('ignores unavailable local storage when reading the API key', () => { - const localStorageGetter = vi - .spyOn(window, 'localStorage', 'get') - .mockImplementation(() => { - throw new Error('localStorage unavailable'); - }); - - expect(getStoredApiKey()).toBeNull(); + expect(() => clearLegacyStoredApiKey()).not.toThrow(); localStorageGetter.mockRestore(); }); }); +describe('auth endpoints', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it('GET /api/auth/config', async () => { + const fetchMock = vi + .spyOn(window, 'fetch') + .mockResolvedValue(jsonResponse({ oidcEnabled: true, localLoginEnabled: true, setupRequired: false })); + + const config = await getAuthConfig(); + + expect(config).toEqual({ oidcEnabled: true, localLoginEnabled: true, setupRequired: false }); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/config', expect.objectContaining({ method: 'GET' })); + }); + + it('GET /api/auth/session', async () => { + const fetchMock = vi + .spyOn(window, 'fetch') + .mockResolvedValue(jsonResponse({ authenticated: true, username: 'admin', method: 'local' })); + + const session = await getAuthSession(); + + expect(session).toEqual({ authenticated: true, username: 'admin', method: 'local' }); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/session', expect.objectContaining({ method: 'GET' })); + }); + + it('GET /api/auth/session for an anonymous caller (username/method omitted)', async () => { + // The server serializes anonymous sessions as `{ "authenticated": false }` — username/method are + // dropped by Newtonsoft's global NullValueHandling.Ignore, so AuthSession must treat them as + // optional/undefined rather than present-but-null. + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ authenticated: false })); + + const session = await getAuthSession(); + + expect(session).toEqual({ authenticated: false }); + expect(session.username).toBeUndefined(); + expect(session.method).toBeUndefined(); + }); + + it('POST /api/auth/login with credentials in the body', async () => { + const fetchMock = vi + .spyOn(window, 'fetch') + .mockResolvedValue(jsonResponse({ authenticated: true, username: 'admin', method: 'local' })); + + await login('admin', 'hunter2'); + + expect(fetchMock).toHaveBeenCalledWith( + '/api/auth/login', + expect.objectContaining({ body: JSON.stringify({ username: 'admin', password: 'hunter2' }), method: 'POST' }) + ); + }); + + it('login does not trip the global 401 banner on a wrong-password 401', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ status: 401, title: 'Unauthorized' }, 401)); + const onUnauthorized = vi.fn(); + const unsubscribe = subscribeUnauthorized(onUnauthorized); + + await expect(login('admin', 'wrong')).rejects.toMatchObject({ status: 401 }); + + expect(onUnauthorized).not.toHaveBeenCalled(); + unsubscribe(); + }); + + it('POST /api/auth/setup with credentials in the body', async () => { + const fetchMock = vi + .spyOn(window, 'fetch') + .mockResolvedValue(jsonResponse({ authenticated: true, username: 'admin', method: 'local' })); + + await setup('admin', 'hunter2'); + + expect(fetchMock).toHaveBeenCalledWith( + '/api/auth/setup', + expect.objectContaining({ body: JSON.stringify({ username: 'admin', password: 'hunter2' }), method: 'POST' }) + ); + }); + + it('POST /api/auth/logout', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); + + await logout(); + + expect(fetchMock).toHaveBeenCalledWith('/api/auth/logout', expect.objectContaining({ method: 'POST' })); + }); + + it('POST /api/auth/password with both passwords, suppressing the 401 banner', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); + + await changePassword('old', 'new'); + + expect(fetchMock).toHaveBeenCalledWith( + '/api/auth/password', + expect.objectContaining({ body: JSON.stringify({ currentPassword: 'old', newPassword: 'new' }), method: 'POST' }) + ); + }); + + it('GET /api/auth/machine-key', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ apiKey: 'abc123' })); + + const result = await getMachineKey(); + + expect(result).toEqual({ apiKey: 'abc123' }); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/machine-key', expect.objectContaining({ method: 'GET' })); + }); +}); + describe('unauthorized signal', () => { it('notifies subscribers and stops after unsubscribe', () => { const listener = vi.fn(); diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts index e028af88c..fdaa672b6 100644 --- a/web/src/api/auth.ts +++ b/web/src/api/auth.ts @@ -1,4 +1,37 @@ -const apiKeyStorageKey = 'ctv-api-key'; +import { request } from './client'; + +// --- wire types ------------------------------------------------------------- +// The auth surface (`/api/auth/*`) is deliberately excluded from the OpenAPI document (server-side +// [IgnoreApi]), so — unlike every other domain module (spa-conventions §4) — these DTOs are NOT in the +// generated types and are hand-written here. Keep the field names camelCase to match the server records +// exactly (the JSON the auth endpoints emit). This deviation is intentional; do not try to source these +// from `./generated/v1`. + +/** `GET /api/auth/config` — PUBLIC; drives the boot gate. */ +export interface AuthConfig { + oidcEnabled: boolean; + localLoginEnabled: boolean; + setupRequired: boolean; +} + +/** `GET /api/auth/session` — anonymous callers get 200 with `authenticated: false` (never 401). */ +export interface AuthSession { + authenticated: boolean; + // Omitted (undefined) for anonymous callers — the server serializes `{ "authenticated": false }` and + // Newtonsoft's global NullValueHandling.Ignore drops these when null, so they are optional on the wire. + username?: string | null; + method?: string | null; +} + +/** + * `GET /api/auth/machine-key` — the server-generated machine API key. + * The wire field is `apiKey` (server record `MachineKeyResponse(string ApiKey)`), not `key`. + */ +export interface MachineKey { + apiKey: string; +} + +const legacyApiKeyStorageKey = 'ctv-api-key'; function getStorage(): Storage | undefined { if (typeof window === 'undefined') { @@ -12,32 +45,19 @@ function getStorage(): Storage | undefined { } } -export function getStoredApiKey(): string | null { - const value = getStorage()?.getItem(apiKeyStorageKey); - return value && value.trim().length > 0 ? value : null; -} - -export function setStoredApiKey(apiKey: string): void { - const trimmed = apiKey.trim(); - - if (trimmed.length === 0) { - clearStoredApiKey(); - return; - } - - getStorage()?.setItem(apiKeyStorageKey, trimmed); -} - -export function clearStoredApiKey(): void { - getStorage()?.removeItem(apiKeyStorageKey); +// The SPA no longer stores or sends an API key — it authenticates with the session cookie (#295). This +// one-shot cleanup removes any legacy `ctv-api-key` left over from the pre-session model; AuthGate calls +// it once on reaching `ready`. (The former `get/set/clearStoredApiKey` shims were removed once the +// ApiKeyScreen stopped consuming them — this is the sole remaining reader of the legacy key.) +export function clearLegacyStoredApiKey(): void { + getStorage()?.removeItem(legacyApiKeyStorageKey); } // --- 401 signal ------------------------------------------------------------- -// The whole `/api` surface is gated behind the API key (#197). Rather than teach -// every screen's error path to special-case 401, the request client emits a single -// app-wide signal when any request comes back Unauthorized; a shell-level banner -// subscribes and points the user at the API Key screen. Kept here (next to the key -// storage it concerns) so it never depends on a successful `/api` call. +// The whole `/api` surface is gated behind an authenticated session cookie (#295). Rather than teach +// every screen's error path to special-case 401, the request client emits a single app-wide signal when +// any request comes back Unauthorized; a shell-level banner subscribes and prompts the user to sign in. +// Kept here (in the auth domain module) so it never depends on a successful `/api` call. type UnauthorizedListener = () => void; const unauthorizedListeners = new Set(); @@ -54,3 +74,46 @@ export function notifyUnauthorized(): void { listener(); } } + +// --- auth endpoints --------------------------------------------------------- + +export function getAuthConfig(): Promise { + return request('/api/auth/config'); +} + +export function getAuthSession(): Promise { + return request('/api/auth/session'); +} + +export function login(username: string, password: string): Promise { + // A wrong-password 401 is an expected inline answer here — it must NOT trip the global 401 banner. + return request('/api/auth/login', { + body: { username, password }, + method: 'POST', + suppressUnauthorizedSignal: true + }); +} + +export function setup(username: string, password: string): Promise { + return request('/api/auth/setup', { + body: { username, password }, + method: 'POST' + }); +} + +export function logout(): Promise { + return request('/api/auth/logout', { method: 'POST' }); +} + +export function changePassword(currentPassword: string, newPassword: string): Promise { + // A wrong current-password 401 is shown inline, not via the global banner. + return request('/api/auth/password', { + body: { currentPassword, newPassword }, + method: 'POST', + suppressUnauthorizedSignal: true + }); +} + +export function getMachineKey(): Promise { + return request('/api/auth/machine-key'); +} diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts index 06aa893fc..0863d5d57 100644 --- a/web/src/api/client.test.ts +++ b/web/src/api/client.test.ts @@ -1,33 +1,37 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { setStoredApiKey, subscribeUnauthorized } from './auth'; +import { subscribeUnauthorized } from './auth'; import { ApiError, request, requestWithMeta } from './client'; +// Reads the X-Csrf header off the object handed to fetch (the client sets it post-normalization). +function csrfHeaderFrom(fetchMock: ReturnType): unknown { + const init = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined; + return (init?.headers as Record | undefined)?.['X-Csrf']; +} + describe('API request client', () => { beforeEach(() => { window.localStorage.clear(); vi.restoreAllMocks(); }); - it('adds the API key header for read requests when a key is stored', async () => { - const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue( - new Response(JSON.stringify([{ id: 1, number: '1', name: 'News' }]), { - headers: { 'Content-Type': 'application/json' }, - status: 200 - }) - ); - setStoredApiKey('read-secret'); + it.each(['POST', 'PUT', 'PATCH', 'DELETE'] as const)( + 'attaches the X-CSRF header on %s (session-auth mutation, #295)', + async (method) => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); - await request('/api/channels'); + await request('/api/channels/1', { method }); - expect(fetchMock).toHaveBeenCalledWith( - '/api/channels', - expect.objectContaining({ - headers: expect.objectContaining({ 'X-Api-Key': 'read-secret' }) - }) - ); - }); + expect(fetchMock).toHaveBeenCalledWith( + '/api/channels/1', + expect.objectContaining({ + headers: expect.objectContaining({ 'X-Csrf': '1' }), + method + }) + ); + } + ); - it('sends no API key header when none is stored', async () => { + it('does not attach the X-CSRF header on a GET', async () => { const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue( new Response(JSON.stringify([]), { headers: { 'Content-Type': 'application/json' }, @@ -40,24 +44,23 @@ describe('API request client', () => { expect(fetchMock).toHaveBeenCalledWith( '/api/channels', expect.objectContaining({ - headers: expect.not.objectContaining({ 'X-Api-Key': expect.anything() }) + headers: expect.not.objectContaining({ 'X-Csrf': expect.anything() }) }) ); + expect(csrfHeaderFrom(fetchMock)).toBeUndefined(); }); - it('adds the API key header for mutating requests', async () => { + it('never sends an X-Api-Key header, even with a legacy ctv-api-key in localStorage', async () => { const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); - setStoredApiKey('write-secret'); + window.localStorage.setItem('ctv-api-key', 'legacy-secret'); + await request('/api/channels'); await request('/api/channels/1', { method: 'DELETE' }); - expect(fetchMock).toHaveBeenCalledWith( - '/api/channels/1', - expect.objectContaining({ - headers: expect.objectContaining({ 'X-Api-Key': 'write-secret' }), - method: 'DELETE' - }) - ); + for (const call of fetchMock.mock.calls) { + const headers = (call[1] as RequestInit | undefined)?.headers as Record | undefined; + expect(headers).not.toHaveProperty('X-Api-Key'); + } }); it('throws an ApiError with problem details for non-OK responses', async () => { @@ -98,6 +101,25 @@ describe('API request client', () => { unsubscribe(); }); + it('does NOT signal unauthorized subscribers on a 401 when suppressUnauthorizedSignal is set', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ status: 401, title: 'Unauthorized' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: 401 + }) + ); + + const onUnauthorized = vi.fn(); + const unsubscribe = subscribeUnauthorized(onUnauthorized); + + await expect( + request('/api/auth/login', { body: { username: 'x', password: 'y' }, method: 'POST', suppressUnauthorizedSignal: true }) + ).rejects.toMatchObject({ status: 401 }); + + expect(onUnauthorized).not.toHaveBeenCalled(); + unsubscribe(); + }); + it('does not signal unauthorized subscribers on other error statuses', async () => { vi.spyOn(window, 'fetch').mockResolvedValue( new Response(JSON.stringify({ status: 403, title: 'Forbidden' }), { @@ -115,21 +137,6 @@ describe('API request client', () => { unsubscribe(); }); - it('reads problem details from application/problem+json responses', async () => { - vi.spyOn(window, 'fetch').mockResolvedValue( - new Response(JSON.stringify({ status: 401, title: 'Unauthorized', detail: 'A valid API key is required for write requests.' }), { - headers: { 'Content-Type': 'application/problem+json' }, - status: 401 - }) - ); - - await expect(request('/api/channels', { method: 'POST' })).rejects.toMatchObject({ - detail: 'A valid API key is required for write requests.', - message: 'Unauthorized', - status: 401 - } satisfies Partial); - }); - it('does not add a duplicate JSON content type when callers provide lowercase content-type', async () => { const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index f68e69856..3723699c4 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -1,9 +1,11 @@ -import { getStoredApiKey, notifyUnauthorized } from './auth'; +import { notifyUnauthorized } from './auth'; import type { components } from './generated/v1'; type ProblemDetails = components['schemas']['ProblemDetails']; type RequestBody = BodyInit | Record | null; +const MUTATING_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE']; + export class ApiError extends Error { readonly detail?: string | null; readonly problem?: ProblemDetails; @@ -20,6 +22,12 @@ export class ApiError extends Error { export interface ApiRequestOptions extends Omit { body?: RequestBody; + /** + * When set, a 401 on this request does NOT fire the app-wide unauthorized signal (#295). Used by the + * auth flows (login / change-password) where a 401 is an expected wrong-credentials answer that must + * be shown inline, not surfaced as the global "your session expired" banner. + */ + suppressUnauthorizedSignal?: boolean; } export interface ResponseWithMeta { @@ -37,6 +45,7 @@ export async function requestWithMeta( path: string, options: ApiRequestOptions = {} ): Promise> { + const { suppressUnauthorizedSignal, ...fetchOptions } = options; const method = (options.method ?? 'GET').toUpperCase(); const headers = normalizeHeaders({ Accept: 'application/json', @@ -44,25 +53,27 @@ export async function requestWithMeta( }); const body = serializeBody(options.body, headers); - const apiKey = getStoredApiKey(); - // #197/#282: the whole `/api` surface is gated (reads too, since `Api:RequireKeyForReads` - // defaults true), so send the key on every request whenever one is stored — not only mutations. - if (apiKey) { - headers['X-Api-Key'] = apiKey; + // #295: session-authenticated mutations must carry a CSRF header or the server answers 403. Set it + // post-normalization (as the API key was), so it survives header canonicalization. The server lookup + // is case-insensitive, so `X-Csrf` matches its `X-CSRF`. Machine-key (`X-Api-Key`) callers are exempt + // server-side, but sending the header on every mutation is harmless — the SPA is always session-auth. + if (MUTATING_METHODS.includes(method)) { + headers['X-Csrf'] ??= '1'; } const response = await fetch(path, { - ...options, + ...fetchOptions, body, headers, method }); if (!response.ok) { - // A gated `/api` surface answers a missing/wrong key with 401 (#197). Signal the shell so it can - // point the user at the API Key screen, regardless of which screen made the call. - if (response.status === 401) { + // A session-gated `/api` surface answers a missing/expired session with 401 (#295). Signal the + // shell so it can prompt re-login, regardless of which screen made the call — unless the caller + // opted out (an expected wrong-credentials 401 on login/change-password). + if (response.status === 401 && !suppressUnauthorizedSignal) { notifyUnauthorized(); } diff --git a/web/src/api/generated/v1.d.ts b/web/src/api/generated/v1.d.ts index 22f0e30ce..ad9f715d3 100644 --- a/web/src/api/generated/v1.d.ts +++ b/web/src/api/generated/v1.d.ts @@ -1434,6 +1434,18 @@ export interface components { "id": number; "name": string; "query": string; + }; + "StartTroubleshootingPlaybackRequest": { + "mediaItem": number; + "channel": number; + "ffmpegProfile": number; + "streamingMode": components["schemas"]["StreamingMode"]; + "watermark": null | Array; + "graphicsElement": null | Array; + "streamSelector": null | string; + "subtitleId": null | number; + "seekSeconds": number; + "start": null | string; }; "StartType": "Dynamic" | "Fixed"; "StreamingMode": "TransportStream" | "HttpLiveStreamingDirect" | "HttpLiveStreamingSegmenter" | "TransportStreamHybrid"; @@ -1485,6 +1497,9 @@ export interface components { "qsvCapabilities": null | string; "vaapiCapabilities": null | string; "videoToolboxCapabilities": null | string; + }; + "TroubleshootingPlaybackStartedResponseModel": { + "url": string; }; "TroubleshootingPlaybackStatusResponseModel": { "state": string; diff --git a/web/src/api/troubleshoot.test.ts b/web/src/api/troubleshoot.test.ts index 75bc36f8c..0fb5d5411 100644 --- a/web/src/api/troubleshoot.test.ts +++ b/web/src/api/troubleshoot.test.ts @@ -1,12 +1,26 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { subscribeUnauthorized } from './auth'; import { + downloadTroubleshootingArchive, + downloadTroubleshootingMediaSample, getTroubleshootingInfo, getTroubleshootingPlaybackStatus, getTroubleshootingStreamSelectors, getTroubleshootingSubtitles, - validateSequentialSchedule + startTroubleshootingPlayback, + validateSequentialSchedule, + type StartTroubleshootingPlaybackBody } from './troubleshoot'; +function headerValue(init: RequestInit | undefined, name: string): string | undefined { + const headers = init?.headers as Record | undefined; + if (!headers) { + return undefined; + } + const match = Object.keys(headers).find((key) => key.toLowerCase() === name.toLowerCase()); + return match ? headers[match] : undefined; +} + function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); } @@ -119,3 +133,155 @@ describe('troubleshooting playback wrappers', () => { expect(fetchSpy.mock.calls[0][0]).toBe('/api/troubleshoot/playback/status'); }); }); + +describe('startTroubleshootingPlayback', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it('POSTs /api/troubleshoot/playback/start with the mapped body and a CSRF header, returning the url', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue( + jsonResponse({ url: '/iptv/session/.troubleshooting/live.m3u8' }) + ); + + // Arrays are carried through, and the mutually-exclusive pair is preserved as the caller mapped it + // (streamSelector set → subtitleId null). + const body: StartTroubleshootingPlaybackBody = { + mediaItem: 5, + channel: 0, + ffmpegProfile: 2, + streamingMode: 'HttpLiveStreamingSegmenter', + watermark: [10, 11], + graphicsElement: [20], + streamSelector: 'selector-a', + subtitleId: null, + seekSeconds: 1200, + start: null + }; + + await expect(startTroubleshootingPlayback(body)).resolves.toEqual({ + url: '/iptv/session/.troubleshooting/live.m3u8' + }); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/troubleshoot/playback/start'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('POST'); + expect(headerValue(init, 'X-Csrf')).toBe('1'); + expect(JSON.parse(String(init?.body))).toEqual(body); + }); + + it('rejects with the ApiError status (409) so the screen can surface "another session running"', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ status: 409, title: 'Conflict', detail: 'Another session is running.' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: 409 + }) + ); + + await expect( + startTroubleshootingPlayback({ + mediaItem: 5, + channel: 0, + ffmpegProfile: 1, + streamingMode: 'HttpLiveStreamingSegmenter', + watermark: [], + graphicsElement: [], + streamSelector: null, + subtitleId: null, + seekSeconds: 0, + start: null + }) + ).rejects.toMatchObject({ status: 409, detail: 'Another session is running.' }); + }); +}); + +describe('troubleshooting download helpers', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + // Engine-neutral fake: a real `new Response(new Blob(...))` fails in CI (undici) because a + // jsdom Blob has no `.stream()` for undici's Response body to consume ("object.stream is not a + // function"). Passing settings through a plain object with an async `blob()` avoids any + // Blob→Response interop crossing; `URL.createObjectURL` is stubbed so the blob body is inert. + function zipResponse(filename: string): Response { + return { + ok: true, + status: 200, + headers: new Headers({ + 'Content-Type': 'application/zip', + 'Content-Disposition': `attachment; filename="${filename}"` + }), + blob: async () => new Blob(['zip-bytes']) + } as unknown as Response; + } + + function stubBrowserDownload() { + const createObjectURL = vi.fn(() => 'blob:mock'); + const revokeObjectURL = vi.fn(); + // jsdom does not implement these on URL; install spies so the anchor-click download path runs. + (URL as unknown as { createObjectURL: unknown }).createObjectURL = createObjectURL; + (URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = revokeObjectURL; + const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}); + return { createObjectURL, revokeObjectURL, clickSpy }; + } + + it('POSTs (not GETs) the archive with a CSRF header and triggers a download', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(zipResponse('ersatztv-troubleshooting-123.zip')); + const { createObjectURL, revokeObjectURL, clickSpy } = stubBrowserDownload(); + + await downloadTroubleshootingArchive(); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/troubleshoot/playback/archive'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('POST'); + expect(headerValue(init, 'X-Csrf')).toBe('1'); + expect(createObjectURL).toHaveBeenCalledTimes(1); + expect(clickSpy).toHaveBeenCalledTimes(1); + expect(revokeObjectURL).toHaveBeenCalledTimes(1); + }); + + it('POSTs the media sample for a given id with a CSRF header', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(zipResponse('ersatztv-media-sample-123.zip')); + stubBrowserDownload(); + + await downloadTroubleshootingMediaSample(42); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/troubleshoot/playback/sample/42'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('POST'); + expect(headerValue(init, 'X-Csrf')).toBe('1'); + }); + + it('throws an ApiError on a non-ok download response', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ status: 404, title: 'Not Found' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: 404 + }) + ); + stubBrowserDownload(); + + await expect(downloadTroubleshootingArchive()).rejects.toMatchObject({ status: 404 }); + }); + + it('fires the global 401 signal on an unauthorized download response', async () => { + // downloadViaPost raw-fetches (binary body), bypassing the central client's 401 handling, so it + // must emit notifyUnauthorized() itself — an expired session mid-download should raise the global + // re-login banner, not just an inline error. + vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ status: 401, title: 'Unauthorized' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: 401 + }) + ); + stubBrowserDownload(); + const onUnauthorized = vi.fn(); + const unsubscribe = subscribeUnauthorized(onUnauthorized); + + await expect(downloadTroubleshootingArchive()).rejects.toMatchObject({ status: 401 }); + + expect(onUnauthorized).toHaveBeenCalledTimes(1); + unsubscribe(); + }); +}); diff --git a/web/src/api/troubleshoot.ts b/web/src/api/troubleshoot.ts index 7257ac7d3..dcd55e3e4 100644 --- a/web/src/api/troubleshoot.ts +++ b/web/src/api/troubleshoot.ts @@ -1,3 +1,4 @@ +import { notifyUnauthorized } from './auth'; import { ApiError, request } from './client'; import type { components } from './generated/v1'; @@ -5,6 +6,8 @@ export type TroubleshootingInfo = components['schemas']['TroubleshootingInfoResp export type ValidateScheduleResult = components['schemas']['ValidateSequentialScheduleResponseModel']; export type TroubleshootingSubtitle = components['schemas']['TroubleshootingSubtitleResponseModel']; export type TroubleshootingPlaybackStatus = components['schemas']['TroubleshootingPlaybackStatusResponseModel']; +export type StartTroubleshootingPlaybackBody = components['schemas']['StartTroubleshootingPlaybackRequest']; +export type TroubleshootingPlaybackStarted = components['schemas']['TroubleshootingPlaybackStartedResponseModel']; export function getTroubleshootingInfo(): Promise { return request('/api/troubleshoot/info'); @@ -28,6 +31,94 @@ export function getTroubleshootingPlaybackStatus(): Promise('/api/troubleshoot/playback/status'); } +// Start a troubleshooting playback session (#295 — was a GET on `playback.m3u8` that started the +// session as a side effect of the manifest fetch; now an explicit POST with a JSON body). The server +// blocks until the first segments exist, then returns the open `/iptv` live manifest URL to feed to +// HlsPlayer. A 404/409/422 surfaces as an ApiError the caller can show inline. +export function startTroubleshootingPlayback( + body: StartTroubleshootingPlaybackBody +): Promise { + return request('/api/troubleshoot/playback/start', { + body, + method: 'POST' + }); +} + +// File-download endpoints — these return a binary zip, not JSON, so they must NOT go through +// `request()` (which JSON-parses the body). Fetch directly with the CSRF header (both are POST since +// #295), read the blob, and trigger a browser download. Same-origin fetch can read Content-Disposition +// so we use the server-provided filename when present. +export function downloadTroubleshootingArchive(): Promise { + return downloadViaPost('/api/troubleshoot/playback/archive', 'ersatztv-troubleshooting.zip'); +} + +export function downloadTroubleshootingMediaSample(id: number): Promise { + return downloadViaPost(`/api/troubleshoot/playback/sample/${id}`, 'ersatztv-media-sample.zip'); +} + +async function downloadViaPost(path: string, fallbackName: string): Promise { + const response = await fetch(path, { method: 'POST', headers: { 'X-Csrf': '1' } }); + + if (!response.ok) { + // This raw fetch bypasses the central client, so emit the app-wide 401 signal ourselves — an + // expired session mid-download should raise the global re-login banner, not just an inline error. + if (response.status === 401) { + notifyUnauthorized(); + } + throw new ApiError(response.status, await readProblemDetailsSafe(response)); + } + + const blob = await response.blob(); + const filename = filenameFromContentDisposition(response.headers.get('Content-Disposition'), fallbackName); + const objectUrl = URL.createObjectURL(blob); + try { + const anchor = document.createElement('a'); + anchor.href = objectUrl; + anchor.download = filename; + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + } finally { + URL.revokeObjectURL(objectUrl); + } +} + +async function readProblemDetailsSafe(response: Response): Promise { + const contentType = response.headers.get('Content-Type') ?? ''; + if (!contentType.includes('application/json') && !contentType.includes('problem+json')) { + return undefined; + } + try { + return (await response.json()) as components['schemas']['ProblemDetails']; + } catch { + return undefined; + } +} + +// Parse `filename="…"` / `filename*=UTF-8''…` from a Content-Disposition header, falling back when the +// header is absent or unparseable. +function filenameFromContentDisposition(header: null | string, fallback: string): string { + if (!header) { + return fallback; + } + + const extended = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header); + if (extended?.[1]) { + try { + return decodeURIComponent(extended[1].trim().replace(/^"|"$/g, '')); + } catch { + // fall through to the plain filename form + } + } + + const plain = /filename="?([^";]+)"?/i.exec(header); + if (plain?.[1]) { + return plain[1].trim(); + } + + return fallback; +} + export function validateSequentialSchedule(yaml: string, isImport: boolean): Promise { return request('/api/troubleshoot/validate-schedule', { body: { yaml, isImport }, diff --git a/web/src/main.tsx b/web/src/main.tsx index b241e5092..9f2da3c6f 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -1,11 +1,14 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { App } from './App'; +import { AuthGate } from './AuthGate'; import './designSystem'; import './shell.css'; createRoot(document.getElementById('root')!).render( - + + + ); diff --git a/web/src/screens/ApiKeyScreen.test.tsx b/web/src/screens/ApiKeyScreen.test.tsx index ae8789ac6..ee353b765 100644 --- a/web/src/screens/ApiKeyScreen.test.tsx +++ b/web/src/screens/ApiKeyScreen.test.tsx @@ -1,69 +1,138 @@ -import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { ReactNode } from 'react'; import { ApiKeyScreen } from './ApiKeyScreen'; +import { AuthContext, type AuthContextValue } from '../AuthGate'; + +// The repurposed screen (#295) is a normal authenticated screen: it loads the machine key from +// `/api/auth/machine-key` and, for local accounts, changes the password via `/api/auth/password`. Its +// self-contained fetch mock (spa-conventions §6) covers only those two endpoints. +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); +} + +function installFetch(options: { machineKey?: string; passwordStatus?: number } = {}) { + const { machineKey = 'machine-secret', passwordStatus = 204 } = options; + return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + if (url === '/api/auth/machine-key') { + return Promise.resolve(json({ apiKey: machineKey })); + } + if (url === '/api/auth/password') { + if (passwordStatus >= 400) { + return Promise.resolve( + new Response(JSON.stringify({ status: passwordStatus, title: 'Unauthorized', detail: 'Wrong password.' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: passwordStatus + }) + ); + } + return Promise.resolve(new Response(null, { status: passwordStatus })); + } + return Promise.resolve(json({}, 404)); + }); +} + +function renderWith(method: string | null, children: ReactNode = ) { + const value: AuthContextValue = { + username: 'admin', + method, + signOut: () => {}, + requireLogin: () => {} + }; + return render({children}); +} describe('ApiKeyScreen', () => { beforeEach(() => { window.localStorage.clear(); vi.restoreAllMocks(); + Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } }); }); afterEach(() => { cleanup(); }); - it('renders and functions without any /api call', () => { - const fetchSpy = vi.spyOn(window, 'fetch'); + it('shows the machine key masked by default, then reveals it', async () => { + installFetch({ machineKey: 'machine-secret' }); - render(); + renderWith('local'); - expect(screen.getByText('No key')).toBeTruthy(); - expect(screen.getByText(/No key is stored in this browser/)).toBeTruthy(); - expect(fetchSpy).not.toHaveBeenCalled(); + // The masked code cell renders without leaking the key into the DOM. + const cell = await screen.findByTestId('machine-key'); + expect(cell.textContent).not.toContain('machine-secret'); + expect(document.body.innerHTML).not.toContain('machine-secret'); + + fireEvent.click(screen.getByRole('button', { name: /Reveal/i })); + + await waitFor(() => expect(screen.getByTestId('machine-key').textContent).toBe('machine-secret')); }); - it('saves a pasted key to local storage and shows the key-set state', () => { - render(); + it('copies the real machine key regardless of the masked state', async () => { + installFetch({ machineKey: 'machine-secret' }); - fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' secret-123 ' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save key' })); + renderWith('local'); + await screen.findByTestId('machine-key'); - // Trimmed and written through to the shared ctv-api-key slot. - expect(window.localStorage.getItem('ctv-api-key')).toBe('secret-123'); - expect(screen.getByText('Key set')).toBeTruthy(); - expect(screen.getByText(/Key saved/)).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: /Copy/i })); + + expect(navigator.clipboard.writeText).toHaveBeenCalledWith('machine-secret'); }); - it('does not render the stored key value in plaintext', () => { - window.localStorage.setItem('ctv-api-key', 'super-secret'); + it('renders the local-password card only for a local account', async () => { + installFetch(); - render(); - - expect(screen.getByText('Key set')).toBeTruthy(); - // The masked state never echoes the stored key back to the DOM. - expect(screen.queryByText(/super-secret/)).toBeNull(); - expect(document.body.innerHTML).not.toContain('super-secret'); + renderWith('local'); + expect(await screen.findByText('Local admin password')).toBeTruthy(); }); - it('clears a stored key', () => { - window.localStorage.setItem('ctv-api-key', 'super-secret'); + it('hides the local-password card for a non-local (oidc) account', async () => { + installFetch(); - render(); - - fireEvent.click(screen.getByRole('button', { name: 'Clear key' })); - - expect(window.localStorage.getItem('ctv-api-key')).toBeNull(); - expect(screen.getByText('No key')).toBeTruthy(); + renderWith('oidc'); + // Machine key card still loads. + await screen.findByTestId('machine-key'); + expect(screen.queryByText('Local admin password')).toBeNull(); }); - it('ignores a save with only whitespace', () => { - render(); + it('changes the password via /api/auth/password and confirms on success', async () => { + const fetchSpy = installFetch({ passwordStatus: 204 }); - const save = screen.getByRole('button', { name: 'Save key' }); - expect(save.hasAttribute('disabled')).toBe(true); + renderWith('local'); + await screen.findByText('Local admin password'); + + fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'old-pass' } }); + fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'new-pass' } }); + fireEvent.click(screen.getByRole('button', { name: /Change password/i })); + + await waitFor(() => expect(screen.getByText('Password changed.')).toBeTruthy()); + + const passwordCall = fetchSpy.mock.calls.find((call) => call[0] === '/api/auth/password'); + expect(passwordCall).toBeTruthy(); + expect((passwordCall?.[1]?.method ?? 'GET').toUpperCase()).toBe('POST'); + expect(JSON.parse(String(passwordCall?.[1]?.body))).toEqual({ currentPassword: 'old-pass', newPassword: 'new-pass' }); + }); + + it('surfaces the ProblemDetails detail inline on a wrong-current-password 401', async () => { + installFetch({ passwordStatus: 401 }); + + renderWith('local'); + await screen.findByText('Local admin password'); + + fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'wrong' } }); + fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'new-pass' } }); + fireEvent.click(screen.getByRole('button', { name: /Change password/i })); + + await waitFor(() => expect(screen.getByText('Wrong password.')).toBeTruthy()); + }); + + it('never touches the legacy ctv-api-key localStorage slot', async () => { + installFetch(); + + renderWith('local'); + await screen.findByTestId('machine-key'); - fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' ' } }); - expect(save.hasAttribute('disabled')).toBe(true); expect(window.localStorage.getItem('ctv-api-key')).toBeNull(); }); }); diff --git a/web/src/screens/ApiKeyScreen.tsx b/web/src/screens/ApiKeyScreen.tsx index 55c119308..d5b7a97de 100644 --- a/web/src/screens/ApiKeyScreen.tsx +++ b/web/src/screens/ApiKeyScreen.tsx @@ -1,99 +1,256 @@ -import { useState } from 'react'; -import { Check, KeyRound, ShieldCheck, Trash2, TriangleAlert } from 'lucide-react'; -import { Badge, Button, Card, Input } from '../components'; -import { clearStoredApiKey, getStoredApiKey, setStoredApiKey } from '../api'; +import { useCallback, useContext, useEffect, useRef, useState } from 'react'; +import { Check, Copy, Eye, EyeOff, KeyRound, Lock, ShieldCheck, TriangleAlert } from 'lucide-react'; +import { Button, Card, Input, Spinner } from '../components'; +import { ApiError, changePassword, getMachineKey } from '../api'; +import { AuthContext } from '../AuthGate'; -// The one screen that must work with ZERO successful `/api` calls: a keyless first load 401s every -// read, so this screen relies only on localStorage (auth.ts helpers) and never fetches from `/api`. -// It's how a fresh install gets its key in before anything else can load (#280 / #197). -export function ApiKeyScreen() { - const [hasKey, setHasKey] = useState(() => getStoredApiKey() !== null); - const [draft, setDraft] = useState(''); - const [justSaved, setJustSaved] = useState(false); +// Since #295 the browser authenticates with the session cookie, so this screen no longer bootstraps an +// API key. It now MANAGES the server's machine key (for MCP / external REST clients) and — for local +// admin accounts — offers a password change. It's a normal authenticated screen: it reads the machine +// key from `/api/auth/machine-key` (a real `/api` call), unlike the old keyless localStorage-only shape. +type KeyState = + | { status: 'loading' } + | { status: 'error'; message: string } + | { status: 'success'; key: string }; - const trimmed = draft.trim(); +function messageFromError(error: unknown, fallback: string): string { + if (error instanceof ApiError) { + return error.detail ?? error.message; + } + if (error instanceof Error) { + return error.message; + } + return fallback; +} - const save = () => { - if (trimmed.length === 0) { - return; - } +function CopyButton({ text }: { text: string }) { + const [copied, setCopied] = useState(false); - setStoredApiKey(trimmed); - setHasKey(true); - setDraft(''); - setJustSaved(true); - }; - - const clear = () => { - clearStoredApiKey(); - setHasKey(false); - setJustSaved(false); + const copy = () => { + void navigator.clipboard?.writeText(text).then(() => { + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + }); }; return ( -
- Key set - ) : ( - No key - ) + + ); +} + +function MachineKeyCard() { + const [state, setState] = useState({ status: 'loading' }); + const [revealed, setRevealed] = useState(false); + const activeRef = useRef(true); + const seqRef = useRef(0); + + useEffect(() => { + activeRef.current = true; + return () => { + activeRef.current = false; + }; + }, []); + + // State transitions live in the promise callbacks (never synchronously in the effect body) per + // docs/spa-conventions.md §3. + const load = useCallback(() => { + const seq = ++seqRef.current; + getMachineKey() + .then((result) => { + if (!activeRef.current || seq !== seqRef.current) { + return; } - padded - subtitle="This server requires an API key on every request. The server generates one on first run and writes it to /config/api.key on the server host — open that file and paste its contents below." - title="API Key" - > - {hasKey ? ( -
-
- ) : ( -
-
- )} + setState({ status: 'success', key: result.apiKey }); + }) + .catch((error: unknown) => { + if (!activeRef.current || seq !== seqRef.current) { + return; + } + setState({ status: 'error', message: messageFromError(error, 'Unable to load the machine key') }); + }); + }, []); -
- } - onChange={(event) => { - setDraft(event.target.value); - setJustSaved(false); - }} - placeholder="Paste the contents of /config/api.key" - style={{ fontFamily: 'var(--font-mono)' }} - type="password" - value={draft} - /> + useEffect(() => { + load(); + }, [load]); + + return ( + + {state.status === 'loading' && ( +
+ + Loading machine key…
+ )} -
- {justSaved && ( - - - )} + {state.status === 'error' && ( +
+
- + )} + + {state.status === 'success' && ( + <> +
+
+ +
+ Machine key + + + + {/* Masked by default: the real key is never in the DOM until Reveal — Copy always copies + the real value regardless of the masked/revealed toggle. */} + + {revealed ? state.key : '••••••••••••••••••••••••'} + + +
+ +
+ + + +
+ + )} + + ); +} + +function LocalPasswordCard() { + const [currentPassword, setCurrentPassword] = useState(''); + const [newPassword, setNewPassword] = useState(''); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const [justSaved, setJustSaved] = useState(false); + + const canSubmit = currentPassword.length > 0 && newPassword.length > 0 && !saving; + + const submit = async () => { + if (!canSubmit) { + return; + } + setSaving(true); + setError(null); + setJustSaved(false); + try { + await changePassword(currentPassword, newPassword); + setCurrentPassword(''); + setNewPassword(''); + setJustSaved(true); + } catch (err: unknown) { + // A 401 is the expected wrong-current-password answer — surface its ProblemDetails detail inline. + if (err instanceof ApiError && err.status === 401) { + setError(err.detail ?? 'Your current password is incorrect.'); + } else { + setError(messageFromError(err, 'Unable to change your password')); + } + } finally { + setSaving(false); + } + }; + + return ( + + {error && ( +
+
+ )} + +
+ } + onChange={(event) => { + setCurrentPassword(event.target.value); + setJustSaved(false); + }} + type="password" + value={currentPassword} + /> +
+ +
+ } + onChange={(event) => { + setNewPassword(event.target.value); + setJustSaved(false); + }} + type="password" + value={newPassword} + /> +
+ +
+ {justSaved && ( + + + )} + + +
+
+ ); +} + +export function ApiKeyScreen() { + const { method } = useContext(AuthContext); + + return ( +
+ + {method === 'local' && }
); } diff --git a/web/src/screens/LoginScreen.test.tsx b/web/src/screens/LoginScreen.test.tsx new file mode 100644 index 000000000..70419b911 --- /dev/null +++ b/web/src/screens/LoginScreen.test.tsx @@ -0,0 +1,84 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { LoginScreen } from './LoginScreen'; +import type { AuthConfig } from '../api'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json' }, + status + }); +} + +const localConfig: AuthConfig = { oidcEnabled: false, localLoginEnabled: true, setupRequired: false }; + +describe('LoginScreen', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('signs in and calls onAuthenticated with the session', async () => { + const session = { authenticated: true, username: 'admin', method: 'local' }; + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse(session)); + const onAuthenticated = vi.fn(); + + render(); + + fireEvent.change(screen.getByPlaceholderText('Username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Password'), { target: { value: 'hunter2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + await waitFor(() => expect(onAuthenticated).toHaveBeenCalledWith(session)); + }); + + it('shows an inline error on a 401 without calling onAuthenticated', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ status: 401, title: 'Unauthorized' }, 401)); + const onAuthenticated = vi.fn(); + + render(); + + fireEvent.change(screen.getByPlaceholderText('Username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Password'), { target: { value: 'wrong' } }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + expect(await screen.findByText('Invalid username or password.')).toBeTruthy(); + expect(onAuthenticated).not.toHaveBeenCalled(); + }); + + it('renders the SSO button and navigates to the OIDC endpoint', () => { + const originalLocation = window.location; + // jsdom: replace location with a settable href sink. + Object.defineProperty(window, 'location', { + configurable: true, + value: { ...originalLocation, href: '' } + }); + + render( + + ); + + fireEvent.click(screen.getByRole('button', { name: /Sign in with SSO/ })); + expect(window.location.href).toBe('/auth/oidc/login'); + + Object.defineProperty(window, 'location', { configurable: true, value: originalLocation }); + }); + + it('hides the local form when local login is disabled', () => { + render( + + ); + + expect(screen.queryByPlaceholderText('Username')).toBeNull(); + expect(screen.getByRole('button', { name: /Sign in with SSO/ })).toBeTruthy(); + }); +}); diff --git a/web/src/screens/LoginScreen.tsx b/web/src/screens/LoginScreen.tsx new file mode 100644 index 000000000..387d84926 --- /dev/null +++ b/web/src/screens/LoginScreen.tsx @@ -0,0 +1,120 @@ +import { useState, type FormEvent } from 'react'; +import { KeyRound, LogIn, ShieldCheck, User } from 'lucide-react'; +import { Button, Card, Input } from '../components'; +import { ApiError, login, type AuthConfig, type AuthSession } from '../api'; + +// Shell-less centered sign-in card (#295). Rendered by AuthGate OUTSIDE the app shell — it mints no URL, +// so a deep link is preserved across the sign-in. Local username/password form shows only when the server +// enables local login; SSO button shows when OIDC is enabled (a top-level browser redirect, not an `/api` +// call). A wrong-credentials 401 is shown inline (login() suppresses the global 401 banner). +export interface LoginScreenProps { + config: AuthConfig; + onAuthenticated: (session: AuthSession) => void; +} + +export function LoginScreen({ config, onAuthenticated }: LoginScreenProps) { + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [error, setError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + const canSubmit = username.trim().length > 0 && password.length > 0 && !submitting; + + const onSubmit = (event: FormEvent) => { + event.preventDefault(); + + if (!canSubmit) { + return; + } + + setSubmitting(true); + setError(null); + + login(username.trim(), password) + .then((session) => { + onAuthenticated(session); + }) + .catch((caught: unknown) => { + if (caught instanceof ApiError && caught.status === 401) { + setError('Invalid username or password.'); + } else { + setError('Sign-in failed. Please try again.'); + } + setSubmitting(false); + }); + }; + + return ( +
+ + {config.localLoginEnabled && ( +
+
+ } + onChange={(event) => { + setUsername(event.target.value); + setError(null); + }} + placeholder="Username" + value={username} + /> + } + onChange={(event) => { + setPassword(event.target.value); + setError(null); + }} + placeholder="Password" + type="password" + value={password} + /> +
+ + {error && ( +
+ {error} +
+ )} + +
+ +
+
+ )} + + {config.oidcEnabled && ( +
+ +
+ )} + + {!config.localLoginEnabled && !config.oidcEnabled && ( +
+ No sign-in method is enabled on this server. Check the server configuration. +
+ )} +
+
+ ); +} diff --git a/web/src/screens/PlaybackTroubleshootingScreen.test.tsx b/web/src/screens/PlaybackTroubleshootingScreen.test.tsx index 63f02ed52..3b8e540df 100644 --- a/web/src/screens/PlaybackTroubleshootingScreen.test.tsx +++ b/web/src/screens/PlaybackTroubleshootingScreen.test.tsx @@ -39,11 +39,57 @@ function json(body: unknown, status = 200): Response { const IDLE: Status = { state: 'idle', exitCode: null, speed: null, logs: null }; +// The open `/iptv` live manifest the start endpoint returns (was the manifest GET's own URL pre-#295). +const LIVE_MANIFEST = '/iptv/session/.troubleshooting/live.m3u8'; + +// Engine-neutral fake: a real `new Response(new Blob(...))` fails in CI (undici) because a jsdom +// Blob has no `.stream()` for undici's Response body ("object.stream is not a function"), which +// rejects `response.blob()` so the download never clicks. A plain object with an async `blob()` +// avoids the Blob→Response interop crossing; `URL.createObjectURL` is stubbed so the body is inert. +function zipResponse(): Response { + return { + ok: true, + status: 200, + headers: new Headers({ + 'Content-Type': 'application/zip', + 'Content-Disposition': 'attachment; filename="out.zip"' + }), + blob: async () => new Blob(['zip-bytes']) + } as unknown as Response; +} + // A fetch stub keyed by URL. `statusRef.current` lets a test flip the polled status over time. -function installFetch(statusRef: { current: Status }) { - return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { +// `startBody` captures the POSTed start-playback body; `startStatus` lets a test force a start error. +function installFetch( + statusRef: { current: Status }, + options: { startStatus?: number; startBody?: { current: unknown }; startPending?: boolean } = {} +) { + return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + if (url === '/api/troubleshoot/playback/start') { + if (options.startBody) { + options.startBody.current = init?.body ? JSON.parse(String(init.body)) : null; + } + if (options.startStatus && options.startStatus >= 400) { + return Promise.resolve( + new Response(JSON.stringify({ status: options.startStatus, title: 'Conflict', detail: 'Another session is running.' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: options.startStatus + }) + ); + } + // Simulate a slow server that blocks past the starting timeout (never returns segments) — the + // only path that keeps the screen in the 'starting' phase now that a 200 promotes to running. + if (options.startPending) { + return new Promise(() => {}); + } + return Promise.resolve(json({ url: LIVE_MANIFEST })); + } + if (url === '/api/troubleshoot/playback/archive' || url.startsWith('/api/troubleshoot/playback/sample/')) { + return Promise.resolve(zipResponse()); + } + if (url.startsWith('/api/ffmpeg/profiles')) { return Promise.resolve(json([{ id: 1, name: 'Default' }, { id: 2, name: 'Hardware' }])); } @@ -155,10 +201,11 @@ describe('PlaybackTroubleshootingScreen', () => { expect(screen.queryByText('Seek Seconds')).toBeNull(); }); - it('sends the channel profile id (not 0) in the channel-mode playback URL', async () => { + it('sends the channel profile id (not 0) in the channel-mode start body', async () => { setLocation('/app/troubleshooting/playback?channel=7'); const statusRef = { current: IDLE }; - installFetch(statusRef); + const startBody = { current: null as unknown }; + installFetch(statusRef, { startBody }); render(); await screen.findByText(/Channel Settings — Channel Seven/i); @@ -172,21 +219,26 @@ describe('PlaybackTroubleshootingScreen', () => { fireEvent.click(screen.getByRole('button', { name: 'Play' })); - expect(hlsMock.loadSource).toHaveBeenCalledTimes(1); - const params = new URLSearchParams(String(hlsMock.loadSource.mock.calls[0][0]).split('?')[1]); + // The start endpoint returns the live manifest, which is fed to hls.js. + await waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledWith(LIVE_MANIFEST)); + // The regression this pins: the runtime channel JSON key is ffmpegProfileId (#198). Before the - // spec was aligned, reading the spec-cased fFmpegProfileId left the profile null and the URL + // spec was aligned, reading the spec-cased fFmpegProfileId left the profile null and the body // fell back to ffmpegProfile=0. - expect(params.get('ffmpegProfile')).toBe('2'); - expect(params.get('channel')).toBe('7'); - expect(params.get('start')).toBe(new Date('2026-07-09T20:00').toISOString()); - expect(params.get('mediaItem')).toBeNull(); + expect(startBody.current).toMatchObject({ + ffmpegProfile: 2, + channel: 7, + mediaItem: 0, + streamingMode: 'HttpLiveStreamingSegmenter', + start: new Date('2026-07-09T20:00').toISOString() + }); }); - it('builds the correct playback.m3u8 query on Play and starts polling', async () => { + it('POSTs the correct start body on Play, feeds the returned manifest to hls.js, and starts polling', async () => { setLocation('/app/troubleshooting/playback?mediaItem=5'); const statusRef = { current: IDLE }; - installFetch(statusRef); + const startBody = { current: null as unknown }; + installFetch(statusRef, { startBody }); vi.useFakeTimers(); try { @@ -198,15 +250,16 @@ describe('PlaybackTroubleshootingScreen', () => { fireEvent.click(screen.getByRole('button', { name: 'Play' })); - expect(hlsMock.loadSource).toHaveBeenCalledTimes(1); - const url = String(hlsMock.loadSource.mock.calls[0][0]); - expect(url.startsWith('/api/troubleshoot/playback.m3u8?')).toBe(true); - const params = new URLSearchParams(url.split('?')[1]); - expect(params.get('ffmpegProfile')).toBe('1'); - expect(params.get('streamingMode')).toBe('4'); - expect(params.get('mediaItem')).toBe('5'); - expect(params.get('seekSeconds')).toBe('1200'); // 40 min / 2 - expect(params.get('channel')).toBeNull(); + // The POST resolves with the live manifest, which is handed to hls.js. + await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledWith(LIVE_MANIFEST)); + + expect(startBody.current).toMatchObject({ + ffmpegProfile: 1, + streamingMode: 'HttpLiveStreamingSegmenter', + mediaItem: 5, + channel: 0, + seekSeconds: 1200 // 40 min / 2 + }); // Polling picks up the running status → Play becomes disabled. await vi.advanceTimersByTimeAsync(2000); @@ -216,6 +269,22 @@ describe('PlaybackTroubleshootingScreen', () => { } }); + it('surfaces the ProblemDetails detail and returns to idle when start fails (409)', async () => { + setLocation('/app/troubleshooting/playback?mediaItem=5'); + const statusRef = { current: IDLE }; + installFetch(statusRef, { startStatus: 409 }); + + render(); + await screen.findByText(/Movie Settings/i); + + fireEvent.click(screen.getByRole('button', { name: 'Play' })); + + // 409 detail surfaces via the notice, and Play returns to the idle (enabled) phase. + await waitFor(() => expect(screen.getByText('Another session is running.')).toBeTruthy()); + await waitFor(() => expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false)); + expect(hlsMock.loadSource).not.toHaveBeenCalled(); + }); + it('surfaces logs and a speed badge when polling transitions running → completed', async () => { setLocation('/app/troubleshooting/playback?mediaItem=5'); const statusRef = { current: IDLE }; @@ -256,10 +325,11 @@ describe('PlaybackTroubleshootingScreen', () => { render(); await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy()); - // First play through to completion. + // First play through to completion. The start POST resolves with the constant live manifest. statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null }; fireEvent.click(screen.getByRole('button', { name: 'Play' })); - expect(hlsMock.loadSource).toHaveBeenCalledTimes(1); + await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledTimes(1)); + expect(hlsMock.loadSource.mock.calls[0][0]).toBe(LIVE_MANIFEST); await vi.advanceTimersByTimeAsync(2000); // observe running statusRef.current = { state: 'completed', exitCode: 0, speed: 1.1, logs: 'done' }; @@ -268,10 +338,11 @@ describe('PlaybackTroubleshootingScreen', () => { expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false) ); - // Repeat Play with untouched settings: identical URL, but the manifest request MUST fire - // again (the GET is what starts a session server-side). + // Repeat Play with untouched settings: the manifest URL is identical, but HlsPlayer MUST + // re-attach (the playToken bump) so the returned live manifest is re-requested. + statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null }; fireEvent.click(screen.getByRole('button', { name: 'Play' })); - expect(hlsMock.loadSource).toHaveBeenCalledTimes(2); + await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledTimes(2)); expect(hlsMock.loadSource.mock.calls[1][0]).toBe(hlsMock.loadSource.mock.calls[0][0]); expect(hlsMock.destroy).toHaveBeenCalled(); // previous instance torn down before re-attach } finally { @@ -279,41 +350,32 @@ describe('PlaybackTroubleshootingScreen', () => { } }); - it('ignores a stale settled status while starting and only settles after observing running', async () => { + it('promotes to running on the start POST 200 and settles a fast-completing clip (Codex race fix)', async () => { setLocation('/app/troubleshooting/playback?mediaItem=5'); - // The store still holds the PREVIOUS session's result when Play is clicked. - const statusRef = { - current: { state: 'completed', exitCode: 0, speed: 2, logs: 'old logs' } as Status - }; + // PrepareTroubleshootingPlayback calls statusStore.Reset() server-side and the start POST returns + // 200 only after segments exist, so any settled status seen afterward is THIS session's. A short + // clip can settle between polls without any poll ever observing 'running' — it must still settle. + const statusRef = { current: IDLE }; installFetch(statusRef); vi.useFakeTimers(); try { render(); await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy()); - // Mount poll surfaces the previous session's logs (post-restart log recovery) without a toast. - await vi.waitFor(() => expect(screen.getByDisplayValue('old logs')).toBeTruthy()); - expect(screen.queryByText(/exited successfully/i)).toBeNull(); fireEvent.click(screen.getByRole('button', { name: 'Play' })); - // 'starting': Play disabled immediately, indicator shown, old logs cleared. + // 'starting': Play disabled immediately, indicator shown. expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(true); expect(screen.getByText('Starting…')).toBeTruthy(); - expect(screen.queryByDisplayValue('old logs')).toBeNull(); - // A poll returning the STALE completed result must be ignored — no toast, still gated. - await vi.advanceTimersByTimeAsync(2000); - expect(screen.queryByText(/exited successfully/i)).toBeNull(); - expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(true); - expect(screen.queryByDisplayValue('old logs')).toBeNull(); - - // Server reports running → transcoding phase. - statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null }; - await vi.advanceTimersByTimeAsync(2000); + // The start POST resolves 200 → phase promotes 'starting' → 'running' even though no poll has + // observed a 'running' status (statusRef is still IDLE), proving the promotion came from the POST. + await vi.advanceTimersByTimeAsync(0); await vi.waitFor(() => expect(screen.getByText('Transcoding…')).toBeTruthy()); - // Real completion → toast + new logs + Play re-enabled. + // The clip completed fast: the very next poll returns 'completed' and it is ACCEPTED (previously + // discarded as a stale result), so the toast + new logs appear and Play re-enables. statusRef.current = { state: 'completed', exitCode: 0, speed: 1.2, logs: 'new logs' }; await vi.advanceTimersByTimeAsync(2000); await vi.waitFor(() => expect(screen.getByText(/exited successfully/i)).toBeTruthy()); @@ -324,10 +386,12 @@ describe('PlaybackTroubleshootingScreen', () => { } }); - it('gives up with an error when the session never reports running', async () => { + it('gives up with an error when the start POST hangs and the session never reports running', async () => { setLocation('/app/troubleshooting/playback?mediaItem=5'); const statusRef = { current: IDLE }; - installFetch(statusRef); + // The start POST never resolves (slow server), so the only exit from 'starting' is the timeout — + // polls keep returning idle and no 200 ever promotes to running. + installFetch(statusRef, { startPending: true }); vi.useFakeTimers(); try { @@ -336,7 +400,7 @@ describe('PlaybackTroubleshootingScreen', () => { fireEvent.click(screen.getByRole('button', { name: 'Play' })); - // Status stays idle past the 30s starting timeout → error notice, Play re-enabled. + // Stays in 'starting' past the 30s timeout → error notice, Play re-enabled. await vi.advanceTimersByTimeAsync(32_000); await vi.waitFor(() => expect(screen.getByText(/did not start within 30 seconds/i)).toBeTruthy()); expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false); @@ -345,20 +409,32 @@ describe('PlaybackTroubleshootingScreen', () => { } }); - it('opens the archive and media-sample downloads, gated while a session is active', async () => { + it('downloads the archive and media sample via a POST-blob fetch (never a browser tab), gated while active', async () => { setLocation('/app/troubleshooting/playback?mediaItem=5'); const statusRef = { current: IDLE }; - installFetch(statusRef); + const fetchSpy = installFetch(statusRef); + // Never open a download endpoint in a browser tab. const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + // jsdom lacks these on URL — stub the object-URL/anchor-click download path. + (URL as unknown as { createObjectURL: unknown }).createObjectURL = vi.fn(() => 'blob:mock'); + (URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = vi.fn(); + const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}); + + const postCall = (path: string) => + fetchSpy.mock.calls.find( + (call) => call[0] === path && (call[1]?.method ?? 'GET').toUpperCase() === 'POST' + ); + vi.useFakeTimers(); try { render(); await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy()); - // Download Media Sample is available while idle. + // Download Media Sample is available while idle → POST-blob, not window.open. fireEvent.click(screen.getByRole('button', { name: /Download Media Sample/i })); - expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/sample/5'); + await vi.waitFor(() => expect(postCall('/api/troubleshoot/playback/sample/5')).toBeTruthy()); + expect(openSpy).not.toHaveBeenCalled(); // Both downloads are gated while a session is starting/running. statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null }; @@ -366,15 +442,18 @@ describe('PlaybackTroubleshootingScreen', () => { expect((screen.getByRole('button', { name: /Download Results/i }) as HTMLButtonElement).disabled).toBe(true); expect((screen.getByRole('button', { name: /Download Media Sample/i }) as HTMLButtonElement).disabled).toBe(true); - // Run to completion → Download Results enabled (hasPlayed && not busy). - await vi.advanceTimersByTimeAsync(2000); + // Drive to completion so Download Results enables (hasPlayed && not busy). + await vi.advanceTimersByTimeAsync(2000); // observe running statusRef.current = { state: 'completed', exitCode: 0, speed: 1, logs: 'done' }; - await vi.advanceTimersByTimeAsync(2000); + await vi.advanceTimersByTimeAsync(2000); // observe completed await vi.waitFor(() => expect((screen.getByRole('button', { name: /Download Results/i }) as HTMLButtonElement).disabled).toBe(false) ); + fireEvent.click(screen.getByRole('button', { name: /Download Results/i })); - expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/archive'); + await vi.waitFor(() => expect(postCall('/api/troubleshoot/playback/archive')).toBeTruthy()); + expect(clickSpy).toHaveBeenCalled(); + expect(openSpy).not.toHaveBeenCalled(); } finally { vi.useRealTimers(); } diff --git a/web/src/screens/PlaybackTroubleshootingScreen.tsx b/web/src/screens/PlaybackTroubleshootingScreen.tsx index 4fd518aee..c6dc74e1c 100644 --- a/web/src/screens/PlaybackTroubleshootingScreen.tsx +++ b/web/src/screens/PlaybackTroubleshootingScreen.tsx @@ -2,6 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro import { Download, DownloadCloud, PlayCircle, Stethoscope, TriangleAlert } from 'lucide-react'; import { Button, Card, Checkbox, Input, Select, Spinner, Toast } from '../components'; import { + downloadTroubleshootingArchive, + downloadTroubleshootingMediaSample, getChannelById, getFFmpegProfiles, getGraphicsElements, @@ -11,10 +13,12 @@ import { getTroubleshootingSubtitles, getWatermarks, messageFromTroubleshootError, + startTroubleshootingPlayback, type Channel, type FFmpegProfile, type GraphicsElement, type MediaItemInfo, + type StartTroubleshootingPlaybackBody, type TroubleshootingPlaybackStatus, type TroubleshootingSubtitle, type Watermark @@ -23,8 +27,9 @@ import { HlsPlayer } from '../media/HlsPlayer'; import { parseDurationSeconds } from '../media/mediaKinds'; // StreamingMode.HttpLiveStreamingSegmenter — mirrors PlaybackTroubleshooting.razor, which always -// requests the segmenter mode for troubleshooting playback. -const STREAMING_MODE_HLS_SEGMENTER = 4; +// requests the segmenter mode for troubleshooting playback. The start endpoint takes the StreamingMode +// as its serialized enum name (the generated request type is a string union), not the numeric value. +const STREAMING_MODE_HLS_SEGMENTER: StartTroubleshootingPlaybackBody['streamingMode'] = 'HttpLiveStreamingSegmenter'; const STATUS_POLL_MS = 2000; // How long after Play we keep waiting for the server to report 'running' before giving up. // PrepareTroubleshootingPlayback runs several DB queries before it takes the playback lock, so the @@ -364,15 +369,48 @@ export function PlaybackTroubleshootingScreen() { // Busy = a session this screen is aware of is starting or transcoding; gates Play + downloads. const isBusy = playPhase !== 'idle'; - // Build the playback.m3u8 query string, mirroring PlaybackTroubleshooting.razor PreviewChannel. - const buildPlaybackUrl = useCallback((): null | string => { - // Sending ffmpegProfile=0 is always wrong (no such profile) — refuse to build a URL without one. + const onDownloadArchive = async () => { + try { + await downloadTroubleshootingArchive(); + } catch (error: unknown) { + setNotice({ tone: 'error', message: messageFromTroubleshootError(error, 'Unable to download results') }); + } + }; + + const onDownloadMediaSample = async (id: number) => { + try { + await downloadTroubleshootingMediaSample(id); + } catch (error: unknown) { + setNotice({ tone: 'error', message: messageFromTroubleshootError(error, 'Unable to download media sample') }); + } + }; + + // Build the start-playback request body, mirroring PlaybackTroubleshooting.razor PreviewChannel. + // Returns null on invalid input (no profile, or a channel without a valid start datetime) — the same + // guard the old URL builder used; Play is also disabled in those states so null is defensive. + const buildPlaybackParams = useCallback((): StartTroubleshootingPlaybackBody | null => { + // Sending ffmpegProfile=0 is always wrong (no such profile) — refuse without one. if (form.ffmpegProfileId == null) { return null; } - const params = new URLSearchParams(); - params.set('ffmpegProfile', String(form.ffmpegProfileId)); - params.set('streamingMode', String(STREAMING_MODE_HLS_SEGMENTER)); + + // Stream selector and subtitle are mutually exclusive (selector wins). + let streamSelector: null | string = null; + let subtitleId: null | number = null; + if (form.streamSelector !== '') { + streamSelector = form.streamSelector; + } else if (form.subtitleId != null) { + subtitleId = form.subtitleId; + } + + const common = { + ffmpegProfile: form.ffmpegProfileId, + streamingMode: STREAMING_MODE_HLS_SEGMENTER, + watermark: form.watermarkIds, + graphicsElement: form.graphicsElementIds, + streamSelector, + subtitleId + }; if (mode.kind === 'channel') { if (form.startValue === '') { @@ -382,35 +420,31 @@ export function PlaybackTroubleshootingScreen() { if (Number.isNaN(parsed.getTime())) { return null; } - params.set('channel', String(mode.channelId)); - params.set('start', parsed.toISOString()); - } else if (mode.kind === 'media') { - params.set('mediaItem', String(mode.mediaItemId)); - params.set('seekSeconds', String(form.seekSeconds)); - } else { - return null; + return { + ...common, + mediaItem: 0, + channel: mode.channelId, + seekSeconds: 0, + start: parsed.toISOString() + }; } - for (const id of form.watermarkIds) { - params.append('watermark', String(id)); - } - for (const id of form.graphicsElementIds) { - params.append('graphicsElement', String(id)); + if (mode.kind === 'media') { + return { + ...common, + mediaItem: mode.mediaItemId, + channel: 0, + seekSeconds: form.seekSeconds, + start: null + }; } - // Stream selector and subtitle are mutually exclusive (selector wins). - if (form.streamSelector !== '') { - params.set('streamSelector', form.streamSelector); - } else if (form.subtitleId != null) { - params.set('subtitleId', String(form.subtitleId)); - } - - return `/api/troubleshoot/playback.m3u8?${params.toString()}`; + return null; }, [form, mode]); - const onPlay = () => { - const url = buildPlaybackUrl(); - if (url === null) { + const onPlay = async () => { + const body = buildPlaybackParams(); + if (body === null) { return; } setNotice(null); @@ -418,10 +452,38 @@ export function PlaybackTroubleshootingScreen() { setPhase('starting'); startingSinceRef.current = Date.now(); setHasPlayed(true); - setPlayerSrc(url); - // Bump the token so HlsPlayer re-attaches even when the URL is identical to the previous play. - setPlayToken((current) => current + 1); startPolling(); + + try { + const result = await startTroubleshootingPlayback(body); + if (!activeRef.current) { + return; + } + // The start endpoint returns the open `/iptv` live manifest — feed it to HlsPlayer. The URL is + // constant across plays, so bump the token to force a re-attach even on a repeat play. + setPlayerSrc(result.url); + setPlayToken((current) => current + 1); + // Fast-completion race (Codex MAJOR): the POST returns 200 only after segments exist, so a short + // clip can settle between polls; applyStatus discards settled states while 'starting', turning a + // genuine completion into a false 30s startup-failure. PrepareTroubleshootingPlayback calls + // statusStore.Reset() server-side, so ANY status observed after a 200 belongs to THIS session — + // promote 'starting' → 'running' here so the next poll's terminal status is accepted, not + // discarded. The poll-based promotion is kept for the (normal) still-running case. + if (phaseRef.current === 'starting') { + setPhase('running'); + } + } catch (error: unknown) { + if (!activeRef.current) { + return; + } + // A 409 (another session running) / 404 / 422 now surfaces its ProblemDetails detail inline. + stopPolling(); + setPhase('idle'); + setNotice({ + tone: 'error', + message: messageFromTroubleshootError(error, 'Unable to start troubleshooting playback') + }); + } }; if (mode.kind === 'empty') { @@ -506,7 +568,7 @@ export function PlaybackTroubleshootingScreen() {
+
+ +
+ ); + } + + return ( +
+ +
+
+ } + onChange={(event) => { + setUsername(event.target.value); + setError(null); + }} + placeholder="Choose a username" + value={username} + /> + } + onChange={(event) => { + setPassword(event.target.value); + setError(null); + }} + placeholder="Choose a password" + type="password" + value={password} + /> + 0 && !passwordsMatch ? 'Passwords do not match.' : null} + label="Confirm password" + leadingIcon={
+ + {error && ( +
+ {error} +
+ )} + +
+ +
+
+
+
+ ); +} diff --git a/web/src/shell.css b/web/src/shell.css index 600186bd9..1a9b7f06d 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -4465,3 +4465,14 @@ body { padding: 4px; border-radius: var(--radius-sm); } + +/* Shell-less boot pages (login / setup / checking / error) — the AuthGate renders these OUTSIDE the app + shell, so they own their own full-viewport centered layout (#295). */ +.ctv-auth-page { + display: flex; + align-items: center; + justify-content: center; + min-height: 100vh; + padding: 24px; + background: var(--surface-app); +}