2
0

CustomAuthenticationHandlerTests.cs 5.7 KB

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