[backend/signalr] Add authentication & authorization (ISH-244)

This commit is contained in:
Laura Hausmann 2024-04-03 21:46:05 +02:00
parent 41ac042ec3
commit 66675146d9
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
7 changed files with 149 additions and 2 deletions

View file

@ -9,6 +9,8 @@ using Iceshrimp.Backend.Core.Federation.WebFinger;
using Iceshrimp.Backend.Core.Helpers.LibMfm.Conversion;
using Iceshrimp.Backend.Core.Middleware;
using Iceshrimp.Backend.Core.Services;
using Iceshrimp.Backend.Hubs.Authentication;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
@ -16,6 +18,8 @@ using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.OpenApi.Models;
using AuthenticationMiddleware = Iceshrimp.Backend.Core.Middleware.AuthenticationMiddleware;
using AuthorizationMiddleware = Iceshrimp.Backend.Core.Middleware.AuthorizationMiddleware;
using NoteRenderer = Iceshrimp.Backend.Controllers.Renderers.NoteRenderer;
using NotificationRenderer = Iceshrimp.Backend.Controllers.Renderers.NotificationRenderer;
using UserRenderer = Iceshrimp.Backend.Controllers.Renderers.UserRenderer;
@ -242,4 +246,23 @@ public static class ServiceExtensions
});
});
}
public static void AddAuthorizationPolicies(this IServiceCollection services)
{
services.AddAuthorizationBuilder()
.AddPolicy("HubAuthorization", policy =>
{
policy.Requirements.Add(new HubAuthorizationRequirement());
policy.AuthenticationSchemes = ["HubAuthenticationScheme"];
});
services.AddAuthentication(options =>
{
options.AddScheme<HubAuthenticationHandler>("HubAuthenticationScheme", null);
// Add a stub authentication handler to bypass strange ASP.NET Core >=7.0 defaults
// Ref: https://github.com/dotnet/aspnetcore/issues/44661
options.AddScheme<IAuthenticationHandler>("StubAuthenticationHandler", null);
});
}
}

View file

@ -506,6 +506,9 @@ public class UserService(
{
UpdateUserLastActive(session.User);
if (session.LastActiveDate != null && session.LastActiveDate > DateTime.UtcNow - TimeSpan.FromMinutes(5))
return;
_ = followupTaskSvc.ExecuteTask("UpdateSessionMetadata", async provider =>
{
var bgDb = provider.GetRequiredService<DatabaseContext>();
@ -516,7 +519,8 @@ public class UserService(
private void UpdateUserLastActive(User user)
{
if (user.LastActiveDate != null && user.LastActiveDate > DateTime.UtcNow - TimeSpan.FromHours(1)) return;
if (user.LastActiveDate != null && user.LastActiveDate > DateTime.UtcNow - TimeSpan.FromMinutes(5))
return;
_ = followupTaskSvc.ExecuteTask("UpdateUserLastActive", async provider =>
{

View file

@ -0,0 +1,99 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Iceshrimp.Backend.Core.Database;
using Iceshrimp.Backend.Core.Middleware;
using Iceshrimp.Backend.Core.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace Iceshrimp.Backend.Hubs.Authentication;
public class HubAuthorizationRequirement : IAuthorizationRequirement;
public class HubAuthenticationHandler(
IOptionsMonitor<BearerTokenOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
DatabaseContext db,
UserService userSvc
) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string token;
if (Request.Query.ContainsKey("access_token"))
{
token = Request.Query["access_token"].ToString();
}
else
{
var header = Request.Headers.Authorization.ToString();
if (!header.ToLowerInvariant().StartsWith("bearer "))
return AuthenticateResult.NoResult();
token = header[7..];
}
var session = await db.Sessions
.Include(p => p.User.UserProfile)
.Include(p => p.User.UserSettings)
.FirstOrDefaultAsync(p => p.Token == token && p.Active);
if (session is not { Active: true })
return AuthenticateResult.NoResult();
var claims = new[] { new Claim("token", token), new Claim("userId", session.UserId) };
var identity = new ClaimsIdentity(claims, nameof(HubAuthenticationHandler));
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name);
userSvc.UpdateSessionMetadata(session);
Context.SetSession(session);
return AuthenticateResult.Success(ticket);
}
}
public class HubAuthorizationHandler(
IHttpContextAccessor httpContextAccessor
) : AuthorizationHandler<HubAuthorizationRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context, HubAuthorizationRequirement requirement
)
{
var ctx = httpContextAccessor.HttpContext;
if (ctx == null)
throw new Exception("HttpContext must not be null at this stage");
if (ctx.GetUser() == null)
context.Fail(new AuthorizationFailureReason(this, "Unauthorized"));
else
context.Succeed(requirement);
return Task.CompletedTask;
}
}
public class HubUserIdProvider(IHttpContextAccessor httpContextAccessor) : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
if (httpContextAccessor.HttpContext == null)
throw new Exception("HttpContext must not be null at this stage");
return httpContextAccessor.HttpContext.GetUserOrFail().Id;
}
}
public static class AuthenticationServiceExtensions
{
public static void AddAuthenticationServices(this IServiceCollection services)
{
services.AddScoped<IAuthenticationHandler, HubAuthenticationHandler>()
.AddSingleton<IAuthorizationHandler, HubAuthorizationHandler>()
.AddSingleton<IHttpContextAccessor, HttpContextAccessor>()
.AddSingleton<IUserIdProvider, HubUserIdProvider>();
}
}

View file

@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Iceshrimp.Backend.Hubs;
[Authorize(Policy = "HubAuthorization")]
public class StreamingHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", "SignalR", "ping!");
}
}

View file

@ -1,5 +1,6 @@
using Iceshrimp.Backend.Core.Extensions;
using Iceshrimp.Backend.Hubs;
using Iceshrimp.Backend.Hubs.Authentication;
var builder = WebApplication.CreateBuilder(args);
@ -17,6 +18,8 @@ builder.Services.AddLogging(logging => logging.AddCustomConsoleFormatter());
builder.Services.AddDatabaseContext(builder.Configuration);
builder.Services.AddSlidingWindowRateLimiter();
builder.Services.AddCorsPolicies();
builder.Services.AddAuthorizationPolicies();
builder.Services.AddAuthenticationServices();
builder.Services.AddSignalR().AddMessagePackProtocol();
builder.Services.AddResponseCompression();
@ -50,6 +53,7 @@ app.UseCustomMiddleware();
app.MapControllers();
app.MapFallbackToController("/api/{**slug}", "FallbackAction", "Fallback");
app.MapHub<ExampleHub>("/hubs/example");
app.MapHub<StreamingHub>("/hubs/streaming");
app.MapRazorPages();
app.MapFallbackToPage("/Shared/FrontendSPA");

View file

@ -90,4 +90,5 @@ Iceshrimp = Information
Microsoft.AspNetCore = Warning
Microsoft.EntityFrameworkCore = Warning
Microsoft.EntityFrameworkCore.Migrations = Information
Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager = Critical
Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager = Critical
Iceshrimp.Backend.Hubs.Authentication.HubAuthenticationHandler = Warning

View file

@ -40,6 +40,9 @@
.WithUrl(Navigation.ToAbsoluteUri("/hubs/example"))
.AddMessagePackProtocol()
.Build();
//TODO: authentication is done like this:
//options => { options.AccessTokenProvider = () => Task.FromResult("the_access_token")!; })
_hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{