House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
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
This commit is contained in:
thepraandClaude Opus 5.5 committed 2026-11-10 01:24:43 +01:00
1 parent f0a14c737f
commit 0f73f69239
176 files changed
+2789 -3974

No files matched your search

@@ -31,31 +31,16 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController,
Route("clientapi/admin"),
Authorize(Policy = Policies.IsAdmin)]
public class AdminController : ControllerBase
public class AdminController(
ILogger<RootUserController> logger,
IStringLocalizer<GenericRes> localizer,
IRootUsersService rootUsersService,
IModerationLog moderationLog,
DbEntities dbEntities,
ILocalActorService localActors) : ControllerBase
{
const int MaxRootsPage = 100;
readonly IRootUsersService RootUsersService;
readonly ILogger<RootUserController> Logger;
readonly IStringLocalizer Localizer;
readonly IModerationLog _log;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public AdminController(ILogger<RootUserController> logger,
IStringLocalizer<GenericRes> localizer,
IRootUsersService rootUsersService,
IModerationLog log,
DbEntities dbEntities,
ILocalActorService localActors)
{
Logger = logger;
Localizer = localizer;
RootUsersService = rootUsersService;
_log = log;
_dbEntities = dbEntities;
_localActors = localActors;
}
// an administrator never removes, bans or unbans itself; the request's own list is left as it came
UsersIds Others(UsersIds usersIds)
@@ -81,17 +66,17 @@ namespace PrivaPub.Controllers.ClientToServer
{
var others = Others(usersIds);
var named = await Named(others, token);
result = await RootUsersService.RemoveUserAsync(others);
result = await rootUsersService.RemoveUserAsync(others, token);
if (!result.IsValid)
return StatusCode(result.StatusCode, result);
foreach (var (id, name) in named)
await _log.Write(User.GetUserId(), AdminActions.RootDelete, AdminTargets.Root, id, name, token: CancellationToken.None);
await moderationLog.Write(User.GetUserId(), AdminActions.RootDelete, AdminTargets.Root, id, name, token: CancellationToken.None);
return Ok();
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveUsers)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveUsers)}()");
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
}
}
@@ -108,7 +93,7 @@ namespace PrivaPub.Controllers.ClientToServer
var others = Others(usersIds);
var named = await Named(others, token);
var banned = (await DB.Default.Find<RootUser>().Match(u => others.UserIdList.Contains(u.ID) && u.IsBanned).ExecuteAsync(token)).Select(u => u.ID).ToHashSet();
result = await RootUsersService.BanUserAsync(others);
result = await rootUsersService.BanUserAsync(others, token);
if (!result.IsValid)
return StatusCode(result.StatusCode, result);
@@ -116,16 +101,16 @@ namespace PrivaPub.Controllers.ClientToServer
foreach (var (id, name) in named.Where(n => !banned.Contains(n.Key)))
{
await sessions.Revoke(id, CancellationToken.None);
foreach (var link in await _dbEntities.RootToAvatars.Match(ra => ra.RootId == id).ExecuteAsync(token))
foreach (var link in await dbEntities.RootToAvatars.Match(ra => ra.RootId == id).ExecuteAsync(token))
Streams.CloseFor(link.AvatarId);
await _log.Write(User.GetUserId(), AdminActions.RootBan, AdminTargets.Root, id, name, token: CancellationToken.None);
await moderationLog.Write(User.GetUserId(), AdminActions.RootBan, AdminTargets.Root, id, name, token: CancellationToken.None);
}
return Ok();
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(User)}.{nameof(BanUsers)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
logger.LogError(ex, $"{nameof(User)}.{nameof(BanUsers)}()");
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
}
}
@@ -140,18 +125,18 @@ namespace PrivaPub.Controllers.ClientToServer
var others = Others(usersIds);
var named = await Named(others, token);
var banned = (await DB.Default.Find<RootUser>().Match(u => others.UserIdList.Contains(u.ID) && u.IsBanned).ExecuteAsync(token)).Select(u => u.ID).ToHashSet();
result = await RootUsersService.UnbanUserAsync(others);
result = await rootUsersService.UnbanUserAsync(others, token);
if (!result.IsValid)
return StatusCode(result.StatusCode, result);
await Restrictions.Reload(CancellationToken.None);
foreach (var (id, name) in named.Where(n => banned.Contains(n.Key)))
await _log.Write(User.GetUserId(), AdminActions.RootUnban, AdminTargets.Root, id, name, token: CancellationToken.None);
await moderationLog.Write(User.GetUserId(), AdminActions.RootUnban, AdminTargets.Root, id, name, token: CancellationToken.None);
return Ok();
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(User)}.{nameof(UnbanUsers)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."]));
logger.LogError(ex, $"{nameof(User)}.{nameof(UnbanUsers)}()");
return BadRequest(result.Invalidate(localizer["Something went wrong."]));
}
}
@@ -198,9 +183,9 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> Role(string id, RootRoleForm form, CancellationToken token)
{
if (!ModelState.IsValid || !RootUser.TryParseRole(form.Role, out var role))
return UnprocessableEntity(new WebResult().Invalidate(Localizer["Unknown role."], StatusCodes.Status422UnprocessableEntity));
return UnprocessableEntity(new WebResult().Invalidate(localizer["Unknown role."], StatusCodes.Status422UnprocessableEntity));
if (id == User.GetUserId())
return Conflict(new WebResult().Invalidate(Localizer["You can't change your own role."], StatusCodes.Status409Conflict));
return Conflict(new WebResult().Invalidate(localizer["You can't change your own role."], StatusCodes.Status409Conflict));
var root = await DB.Default.Find<RootUser>().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
if (root == default)
return NotFound();
@@ -208,7 +193,7 @@ namespace PrivaPub.Controllers.ClientToServer
if (was == role)
return Ok((await Views(new List<RootUser> { root }, token))[0]);
if (was == RootRole.Admin && !await OtherAdministrators(root.ID, token))
return Conflict(new WebResult().Invalidate(Localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
return Conflict(new WebResult().Invalidate(localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
root.SetRole(role);
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Policies, root.Policies).Modify(u => u.UpdatedAt, root.UpdatedAt)
.ExecuteAsync(CancellationToken.None);
@@ -217,11 +202,11 @@ namespace PrivaPub.Controllers.ClientToServer
{
root.SetRole(was);
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Policies, root.Policies).ExecuteAsync(CancellationToken.None);
return Conflict(new WebResult().Invalidate(Localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
return Conflict(new WebResult().Invalidate(localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
}
if (role == RootRole.Admin)
await ServerSetup.Seal(root.ID, default);//an administrator exists: the client's setup is closed
await _log.Write(User.GetUserId(), AdminActions.RootRole, AdminTargets.Root, root.ID, root.UserName,
await moderationLog.Write(User.GetUserId(), AdminActions.RootRole, AdminTargets.Root, root.ID, root.UserName,
note: $"{RoleName(was)} → {RoleName(role)}", token: CancellationToken.None);
return Ok((await Views(new List<RootUser> { root }, token))[0]);
}
@@ -236,12 +221,12 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> ResetTotp(string id, CancellationToken token)
{
if (id == User.GetUserId())
return Conflict(new WebResult().Invalidate(Localizer["Turn your own two-factor sign-in off from your account."], StatusCodes.Status409Conflict));
return Conflict(new WebResult().Invalidate(localizer["Turn your own two-factor sign-in off from your account."], StatusCodes.Status409Conflict));
var root = await DB.Default.Find<RootUser>().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
if (root == default)
return NotFound();
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Totp, null).ExecuteAsync(CancellationToken.None);
await _log.Write(User.GetUserId(), AdminActions.RootResetTotp, AdminTargets.Root, root.ID, root.UserName, token: CancellationToken.None);
await moderationLog.Write(User.GetUserId(), AdminActions.RootResetTotp, AdminTargets.Root, root.ID, root.UserName, token: CancellationToken.None);
return Ok();
}
@@ -251,16 +236,16 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> DeletePersona(string id, AdminPasswordForm form, [FromServices] IPersonaRemoval personas, CancellationToken token)
{
if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
if (!await RootUsersService.PasswordMatches(User.GetUserId(), form.Password))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(Localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
var avatar = await _dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
if (!await rootUsersService.PasswordMatches(User.GetUserId(), form.Password, token))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
var avatar = await dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (avatar == default)
return NotFound();
var label = "@" + _localActors.FromAvatar(avatar).Handle;
var label = "@" + localActors.FromAvatar(avatar).Handle;
if (!await personas.Remove(avatar.ID, CancellationToken.None))
return NotFound();
await _log.Write(User.GetUserId(), AdminActions.PersonaDelete, AdminTargets.Persona, avatar.ID, label, note: form.Note, token: CancellationToken.None);
await moderationLog.Write(User.GetUserId(), AdminActions.PersonaDelete, AdminTargets.Persona, avatar.ID, label, note: form.Note, token: CancellationToken.None);
return Ok();
}
@@ -268,30 +253,30 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> DeleteGroup(string id, AdminPasswordForm form, [FromServices] IGroupRemoval groups, CancellationToken token)
{
if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."]));
if (!await RootUsersService.PasswordMatches(User.GetUserId(), form.Password))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(Localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
var group = await _dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
if (!await rootUsersService.PasswordMatches(User.GetUserId(), form.Password, token))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
var group = await dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (group == default)
return NotFound();
var label = "@" + _localActors.FromGroup(group).Handle;
var label = "@" + localActors.FromGroup(group).Handle;
if (!await groups.Remove(group.ID, CancellationToken.None))
return NotFound();
await _log.Write(User.GetUserId(), AdminActions.GroupDelete, AdminTargets.Group, group.ID, label, note: form.Note, token: CancellationToken.None);
await moderationLog.Write(User.GetUserId(), AdminActions.GroupDelete, AdminTargets.Group, group.ID, label, note: form.Note, token: CancellationToken.None);
return Ok();
}
async Task<List<ViewAdminRoot>> Views(List<RootUser> roots, CancellationToken token)
{
var ids = roots.Select(r => r.ID).ToList();
var links = ids.Count == 0 ? new List<RootToAvatar>() : await _dbEntities.RootToAvatars.Match(ra => ids.Contains(ra.RootId)).ExecuteAsync(token);
var links = ids.Count == 0 ? new List<RootToAvatar>() : await dbEntities.RootToAvatars.Match(ra => ids.Contains(ra.RootId)).ExecuteAsync(token);
var avatarIds = links.Select(l => l.AvatarId).Distinct().ToList();
var avatars = avatarIds.Count == 0
? new Dictionary<string, Avatar>()
: (await _dbEntities.Avatars.Match(a => avatarIds.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token)).ToDictionary(a => a.ID);
: (await dbEntities.Avatars.Match(a => avatarIds.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token)).ToDictionary(a => a.ID);
var owned = avatarIds.Count == 0
? new List<GroupEntity>()
: await _dbEntities.Groups.Match(g => avatarIds.Contains(g.OwnerAvatarId) && !g.DeletionAt.HasValue).ExecuteAsync(token);
: await dbEntities.Groups.Match(g => avatarIds.Contains(g.OwnerAvatarId) && !g.DeletionAt.HasValue).ExecuteAsync(token);
var me = User.GetUserId();
return roots.Select(root => new ViewAdminRoot
{
@@ -308,7 +293,7 @@ namespace PrivaPub.Controllers.ClientToServer
.OrderBy(a => a.UserName, StringComparer.Ordinal)
.Select(a =>
{
var persona = _localActors.FromAvatar(a);
var persona = localActors.FromAvatar(a);
return new ViewAdminPersona
{
Id = a.ID,