diff --git a/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs b/source/src/Slackbot.Net.Endpoints/Hosting/ServiceCollectionExtensions.cs index a8cc959..acbc422 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,25 @@ 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 , + /// 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; } + + /// + /// 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..b7769bf 100644 --- a/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs +++ b/source/src/Slackbot.Net.Endpoints/Middlewares/SlackbotCodeTokenExchangeMiddleware.cs @@ -14,41 +14,85 @@ 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)) { + var error = ctx.Request.Query["error"].FirstOrDefault(); + logger.LogInformation("Install callback without a code: {Error}", error); + if (settings.CancelledRedirectUri is { } cancelled) + { + var page = SuccessRedirect(cancelled, stateTheAppSent); + ctx.Response.Redirect(string.IsNullOrEmpty(error) ? page : QueryHelpers.AddQueryString(page, "error", error)); + 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"); + await 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"); + await 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); + await 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 async Task 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); + await 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..31db62d --- /dev/null +++ b/source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs @@ -0,0 +1,177 @@ +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_GoesToTheCancelledPageWithItsStateAndSlacksError_AndExchangesNothing() + { + var callback = await CallbackAsync("?error=access_denied&state=s1", o => o.CancelledRedirectUri = "/cancelled"); + + 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() + { + 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; + } +}