From 3059686992918bcdaef613ed4741f57f3f488543 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Sun, 29 Nov 2026 22:00:55 -0600 Subject: [PATCH 1/2] Fix Microsoft sign-in configuration and provider handling --- build/update-config.sh | 11 ++- docs/docs/self-hosting/configuration.md | 5 ++ src/Exceptionless.Core/Bootstrapper.cs | 5 +- .../Configuration/AuthOptions.cs | 3 + .../Api/Endpoints/AuthEndpoints.cs | 4 ++ .../Api/Handlers/AuthHandler.cs | 64 +++++++++++++++-- .../src/lib/features/auth/index.svelte.ts | 5 +- .../src/lib/features/auth/microsoft.test.ts | 20 ++++-- .../Exceptionless.Web.csproj | 2 +- src/Exceptionless.Web/Program.cs | 2 +- .../Exceptionless.Tests/Api/Data/openapi.json | 20 ++++++ .../Api/Endpoints/AuthEndpointTests.cs | 2 +- .../Endpoints/MicrosoftAuthEndpointTests.cs | 8 +-- .../Api/Handlers/AuthHandlerTests.cs | 72 ++++++++++++++++++- .../Exceptionless.Tests/BootstrapperTests.cs | 3 +- .../Utility/TestOAuthProviderClient.cs | 2 + 16 files changed, 201 insertions(+), 27 deletions(-) diff --git a/build/update-config.sh b/build/update-config.sh index e23eb6707a..9a9b80b7a5 100644 --- a/build/update-config.sh +++ b/build/update-config.sh @@ -3,6 +3,7 @@ set -euo pipefail # Only publish client IDs. OAuth secrets must never enter env.js or startup logs. declare -A oauth_ids=() +microsoft_secret_configured=false IFS=';' read -ra oauth_parts <<< "${EX_ConnectionStrings__OAuth:-}" for part in "${oauth_parts[@]}"; do key="${part%%=*}" @@ -13,9 +14,17 @@ for part in "${oauth_parts[@]}"; do case "$key" in GitHubId|GoogleId|IntercomId|MicrosoftId|SlackId) oauth_ids[$key]="$value" ;; + MicrosoftSecret) + microsoft_secret_configured=false + [[ -z "$value" ]] || microsoft_secret_configured=true ;; esac done +microsoft_id="${oauth_ids[MicrosoftId]:-}" +if [[ "$microsoft_secret_configured" == false || ! "$microsoft_id" =~ ^[[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}$ || "$microsoft_id" == 00000000-0000-0000-0000-000000000000 ]]; then + microsoft_id="" +fi + js_string() { local value="${1:-}" value="${value//\\/\\\\}" @@ -45,7 +54,7 @@ mkdir -p _app write_setting PUBLIC_STRIPE_PUBLISHABLE_KEY "${EX_StripePublishableApiKey:-}" write_setting PUBLIC_GITHUB_APPID "${oauth_ids[GitHubId]:-}" write_setting PUBLIC_GOOGLE_APPID "${oauth_ids[GoogleId]:-}" - write_setting PUBLIC_MICROSOFT_APPID "${oauth_ids[MicrosoftId]:-}" + write_setting PUBLIC_MICROSOFT_APPID "$microsoft_id" write_setting PUBLIC_INTERCOM_APPID "${oauth_ids[IntercomId]:-}" write_setting PUBLIC_SLACK_APPID "${oauth_ids[SlackId]:-}" printf '};\n' diff --git a/docs/docs/self-hosting/configuration.md b/docs/docs/self-hosting/configuration.md index d34b8de5df..09754bf507 100644 --- a/docs/docs/self-hosting/configuration.md +++ b/docs/docs/self-hosting/configuration.md @@ -184,6 +184,11 @@ Include only the providers you use. Each provider sends users back to the origin | GitHub | `GitHubId`, `GitHubSecret` | A GitHub OAuth app. Set its authorization callback URL to your web app's origin. Exceptionless asks for the `user:email` scope. | | Google | `GoogleId`, `GoogleSecret` | An OAuth client ID of type **Web application** in Google Cloud, with your web app's origin as an authorized redirect URI. Exceptionless asks for `openid profile email`. | +Use the Entra **Application (client) ID** for `MicrosoftId`. Replace any saved 16-character Windows Live ID when migrating. +For `MicrosoftSecret`, use the unexpired client secret **Value** from the same app registration. If Microsoft rejects +token exchange, look for the OAuth error and Entra error code in the server log and check it against the +[Microsoft Entra error reference](https://learn.microsoft.com/en-us/entra/identity-platform/reference-error-codes). + ### Slack Slack notifications use the same connection string, with `SlackId` and `SlackSecret` from a Slack app: diff --git a/src/Exceptionless.Core/Bootstrapper.cs b/src/Exceptionless.Core/Bootstrapper.cs index 7bc92f0526..4a8c4f03fe 100644 --- a/src/Exceptionless.Core/Bootstrapper.cs +++ b/src/Exceptionless.Core/Bootstrapper.cs @@ -334,6 +334,9 @@ public static void LogConfiguration(IServiceProvider serviceProvider, AppOptions if (!appOptions.AuthOptions.EnableAccountCreation) logger.LogWarning("Account Creation is NOT enabled on {MachineName}", Environment.MachineName); + + if (!String.IsNullOrWhiteSpace(appOptions.AuthOptions.MicrosoftId) && !appOptions.AuthOptions.IsMicrosoftConfigured) + logger.LogWarning("Microsoft sign-in requires an Entra application ID in GUID format and a client secret value"); } private static void LogConfigurationSummary(IServiceProvider serviceProvider, AppOptions options, ILogger logger) @@ -385,7 +388,7 @@ private static string GetEnabledIntegrations(AppOptions options) List integrations = []; if (!String.IsNullOrWhiteSpace(options.AuthOptions.GoogleId)) integrations.Add("Google OAuth"); - if (!String.IsNullOrWhiteSpace(options.AuthOptions.MicrosoftId)) + if (options.AuthOptions.IsMicrosoftConfigured) integrations.Add("Microsoft OAuth"); if (!String.IsNullOrWhiteSpace(options.AuthOptions.GitHubId)) integrations.Add("GitHub OAuth"); diff --git a/src/Exceptionless.Core/Configuration/AuthOptions.cs b/src/Exceptionless.Core/Configuration/AuthOptions.cs index b7bb6ce807..cf9fcf56bb 100644 --- a/src/Exceptionless.Core/Configuration/AuthOptions.cs +++ b/src/Exceptionless.Core/Configuration/AuthOptions.cs @@ -13,6 +13,9 @@ public class AuthOptions public string? MicrosoftSecret { get; internal set; } + public bool IsMicrosoftConfigured => Guid.TryParseExact(MicrosoftId, "D", out var clientId) + && clientId != Guid.Empty && !String.IsNullOrWhiteSpace(MicrosoftSecret); + public string? GitHubId { get; internal set; } public string? GitHubSecret { get; internal set; } diff --git a/src/Exceptionless.Web/Api/Endpoints/AuthEndpoints.cs b/src/Exceptionless.Web/Api/Endpoints/AuthEndpoints.cs index e0bcc0d053..826d9dcd70 100644 --- a/src/Exceptionless.Web/Api/Endpoints/AuthEndpoints.cs +++ b/src/Exceptionless.Web/Api/Endpoints/AuthEndpoints.cs @@ -140,14 +140,18 @@ headers api_key input box. .AllowAnonymous() .Accepts("application/json", "application/*+json") .Produces() + .ProducesProblem(StatusCodes.Status401Unauthorized) .ProducesProblem(StatusCodes.Status403Forbidden) .ProducesProblem(StatusCodes.Status422UnprocessableEntity) + .ProducesProblem(StatusCodes.Status503ServiceUnavailable) .WithSummary("Sign in with Microsoft") .WithMetadata(new EndpointDocumentation { ResponseDescriptions = new() { ["200"] = "User Authentication Token", + ["401"] = "The Microsoft authorization code expired or was rejected", ["403"] = "Account Creation is currently disabled, or the email belongs to an existing account that must sign in and link Microsoft first", ["422"] = "Validation error", + ["503"] = "Microsoft sign-in is unavailable", } }); diff --git a/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs b/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs index 8e86aec99d..1cc9f39dbe 100644 --- a/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs +++ b/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs @@ -1,6 +1,8 @@ using System.Configuration; using System.IdentityModel.Tokens.Jwt; +using System.Net; using System.Text; +using System.Text.Json; using Exceptionless.Core.Authentication; using Exceptionless.Core.Authorization; using Exceptionless.Core.Configuration; @@ -18,6 +20,7 @@ using Foundatio.Mediator; using Foundatio.Repositories; using Microsoft.IdentityModel.Tokens; +using OAuth2.Client; using OAuth2.Models; namespace Exceptionless.Web.Api.Handlers; @@ -37,6 +40,7 @@ public class AuthHandler( TimeProvider timeProvider, ILogger logger) { + private const string MicrosoftSignInUnavailableMessage = "Microsoft sign-in is unavailable. Try another sign-in method."; private readonly ScopedCacheClient _cache = new(cacheClient, "Auth"); private static bool _isFirstUserChecked; private static readonly TimeSpan IntercomJwtLifetime = TimeSpan.FromMinutes(60); @@ -257,7 +261,7 @@ public async Task> Handle(SignupMessage message) public Task> Handle(GitHubLogin message) { - return ExternalLoginAsync(message.AuthInfo, message.Context, + return ExternalLoginAsync(message.AuthInfo, message.Context, "GitHub", authOptions.GitHubId, authOptions.GitHubSecret, oauthProviderClient.GetGitHubUserInfoAsync @@ -266,7 +270,7 @@ public Task> Handle(GitHubLogin message) public Task> Handle(GoogleLogin message) { - return ExternalLoginAsync(message.AuthInfo, message.Context, + return ExternalLoginAsync(message.AuthInfo, message.Context, "Google", authOptions.GoogleId, authOptions.GoogleSecret, oauthProviderClient.GetGoogleUserInfoAsync @@ -275,7 +279,10 @@ public Task> Handle(GoogleLogin message) public Task> Handle(MicrosoftLogin message) { - return ExternalLoginAsync(message.AuthInfo, message.Context, + if (!authOptions.IsMicrosoftConfigured) + return Task.FromResult>(Result.Unavailable(MicrosoftSignInUnavailableMessage)); + + return ExternalLoginAsync(message.AuthInfo, message.Context, OAuthAccount.KnownProviders.Microsoft, authOptions.MicrosoftId, authOptions.MicrosoftSecret, oauthProviderClient.GetMicrosoftUserInfoAsync @@ -491,9 +498,9 @@ private async Task AddGlobalAdminRoleIfFirstUserAsync(User user) _isFirstUserChecked = true; } - private async Task> ExternalLoginAsync(ExternalAuthInfo authInfo, HttpContext httpContext, string? appId, string? appSecret, Func> getUserInfoAsync) + private async Task> ExternalLoginAsync(ExternalAuthInfo authInfo, HttpContext httpContext, string providerName, string? appId, string? appSecret, Func> getUserInfoAsync) { - using var _ = logger.BeginScope(new ExceptionlessState().Tag("External Login").SetHttpContext(httpContext)); + using var loginScope = logger.BeginScope(new ExceptionlessState().Tag("External Login")); if (String.IsNullOrEmpty(appId) || String.IsNullOrEmpty(appSecret)) throw new ConfigurationErrorsException("Missing Configuration for OAuth provider"); @@ -503,12 +510,25 @@ private async Task> ExternalLoginAsync(ExternalAuthInfo auth { userInfo = await getUserInfoAsync(authInfo, appId, appSecret); } + catch (UnexpectedResponseException ex) when (IsMicrosoftProvider(providerName)) + { + var status = ex.Response?.StatusCode; + var (error, entraErrorCode) = ReadMicrosoftOAuthError(ex.Response?.Content); + logger.LogWarning("Microsoft sign-in failed with HTTP {ProviderStatus}, OAuth error {OAuthError}, Entra error code {EntraErrorCode}", + (int?)status, error, entraErrorCode); + + if (error is "invalid_grant" && status is (HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized)) + return Result.Unauthorized("Microsoft sign-in expired or was rejected. Start sign-in again."); + + return Result.Unavailable(MicrosoftSignInUnavailableMessage); + } catch (Exception ex) { - logger.LogCritical(ex, "External login failed RedirectUri={AuthRedirectUri}: {Message}", authInfo.RedirectUri, ex.Message); + logger.LogCritical(ex, "External login failed for {Provider}: {Message}", providerName, ex.Message); throw; } + using var requestScope = logger.BeginScope(new ExceptionlessState().SetHttpContext(httpContext)); Result result; try { @@ -541,6 +561,38 @@ private async Task> ExternalLoginAsync(ExternalAuthInfo auth return new TokenResult { Token = await GetOrCreateAuthenticationTokenAsync(user) }; } + private static (string? Error, int? EntraErrorCode) ReadMicrosoftOAuthError(string? content) + { + if (String.IsNullOrEmpty(content)) + return default; + + try + { + using var document = JsonDocument.Parse(content); + var body = document.RootElement; + if (body.ValueKind is not JsonValueKind.Object) + return default; + + string? error = body.TryGetProperty("error", out var errorValue) && errorValue.ValueKind is JsonValueKind.String + ? errorValue.GetString() + : null; + if (error is not ("invalid_client" or "invalid_grant" or "invalid_request" or "invalid_resource" or "invalid_scope" + or "unauthorized_client" or "interaction_required" or "temporarily_unavailable")) + error = null; + + int? entraErrorCode = null; + if (body.TryGetProperty("error_codes", out var codes) && codes.ValueKind is JsonValueKind.Array && codes.GetArrayLength() > 0 + && codes[0].ValueKind is JsonValueKind.Number && codes[0].TryGetInt32(out int code)) + entraErrorCode = code; + + return (error, entraErrorCode); + } + catch (JsonException) + { + return default; + } + } + private async Task> FromExternalLoginAsync(UserInfo userInfo, string? inviteToken, HttpContext httpContext) { ArgumentException.ThrowIfNullOrWhiteSpace(userInfo.Id); diff --git a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts index 2ff0f366ad..f3939aecd7 100644 --- a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts +++ b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts @@ -184,7 +184,7 @@ async function oauthLogin(options: OAuthLoginOptions) { state: data.state }, { - expectedStatusCodes: [401, 403, 422] + expectedStatusCodes: options.provider === 'microsoft' ? [401, 403, 422, 503] : [401, 403, 422] } ); @@ -192,7 +192,8 @@ async function oauthLogin(options: OAuthLoginOptions) { accessToken.current = response.data.token; await gotoRedirect(options.redirectUrl || resolve('/(app)')); } else { - toast.error(getProblemMessage(response.problem, 'Unable to sign in. Please try again.')); + const unavailableMessage = response.status === 503 ? response.problem?.detail : undefined; + toast.error(unavailableMessage || getProblemMessage(response.problem, 'Unable to sign in. Please try again.')); } } diff --git a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/microsoft.test.ts b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/microsoft.test.ts index 6efb5c902c..76b7cfd0cb 100644 --- a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/microsoft.test.ts +++ b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/microsoft.test.ts @@ -74,7 +74,7 @@ describe('microsoftLogin', () => { redirectUri: 'http://localhost:7131', state }, - { expectedStatusCodes: [401, 403, 422] } + { expectedStatusCodes: [401, 403, 422, 503] } ); expect(accessToken.current).toBe('session-token'); expect(goto).toHaveBeenCalledExactlyOnceWith('/organization/invited'); @@ -132,8 +132,12 @@ describe('microsoftLogin', () => { expect(popup.close).toHaveBeenCalledOnce(); }); - it('displays the 403 with the application error callback enabled', async () => { - const message = 'Account Creation is currently disabled'; + it.each([ + { status: 401, title: 'Microsoft sign-in expired or was rejected. Start sign-in again.' }, + { status: 403, title: 'Account Creation is currently disabled' }, + { detail: 'Microsoft sign-in is unavailable. Try another sign-in method.', status: 503, title: 'Service Unavailable' } + ])('displays the $status response with the application error callback enabled', async (problem) => { + // Arrange const client = new FetchClient({ baseUrl: 'http://localhost/api/v2', defaultRequestOptions: { @@ -142,19 +146,23 @@ describe('microsoftLogin', () => { } }, fetch: async () => - new Response(JSON.stringify({ status: 403, title: message }), { + new Response(JSON.stringify(problem), { headers: { 'Content-Type': 'application/problem+json' }, - status: 403 + status: problem.status }) }); postJSON.mockImplementation(client.postJSON.bind(client)); vi.stubGlobal('crypto', { randomUUID: () => 'expected-state' }); + + // Act const login = microsoftLogin(); const completed = expect(login).resolves.toBeUndefined(); popup.location = new URL('http://localhost:7131/?code=authorization-code&state=expected-state'); await vi.advanceTimersByTimeAsync(500); + + // Assert await completed; - expect(toastError).toHaveBeenCalledExactlyOnceWith(message); + expect(toastError).toHaveBeenCalledExactlyOnceWith(problem.detail ?? problem.title); expect(accessToken.current).toBeNull(); expect(goto).not.toHaveBeenCalled(); }); diff --git a/src/Exceptionless.Web/Exceptionless.Web.csproj b/src/Exceptionless.Web/Exceptionless.Web.csproj index 3b9ed87536..b41eb52b2f 100644 --- a/src/Exceptionless.Web/Exceptionless.Web.csproj +++ b/src/Exceptionless.Web/Exceptionless.Web.csproj @@ -19,7 +19,7 @@ - + diff --git a/src/Exceptionless.Web/Program.cs b/src/Exceptionless.Web/Program.cs index 79050324b4..b7851ade71 100644 --- a/src/Exceptionless.Web/Program.cs +++ b/src/Exceptionless.Web/Program.cs @@ -444,7 +444,7 @@ private static void SetClientEnvironmentVariablesInDevelopmentMode(AppOptions op options.StripeOptions.StripePublishableApiKey); Environment.SetEnvironmentVariable("PUBLIC_GITHUB_APPID", options.AuthOptions.GitHubId); Environment.SetEnvironmentVariable("PUBLIC_GOOGLE_APPID", options.AuthOptions.GoogleId); - Environment.SetEnvironmentVariable("PUBLIC_MICROSOFT_APPID", options.AuthOptions.MicrosoftId); + Environment.SetEnvironmentVariable("PUBLIC_MICROSOFT_APPID", options.AuthOptions.IsMicrosoftConfigured ? options.AuthOptions.MicrosoftId : null); Environment.SetEnvironmentVariable("PUBLIC_INTERCOM_APPID", options.IntercomOptions.IntercomId); Environment.SetEnvironmentVariable("PUBLIC_SLACK_APPID", options.SlackOptions.SlackId); } diff --git a/tests/Exceptionless.Tests/Api/Data/openapi.json b/tests/Exceptionless.Tests/Api/Data/openapi.json index b538a5a788..378f8aacbf 100644 --- a/tests/Exceptionless.Tests/Api/Data/openapi.json +++ b/tests/Exceptionless.Tests/Api/Data/openapi.json @@ -1948,6 +1948,16 @@ } } }, + "401": { + "description": "The Microsoft authorization code expired or was rejected", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, "403": { "description": "Account Creation is currently disabled, or the email belongs to an existing account that must sign in and link Microsoft first", "content": { @@ -1967,6 +1977,16 @@ } } } + }, + "503": { + "description": "Microsoft sign-in is unavailable", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } } } } diff --git a/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs b/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs index 20ebddb6ad..90c227d7bc 100644 --- a/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs +++ b/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs @@ -86,7 +86,7 @@ private void ConfigureAuthOptions() _authOptions.GitHubSecret = "github-client-secret"; _authOptions.GoogleId = "google-client-id"; _authOptions.GoogleSecret = "google-client-secret"; - _authOptions.MicrosoftId = "microsoft-client-id"; + _authOptions.MicrosoftId = TestOAuthProviderClient.MicrosoftClientId; _authOptions.MicrosoftSecret = "microsoft-client-secret"; } diff --git a/tests/Exceptionless.Tests/Api/Endpoints/MicrosoftAuthEndpointTests.cs b/tests/Exceptionless.Tests/Api/Endpoints/MicrosoftAuthEndpointTests.cs index 616181e69f..4adbdda95b 100644 --- a/tests/Exceptionless.Tests/Api/Endpoints/MicrosoftAuthEndpointTests.cs +++ b/tests/Exceptionless.Tests/Api/Endpoints/MicrosoftAuthEndpointTests.cs @@ -57,7 +57,7 @@ protected override async Task ResetDataAsync() { await base.ResetDataAsync(); _authOptions.EnableAccountCreation = true; - _authOptions.MicrosoftId = "microsoft-client-id"; + _authOptions.MicrosoftId = TestOAuthProviderClient.MicrosoftClientId; _authOptions.MicrosoftSecret = "microsoft-client-secret"; _authOptions.GitHubId = "github-client-id"; _authOptions.GitHubSecret = "github-client-secret"; @@ -144,7 +144,7 @@ public async Task MicrosoftAsync_ExactEmailMatch_RequiresAuthenticatedLink() var problem = await SendRequestAsAsync(request => request .Post() .AppendPaths("auth", "microsoft") - .Content(new ExternalAuthInfo { ClientId = "microsoft-client-id", Code = code, RedirectUri = "http://localhost" }) + .Content(new ExternalAuthInfo { ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = code, RedirectUri = "http://localhost" }) .StatusCodeShouldBeForbidden()); // Assert @@ -320,7 +320,7 @@ public async Task TrustedProviderLogin_AccountCreatedWithMicrosoft_RemovesUnveri var squatterRetry = await SendRequestAsAsync(request => request .Post() .AppendPaths("auth", "microsoft") - .Content(new ExternalAuthInfo { ClientId = "microsoft-client-id", Code = code, RedirectUri = "http://localhost" }) + .Content(new ExternalAuthInfo { ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = code, RedirectUri = "http://localhost" }) .StatusCodeShouldBeForbidden()); // Assert @@ -487,7 +487,7 @@ private static User CreateUser(string emailAddress) .AppendPaths("auth", "microsoft") .Content(new ExternalAuthInfo { - ClientId = "microsoft-client-id", + ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = code, InviteToken = inviteToken, RedirectUri = "http://localhost/callback" diff --git a/tests/Exceptionless.Tests/Api/Handlers/AuthHandlerTests.cs b/tests/Exceptionless.Tests/Api/Handlers/AuthHandlerTests.cs index eac6a0f929..d2b90f8eb2 100644 --- a/tests/Exceptionless.Tests/Api/Handlers/AuthHandlerTests.cs +++ b/tests/Exceptionless.Tests/Api/Handlers/AuthHandlerTests.cs @@ -1,3 +1,4 @@ +using System.Net; using System.Security.Claims; using Exceptionless.Core; using Exceptionless.Core.Authentication; @@ -20,6 +21,8 @@ using Foundatio.Repositories.Models; using Microsoft.AspNetCore.Http; using Moq; +using OAuth2.Client; +using RestSharp; using Xunit; namespace Exceptionless.Tests.Api.Handlers; @@ -162,7 +165,7 @@ public async Task Handle_MicrosoftProviderFails_DoesNotAccessUserRepository() // Arrange var userRepository = new Mock(MockBehavior.Strict); var oauthProvider = new Mock(MockBehavior.Strict); - oauthProvider.Setup(provider => provider.GetMicrosoftUserInfoAsync(It.IsAny(), "microsoft-client-id", "microsoft-client-secret")) + oauthProvider.Setup(provider => provider.GetMicrosoftUserInfoAsync(It.IsAny(), TestOAuthProviderClient.MicrosoftClientId, "microsoft-client-secret")) .ThrowsAsync(new InvalidOperationException("Microsoft provider failed.")); var handler = CreateHandler( userRepository.Object, @@ -174,7 +177,7 @@ public async Task Handle_MicrosoftProviderFails_DoesNotAccessUserRepository() var exception = await Record.ExceptionAsync(async () => { _ = await handler.Handle(new MicrosoftLogin( - new ExternalAuthInfo { ClientId = "microsoft-client-id", Code = "provider-failure", RedirectUri = "http://localhost" }, + new ExternalAuthInfo { ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = "provider-failure", RedirectUri = "http://localhost" }, new DefaultHttpContext())); }); @@ -183,10 +186,73 @@ public async Task Handle_MicrosoftProviderFails_DoesNotAccessUserRepository() userRepository.VerifyNoOtherCalls(); } + [Theory] + [InlineData(HttpStatusCode.Unauthorized, """{"error":"invalid_client","error_codes":[7000215],"error_description":"synthetic diagnostic"}""", "invalid_client", 7000215, ResultStatus.Unavailable)] + [InlineData(HttpStatusCode.Unauthorized, """{"error":"synthetic diagnostic","error_codes":["synthetic diagnostic"]}""", null, null, ResultStatus.Unavailable)] + [InlineData(HttpStatusCode.Unauthorized, "synthetic diagnostic", null, null, ResultStatus.Unavailable)] + [InlineData(HttpStatusCode.BadRequest, """{"error":"invalid_grant","error_codes":[54005]}""", "invalid_grant", 54005, ResultStatus.Unauthorized)] + public async Task Handle_MicrosoftTokenExchangeRejected_ReturnsSafeFailure(HttpStatusCode statusCode, string content, string? expectedError, int? expectedEntraCode, ResultStatus expectedStatus) + { + // Arrange + var users = new Mock(MockBehavior.Strict); + var tokens = new Mock(MockBehavior.Strict); + var oauthProvider = new Mock(MockBehavior.Strict); + oauthProvider.Setup(provider => provider.GetMicrosoftUserInfoAsync(It.IsAny(), TestOAuthProviderClient.MicrosoftClientId, "microsoft-client-secret")) + .ThrowsAsync(new UnexpectedResponseException(new RestResponse { StatusCode = statusCode, Content = content })); + var handler = CreateHandler(users.Object, tokens.Object, GetService(), oauthProvider.Object); + var message = new MicrosoftLogin( + new ExternalAuthInfo { ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = "synthetic-code", RedirectUri = "http://localhost" }, + new DefaultHttpContext()); + + // Act + var result = await handler.Handle(message); + + // Assert + Assert.Equal(expectedStatus, result.Status); + Assert.Equal(expectedStatus is ResultStatus.Unauthorized + ? "Microsoft sign-in expired or was rejected. Start sign-in again." + : "Microsoft sign-in is unavailable. Try another sign-in method.", result.Message); + var warning = Assert.Single(Log.LogEntries, entry => entry.LogLevel is LogLevel.Warning && String.Equals(entry.CategoryName, typeof(AuthHandler).FullName, StringComparison.Ordinal)); + var properties = Assert.IsAssignableFrom>>(warning.State).ToDictionary(property => property.Key, property => property.Value); + Assert.Equal((int)statusCode, properties["ProviderStatus"]); + Assert.Equal(expectedError, properties["OAuthError"]); + Assert.Equal(expectedEntraCode, properties["EntraErrorCode"]); + Assert.DoesNotContain("synthetic diagnostic", warning.Message, StringComparison.Ordinal); + Assert.Null(warning.Exception); + users.VerifyNoOtherCalls(); + tokens.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData("abcdef0123456789", "synthetic-secret")] + [InlineData("00000000-0000-0000-0000-000000000000", "synthetic-secret")] + [InlineData(TestOAuthProviderClient.MicrosoftClientId, null)] + public async Task Handle_InvalidMicrosoftConfiguration_ReturnsUnavailableWithoutContactingProvider(string clientId, string? clientSecret) + { + // Arrange + var users = new Mock(MockBehavior.Strict); + var provider = new Mock(MockBehavior.Strict); + var handler = CreateHandler(users.Object, GetService(), GetService(), provider.Object); + var options = GetService(); + options.AuthOptions.MicrosoftId = clientId; + options.AuthOptions.MicrosoftSecret = clientSecret; + var message = new MicrosoftLogin( + new ExternalAuthInfo { ClientId = clientId, Code = "synthetic-code", RedirectUri = "http://localhost" }, + new DefaultHttpContext()); + + // Act + var result = await handler.Handle(message); + + // Assert + Assert.Equal(ResultStatus.Unavailable, result.Status); + provider.VerifyNoOtherCalls(); + users.VerifyNoOtherCalls(); + } + private AuthHandler CreateHandler(IUserRepository userRepository, ITokenRepository tokenRepository, IOAuthTokenRepository oauthTokenRepository, IOAuthProviderClient oauthProvider) { var appOptions = GetService(); - appOptions.AuthOptions.MicrosoftId = "microsoft-client-id"; + appOptions.AuthOptions.MicrosoftId = TestOAuthProviderClient.MicrosoftClientId; appOptions.AuthOptions.MicrosoftSecret = "microsoft-client-secret"; return new AuthHandler( diff --git a/tests/Exceptionless.Tests/BootstrapperTests.cs b/tests/Exceptionless.Tests/BootstrapperTests.cs index 188d72b06e..530e406ada 100644 --- a/tests/Exceptionless.Tests/BootstrapperTests.cs +++ b/tests/Exceptionless.Tests/BootstrapperTests.cs @@ -1,4 +1,5 @@ using Exceptionless.Core; +using Exceptionless.Tests.Utility; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -140,7 +141,7 @@ private static AppOptions CreateConfiguredOptions() new("ConnectionStrings:ElasticsearchToMigrate", "server=\"https://migrate-user:migrate-password-secret-canary@elastic-migrate.example.test:9243\""), new("ConnectionStrings:Email", "smtps://smtp-user:smtp-password-secret-canary@smtp.example.test:465"), new("ConnectionStrings:LDAP", "server=ldap.example.test;port=389;username=ldap-user;password=ldap-password-secret-canary"), - new("ConnectionStrings:OAuth", "GoogleId=google-id;GoogleSecret=google-secret-canary;MicrosoftId=microsoft-id;MicrosoftSecret=microsoft-secret-canary;GitHubId=github-id;GitHubSecret=github-secret-canary;IntercomId=intercom-id;IntercomSecret=intercom-secret-canary;SlackId=slack-id;SlackSecret=slack-secret-canary"), + new("ConnectionStrings:OAuth", $"GoogleId=google-id;GoogleSecret=google-secret-canary;MicrosoftId={TestOAuthProviderClient.MicrosoftClientId};MicrosoftSecret=microsoft-secret-canary;GitHubId=github-id;GitHubSecret=github-secret-canary;IntercomId=intercom-id;IntercomSecret=intercom-secret-canary;SlackId=slack-id;SlackSecret=slack-secret-canary"), new("StripeApiKey", "stripe-api-key-secret-canary"), new("StripePublishableApiKey", "stripe-publishable-key"), new("StripeWebHookSigningSecret", "stripe-signing-secret-canary"), diff --git a/tests/Exceptionless.Tests/Utility/TestOAuthProviderClient.cs b/tests/Exceptionless.Tests/Utility/TestOAuthProviderClient.cs index 235953a8bb..2bf64fe6cf 100644 --- a/tests/Exceptionless.Tests/Utility/TestOAuthProviderClient.cs +++ b/tests/Exceptionless.Tests/Utility/TestOAuthProviderClient.cs @@ -7,6 +7,8 @@ namespace Exceptionless.Tests.Utility; public sealed class TestOAuthProviderClient : IOAuthProviderClient { + public const string MicrosoftClientId = "00000000-0000-4000-8000-000000000001"; + public Task GetGitHubUserInfoAsync(ExternalAuthInfo authInfo, string appId, string appSecret) { return GetUserInfoAsync("GitHub", authInfo); From 74dd423d859794f42dafcb2dafae688a57ac0c49 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Sun, 29 Nov 2026 22:05:20 -0600 Subject: [PATCH 2/2] Limit change to the OAuth2 dependency upgrade --- build/update-config.sh | 11 +-- docs/docs/self-hosting/configuration.md | 5 -- src/Exceptionless.Core/Bootstrapper.cs | 5 +- .../Configuration/AuthOptions.cs | 3 - .../Api/Endpoints/AuthEndpoints.cs | 4 -- .../Api/Handlers/AuthHandler.cs | 64 ++--------------- .../src/lib/features/auth/index.svelte.ts | 5 +- .../src/lib/features/auth/microsoft.test.ts | 20 ++---- src/Exceptionless.Web/Program.cs | 2 +- .../Exceptionless.Tests/Api/Data/openapi.json | 20 ------ .../Api/Endpoints/AuthEndpointTests.cs | 2 +- .../Endpoints/MicrosoftAuthEndpointTests.cs | 8 +-- .../Api/Handlers/AuthHandlerTests.cs | 72 +------------------ .../Exceptionless.Tests/BootstrapperTests.cs | 3 +- .../Utility/TestOAuthProviderClient.cs | 2 - 15 files changed, 26 insertions(+), 200 deletions(-) diff --git a/build/update-config.sh b/build/update-config.sh index 9a9b80b7a5..e23eb6707a 100644 --- a/build/update-config.sh +++ b/build/update-config.sh @@ -3,7 +3,6 @@ set -euo pipefail # Only publish client IDs. OAuth secrets must never enter env.js or startup logs. declare -A oauth_ids=() -microsoft_secret_configured=false IFS=';' read -ra oauth_parts <<< "${EX_ConnectionStrings__OAuth:-}" for part in "${oauth_parts[@]}"; do key="${part%%=*}" @@ -14,17 +13,9 @@ for part in "${oauth_parts[@]}"; do case "$key" in GitHubId|GoogleId|IntercomId|MicrosoftId|SlackId) oauth_ids[$key]="$value" ;; - MicrosoftSecret) - microsoft_secret_configured=false - [[ -z "$value" ]] || microsoft_secret_configured=true ;; esac done -microsoft_id="${oauth_ids[MicrosoftId]:-}" -if [[ "$microsoft_secret_configured" == false || ! "$microsoft_id" =~ ^[[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}$ || "$microsoft_id" == 00000000-0000-0000-0000-000000000000 ]]; then - microsoft_id="" -fi - js_string() { local value="${1:-}" value="${value//\\/\\\\}" @@ -54,7 +45,7 @@ mkdir -p _app write_setting PUBLIC_STRIPE_PUBLISHABLE_KEY "${EX_StripePublishableApiKey:-}" write_setting PUBLIC_GITHUB_APPID "${oauth_ids[GitHubId]:-}" write_setting PUBLIC_GOOGLE_APPID "${oauth_ids[GoogleId]:-}" - write_setting PUBLIC_MICROSOFT_APPID "$microsoft_id" + write_setting PUBLIC_MICROSOFT_APPID "${oauth_ids[MicrosoftId]:-}" write_setting PUBLIC_INTERCOM_APPID "${oauth_ids[IntercomId]:-}" write_setting PUBLIC_SLACK_APPID "${oauth_ids[SlackId]:-}" printf '};\n' diff --git a/docs/docs/self-hosting/configuration.md b/docs/docs/self-hosting/configuration.md index 09754bf507..d34b8de5df 100644 --- a/docs/docs/self-hosting/configuration.md +++ b/docs/docs/self-hosting/configuration.md @@ -184,11 +184,6 @@ Include only the providers you use. Each provider sends users back to the origin | GitHub | `GitHubId`, `GitHubSecret` | A GitHub OAuth app. Set its authorization callback URL to your web app's origin. Exceptionless asks for the `user:email` scope. | | Google | `GoogleId`, `GoogleSecret` | An OAuth client ID of type **Web application** in Google Cloud, with your web app's origin as an authorized redirect URI. Exceptionless asks for `openid profile email`. | -Use the Entra **Application (client) ID** for `MicrosoftId`. Replace any saved 16-character Windows Live ID when migrating. -For `MicrosoftSecret`, use the unexpired client secret **Value** from the same app registration. If Microsoft rejects -token exchange, look for the OAuth error and Entra error code in the server log and check it against the -[Microsoft Entra error reference](https://learn.microsoft.com/en-us/entra/identity-platform/reference-error-codes). - ### Slack Slack notifications use the same connection string, with `SlackId` and `SlackSecret` from a Slack app: diff --git a/src/Exceptionless.Core/Bootstrapper.cs b/src/Exceptionless.Core/Bootstrapper.cs index 4a8c4f03fe..7bc92f0526 100644 --- a/src/Exceptionless.Core/Bootstrapper.cs +++ b/src/Exceptionless.Core/Bootstrapper.cs @@ -334,9 +334,6 @@ public static void LogConfiguration(IServiceProvider serviceProvider, AppOptions if (!appOptions.AuthOptions.EnableAccountCreation) logger.LogWarning("Account Creation is NOT enabled on {MachineName}", Environment.MachineName); - - if (!String.IsNullOrWhiteSpace(appOptions.AuthOptions.MicrosoftId) && !appOptions.AuthOptions.IsMicrosoftConfigured) - logger.LogWarning("Microsoft sign-in requires an Entra application ID in GUID format and a client secret value"); } private static void LogConfigurationSummary(IServiceProvider serviceProvider, AppOptions options, ILogger logger) @@ -388,7 +385,7 @@ private static string GetEnabledIntegrations(AppOptions options) List integrations = []; if (!String.IsNullOrWhiteSpace(options.AuthOptions.GoogleId)) integrations.Add("Google OAuth"); - if (options.AuthOptions.IsMicrosoftConfigured) + if (!String.IsNullOrWhiteSpace(options.AuthOptions.MicrosoftId)) integrations.Add("Microsoft OAuth"); if (!String.IsNullOrWhiteSpace(options.AuthOptions.GitHubId)) integrations.Add("GitHub OAuth"); diff --git a/src/Exceptionless.Core/Configuration/AuthOptions.cs b/src/Exceptionless.Core/Configuration/AuthOptions.cs index cf9fcf56bb..b7bb6ce807 100644 --- a/src/Exceptionless.Core/Configuration/AuthOptions.cs +++ b/src/Exceptionless.Core/Configuration/AuthOptions.cs @@ -13,9 +13,6 @@ public class AuthOptions public string? MicrosoftSecret { get; internal set; } - public bool IsMicrosoftConfigured => Guid.TryParseExact(MicrosoftId, "D", out var clientId) - && clientId != Guid.Empty && !String.IsNullOrWhiteSpace(MicrosoftSecret); - public string? GitHubId { get; internal set; } public string? GitHubSecret { get; internal set; } diff --git a/src/Exceptionless.Web/Api/Endpoints/AuthEndpoints.cs b/src/Exceptionless.Web/Api/Endpoints/AuthEndpoints.cs index 826d9dcd70..e0bcc0d053 100644 --- a/src/Exceptionless.Web/Api/Endpoints/AuthEndpoints.cs +++ b/src/Exceptionless.Web/Api/Endpoints/AuthEndpoints.cs @@ -140,18 +140,14 @@ headers api_key input box. .AllowAnonymous() .Accepts("application/json", "application/*+json") .Produces() - .ProducesProblem(StatusCodes.Status401Unauthorized) .ProducesProblem(StatusCodes.Status403Forbidden) .ProducesProblem(StatusCodes.Status422UnprocessableEntity) - .ProducesProblem(StatusCodes.Status503ServiceUnavailable) .WithSummary("Sign in with Microsoft") .WithMetadata(new EndpointDocumentation { ResponseDescriptions = new() { ["200"] = "User Authentication Token", - ["401"] = "The Microsoft authorization code expired or was rejected", ["403"] = "Account Creation is currently disabled, or the email belongs to an existing account that must sign in and link Microsoft first", ["422"] = "Validation error", - ["503"] = "Microsoft sign-in is unavailable", } }); diff --git a/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs b/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs index 1cc9f39dbe..8e86aec99d 100644 --- a/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs +++ b/src/Exceptionless.Web/Api/Handlers/AuthHandler.cs @@ -1,8 +1,6 @@ using System.Configuration; using System.IdentityModel.Tokens.Jwt; -using System.Net; using System.Text; -using System.Text.Json; using Exceptionless.Core.Authentication; using Exceptionless.Core.Authorization; using Exceptionless.Core.Configuration; @@ -20,7 +18,6 @@ using Foundatio.Mediator; using Foundatio.Repositories; using Microsoft.IdentityModel.Tokens; -using OAuth2.Client; using OAuth2.Models; namespace Exceptionless.Web.Api.Handlers; @@ -40,7 +37,6 @@ public class AuthHandler( TimeProvider timeProvider, ILogger logger) { - private const string MicrosoftSignInUnavailableMessage = "Microsoft sign-in is unavailable. Try another sign-in method."; private readonly ScopedCacheClient _cache = new(cacheClient, "Auth"); private static bool _isFirstUserChecked; private static readonly TimeSpan IntercomJwtLifetime = TimeSpan.FromMinutes(60); @@ -261,7 +257,7 @@ public async Task> Handle(SignupMessage message) public Task> Handle(GitHubLogin message) { - return ExternalLoginAsync(message.AuthInfo, message.Context, "GitHub", + return ExternalLoginAsync(message.AuthInfo, message.Context, authOptions.GitHubId, authOptions.GitHubSecret, oauthProviderClient.GetGitHubUserInfoAsync @@ -270,7 +266,7 @@ public Task> Handle(GitHubLogin message) public Task> Handle(GoogleLogin message) { - return ExternalLoginAsync(message.AuthInfo, message.Context, "Google", + return ExternalLoginAsync(message.AuthInfo, message.Context, authOptions.GoogleId, authOptions.GoogleSecret, oauthProviderClient.GetGoogleUserInfoAsync @@ -279,10 +275,7 @@ public Task> Handle(GoogleLogin message) public Task> Handle(MicrosoftLogin message) { - if (!authOptions.IsMicrosoftConfigured) - return Task.FromResult>(Result.Unavailable(MicrosoftSignInUnavailableMessage)); - - return ExternalLoginAsync(message.AuthInfo, message.Context, OAuthAccount.KnownProviders.Microsoft, + return ExternalLoginAsync(message.AuthInfo, message.Context, authOptions.MicrosoftId, authOptions.MicrosoftSecret, oauthProviderClient.GetMicrosoftUserInfoAsync @@ -498,9 +491,9 @@ private async Task AddGlobalAdminRoleIfFirstUserAsync(User user) _isFirstUserChecked = true; } - private async Task> ExternalLoginAsync(ExternalAuthInfo authInfo, HttpContext httpContext, string providerName, string? appId, string? appSecret, Func> getUserInfoAsync) + private async Task> ExternalLoginAsync(ExternalAuthInfo authInfo, HttpContext httpContext, string? appId, string? appSecret, Func> getUserInfoAsync) { - using var loginScope = logger.BeginScope(new ExceptionlessState().Tag("External Login")); + using var _ = logger.BeginScope(new ExceptionlessState().Tag("External Login").SetHttpContext(httpContext)); if (String.IsNullOrEmpty(appId) || String.IsNullOrEmpty(appSecret)) throw new ConfigurationErrorsException("Missing Configuration for OAuth provider"); @@ -510,25 +503,12 @@ private async Task> ExternalLoginAsync(ExternalAuthInfo auth { userInfo = await getUserInfoAsync(authInfo, appId, appSecret); } - catch (UnexpectedResponseException ex) when (IsMicrosoftProvider(providerName)) - { - var status = ex.Response?.StatusCode; - var (error, entraErrorCode) = ReadMicrosoftOAuthError(ex.Response?.Content); - logger.LogWarning("Microsoft sign-in failed with HTTP {ProviderStatus}, OAuth error {OAuthError}, Entra error code {EntraErrorCode}", - (int?)status, error, entraErrorCode); - - if (error is "invalid_grant" && status is (HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized)) - return Result.Unauthorized("Microsoft sign-in expired or was rejected. Start sign-in again."); - - return Result.Unavailable(MicrosoftSignInUnavailableMessage); - } catch (Exception ex) { - logger.LogCritical(ex, "External login failed for {Provider}: {Message}", providerName, ex.Message); + logger.LogCritical(ex, "External login failed RedirectUri={AuthRedirectUri}: {Message}", authInfo.RedirectUri, ex.Message); throw; } - using var requestScope = logger.BeginScope(new ExceptionlessState().SetHttpContext(httpContext)); Result result; try { @@ -561,38 +541,6 @@ private async Task> ExternalLoginAsync(ExternalAuthInfo auth return new TokenResult { Token = await GetOrCreateAuthenticationTokenAsync(user) }; } - private static (string? Error, int? EntraErrorCode) ReadMicrosoftOAuthError(string? content) - { - if (String.IsNullOrEmpty(content)) - return default; - - try - { - using var document = JsonDocument.Parse(content); - var body = document.RootElement; - if (body.ValueKind is not JsonValueKind.Object) - return default; - - string? error = body.TryGetProperty("error", out var errorValue) && errorValue.ValueKind is JsonValueKind.String - ? errorValue.GetString() - : null; - if (error is not ("invalid_client" or "invalid_grant" or "invalid_request" or "invalid_resource" or "invalid_scope" - or "unauthorized_client" or "interaction_required" or "temporarily_unavailable")) - error = null; - - int? entraErrorCode = null; - if (body.TryGetProperty("error_codes", out var codes) && codes.ValueKind is JsonValueKind.Array && codes.GetArrayLength() > 0 - && codes[0].ValueKind is JsonValueKind.Number && codes[0].TryGetInt32(out int code)) - entraErrorCode = code; - - return (error, entraErrorCode); - } - catch (JsonException) - { - return default; - } - } - private async Task> FromExternalLoginAsync(UserInfo userInfo, string? inviteToken, HttpContext httpContext) { ArgumentException.ThrowIfNullOrWhiteSpace(userInfo.Id); diff --git a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts index f3939aecd7..2ff0f366ad 100644 --- a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts +++ b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/index.svelte.ts @@ -184,7 +184,7 @@ async function oauthLogin(options: OAuthLoginOptions) { state: data.state }, { - expectedStatusCodes: options.provider === 'microsoft' ? [401, 403, 422, 503] : [401, 403, 422] + expectedStatusCodes: [401, 403, 422] } ); @@ -192,8 +192,7 @@ async function oauthLogin(options: OAuthLoginOptions) { accessToken.current = response.data.token; await gotoRedirect(options.redirectUrl || resolve('/(app)')); } else { - const unavailableMessage = response.status === 503 ? response.problem?.detail : undefined; - toast.error(unavailableMessage || getProblemMessage(response.problem, 'Unable to sign in. Please try again.')); + toast.error(getProblemMessage(response.problem, 'Unable to sign in. Please try again.')); } } diff --git a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/microsoft.test.ts b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/microsoft.test.ts index 76b7cfd0cb..6efb5c902c 100644 --- a/src/Exceptionless.Web/ClientApp/src/lib/features/auth/microsoft.test.ts +++ b/src/Exceptionless.Web/ClientApp/src/lib/features/auth/microsoft.test.ts @@ -74,7 +74,7 @@ describe('microsoftLogin', () => { redirectUri: 'http://localhost:7131', state }, - { expectedStatusCodes: [401, 403, 422, 503] } + { expectedStatusCodes: [401, 403, 422] } ); expect(accessToken.current).toBe('session-token'); expect(goto).toHaveBeenCalledExactlyOnceWith('/organization/invited'); @@ -132,12 +132,8 @@ describe('microsoftLogin', () => { expect(popup.close).toHaveBeenCalledOnce(); }); - it.each([ - { status: 401, title: 'Microsoft sign-in expired or was rejected. Start sign-in again.' }, - { status: 403, title: 'Account Creation is currently disabled' }, - { detail: 'Microsoft sign-in is unavailable. Try another sign-in method.', status: 503, title: 'Service Unavailable' } - ])('displays the $status response with the application error callback enabled', async (problem) => { - // Arrange + it('displays the 403 with the application error callback enabled', async () => { + const message = 'Account Creation is currently disabled'; const client = new FetchClient({ baseUrl: 'http://localhost/api/v2', defaultRequestOptions: { @@ -146,23 +142,19 @@ describe('microsoftLogin', () => { } }, fetch: async () => - new Response(JSON.stringify(problem), { + new Response(JSON.stringify({ status: 403, title: message }), { headers: { 'Content-Type': 'application/problem+json' }, - status: problem.status + status: 403 }) }); postJSON.mockImplementation(client.postJSON.bind(client)); vi.stubGlobal('crypto', { randomUUID: () => 'expected-state' }); - - // Act const login = microsoftLogin(); const completed = expect(login).resolves.toBeUndefined(); popup.location = new URL('http://localhost:7131/?code=authorization-code&state=expected-state'); await vi.advanceTimersByTimeAsync(500); - - // Assert await completed; - expect(toastError).toHaveBeenCalledExactlyOnceWith(problem.detail ?? problem.title); + expect(toastError).toHaveBeenCalledExactlyOnceWith(message); expect(accessToken.current).toBeNull(); expect(goto).not.toHaveBeenCalled(); }); diff --git a/src/Exceptionless.Web/Program.cs b/src/Exceptionless.Web/Program.cs index b7851ade71..79050324b4 100644 --- a/src/Exceptionless.Web/Program.cs +++ b/src/Exceptionless.Web/Program.cs @@ -444,7 +444,7 @@ private static void SetClientEnvironmentVariablesInDevelopmentMode(AppOptions op options.StripeOptions.StripePublishableApiKey); Environment.SetEnvironmentVariable("PUBLIC_GITHUB_APPID", options.AuthOptions.GitHubId); Environment.SetEnvironmentVariable("PUBLIC_GOOGLE_APPID", options.AuthOptions.GoogleId); - Environment.SetEnvironmentVariable("PUBLIC_MICROSOFT_APPID", options.AuthOptions.IsMicrosoftConfigured ? options.AuthOptions.MicrosoftId : null); + Environment.SetEnvironmentVariable("PUBLIC_MICROSOFT_APPID", options.AuthOptions.MicrosoftId); Environment.SetEnvironmentVariable("PUBLIC_INTERCOM_APPID", options.IntercomOptions.IntercomId); Environment.SetEnvironmentVariable("PUBLIC_SLACK_APPID", options.SlackOptions.SlackId); } diff --git a/tests/Exceptionless.Tests/Api/Data/openapi.json b/tests/Exceptionless.Tests/Api/Data/openapi.json index 378f8aacbf..b538a5a788 100644 --- a/tests/Exceptionless.Tests/Api/Data/openapi.json +++ b/tests/Exceptionless.Tests/Api/Data/openapi.json @@ -1948,16 +1948,6 @@ } } }, - "401": { - "description": "The Microsoft authorization code expired or was rejected", - "content": { - "application/problem\u002Bjson": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, "403": { "description": "Account Creation is currently disabled, or the email belongs to an existing account that must sign in and link Microsoft first", "content": { @@ -1977,16 +1967,6 @@ } } } - }, - "503": { - "description": "Microsoft sign-in is unavailable", - "content": { - "application/problem\u002Bjson": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } } } } diff --git a/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs b/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs index 90c227d7bc..20ebddb6ad 100644 --- a/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs +++ b/tests/Exceptionless.Tests/Api/Endpoints/AuthEndpointTests.cs @@ -86,7 +86,7 @@ private void ConfigureAuthOptions() _authOptions.GitHubSecret = "github-client-secret"; _authOptions.GoogleId = "google-client-id"; _authOptions.GoogleSecret = "google-client-secret"; - _authOptions.MicrosoftId = TestOAuthProviderClient.MicrosoftClientId; + _authOptions.MicrosoftId = "microsoft-client-id"; _authOptions.MicrosoftSecret = "microsoft-client-secret"; } diff --git a/tests/Exceptionless.Tests/Api/Endpoints/MicrosoftAuthEndpointTests.cs b/tests/Exceptionless.Tests/Api/Endpoints/MicrosoftAuthEndpointTests.cs index 4adbdda95b..616181e69f 100644 --- a/tests/Exceptionless.Tests/Api/Endpoints/MicrosoftAuthEndpointTests.cs +++ b/tests/Exceptionless.Tests/Api/Endpoints/MicrosoftAuthEndpointTests.cs @@ -57,7 +57,7 @@ protected override async Task ResetDataAsync() { await base.ResetDataAsync(); _authOptions.EnableAccountCreation = true; - _authOptions.MicrosoftId = TestOAuthProviderClient.MicrosoftClientId; + _authOptions.MicrosoftId = "microsoft-client-id"; _authOptions.MicrosoftSecret = "microsoft-client-secret"; _authOptions.GitHubId = "github-client-id"; _authOptions.GitHubSecret = "github-client-secret"; @@ -144,7 +144,7 @@ public async Task MicrosoftAsync_ExactEmailMatch_RequiresAuthenticatedLink() var problem = await SendRequestAsAsync(request => request .Post() .AppendPaths("auth", "microsoft") - .Content(new ExternalAuthInfo { ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = code, RedirectUri = "http://localhost" }) + .Content(new ExternalAuthInfo { ClientId = "microsoft-client-id", Code = code, RedirectUri = "http://localhost" }) .StatusCodeShouldBeForbidden()); // Assert @@ -320,7 +320,7 @@ public async Task TrustedProviderLogin_AccountCreatedWithMicrosoft_RemovesUnveri var squatterRetry = await SendRequestAsAsync(request => request .Post() .AppendPaths("auth", "microsoft") - .Content(new ExternalAuthInfo { ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = code, RedirectUri = "http://localhost" }) + .Content(new ExternalAuthInfo { ClientId = "microsoft-client-id", Code = code, RedirectUri = "http://localhost" }) .StatusCodeShouldBeForbidden()); // Assert @@ -487,7 +487,7 @@ private static User CreateUser(string emailAddress) .AppendPaths("auth", "microsoft") .Content(new ExternalAuthInfo { - ClientId = TestOAuthProviderClient.MicrosoftClientId, + ClientId = "microsoft-client-id", Code = code, InviteToken = inviteToken, RedirectUri = "http://localhost/callback" diff --git a/tests/Exceptionless.Tests/Api/Handlers/AuthHandlerTests.cs b/tests/Exceptionless.Tests/Api/Handlers/AuthHandlerTests.cs index d2b90f8eb2..eac6a0f929 100644 --- a/tests/Exceptionless.Tests/Api/Handlers/AuthHandlerTests.cs +++ b/tests/Exceptionless.Tests/Api/Handlers/AuthHandlerTests.cs @@ -1,4 +1,3 @@ -using System.Net; using System.Security.Claims; using Exceptionless.Core; using Exceptionless.Core.Authentication; @@ -21,8 +20,6 @@ using Foundatio.Repositories.Models; using Microsoft.AspNetCore.Http; using Moq; -using OAuth2.Client; -using RestSharp; using Xunit; namespace Exceptionless.Tests.Api.Handlers; @@ -165,7 +162,7 @@ public async Task Handle_MicrosoftProviderFails_DoesNotAccessUserRepository() // Arrange var userRepository = new Mock(MockBehavior.Strict); var oauthProvider = new Mock(MockBehavior.Strict); - oauthProvider.Setup(provider => provider.GetMicrosoftUserInfoAsync(It.IsAny(), TestOAuthProviderClient.MicrosoftClientId, "microsoft-client-secret")) + oauthProvider.Setup(provider => provider.GetMicrosoftUserInfoAsync(It.IsAny(), "microsoft-client-id", "microsoft-client-secret")) .ThrowsAsync(new InvalidOperationException("Microsoft provider failed.")); var handler = CreateHandler( userRepository.Object, @@ -177,7 +174,7 @@ public async Task Handle_MicrosoftProviderFails_DoesNotAccessUserRepository() var exception = await Record.ExceptionAsync(async () => { _ = await handler.Handle(new MicrosoftLogin( - new ExternalAuthInfo { ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = "provider-failure", RedirectUri = "http://localhost" }, + new ExternalAuthInfo { ClientId = "microsoft-client-id", Code = "provider-failure", RedirectUri = "http://localhost" }, new DefaultHttpContext())); }); @@ -186,73 +183,10 @@ public async Task Handle_MicrosoftProviderFails_DoesNotAccessUserRepository() userRepository.VerifyNoOtherCalls(); } - [Theory] - [InlineData(HttpStatusCode.Unauthorized, """{"error":"invalid_client","error_codes":[7000215],"error_description":"synthetic diagnostic"}""", "invalid_client", 7000215, ResultStatus.Unavailable)] - [InlineData(HttpStatusCode.Unauthorized, """{"error":"synthetic diagnostic","error_codes":["synthetic diagnostic"]}""", null, null, ResultStatus.Unavailable)] - [InlineData(HttpStatusCode.Unauthorized, "synthetic diagnostic", null, null, ResultStatus.Unavailable)] - [InlineData(HttpStatusCode.BadRequest, """{"error":"invalid_grant","error_codes":[54005]}""", "invalid_grant", 54005, ResultStatus.Unauthorized)] - public async Task Handle_MicrosoftTokenExchangeRejected_ReturnsSafeFailure(HttpStatusCode statusCode, string content, string? expectedError, int? expectedEntraCode, ResultStatus expectedStatus) - { - // Arrange - var users = new Mock(MockBehavior.Strict); - var tokens = new Mock(MockBehavior.Strict); - var oauthProvider = new Mock(MockBehavior.Strict); - oauthProvider.Setup(provider => provider.GetMicrosoftUserInfoAsync(It.IsAny(), TestOAuthProviderClient.MicrosoftClientId, "microsoft-client-secret")) - .ThrowsAsync(new UnexpectedResponseException(new RestResponse { StatusCode = statusCode, Content = content })); - var handler = CreateHandler(users.Object, tokens.Object, GetService(), oauthProvider.Object); - var message = new MicrosoftLogin( - new ExternalAuthInfo { ClientId = TestOAuthProviderClient.MicrosoftClientId, Code = "synthetic-code", RedirectUri = "http://localhost" }, - new DefaultHttpContext()); - - // Act - var result = await handler.Handle(message); - - // Assert - Assert.Equal(expectedStatus, result.Status); - Assert.Equal(expectedStatus is ResultStatus.Unauthorized - ? "Microsoft sign-in expired or was rejected. Start sign-in again." - : "Microsoft sign-in is unavailable. Try another sign-in method.", result.Message); - var warning = Assert.Single(Log.LogEntries, entry => entry.LogLevel is LogLevel.Warning && String.Equals(entry.CategoryName, typeof(AuthHandler).FullName, StringComparison.Ordinal)); - var properties = Assert.IsAssignableFrom>>(warning.State).ToDictionary(property => property.Key, property => property.Value); - Assert.Equal((int)statusCode, properties["ProviderStatus"]); - Assert.Equal(expectedError, properties["OAuthError"]); - Assert.Equal(expectedEntraCode, properties["EntraErrorCode"]); - Assert.DoesNotContain("synthetic diagnostic", warning.Message, StringComparison.Ordinal); - Assert.Null(warning.Exception); - users.VerifyNoOtherCalls(); - tokens.VerifyNoOtherCalls(); - } - - [Theory] - [InlineData("abcdef0123456789", "synthetic-secret")] - [InlineData("00000000-0000-0000-0000-000000000000", "synthetic-secret")] - [InlineData(TestOAuthProviderClient.MicrosoftClientId, null)] - public async Task Handle_InvalidMicrosoftConfiguration_ReturnsUnavailableWithoutContactingProvider(string clientId, string? clientSecret) - { - // Arrange - var users = new Mock(MockBehavior.Strict); - var provider = new Mock(MockBehavior.Strict); - var handler = CreateHandler(users.Object, GetService(), GetService(), provider.Object); - var options = GetService(); - options.AuthOptions.MicrosoftId = clientId; - options.AuthOptions.MicrosoftSecret = clientSecret; - var message = new MicrosoftLogin( - new ExternalAuthInfo { ClientId = clientId, Code = "synthetic-code", RedirectUri = "http://localhost" }, - new DefaultHttpContext()); - - // Act - var result = await handler.Handle(message); - - // Assert - Assert.Equal(ResultStatus.Unavailable, result.Status); - provider.VerifyNoOtherCalls(); - users.VerifyNoOtherCalls(); - } - private AuthHandler CreateHandler(IUserRepository userRepository, ITokenRepository tokenRepository, IOAuthTokenRepository oauthTokenRepository, IOAuthProviderClient oauthProvider) { var appOptions = GetService(); - appOptions.AuthOptions.MicrosoftId = TestOAuthProviderClient.MicrosoftClientId; + appOptions.AuthOptions.MicrosoftId = "microsoft-client-id"; appOptions.AuthOptions.MicrosoftSecret = "microsoft-client-secret"; return new AuthHandler( diff --git a/tests/Exceptionless.Tests/BootstrapperTests.cs b/tests/Exceptionless.Tests/BootstrapperTests.cs index 530e406ada..188d72b06e 100644 --- a/tests/Exceptionless.Tests/BootstrapperTests.cs +++ b/tests/Exceptionless.Tests/BootstrapperTests.cs @@ -1,5 +1,4 @@ using Exceptionless.Core; -using Exceptionless.Tests.Utility; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -141,7 +140,7 @@ private static AppOptions CreateConfiguredOptions() new("ConnectionStrings:ElasticsearchToMigrate", "server=\"https://migrate-user:migrate-password-secret-canary@elastic-migrate.example.test:9243\""), new("ConnectionStrings:Email", "smtps://smtp-user:smtp-password-secret-canary@smtp.example.test:465"), new("ConnectionStrings:LDAP", "server=ldap.example.test;port=389;username=ldap-user;password=ldap-password-secret-canary"), - new("ConnectionStrings:OAuth", $"GoogleId=google-id;GoogleSecret=google-secret-canary;MicrosoftId={TestOAuthProviderClient.MicrosoftClientId};MicrosoftSecret=microsoft-secret-canary;GitHubId=github-id;GitHubSecret=github-secret-canary;IntercomId=intercom-id;IntercomSecret=intercom-secret-canary;SlackId=slack-id;SlackSecret=slack-secret-canary"), + new("ConnectionStrings:OAuth", "GoogleId=google-id;GoogleSecret=google-secret-canary;MicrosoftId=microsoft-id;MicrosoftSecret=microsoft-secret-canary;GitHubId=github-id;GitHubSecret=github-secret-canary;IntercomId=intercom-id;IntercomSecret=intercom-secret-canary;SlackId=slack-id;SlackSecret=slack-secret-canary"), new("StripeApiKey", "stripe-api-key-secret-canary"), new("StripePublishableApiKey", "stripe-publishable-key"), new("StripeWebHookSigningSecret", "stripe-signing-secret-canary"), diff --git a/tests/Exceptionless.Tests/Utility/TestOAuthProviderClient.cs b/tests/Exceptionless.Tests/Utility/TestOAuthProviderClient.cs index 2bf64fe6cf..235953a8bb 100644 --- a/tests/Exceptionless.Tests/Utility/TestOAuthProviderClient.cs +++ b/tests/Exceptionless.Tests/Utility/TestOAuthProviderClient.cs @@ -7,8 +7,6 @@ namespace Exceptionless.Tests.Utility; public sealed class TestOAuthProviderClient : IOAuthProviderClient { - public const string MicrosoftClientId = "00000000-0000-4000-8000-000000000001"; - public Task GetGitHubUserInfoAsync(ExternalAuthInfo authInfo, string appId, string appSecret) { return GetUserInfoAsync("GitHub", authInfo);