From 31934e837e3b5cbb3c387e300b13b1e9ac87650b Mon Sep 17 00:00:00 2001 From: John Korsnes Date: Mon, 2 Nov 2026 14:45:33 +0100 Subject: [PATCH 1/3] feat: harden the install callback: full redirect_uri, no exchange without a code, an optional state check - redirect_uri is the callback's PathBase plus Path, so the middleware works mounted as an endpoint as well as with app.Map - a callback without a code never exchanges; OAuthOptions.CancelledRedirectUri takes a declined install to the app's page - OAuthOptions.ValidateState runs before the exchange; a refused state, or a code Slack refuses, goes to FailedRedirectUri (a bare 403 or 500 without one) --- .../Hosting/ServiceCollectionExtensions.cs | 21 +++ .../SlackbotCodeTokenExchangeMiddleware.cs | 88 ++++++--- .../OAuthCallbackTests.cs | 169 ++++++++++++++++++ 3 files changed, 255 insertions(+), 23 deletions(-) create mode 100644 source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs diff --git a/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs b/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs index a8cc959..13aab79 100644 --- a/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs +++ b/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs @@ -1,3 +1,4 @@ +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Slackbot.Net.Abstractions.Hosting; using Slackbot.Net.Endpoints.Abstractions; @@ -44,4 +45,24 @@ public class OAuthOptions /// can pick it up — this library never interprets it. /// public string SuccessRedirectUri { get; set; } = "/success?default=1"; + + /// + /// Where the user ends up when the callback carries no code, as when they cancel on Slack's install + /// screen (?error=access_denied). The state is appended as for . + /// Left null, the request goes on to the next middleware, as before. + /// + public string CancelledRedirectUri { get; set; } + + /// + /// Where the user ends up when refuses the callback or Slack refuses the code + /// exchange. Left null, the response is a bare 403 or 500. + /// + public string FailedRedirectUri { get; set; } + + /// + /// Checks the callback's state (null when there is none) against the one the app sent, before the code + /// is exchanged and before runs. Return false to refuse + /// the callback: nothing is exchanged and nothing installed. Left null, every callback is accepted, as before. + /// + public Func> ValidateState { get; set; } } diff --git a/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs b/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs index f9c8683..5010aa1 100644 --- a/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs +++ b/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs @@ -14,41 +14,83 @@ public async Task Invoke(HttpContext ctx, OAuthClient oAuthAccessClient, IOptions options, IWorkspaceInstallationHandler installationHandler, ILogger logger) { - logger.LogInformation("Installing!"); - var redirect_uri = new Uri($"{ctx.Request.Scheme}://{ctx.Request.Host.Value}{ctx.Request.PathBase.Value}"); + var settings = options.Value; var code = ctx.Request.Query["code"].FirstOrDefault(); + var stateTheAppSent = ctx.Request.Query["state"].FirstOrDefault(); - if (code == null) + if (string.IsNullOrEmpty(code)) { + logger.LogInformation("Install callback without a code: {Error}", ctx.Request.Query["error"].FirstOrDefault()); + if (settings.CancelledRedirectUri is { } cancelled) + { + ctx.Response.Redirect(SuccessRedirect(cancelled, stateTheAppSent)); + return; + } + await next(ctx); + return; } - var response = await oAuthAccessClient.OAuthAccessV2(new OAuthClient.OauthAccessV2Request( - code, - options.Value.CLIENT_ID, - options.Value.CLIENT_SECRET, - redirect_uri.ToString() - )); + if (settings.ValidateState is { } validate && !await validate(ctx, stateTheAppSent)) + { + logger.LogWarning("Install callback refused: the app didn't accept its state"); + Fail(ctx, settings, StatusCodes.Status403Forbidden, null); + return; + } - if (response.Ok) + OAuthClient.OAuthAccessV2Response response; + try { - logger.LogInformation($"Oauth response! ok:{response.Ok}"); - await installationHandler.Install(new Workspace - ( - response.Team.Id, - response.Team.Name, - response.Access_Token, - await Installer(oAuthAccessClient, response.Authed_User, logger) + response = await oAuthAccessClient.OAuthAccessV2(new OAuthClient.OauthAccessV2Request( + code, + settings.CLIENT_ID, + settings.CLIENT_SECRET, + RedirectUri(ctx.Request) )); + } + catch (Exception e) when (settings.FailedRedirectUri is not null && e is HttpRequestException or SlackApiException or System.Text.Json.JsonException) + { + logger.LogError(e, "Slack refused to exchange the install's code"); + Fail(ctx, settings, StatusCodes.Status500InternalServerError, null); + return; + } - var stateTheAppSent = ctx.Request.Query["state"].FirstOrDefault(); - ctx.Response.Redirect(SuccessRedirect(options.Value.SuccessRedirectUri, stateTheAppSent)); + if (!response.Ok) + { + logger.LogError("Bad Oauth response! {Error}", response.Error); + Fail(ctx, settings, StatusCodes.Status500InternalServerError, response.Error); + return; } - else + + logger.LogInformation("Oauth response! ok:{Ok}", response.Ok); + await installationHandler.Install(new Workspace + ( + response.Team.Id, + response.Team.Name, + response.Access_Token, + await Installer(oAuthAccessClient, response.Authed_User, logger) + )); + + ctx.Response.Redirect(SuccessRedirect(settings.SuccessRedirectUri, stateTheAppSent)); + } + + // Slack requires the exchange's redirect_uri to equal the one the install started with: the callback's + // full URL without its query, whether it's mounted with app.Map (PathBase) or as an endpoint (Path). + internal static string RedirectUri(HttpRequest request) => + $"{request.Scheme}://{request.Host.Value}{request.PathBase.Value}{request.Path.Value}"; + + private static void Fail(HttpContext ctx, OAuthOptions settings, int status, string error) + { + if (settings.FailedRedirectUri is { } failed) + { + ctx.Response.Redirect(failed); + return; + } + + ctx.Response.StatusCode = status; + if (error is not null) { - logger.LogError($"Bad Oauth response! {response}"); - ctx.Response.StatusCode = StatusCodes.Status500InternalServerError; - await ctx.Response.WriteAsync(response.Error); + ctx.Response.WriteAsync(error); } } diff --git a/source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs b/source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs new file mode 100644 index 0000000..8c29bb7 --- /dev/null +++ b/source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs @@ -0,0 +1,169 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.DependencyInjection; +using Slackbot.Net.Abstractions.Hosting; +using Slackbot.Net.Endpoints.Hosting; + +namespace Slackbot.Net.Tests; + +public class OAuthCallbackTests +{ + private const string Installed = + """{"ok":true,"access_token":"xoxb-token","scope":"chat:write","team":{"id":"T1","name":"Team"},"app_id":"A1"}"""; + + [Theory] + [InlineData("/slack/oauth", "", "https://example.com/slack/oauth")] + [InlineData("", "/slack/oauth", "https://example.com/slack/oauth")] + [InlineData("/app", "/slack/oauth", "https://example.com/app/slack/oauth")] + public async Task TheRedirectUriIsTheCallbacksUrl_MountedWithMapOrAsAnEndpoint(string pathBase, string path, string redirectUri) + { + var callback = await CallbackAsync("?code=the-code", pathBase: pathBase, path: path); + + Assert.Equal(redirectUri, Assert.Single(callback.Exchanges)["redirect_uri"]); + } + + [Fact] + public async Task ADeclinedInstall_GoesToTheCancelledPageWithItsState_AndExchangesNothing() + { + var callback = await CallbackAsync("?error=access_denied&state=s1", o => o.CancelledRedirectUri = "/cancelled"); + + Assert.Equal("/cancelled?state=s1", callback.Context.Response.Headers.Location.ToString()); + Assert.Empty(callback.Exchanges); + Assert.Empty(callback.Handler.Installed); + } + + [Fact] + public async Task ACallbackWithoutACode_GoesOnToTheNextMiddleware_AndExchangesNothing() + { + var callback = await CallbackAsync("?error=access_denied"); + + Assert.True(callback.ReachedNext); + Assert.Empty(callback.Exchanges); + Assert.Empty(callback.Handler.Installed); + } + + [Fact] + public async Task AStateTheAppRefuses_ExchangesNothing_AndInstallsNothing() + { + var callback = await CallbackAsync("?code=the-code&state=forged", o => + { + o.ValidateState = (_, state) => Task.FromResult(state == "the-one-we-sent"); + o.FailedRedirectUri = "/failed"; + }); + + Assert.Equal("/failed", callback.Context.Response.Headers.Location.ToString()); + Assert.Empty(callback.Exchanges); + Assert.Empty(callback.Handler.Installed); + } + + [Fact] + public async Task AStateTheAppAccepts_Installs() + { + HttpContext seen = null; + var callback = await CallbackAsync("?code=the-code&state=the-one-we-sent", o => o.ValidateState = (ctx, state) => + { + seen = ctx; + return Task.FromResult(state == "the-one-we-sent"); + }); + + Assert.Same(callback.Context, seen); + Assert.Single(callback.Handler.Installed); + } + + [Fact] + public async Task ARefusedStateWithoutAFailedPage_IsABare403() + { + var callback = await CallbackAsync("?code=the-code&state=forged", o => o.ValidateState = (_, _) => Task.FromResult(false)); + + Assert.Equal(StatusCodes.Status403Forbidden, callback.Context.Response.StatusCode); + Assert.Empty(callback.Exchanges); + } + + [Fact] + public async Task ACodeSlackRefuses_GoesToTheFailedPage_AndInstallsNothing() + { + var callback = await CallbackAsync( + "?code=stale", o => o.FailedRedirectUri = "/failed", oauthAccessResponse: """{"ok":false,"error":"invalid_code"}"""); + + Assert.Equal("/failed", callback.Context.Response.Headers.Location.ToString()); + Assert.Empty(callback.Handler.Installed); + } + + private static async Task CallbackAsync( + string query, Action configure = null, string pathBase = "/oauth", string path = "", + string oauthAccessResponse = Installed) + { + var slack = new SlackApiStub(oauthAccessResponse); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSlackBotEvents(); + services.AddSlackbotDistribution(o => + { + o.CLIENT_ID = "client-id"; + o.CLIENT_SECRET = "client-secret"; + o.SuccessRedirectUri = "/success"; + configure?.Invoke(o); + }); + services.ConfigureHttpClientDefaults(b => b.ConfigurePrimaryHttpMessageHandler(() => slack)); + + await using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + await using var scope = provider.CreateAsyncScope(); + + var reachedNext = false; + var pipeline = new ApplicationBuilder(provider) + .UseSlackbotDistribution() + .Use(_ => _ => + { + reachedNext = true; + return Task.CompletedTask; + }) + .Build(); + + var ctx = new DefaultHttpContext { RequestServices = scope.ServiceProvider }; + ctx.Request.Scheme = "https"; + ctx.Request.Host = new HostString("example.com"); + ctx.Request.PathBase = pathBase; + ctx.Request.Path = path; + ctx.Request.QueryString = new QueryString(query); + + await pipeline(ctx); + + var handler = (RecordingInstallationHandler)scope.ServiceProvider.GetRequiredService(); + return new Callback(ctx, handler, slack.Exchanges, reachedNext); + } + + private sealed record Callback(HttpContext Context, RecordingInstallationHandler Handler, List> Exchanges, bool ReachedNext); + + private sealed class SlackApiStub(string oauthAccessResponse) : HttpMessageHandler + { + public List> Exchanges { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri!.AbsolutePath.EndsWith("oauth.v2.access")) + { + var form = await request.Content!.ReadAsStringAsync(cancellationToken); + Exchanges.Add(QueryHelpers.ParseQuery(form).ToDictionary(p => p.Key, p => p.Value.ToString())); + } + + return new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { + Content = new StringContent(oauthAccessResponse, System.Text.Encoding.UTF8, "application/json") + }; + } + } + + private sealed class RecordingInstallationHandler : IWorkspaceInstallationHandler + { + public List Installed { get; } = []; + + public Task Install(Workspace workspace) + { + Installed.Add(workspace); + return Task.CompletedTask; + } + + public Task Uninstall(string teamId) => Task.CompletedTask; + } +} From a34c28fe19a36226669f7bf6681d3e37055d365d Mon Sep 17 00:00:00 2001 From: John Korsnes Date: Mon, 2 Nov 2026 14:51:07 +0100 Subject: [PATCH 2/3] fix: await the failed callback's response body --- .../Middlewares/SlackbotCodeTokenExchangeMiddleware.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs b/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs index 5010aa1..d9f0f5a 100644 --- a/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs +++ b/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs @@ -34,7 +34,7 @@ public async Task Invoke(HttpContext ctx, OAuthClient oAuthAccessClient, if (settings.ValidateState is { } validate && !await validate(ctx, stateTheAppSent)) { logger.LogWarning("Install callback refused: the app didn't accept its state"); - Fail(ctx, settings, StatusCodes.Status403Forbidden, null); + await Fail(ctx, settings, StatusCodes.Status403Forbidden, null); return; } @@ -51,14 +51,14 @@ public async Task Invoke(HttpContext ctx, OAuthClient oAuthAccessClient, catch (Exception e) when (settings.FailedRedirectUri is not null && e is HttpRequestException or SlackApiException or System.Text.Json.JsonException) { logger.LogError(e, "Slack refused to exchange the install's code"); - Fail(ctx, settings, StatusCodes.Status500InternalServerError, null); + await Fail(ctx, settings, StatusCodes.Status500InternalServerError, null); return; } if (!response.Ok) { logger.LogError("Bad Oauth response! {Error}", response.Error); - Fail(ctx, settings, StatusCodes.Status500InternalServerError, response.Error); + await Fail(ctx, settings, StatusCodes.Status500InternalServerError, response.Error); return; } @@ -79,7 +79,7 @@ await Installer(oAuthAccessClient, response.Authed_User, logger) internal static string RedirectUri(HttpRequest request) => $"{request.Scheme}://{request.Host.Value}{request.PathBase.Value}{request.Path.Value}"; - private static void Fail(HttpContext ctx, OAuthOptions settings, int status, string error) + private static async Task Fail(HttpContext ctx, OAuthOptions settings, int status, string error) { if (settings.FailedRedirectUri is { } failed) { @@ -90,7 +90,7 @@ private static void Fail(HttpContext ctx, OAuthOptions settings, int status, str ctx.Response.StatusCode = status; if (error is not null) { - ctx.Response.WriteAsync(error); + await ctx.Response.WriteAsync(error); } } From 4a51aac43df96a115c8d1fea4ab058f07b837382 Mon Sep 17 00:00:00 2001 From: John Korsnes Date: Mon, 2 Nov 2026 14:53:51 +0100 Subject: [PATCH 3/3] feat: the cancelled page also gets Slack's error, so it can tell a cancel from a failure --- .../Hosting/ServiceCollectionExtensions.cs | 3 ++- .../SlackbotCodeTokenExchangeMiddleware.cs | 6 ++++-- .../OAuthCallbackTests.cs | 12 ++++++++++-- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs b/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs index 13aab79..acbc422 100644 --- a/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs +++ b/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs @@ -48,7 +48,8 @@ public class OAuthOptions /// /// Where the user ends up when the callback carries no code, as when they cancel on Slack's install - /// screen (?error=access_denied). The state is appended as for . + /// screen (?error=access_denied). The state is appended as for , + /// and Slack's error, when it sent one, as ?error=, so the page can tell a cancel from a failure. /// Left null, the request goes on to the next middleware, as before. /// public string CancelledRedirectUri { get; set; } diff --git a/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs b/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs index d9f0f5a..b7769bf 100644 --- a/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs +++ b/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs @@ -20,10 +20,12 @@ public async Task Invoke(HttpContext ctx, OAuthClient oAuthAccessClient, if (string.IsNullOrEmpty(code)) { - logger.LogInformation("Install callback without a code: {Error}", ctx.Request.Query["error"].FirstOrDefault()); + var error = ctx.Request.Query["error"].FirstOrDefault(); + logger.LogInformation("Install callback without a code: {Error}", error); if (settings.CancelledRedirectUri is { } cancelled) { - ctx.Response.Redirect(SuccessRedirect(cancelled, stateTheAppSent)); + var page = SuccessRedirect(cancelled, stateTheAppSent); + ctx.Response.Redirect(string.IsNullOrEmpty(error) ? page : QueryHelpers.AddQueryString(page, "error", error)); return; } diff --git a/source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs b/source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs index 8c29bb7..31db62d 100644 --- a/source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs +++ b/source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs @@ -24,15 +24,23 @@ public async Task TheRedirectUriIsTheCallbacksUrl_MountedWithMapOrAsAnEndpoint(s } [Fact] - public async Task ADeclinedInstall_GoesToTheCancelledPageWithItsState_AndExchangesNothing() + public async Task ADeclinedInstall_GoesToTheCancelledPageWithItsStateAndSlacksError_AndExchangesNothing() { var callback = await CallbackAsync("?error=access_denied&state=s1", o => o.CancelledRedirectUri = "/cancelled"); - Assert.Equal("/cancelled?state=s1", callback.Context.Response.Headers.Location.ToString()); + Assert.Equal("/cancelled?state=s1&error=access_denied", callback.Context.Response.Headers.Location.ToString()); Assert.Empty(callback.Exchanges); Assert.Empty(callback.Handler.Installed); } + [Fact] + public async Task ACallbackWithNeitherCodeNorError_GoesToTheCancelledPageWithJustItsState() + { + var callback = await CallbackAsync("?state=s1", o => o.CancelledRedirectUri = "/cancelled"); + + Assert.Equal("/cancelled?state=s1", callback.Context.Response.Headers.Location.ToString()); + } + [Fact] public async Task ACallbackWithoutACode_GoesOnToTheNextMiddleware_AndExchangesNothing() {