|
| 1 | +using Microsoft.AspNetCore.Mvc; |
| 2 | +using Microsoft.EntityFrameworkCore; |
| 3 | +using Npgsql; |
| 4 | +using OpenShock.Common.Models; |
| 5 | +using OpenShock.Common.OpenShockDb; |
| 6 | +using OpenShock.Common.Services.Audit; |
| 7 | + |
| 8 | +namespace OpenShock.API.Controller.Admin; |
| 9 | + |
| 10 | +public sealed partial class AdminController |
| 11 | +{ |
| 12 | + /// <summary> |
| 13 | + /// Deletes an automation token together with every account it created. Refused while any of those |
| 14 | + /// accounts holds a privileged role |
| 15 | + /// </summary> |
| 16 | + [HttpDelete("automationTokens/{id}")] |
| 17 | + [ProducesResponseType(StatusCodes.Status200OK)] |
| 18 | + [ProducesResponseType(StatusCodes.Status404NotFound)] |
| 19 | + [ProducesResponseType(StatusCodes.Status409Conflict)] |
| 20 | + public async Task<IActionResult> DeleteAutomationToken( |
| 21 | + [FromRoute] Guid id, |
| 22 | + [FromServices] IAuditService auditService, |
| 23 | + CancellationToken ct) |
| 24 | + { |
| 25 | + PedanticallyEnsureAdmin(); |
| 26 | + |
| 27 | + var token = await _db.AutomationTokens.AsNoTracking().FirstOrDefaultAsync(t => t.Id == id, ct); |
| 28 | + if (token is null) return NotFound(); |
| 29 | + |
| 30 | + await using var transaction = await _db.Database.BeginTransactionAsync(ct); |
| 31 | + |
| 32 | + var createdUsers = await _db.Users |
| 33 | + .Where(u => u.CreatedByAutomationTokenId == id) |
| 34 | + .Select(u => new { u.Id, u.Roles }) |
| 35 | + .ToListAsync(ct); |
| 36 | + |
| 37 | + if (createdUsers.Any(u => PrivilegedRoles.Any(u.Roles))) return PrivilegedAccountConflict(); |
| 38 | + |
| 39 | + var userIds = createdUsers.Select(u => u.Id).ToArray(); |
| 40 | + |
| 41 | + // The roles are checked again as the rows are deleted, so an account promoted since it was read is kept. |
| 42 | + await _db.Database.ExecuteSqlAsync( |
| 43 | + $"DELETE FROM users WHERE id = ANY({userIds}) AND NOT (roles && {PrivilegedRoles.All})", ct); |
| 44 | + |
| 45 | + // The foreign key restricts, so this fails while any account still references the token: a privileged |
| 46 | + // one, or one created or promoted meanwhile. On success, exactly userIds went with it. |
| 47 | + try |
| 48 | + { |
| 49 | + await _db.AutomationTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct); |
| 50 | + } |
| 51 | + catch (PostgresException e) when (e.SqlState == PostgresErrorCodes.ForeignKeyViolation) |
| 52 | + { |
| 53 | + return PrivilegedAccountConflict(); |
| 54 | + } |
| 55 | + |
| 56 | + await auditService.LogAsync( |
| 57 | + CurrentUser.Id, |
| 58 | + action: AuditAction.AutomationTokenDeleted, |
| 59 | + actorId: CurrentUser.Id, |
| 60 | + metadata: new AutomationTokenDeletedMetadata(token.Id, token.Name, userIds.Length), |
| 61 | + cancellationToken: ct); |
| 62 | + |
| 63 | + await transaction.CommitAsync(ct); |
| 64 | + |
| 65 | + // Each deleted account's own audit log goes with it, so the log line is the lasting record of what went. |
| 66 | + foreach (var userId in userIds) |
| 67 | + { |
| 68 | + _logger.LogInformation( |
| 69 | + "Deleted account {UserId} together with automation token {AutomationTokenId}", |
| 70 | + userId, token.Id); |
| 71 | + } |
| 72 | + |
| 73 | + return Ok(); |
| 74 | + |
| 75 | + IActionResult PrivilegedAccountConflict() => Problem( |
| 76 | + "This automation token created a privileged account; remove its privileged roles before deleting the token.", |
| 77 | + statusCode: StatusCodes.Status409Conflict); |
| 78 | + } |
| 79 | +} |
0 commit comments