CustomAuthenticationHandlerTests.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. using System;
  2. using System.Linq;
  3. using System.Security.Claims;
  4. using System.Text.Encodings.Web;
  5. using System.Threading.Tasks;
  6. using AutoFixture;
  7. using AutoFixture.AutoMoq;
  8. using Jellyfin.Api.Auth;
  9. using Jellyfin.Api.Constants;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Net;
  12. using Microsoft.AspNetCore.Authentication;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.Extensions.Logging;
  15. using Microsoft.Extensions.Logging.Abstractions;
  16. using Microsoft.Extensions.Options;
  17. using Moq;
  18. using Xunit;
  19. namespace Jellyfin.Api.Tests.Auth
  20. {
  21. public class CustomAuthenticationHandlerTests
  22. {
  23. private readonly IFixture _fixture;
  24. private readonly Mock<IAuthService> _jellyfinAuthServiceMock;
  25. private readonly Mock<IOptionsMonitor<AuthenticationSchemeOptions>> _optionsMonitorMock;
  26. private readonly Mock<ISystemClock> _clockMock;
  27. private readonly Mock<IServiceProvider> _serviceProviderMock;
  28. private readonly Mock<IAuthenticationService> _authenticationServiceMock;
  29. private readonly UrlEncoder _urlEncoder;
  30. private readonly HttpContext _context;
  31. private readonly CustomAuthenticationHandler _sut;
  32. private readonly AuthenticationScheme _scheme;
  33. public CustomAuthenticationHandlerTests()
  34. {
  35. var fixtureCustomizations = new AutoMoqCustomization
  36. {
  37. ConfigureMembers = true
  38. };
  39. _fixture = new Fixture().Customize(fixtureCustomizations);
  40. AllowFixtureCircularDependencies();
  41. _jellyfinAuthServiceMock = _fixture.Freeze<Mock<IAuthService>>();
  42. _optionsMonitorMock = _fixture.Freeze<Mock<IOptionsMonitor<AuthenticationSchemeOptions>>>();
  43. _clockMock = _fixture.Freeze<Mock<ISystemClock>>();
  44. _serviceProviderMock = _fixture.Freeze<Mock<IServiceProvider>>();
  45. _authenticationServiceMock = _fixture.Freeze<Mock<IAuthenticationService>>();
  46. _fixture.Register<ILoggerFactory>(() => new NullLoggerFactory());
  47. _urlEncoder = UrlEncoder.Default;
  48. _serviceProviderMock.Setup(s => s.GetService(typeof(IAuthenticationService)))
  49. .Returns(_authenticationServiceMock.Object);
  50. _optionsMonitorMock.Setup(o => o.Get(It.IsAny<string>()))
  51. .Returns(new AuthenticationSchemeOptions
  52. {
  53. ForwardAuthenticate = null
  54. });
  55. _context = new DefaultHttpContext
  56. {
  57. RequestServices = _serviceProviderMock.Object
  58. };
  59. _scheme = new AuthenticationScheme(
  60. _fixture.Create<string>(),
  61. null,
  62. typeof(CustomAuthenticationHandler));
  63. _sut = _fixture.Create<CustomAuthenticationHandler>();
  64. _sut.InitializeAsync(_scheme, _context).Wait();
  65. }
  66. [Fact]
  67. public async Task HandleAuthenticateAsyncShouldFailWithNullUser()
  68. {
  69. _jellyfinAuthServiceMock.Setup(
  70. a => a.Authenticate(
  71. It.IsAny<HttpRequest>(),
  72. It.IsAny<AuthenticatedAttribute>()))
  73. .Returns((User?)null);
  74. var authenticateResult = await _sut.AuthenticateAsync();
  75. Assert.False(authenticateResult.Succeeded);
  76. Assert.True(authenticateResult.None);
  77. // TODO return when legacy API is removed.
  78. // Assert.Equal("Invalid user", authenticateResult.Failure.Message);
  79. }
  80. [Fact]
  81. public async Task HandleAuthenticateAsyncShouldFailOnSecurityException()
  82. {
  83. var errorMessage = _fixture.Create<string>();
  84. _jellyfinAuthServiceMock.Setup(
  85. a => a.Authenticate(
  86. It.IsAny<HttpRequest>(),
  87. It.IsAny<AuthenticatedAttribute>()))
  88. .Throws(new SecurityException(errorMessage));
  89. var authenticateResult = await _sut.AuthenticateAsync();
  90. Assert.False(authenticateResult.Succeeded);
  91. Assert.Equal(errorMessage, authenticateResult.Failure.Message);
  92. }
  93. [Fact]
  94. public async Task HandleAuthenticateAsyncShouldSucceedWithUser()
  95. {
  96. SetupUser();
  97. var authenticateResult = await _sut.AuthenticateAsync();
  98. Assert.True(authenticateResult.Succeeded);
  99. Assert.Null(authenticateResult.Failure);
  100. }
  101. [Fact]
  102. public async Task HandleAuthenticateAsyncShouldAssignNameClaim()
  103. {
  104. var user = SetupUser();
  105. var authenticateResult = await _sut.AuthenticateAsync();
  106. Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Name, user.Name));
  107. }
  108. [Theory]
  109. [InlineData(true)]
  110. [InlineData(false)]
  111. public async Task HandleAuthenticateAsyncShouldAssignRoleClaim(bool isAdmin)
  112. {
  113. var user = SetupUser(isAdmin);
  114. var authenticateResult = await _sut.AuthenticateAsync();
  115. var expectedRole = user.Policy.IsAdministrator ? UserRoles.Administrator : UserRoles.User;
  116. Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Role, expectedRole));
  117. }
  118. [Fact]
  119. public async Task HandleAuthenticateAsyncShouldAssignTicketCorrectScheme()
  120. {
  121. SetupUser();
  122. var authenticatedResult = await _sut.AuthenticateAsync();
  123. Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme);
  124. }
  125. private User SetupUser(bool isAdmin = false)
  126. {
  127. var user = _fixture.Create<User>();
  128. user.Policy.IsAdministrator = isAdmin;
  129. _jellyfinAuthServiceMock.Setup(
  130. a => a.Authenticate(
  131. It.IsAny<HttpRequest>(),
  132. It.IsAny<AuthenticatedAttribute>()))
  133. .Returns(user);
  134. return user;
  135. }
  136. private void AllowFixtureCircularDependencies()
  137. {
  138. // A circular dependency exists in the User entity around parent folders,
  139. // this allows Autofixture to generate a User regardless, rather than throw
  140. // an error.
  141. _fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList()
  142. .ForEach(b => _fixture.Behaviors.Remove(b));
  143. _fixture.Behaviors.Add(new OmitOnRecursionBehavior());
  144. }
  145. }
  146. }