feat: initial fediverse registration/login

This commit is contained in:
sam 2024-11-03 02:07:07 +01:00
parent 5a22807410
commit c4cb08cdc1
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
16 changed files with 467 additions and 111 deletions

View file

@ -0,0 +1,321 @@
using System.Security.Cryptography;
using Foxnouns.Backend.Controllers.Authentication;
using Foxnouns.Backend.Database;
using Foxnouns.Backend.Database.Models;
using Foxnouns.Backend.Utils;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using NodaTime;
namespace Foxnouns.Backend.Services.Auth;
public class AuthService(
IClock clock,
ILogger logger,
DatabaseContext db,
ISnowflakeGenerator snowflakeGenerator,
UserRendererService userRenderer
)
{
private readonly ILogger _logger = logger.ForContext<AuthService>();
private readonly PasswordHasher<User> _passwordHasher = new();
/// <summary>
/// Creates a new user with the given email address and password.
/// This method does <i>not</i> save the resulting user, the caller must still call <see cref="M:Microsoft.EntityFrameworkCore.DbContext.SaveChanges" />.
/// </summary>
public async Task<User> CreateUserWithPasswordAsync(
string username,
string email,
string password,
CancellationToken ct = default
)
{
var user = new User
{
Id = snowflakeGenerator.GenerateSnowflake(),
Username = username,
AuthMethods =
{
new AuthMethod
{
Id = snowflakeGenerator.GenerateSnowflake(),
AuthType = AuthType.Email,
RemoteId = email,
},
},
LastActive = clock.GetCurrentInstant(),
};
db.Add(user);
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
return user;
}
/// <summary>
/// Creates a new user with the given username and remote authentication method.
/// To create a user with email authentication, use <see cref="CreateUserWithPasswordAsync" />
/// This method does <i>not</i> save the resulting user, the caller must still call <see cref="M:Microsoft.EntityFrameworkCore.DbContext.SaveChanges" />.
/// </summary>
public async Task<User> CreateUserWithRemoteAuthAsync(
string username,
AuthType authType,
string remoteId,
string remoteUsername,
FediverseApplication? instance = null,
CancellationToken ct = default
)
{
AssertValidAuthType(authType, instance);
if (await db.Users.AnyAsync(u => u.Username == username, ct))
throw new ApiError.BadRequest("Username is already taken", "username", username);
var user = new User
{
Id = snowflakeGenerator.GenerateSnowflake(),
Username = username,
AuthMethods =
{
new AuthMethod
{
Id = snowflakeGenerator.GenerateSnowflake(),
AuthType = authType,
RemoteId = remoteId,
RemoteUsername = remoteUsername,
FediverseApplication = instance,
},
},
LastActive = clock.GetCurrentInstant(),
};
db.Add(user);
return user;
}
/// <summary>
/// Authenticates a user with email and password.
/// </summary>
/// <param name="email">The user's email address</param>
/// <param name="password">The user's password, in plain text</param>
/// <param name="ct">Cancellation token</param>
/// <returns>A tuple of the authenticated user and whether multi-factor authentication is required</returns>
/// <exception cref="ApiError.NotFound">Thrown if the email address is not associated with any user
/// or if the password is incorrect</exception>
public async Task<(User, EmailAuthenticationResult)> AuthenticateUserAsync(
string email,
string password,
CancellationToken ct = default
)
{
var user = await db.Users.FirstOrDefaultAsync(
u => u.AuthMethods.Any(a => a.AuthType == AuthType.Email && a.RemoteId == email),
ct
);
if (user == null)
throw new ApiError.NotFound(
"No user with that email address found, or password is incorrect",
ErrorCode.UserNotFound
);
var pwResult = await Task.Run(
() => _passwordHasher.VerifyHashedPassword(user, user.Password!, password),
ct
);
if (pwResult == PasswordVerificationResult.Failed) // TODO: this seems to fail on some valid passwords?
throw new ApiError.NotFound(
"No user with that email address found, or password is incorrect",
ErrorCode.UserNotFound
);
if (pwResult == PasswordVerificationResult.SuccessRehashNeeded)
{
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
await db.SaveChangesAsync(ct);
}
return (user, EmailAuthenticationResult.AuthSuccessful);
}
public enum EmailAuthenticationResult
{
AuthSuccessful,
MfaRequired,
}
/// <summary>
/// Validates a user's password outside an authentication context, for when a password is required for changing
/// a setting, such as adding a new email address or changing passwords.
/// </summary>
public async Task<bool> ValidatePasswordAsync(
User user,
string password,
CancellationToken ct = default
)
{
if (user.Password == null)
{
throw new FoxnounsError("Password for user supplied to ValidatePasswordAsync was null");
}
var pwResult = await Task.Run(
() => _passwordHasher.VerifyHashedPassword(user, user.Password!, password),
ct
);
return pwResult
is PasswordVerificationResult.SuccessRehashNeeded
or PasswordVerificationResult.Success;
}
/// <summary>
/// Sets or updates a password for the given user. This method does <i>not</i> save the updated password automatically.
/// </summary>
public async Task SetUserPasswordAsync(
User user,
string password,
CancellationToken ct = default
)
{
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
db.Update(user);
}
/// <summary>
/// Authenticates a user with a remote authentication provider.
/// </summary>
/// <param name="authType">The remote authentication provider type</param>
/// <param name="remoteId">The remote user ID</param>
/// <param name="instance">The Fediverse instance, if authType is Fediverse.
/// Will throw an exception if passed with another authType.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A user object, or null if the remote account isn't linked to any user.</returns>
/// <exception cref="FoxnounsError">Thrown if <c>instance</c> is passed when not required,
/// or not passed when required</exception>
public async Task<User?> AuthenticateUserAsync(
AuthType authType,
string remoteId,
FediverseApplication? instance = null,
CancellationToken ct = default
)
{
AssertValidAuthType(authType, instance);
return await db.Users.FirstOrDefaultAsync(
u =>
u.AuthMethods.Any(a =>
a.AuthType == authType
&& a.RemoteId == remoteId
&& a.FediverseApplication == instance
),
ct
);
}
public async Task<AuthMethod> AddAuthMethodAsync(
Snowflake userId,
AuthType authType,
string remoteId,
string? remoteUsername = null,
CancellationToken ct = default
)
{
AssertValidAuthType(authType, null);
var authMethod = new AuthMethod
{
Id = snowflakeGenerator.GenerateSnowflake(),
AuthType = authType,
RemoteId = remoteId,
RemoteUsername = remoteUsername,
UserId = userId,
};
db.Add(authMethod);
await db.SaveChangesAsync(ct);
return authMethod;
}
public (string, Token) GenerateToken(
User user,
Application application,
string[] scopes,
Instant expires
)
{
if (!AuthUtils.ValidateScopes(application, scopes))
throw new ApiError.BadRequest(
"Invalid scopes requested for this token",
"scopes",
scopes
);
var (token, hash) = GenerateToken();
return (
token,
new Token
{
Id = snowflakeGenerator.GenerateSnowflake(),
Hash = hash,
Application = application,
User = user,
ExpiresAt = expires,
Scopes = scopes,
}
);
}
/// <summary>
/// Generates a token for the given user and adds it to the database, returning a fully formed auth response for the user.
/// This method is always called at the end of an endpoint method, so the resulting token
/// (and user, if this is a registration request) is also saved to the database.
/// </summary>
public async Task<CallbackResponse> GenerateUserTokenAsync(
User user,
CancellationToken ct = default
)
{
var frontendApp = await db.GetFrontendApplicationAsync(ct);
var (tokenStr, token) = GenerateToken(
user,
frontendApp,
["*"],
clock.GetCurrentInstant() + Duration.FromDays(365)
);
db.Add(token);
_logger.Debug("Generated token {TokenId} for {UserId}", user.Id, token.Id);
await db.SaveChangesAsync(ct);
return new CallbackResponse(
HasAccount: true,
Ticket: null,
RemoteUsername: null,
User: await userRenderer.RenderUserAsync(
user,
selfUser: user,
renderMembers: false,
ct: ct
),
Token: tokenStr,
ExpiresAt: token.ExpiresAt
);
}
private static (string, byte[]) GenerateToken()
{
var token = AuthUtils.RandomToken();
var hash = SHA512.HashData(Convert.FromBase64String(token));
return (token, hash);
}
private static void AssertValidAuthType(AuthType authType, FediverseApplication? instance)
{
if (authType == AuthType.Fediverse && instance == null)
throw new FoxnounsError("Fediverse authentication requires an instance.");
if (authType != AuthType.Fediverse && instance != null)
throw new FoxnounsError("Non-Fediverse authentication does not require an instance.");
}
}

