Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Slackbot.Net.Abstractions.Hosting;
using Slackbot.Net.Endpoints.Abstractions;
Expand Down Expand Up @@ -44,4 +45,25 @@ public class OAuthOptions
/// can pick it up — this library never interprets it.
/// </summary>
public string SuccessRedirectUri { get; set; } = "/success?default=1";

/// <summary>
/// Where the user ends up when the callback carries no <c>code</c>, as when they cancel on Slack's install
/// screen (<c>?error=access_denied</c>). The <c>state</c> is appended as for <see cref="SuccessRedirectUri"/>,
/// and Slack's <c>error</c>, when it sent one, as <c>?error=</c>, so the page can tell a cancel from a failure.
/// Left null, the request goes on to the next middleware, as before.
/// </summary>
public string CancelledRedirectUri { get; set; }

/// <summary>
/// Where the user ends up when <see cref="ValidateState"/> refuses the callback or Slack refuses the code
/// exchange. Left null, the response is a bare 403 or 500.
/// </summary>
public string FailedRedirectUri { get; set; }

/// <summary>
/// Checks the callback's <c>state</c> (null when there is none) against the one the app sent, before the code
/// is exchanged and before <see cref="IWorkspaceInstallationHandler.Install"/> runs. Return false to refuse
/// the callback: nothing is exchanged and nothing installed. Left null, every callback is accepted, as before.
/// </summary>
public Func<HttpContext, string, Task<bool>> ValidateState { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,41 +14,85 @@ public async Task Invoke(HttpContext ctx, OAuthClient oAuthAccessClient,
IOptions<OAuthOptions> options, IWorkspaceInstallationHandler installationHandler,
ILogger<SlackbotCodeTokenExchangeMiddleware> 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);
}
}

Expand Down
177 changes: 177 additions & 0 deletions source/test/Slackbot.Net.SlackClients.Http.Tests/OAuthCallbackTests.cs
Original file line number Diff line number Diff line change
@@ -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<Callback> CallbackAsync(
string query, Action<OAuthOptions> configure = null, string pathBase = "/oauth", string path = "",
string oauthAccessResponse = Installed)
{
var slack = new SlackApiStub(oauthAccessResponse);
var services = new ServiceCollection();
services.AddLogging();
services.AddSlackBotEvents<RecordingInstallationHandler>();
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<IWorkspaceInstallationHandler>();
return new Callback(ctx, handler, slack.Exchanges, reachedNext);
}

private sealed record Callback(HttpContext Context, RecordingInstallationHandler Handler, List<Dictionary<string, string>> Exchanges, bool ReachedNext);

private sealed class SlackApiStub(string oauthAccessResponse) : HttpMessageHandler
{
public List<Dictionary<string, string>> Exchanges { get; } = [];

protected override async Task<HttpResponseMessage> 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<Workspace> Installed { get; } = [];

public Task Install(Workspace workspace)
{
Installed.Add(workspace);
return Task.CompletedTask;
}

public Task Uninstall(string teamId) => Task.CompletedTask;
}
}
Loading