Build / Build (push) Successful in 30s
- Services, controllers and jobs take their dependencies through primary constructors and use them directly; where a method already named a local after a dependency, the dependency takes its type's name. - Every async method takes a CancellationToken last and passes it down to MongoDB, HTTP and the job queue. The setup claim is still given back when a request is cancelled. - The federation and media options are read through IOptionsMonitor. - The Mastodon entities keep sending "" for empty strings, and every model field where null means something says so. - The inbox's 503 with Retry-After, which other servers retry, is the one server error left, and says why. - Arasaka.HouseRules.Analyzers checks all of this in every build, here and in PrivaPub.ClientModels as decePubClient builds it. Checked against GoToSocial in the pasture: 64 passed, 0 failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
90 lines
4.2 KiB
C#
90 lines
4.2 KiB
C#
using Microsoft.AspNetCore;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
using OpenIddict.Abstractions;
|
|
using OpenIddict.Server.AspNetCore;
|
|
|
|
using PrivaPub.StaticServices;
|
|
|
|
using System.Security.Claims;
|
|
|
|
using static OpenIddict.Abstractions.OpenIddictConstants;
|
|
|
|
namespace PrivaPub.Api.Mastodon.Auth
|
|
{
|
|
[ApiController]
|
|
public class TokenController(
|
|
DbEntities dbEntities) : ControllerBase
|
|
{
|
|
[HttpPost("/oauth/token"), IgnoreAntiforgeryToken, Produces("application/json")]
|
|
public async Task<IActionResult> Exchange(CancellationToken token)
|
|
{
|
|
var request = HttpContext.GetOpenIddictServerRequest();
|
|
if (request == default)
|
|
return BadRequest();
|
|
|
|
if (request.IsAuthorizationCodeGrantType())
|
|
{
|
|
var principal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;
|
|
if (principal == default || !await Usable(principal.GetClaim(Claims.Subject), token))
|
|
return Refuse(Errors.InvalidGrant, "The persona can no longer be used.");
|
|
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
|
|
}
|
|
|
|
if (request.IsClientCredentialsGrantType())
|
|
{
|
|
var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType, Claims.Name, Claims.Role);
|
|
identity.SetClaim(Claims.Subject, "app:" + request.ClientId);
|
|
identity.SetScopes(MastodonScopes.Parse(request.Scope));
|
|
identity.SetDestinations(_ => new[] { Destinations.AccessToken });
|
|
return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
|
|
}
|
|
|
|
if (request.IsTokenExchangeGrantType())
|
|
return await Persona(request, token);
|
|
|
|
return Refuse(Errors.UnsupportedGrantType, "The grant type is not supported.");
|
|
}
|
|
|
|
//PersonaExchange: the root JWT, validated by RootJwtSubjectToken, for a token of one of the root's personas
|
|
async Task<IActionResult> Persona(OpenIddictRequest request, CancellationToken token)
|
|
{
|
|
var subject = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;
|
|
var rootId = subject?.GetClaim(PersonaExchange.RootClaim);
|
|
var avatarId = (string)request[PersonaExchange.AvatarParameter];
|
|
if (string.IsNullOrEmpty(rootId) || string.IsNullOrEmpty(avatarId))
|
|
return Refuse(Errors.InvalidGrant, "The persona can no longer be used.");
|
|
var owns = await dbEntities.RootToAvatars.Match(r => r.RootId == rootId && r.AvatarId == avatarId).ExecuteAnyAsync(token);
|
|
var avatar = owns ? await dbEntities.Avatars.MatchID(avatarId).ExecuteFirstAsync(token) : default;
|
|
if (avatar == default || !await Usable(avatarId, token))
|
|
return Refuse(Errors.InvalidGrant, "The persona can no longer be used.");
|
|
|
|
var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType, Claims.Name, Claims.Role);
|
|
identity.SetClaim(Claims.Subject, avatar.ID);
|
|
identity.SetClaim(Claims.Name, avatar.UserName);
|
|
identity.SetScopes(MastodonScopes.Parse(request.Scope).Intersect(PersonaExchange.FirstPartyScopes));
|
|
identity.SetDestinations(_ => new[] { Destinations.AccessToken });
|
|
return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
|
|
}
|
|
|
|
async Task<bool> Usable(string avatarId, CancellationToken token)
|
|
{
|
|
if (string.IsNullOrEmpty(avatarId))
|
|
return false;
|
|
var link = await dbEntities.RootToAvatars.Match(r => r.AvatarId == avatarId).ExecuteFirstAsync(token);
|
|
var root = link == default ? default : await dbEntities.RootUsers.MatchID(link.RootId).ExecuteFirstAsync(token);
|
|
var avatar = await dbEntities.Avatars.MatchID(avatarId).ExecuteFirstAsync(token);
|
|
// a suspended persona gets no token (R6), as its tokens were revoked when it was suspended
|
|
return root is { IsBanned: false, DeletedAt: null } && avatar is { DeletionAt: null, SuspendedAt: null };
|
|
}
|
|
|
|
ForbidResult Refuse(string error, string description) => Forbid(new AuthenticationProperties(new Dictionary<string, string>
|
|
{
|
|
[OpenIddictServerAspNetCoreConstants.Properties.Error] = error,
|
|
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = description
|
|
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
|
|
}
|
|
}
|