|
| 1 | +using Mattermost.Exceptions; |
| 2 | +using Mattermost.Models.Users; |
| 3 | +using System.Net; |
| 4 | +using System.Text.Json; |
| 5 | + |
| 6 | +namespace Mattermost.Tests |
| 7 | +{ |
| 8 | + [TestFixture] |
| 9 | + internal class UserMfaTests |
| 10 | + { |
| 11 | + [Test] |
| 12 | + public void MfaSecret_UsesExactNativeCredentialFields() |
| 13 | + { |
| 14 | + const string json = "{\"secret\":\"TEST-SECRET\",\"qr_code\":\"cG5n\"}"; |
| 15 | + MfaSecret model = JsonSerializer.Deserialize<MfaSecret>(json)!; |
| 16 | + Assert.That(JsonSerializer.Serialize(model), Is.EqualTo(json)); |
| 17 | + } |
| 18 | + |
| 19 | + [Test] |
| 20 | + public async Task GenerateMfaSecret_UsesNativePostAndReturnsBothCredentials() |
| 21 | + { |
| 22 | + using HttpClient http = ApiTestHttp.Create((request, _) => |
| 23 | + { |
| 24 | + Assert.That(request.Method, Is.EqualTo(HttpMethod.Post)); |
| 25 | + Assert.That(request.RequestUri!.AbsoluteUri, Is.EqualTo("https://mattermost.example/chat/api/v4/users/user%2F1%3Fx%23y/mfa/generate")); |
| 26 | + Assert.That(request.Content, Is.Null); |
| 27 | + return Task.FromResult(ApiTestHttp.Json(HttpStatusCode.OK, "{\"secret\":\"TEST-SECRET\",\"qr_code\":\"cG5n\"}")); |
| 28 | + }); |
| 29 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 30 | + MfaSecret result = await client.GenerateMfaSecretAsync(" user/1?x#y "); |
| 31 | + Assert.That(result.Secret, Is.EqualTo("TEST-SECRET")); |
| 32 | + Assert.That(result.QRCode, Is.EqualTo("cG5n")); |
| 33 | + } |
| 34 | + |
| 35 | + [TestCase(true, " 123456 ", "{\"activate\":true,\"code\":\" 123456 \"}")] |
| 36 | + [TestCase(false, null, "{\"activate\":false}")] |
| 37 | + [TestCase(false, "ignored", "{\"activate\":false}")] |
| 38 | + public async Task UpdateUserMfa_SendsNativeFieldsAndDoesNotSendInactiveCode(bool activate, string? code, string expected) |
| 39 | + { |
| 40 | + using HttpClient http = ApiTestHttp.Create(async (request, token) => |
| 41 | + { |
| 42 | + Assert.That(request.Method, Is.EqualTo(HttpMethod.Put)); |
| 43 | + Assert.That(request.RequestUri!.AbsoluteUri, Is.EqualTo("https://mattermost.example/chat/api/v4/users/user%2F1%3Fx%23y/mfa")); |
| 44 | + Assert.That(await request.Content!.ReadAsStringAsync(token), Is.EqualTo(expected)); |
| 45 | + return ApiTestHttp.Json(HttpStatusCode.OK, "{\"status\":\"OK\"}"); |
| 46 | + }); |
| 47 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 48 | + await client.UpdateUserMfaAsync(" user/1?x#y ", activate, code); |
| 49 | + } |
| 50 | + |
| 51 | + [TestCase(false)] |
| 52 | + [TestCase(true)] |
| 53 | + public async Task Mfa_CurrentUserAliasIsPreserved(bool generate) |
| 54 | + { |
| 55 | + using HttpClient http = ApiTestHttp.Create((request, _) => |
| 56 | + { |
| 57 | + Assert.That(request.RequestUri!.AbsolutePath, Does.Contain("/users/me/mfa")); |
| 58 | + return Task.FromResult(ApiTestHttp.Json(HttpStatusCode.OK, "{\"secret\":\"test\",\"qr_code\":\"test\"}")); |
| 59 | + }); |
| 60 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 61 | + await InvokeAsync(client, generate, "me"); |
| 62 | + } |
| 63 | + |
| 64 | + [TestCase(false, null)] |
| 65 | + [TestCase(false, "")] |
| 66 | + [TestCase(false, " \t")] |
| 67 | + [TestCase(true, null)] |
| 68 | + [TestCase(true, "")] |
| 69 | + [TestCase(true, " \t")] |
| 70 | + public void Mfa_BlankUserIsRejected(bool generate, string? userId) |
| 71 | + { |
| 72 | + using HttpClient http = ApiTestHttp.RejectRequests(); |
| 73 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 74 | + ArgumentException error = Assert.Throws<ArgumentException>(() => InvokeAsync(client, generate, userId!))!; |
| 75 | + Assert.That(error.ParamName, Is.EqualTo("userId")); |
| 76 | + } |
| 77 | + |
| 78 | + [TestCase(null)] |
| 79 | + [TestCase("")] |
| 80 | + public void UpdateUserMfa_ActivationWithoutCodeIsRejected(string? code) |
| 81 | + { |
| 82 | + using HttpClient http = ApiTestHttp.RejectRequests(); |
| 83 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 84 | + ArgumentException error = Assert.Throws<ArgumentException>(() => client.UpdateUserMfaAsync("me", true, code))!; |
| 85 | + Assert.That(error.ParamName, Is.EqualTo("code")); |
| 86 | + } |
| 87 | + |
| 88 | + [TestCase(false, HttpStatusCode.BadRequest)] |
| 89 | + [TestCase(false, HttpStatusCode.Unauthorized)] |
| 90 | + [TestCase(false, HttpStatusCode.Forbidden)] |
| 91 | + [TestCase(false, HttpStatusCode.NotFound)] |
| 92 | + [TestCase(false, HttpStatusCode.InternalServerError)] |
| 93 | + [TestCase(false, HttpStatusCode.NotImplemented)] |
| 94 | + [TestCase(true, HttpStatusCode.BadRequest)] |
| 95 | + [TestCase(true, HttpStatusCode.Unauthorized)] |
| 96 | + [TestCase(true, HttpStatusCode.Forbidden)] |
| 97 | + [TestCase(true, HttpStatusCode.NotFound)] |
| 98 | + [TestCase(true, HttpStatusCode.InternalServerError)] |
| 99 | + [TestCase(true, HttpStatusCode.NotImplemented)] |
| 100 | + public async Task Mfa_NativeErrorIsPropagatedWithoutRetry(bool generate, HttpStatusCode status) |
| 101 | + { |
| 102 | + int requests = 0; |
| 103 | + using HttpClient http = ApiTestHttp.Create((_, _) => |
| 104 | + { |
| 105 | + requests++; |
| 106 | + return Task.FromResult(ApiTestHttp.Json(status, "{\"message\":\"MFA rejected\"}")); |
| 107 | + }); |
| 108 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 109 | + MattermostClientException error = (await Assert.ThrowsAsync<MattermostClientException>(() => InvokeAsync(client, generate)))!; |
| 110 | + Assert.That(error.StatusCode, Is.EqualTo(status)); |
| 111 | + Assert.That(error.Message, Is.EqualTo("MFA rejected")); |
| 112 | + Assert.That(requests, Is.EqualTo(1)); |
| 113 | + } |
| 114 | + |
| 115 | + [TestCase("null")] |
| 116 | + [TestCase("[]")] |
| 117 | + [TestCase("{broken")] |
| 118 | + public async Task GenerateMfaSecret_InvalidResponseIsRejected(string response) |
| 119 | + { |
| 120 | + using HttpClient http = ApiTestHttp.Create((_, _) => Task.FromResult(ApiTestHttp.Json(HttpStatusCode.OK, response))); |
| 121 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 122 | + await Assert.CatchAsync<JsonException>(() => client.GenerateMfaSecretAsync("me")); |
| 123 | + } |
| 124 | + |
| 125 | + [TestCase(false)] |
| 126 | + [TestCase(true)] |
| 127 | + public void Mfa_CancelledAndDisposedCallsSendNothing(bool generate) |
| 128 | + { |
| 129 | + using HttpClient http = ApiTestHttp.RejectRequests(); |
| 130 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 131 | + using CancellationTokenSource cancellation = new CancellationTokenSource(); |
| 132 | + cancellation.Cancel(); |
| 133 | + Assert.Throws<OperationCanceledException>(() => InvokeAsync(client, generate, token: cancellation.Token)); |
| 134 | + client.Dispose(); |
| 135 | + Assert.Throws<ObjectDisposedException>(() => InvokeAsync(client, generate)); |
| 136 | + } |
| 137 | + |
| 138 | + [TestCase(false, false)] |
| 139 | + [TestCase(false, true)] |
| 140 | + [TestCase(true, false)] |
| 141 | + [TestCase(true, true)] |
| 142 | + public async Task Mfa_CancellationStopsAuthenticationOrRequest(bool generate, bool authentication) |
| 143 | + { |
| 144 | + using CancellationTokenSource cancellation = new CancellationTokenSource(); |
| 145 | + TaskCompletionSource<bool> started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 146 | + using HttpClient http = new HttpClient(new DelegateHttpMessageHandler(async (request, token) => |
| 147 | + { |
| 148 | + if (!authentication && request.RequestUri!.AbsolutePath.EndsWith("/users/me", StringComparison.Ordinal)) |
| 149 | + { |
| 150 | + return ApiTestHttp.Json(HttpStatusCode.OK, "{\"id\":\"user-1\"}"); |
| 151 | + } |
| 152 | + started.TrySetResult(true); |
| 153 | + await Task.Delay(Timeout.InfiniteTimeSpan, token); |
| 154 | + throw new AssertionException("Expected cancellation."); |
| 155 | + })); |
| 156 | + using MattermostClient client = ApiTestHttp.Client(http); |
| 157 | + Task pending = InvokeAsync(client, generate, token: cancellation.Token); |
| 158 | + await started.Task.WaitAsync(TimeSpan.FromSeconds(5)); |
| 159 | + await cancellation.CancelAsync(); |
| 160 | + await Assert.CatchAsync<OperationCanceledException>(async () => await pending.WaitAsync(TimeSpan.FromSeconds(5))); |
| 161 | + } |
| 162 | + |
| 163 | + private static Task InvokeAsync(IMattermostUsersClient client, bool generate, string userId = "user-1", CancellationToken token = default) |
| 164 | + { |
| 165 | + if (generate) { return client.GenerateMfaSecretAsync(userId, token); } |
| 166 | + return client.UpdateUserMfaAsync(userId, true, "123456", token); |
| 167 | + } |
| 168 | + } |
| 169 | +} |
0 commit comments