|
1 | 1 | using Microsoft.AspNetCore.Mvc; |
2 | 2 | using Microsoft.EntityFrameworkCore; |
| 3 | +using Npgsql; |
3 | 4 | using OpenShock.Common.Models; |
4 | 5 | using OpenShock.Common.OpenShockDb; |
5 | 6 | using OpenShock.Common.Services.Audit; |
6 | | -using OpenShock.Common.Services.AutomationTokens; |
7 | 7 |
|
8 | 8 | namespace OpenShock.API.Controller.Admin; |
9 | 9 |
|
10 | 10 | public sealed partial class AdminController |
11 | 11 | { |
12 | 12 | /// <summary> |
13 | 13 | /// Deletes an automation token together with every account it created. Refused while any of those |
14 | | - /// accounts holds a privileged role. Other API instances may keep honoring the token for up to 30 seconds |
| 14 | + /// accounts holds a privileged role |
15 | 15 | /// </summary> |
16 | 16 | [HttpDelete("automationTokens/{id}")] |
17 | 17 | [ProducesResponseType(StatusCodes.Status200OK)] |
18 | 18 | [ProducesResponseType(StatusCodes.Status404NotFound)] |
19 | 19 | [ProducesResponseType(StatusCodes.Status409Conflict)] |
20 | 20 | public async Task<IActionResult> DeleteAutomationToken( |
21 | 21 | [FromRoute] Guid id, |
22 | | - [FromServices] IAutomationTokenService automationTokens, |
23 | 22 | [FromServices] IAuditService auditService, |
24 | 23 | CancellationToken ct) |
25 | 24 | { |
26 | 25 | PedanticallyEnsureAdmin(); |
27 | 26 |
|
28 | | - var token = await _db.AutomationTokens.FirstOrDefaultAsync(t => t.Id == id, ct); |
| 27 | + var token = await _db.AutomationTokens.AsNoTracking().FirstOrDefaultAsync(t => t.Id == id, ct); |
29 | 28 | if (token is null) return NotFound(); |
30 | 29 |
|
31 | 30 | await using var transaction = await _db.Database.BeginTransactionAsync(ct); |
32 | 31 |
|
33 | 32 | var createdUsers = await _db.Users |
34 | 33 | .Where(u => u.CreatedByAutomationTokenId == id) |
35 | | - .Select(u => new |
36 | | - { |
37 | | - u.Id, |
38 | | - IsPrivileged = u.Roles.Any(r => r == RoleType.Staff || r == RoleType.Admin || r == RoleType.System) |
39 | | - }) |
| 34 | + .Select(u => new { u.Id, u.Roles }) |
40 | 35 | .ToListAsync(ct); |
41 | 36 |
|
42 | | - // The accounts go through the database's cascade, which can't skip privileged ones, so refuse instead. |
43 | | - // The same roles AccountService.DeleteAccountAsync treats as privileged. |
44 | | - if (createdUsers.Any(u => u.IsPrivileged)) |
45 | | - return Problem("This automation token created a privileged account; remove its privileged roles before deleting the token.", statusCode: StatusCodes.Status409Conflict); |
| 37 | + if (createdUsers.Any(u => PrivilegedRoles.Any(u.Roles))) return PrivilegedAccountConflict(); |
46 | 38 |
|
47 | | - _db.AutomationTokens.Remove(token); |
48 | | - await _db.SaveChangesAsync(ct); |
| 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 | + } |
49 | 55 |
|
50 | 56 | await auditService.LogAsync( |
51 | 57 | CurrentUser.Id, |
52 | 58 | action: AuditAction.AutomationTokenDeleted, |
53 | 59 | actorId: CurrentUser.Id, |
54 | | - metadata: new AutomationTokenDeletedMetadata(token.Id, token.Name, createdUsers.Count), |
| 60 | + metadata: new AutomationTokenDeletedMetadata(token.Id, token.Name, userIds.Length), |
55 | 61 | cancellationToken: ct); |
56 | 62 |
|
57 | 63 | await transaction.CommitAsync(ct); |
58 | 64 |
|
59 | | - automationTokens.InvalidateCache(); |
60 | | - |
61 | 65 | // Each deleted account's own audit log goes with it, so the log line is the lasting record of what went. |
62 | | - foreach (var user in createdUsers) |
| 66 | + foreach (var userId in userIds) |
63 | 67 | { |
64 | 68 | _logger.LogInformation( |
65 | 69 | "Deleted account {UserId} together with automation token {AutomationTokenId}", |
66 | | - user.Id, token.Id); |
| 70 | + userId, token.Id); |
67 | 71 | } |
68 | 72 |
|
69 | 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); |
70 | 78 | } |
71 | 79 | } |
0 commit comments