CustomAuthenticationHandlerTests.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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.Equal("Invalid user", authenticateResult.Failure.Message);
  77. }
  78. [Fact]
  79. public async Task HandleAuthenticateAsyncShouldFailOnSecurityException()
  80. {
  81. var errorMessage = _fixture.Create<string>();
  82. _jellyfinAuthServiceMock.Setup(
  83. a => a.Authenticate(
  84. It.IsAny<HttpRequest>(),
  85. It.IsAny<AuthenticatedAttribute>()))
  86. .Throws(new SecurityException(errorMessage));
  87. var authenticateResult = await _sut.AuthenticateAsync();
  88. Assert.False(authenticateResult.Succeeded);
  89. Assert.Equal(errorMessage, authenticateResult.Failure.Message);
  90. }
  91. [Fact]
  92. public async Task HandleAuthenticateAsyncShouldSucceedWithUser()
  93. {
  94. SetupUser();
  95. var authenticateResult = await _sut.AuthenticateAsync();
  96. Assert.True(authenticateResult.Succeeded);
  97. Assert.Null(authenticateResult.Failure);
  98. }
  99. [Fact]
  100. public async Task HandleAuthenticateAsyncShouldAssignNameClaim()
  101. {
  102. var user = SetupUser();
  103. var authenticateResult = await _sut.AuthenticateAsync();
  104. Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Name, user.Name));
  105. }
  106. [Theory]
  107. [InlineData(true)]
  108. [InlineData(false)]
  109. public async Task HandleAuthenticateAsyncShouldAssignRoleClaim(bool isAdmin)
  110. {
  111. var user = SetupUser(isAdmin);
  112. var authenticateResult = await _sut.AuthenticateAsync();
  113. var expectedRole = user.Policy.IsAdministrator ? UserRoles.Administrator : UserRoles.User;
  114. Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Role, expectedRole));
  115. }
  116. [Fact]
  117. public async Task HandleAuthenticateAsyncShouldAssignTicketCorrectScheme()
  118. {
  119. SetupUser();
  120. var authenticatedResult = await _sut.AuthenticateAsync();
  121. Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme);
  122. }
  123. private User SetupUser(bool isAdmin = false)
  124. {
  125. var user = _fixture.Create<User>();
  126. user.Policy.IsAdministrator = isAdmin;
  127. _jellyfinAuthServiceMock.Setup(
  128. a => a.Authenticate(
  129. It.IsAny<HttpRequest>(),
  130. It.IsAny<AuthenticatedAttribute>()))
  131. .Returns(user);
  132. return user;
  133. }
  134. private void AllowFixtureCircularDependencies()
  135. {
  136. // A circular dependency exists in the User entity around parent folders,
  137. // this allows Autofixture to generate a User regardless, rather than throw
  138. // an error.
  139. _fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList()
  140. .ForEach(b => _fixture.Behaviors.Remove(b));
  141. _fixture.Behaviors.Add(new OmitOnRecursionBehavior());
  142. }
  143. }
  144. }