View file

@ -0,0 +1,245 @@
using System.Net;
using System.Web;
using Foxnouns.Backend.Database;
using Foxnouns.Backend.Database.Models;
using Duration = NodaTime.Duration;
using J = System.Text.Json.Serialization.JsonPropertyNameAttribute;
namespace Foxnouns.Backend.Services.Auth;
public partial class FediverseAuthService
{
private string MastodonRedirectUri(string instance) =>
$"{_config.BaseUrl}/auth/callback/mastodon/{instance}";
private async Task<FediverseApplication> CreateMastodonApplicationAsync(
string instance,
Snowflake? existingAppId = null
)
{
var resp = await _client.PostAsync(
$"https://{instance}/api/v1/apps",
new FormUrlEncodedContent(
new Dictionary<string, string>
{
{ "client_name", $"pronouns.cc (+{_config.BaseUrl})" },
{ "redirect_uris", MastodonRedirectUri(instance) },
{ "scope", "read:accounts" },
{ "website", _config.BaseUrl },
}
)
);
resp.EnsureSuccessStatusCode();
var mastodonApp = await resp.Content.ReadFromJsonAsync<PartialMastodonApplication>();
if (mastodonApp == null)
throw new FoxnounsError(
$"Application created on Mastodon-compatible instance {instance} was null"
);
var token = await GetMastodonAppTokenAsync(
instance,
mastodonApp.ClientId,
mastodonApp.ClientSecret
);
FediverseApplication app;
if (existingAppId == null)
{
app = new FediverseApplication
{
Id = existingAppId ?? _snowflakeGenerator.GenerateSnowflake(),
ClientId = mastodonApp.ClientId,
ClientSecret = mastodonApp.ClientSecret,
Domain = instance,
InstanceType = FediverseInstanceType.MastodonApi,
AccessToken = token,
TokenValidUntil = _clock.GetCurrentInstant() + Duration.FromDays(60),
};
_db.Add(app);
}
else
{
app =
await _db.FediverseApplications.FindAsync(existingAppId)
?? throw new FoxnounsError($"Existing app with ID {existingAppId} was null");
app.ClientId = mastodonApp.ClientId;
app.ClientSecret = mastodonApp.ClientSecret;
app.InstanceType = FediverseInstanceType.MastodonApi;
app.AccessToken = null;
app.TokenValidUntil = null;
}
await _db.SaveChangesAsync();
return app;
}
private async Task<FediverseUser> GetMastodonUserAsync(FediverseApplication app, string code)
{
var tokenResp = await _client.PostAsync(
MastodonTokenUri(app.Domain),
new FormUrlEncodedContent(
new Dictionary<string, string>
{
{ "grant_type", "authorization_code" },
{ "code", code },
{ "scope", "read:accounts" },
{ "client_id", app.ClientId },
{ "client_secret", app.ClientSecret },
{ "redirect_uri", MastodonRedirectUri(app.Domain) },
}
)
);
if (tokenResp.StatusCode == HttpStatusCode.Unauthorized)
{
throw new FoxnounsError($"Application for instance {app.Domain} was invalid");
}
tokenResp.EnsureSuccessStatusCode();
var token = (
await tokenResp.Content.ReadFromJsonAsync<MastodonTokenResponse>()
)?.AccessToken;
if (token == null)
{
throw new FoxnounsError($"Token response from instance {app.Domain} was invalid");
}
var req = new HttpRequestMessage(HttpMethod.Get, MastodonCurrentUserUri(app.Domain));
req.Headers.Add("Authorization", $"Bearer {token}");
var currentUserResp = await _client.SendAsync(req);
currentUserResp.EnsureSuccessStatusCode();
var user = await currentUserResp.Content.ReadFromJsonAsync<FediverseUser>();
if (user == null)
{
throw new FoxnounsError($"User response from instance {app.Domain} was invalid");
}
return user;
}
private record MastodonTokenResponse([property: J("access_token")] string AccessToken);
// TODO: Mastodon's OAuth documentation doesn't specify a "state" parameter. that feels... wrong
// https://docs.joinmastodon.org/methods/oauth/
private async Task<string> GenerateMastodonAuthUrlAsync(FediverseApplication app)
{
try
{
await ValidateMastodonAppAsync(app);
}
catch (FoxnounsError.RemoteAuthError e)
{
_logger.Error(
e,
"Error validating app token for {AppId} on {Instance}",
app.Id,
app.Domain
);
app = await CreateMastodonApplicationAsync(app.Domain, existingAppId: app.Id);
}
return $"https://{app.Domain}/oauth/authorize?response_type=code"
+ $"&client_id={app.ClientId}"
+ $"&scope={HttpUtility.UrlEncode("read:accounts")}"
+ $"&redirect_uri={HttpUtility.UrlEncode(MastodonRedirectUri(app.Domain))}";
}
private async Task ValidateMastodonAppAsync(FediverseApplication app)
{
// If we don't have an access token stored, or it's too old, get one
// When doing this we don't need to fetch the application info
if (app.AccessToken == null || app.TokenValidUntil < _clock.GetCurrentInstant())
{
_logger.Debug(
"Application {AppId} on instance {Instance} has no valid token, fetching it",
app.Id,
app.Domain
);
app.AccessToken = await GetMastodonAppTokenAsync(
app.Domain,
app.ClientId,
app.ClientSecret
);
app.TokenValidUntil = _clock.GetCurrentInstant() + Duration.FromDays(60);
_db.Update(app);
await _db.SaveChangesAsync();
return;
}
_logger.Debug(
"Checking whether application {AppId} on instance {Instance} is still valid",
app.Id,
app.Domain
);
var req = new HttpRequestMessage(HttpMethod.Get, MastodonCurrentAppUri(app.Domain));
req.Headers.Add("Authorization", $"Bearer {app.AccessToken}");
var resp = await _client.SendAsync(req);
if (!resp.IsSuccessStatusCode)
{
var error = await resp.Content.ReadAsStringAsync();
throw new FoxnounsError.RemoteAuthError(
"Verifying app credentials returned an error",
error
);
}
}
private async Task<string> GetMastodonAppTokenAsync(
string instance,
string clientId,
string clientSecret
)
{
var resp = await _client.PostAsync(
MastodonTokenUri(instance),
new FormUrlEncodedContent(
new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", clientId },
{ "client_secret", clientSecret },
}
)
);
if (!resp.IsSuccessStatusCode)
{
var error = await resp.Content.ReadAsStringAsync();
throw new FoxnounsError.RemoteAuthError(
"Requesting app token returned an error",
error
);
}
var token = (await resp.Content.ReadFromJsonAsync<MastodonTokenResponse>())?.AccessToken;
if (token == null)
{
throw new FoxnounsError($"Token response from instance {instance} was invalid");
}
return token;
}
private static string MastodonTokenUri(string instance) => $"https://{instance}/oauth/token";
private static string MastodonCurrentUserUri(string instance) =>
$"https://{instance}/api/v1/accounts/verify_credentials";
private static string MastodonCurrentAppUri(string instance) =>
$"https://{instance}/api/v1/apps/verify_credentials";
private record PartialMastodonApplication(
[property: J("name")] string Name,
[property: J("client_id")] string ClientId,
[property: J("client_secret")] string ClientSecret
);
}

View file

@ -0,0 +1,159 @@
using Foxnouns.Backend.Database;
using Foxnouns.Backend.Database.Models;
using Microsoft.EntityFrameworkCore;
using NodaTime;
using J = System.Text.Json.Serialization.JsonPropertyNameAttribute;
namespace Foxnouns.Backend.Services.Auth;
public partial class FediverseAuthService
{
private const string NodeInfoRel = "http://nodeinfo.diaspora.software/ns/schema/2.0";
private readonly ILogger _logger;
private readonly HttpClient _client;
private readonly DatabaseContext _db;
private readonly Config _config;
private readonly ISnowflakeGenerator _snowflakeGenerator;
private readonly IClock _clock;
public FediverseAuthService(
ILogger logger,
Config config,
DatabaseContext db,
ISnowflakeGenerator snowflakeGenerator,
IClock clock
)
{
_config = config;
_db = db;
_snowflakeGenerator = snowflakeGenerator;
_clock = clock;
_logger = logger.ForContext<FediverseAuthService>();
_client = new HttpClient();
_client.DefaultRequestHeaders.Remove("User-Agent");
_client.DefaultRequestHeaders.Remove("Accept");
_client.DefaultRequestHeaders.Add("User-Agent", $"pronouns.cc/{BuildInfo.Version}");
_client.DefaultRequestHeaders.Add("Accept", "application/json");
}
public async Task<string> GenerateAuthUrlAsync(string instance)
{
var app = await GetApplicationAsync(instance);
return await GenerateAuthUrlAsync(app);
}
// thank you, gargron and syuilo, for agreeing on a name for *once* in your lives,
// and having both mastodon and misskey use "username" in the self user response
public record FediverseUser(
[property: J("id")] string Id,
[property: J("username")] string Username
);
public async Task<FediverseApplication> GetApplicationAsync(string instance)
{
var app = await _db.FediverseApplications.FirstOrDefaultAsync(a => a.Domain == instance);
if (app != null)
return app;
_logger.Debug("No application for fediverse instance {Instance}, creating it", instance);
var softwareName = await GetSoftwareNameAsync(instance);
if (IsMastodonCompatible(softwareName))
{
return await CreateMastodonApplicationAsync(instance);
}
throw new NotImplementedException();
}
private async Task<string> GetSoftwareNameAsync(string instance)
{
_logger.Debug("Requesting software name for fediverse instance {Instance}", instance);
var wellKnownResp = await _client.GetAsync(
new Uri($"https://{instance}/.well-known/nodeinfo")
);
wellKnownResp.EnsureSuccessStatusCode();
var wellKnown = await wellKnownResp.Content.ReadFromJsonAsync<WellKnownResponse>();
var nodeInfoUrl = wellKnown?.Links.FirstOrDefault(l => l.Rel == NodeInfoRel)?.Href;
if (nodeInfoUrl == null)
{
throw new FoxnounsError(
$".well-known/nodeinfo response for instance {instance} was invalid, no nodeinfo link"
);
}
var nodeInfoResp = await _client.GetAsync(nodeInfoUrl);
nodeInfoResp.EnsureSuccessStatusCode();
var nodeInfo = await nodeInfoResp.Content.ReadFromJsonAsync<PartialNodeInfo>();
return nodeInfo?.Software.Name
?? throw new FoxnounsError(
$"Nodeinfo response for instance {instance} was invalid, no software name"
);
}
private async Task<string> GenerateAuthUrlAsync(FediverseApplication app) =>
app.InstanceType switch
{
FediverseInstanceType.MastodonApi => await GenerateMastodonAuthUrlAsync(app),
FediverseInstanceType.MisskeyApi => throw new NotImplementedException(),
_ => throw new ArgumentOutOfRangeException(nameof(app), app.InstanceType, null),
};
public async Task<FediverseUser> GetRemoteFediverseUserAsync(
FediverseApplication app,
string code
) =>
app.InstanceType switch
{
FediverseInstanceType.MastodonApi => await GetMastodonUserAsync(app, code),
FediverseInstanceType.MisskeyApi => throw new NotImplementedException(),
_ => throw new ArgumentOutOfRangeException(nameof(app), app.InstanceType, null),
};
private static readonly string[] MastodonSoftwareNames =
[
"mastodon",
"hometown",
"akkoma",
"pleroma",
"iceshrimp.net",
"iceshrimp",
"gotosocial",
"pixelfed",
];
private static readonly string[] MisskeySoftwareNames =
[
"misskey",
"foundkey",
"calckey",
"firefish",
"sharkey",
];
private static bool IsMastodonCompatible(string softwareName) =>
MastodonSoftwareNames.Any(n =>
string.Equals(softwareName, n, StringComparison.InvariantCultureIgnoreCase)
);
private static bool IsMisskeyCompatible(string softwareName) =>
MisskeySoftwareNames.Any(n =>
string.Equals(softwareName, n, StringComparison.InvariantCultureIgnoreCase)
);
private record WellKnownResponse([property: J("links")] WellKnownLink[] Links);
private record WellKnownLink(
[property: J("rel")] string Rel,
[property: J("href")] string Href
);
private record PartialNodeInfo([property: J("software")] NodeInfoSoftware Software);
private record NodeInfoSoftware([property: J("name")] string Name);
}