fix(audit): persist config audit rows written after the final save (DEP-1, MGT-1, TPL-3, WP1 task 1.4)

IAuditService.LogAsync only stages the row; every caller that audited
after its last SaveChangesAsync, outside the configuration-command
transaction, lost the row with the DI scope (rig: zero Disable/Enable/
Delete/DeployArtifacts rows, 16 Deploy rows for 62 deployments, one
Create/Instance row for ids up to 3876).

- New IAuditService.LogAndSaveAsync: stage + save, best-effort (logs and
  swallows any failure incl. cancellation, detaches the unsaved row).
- DeploymentService (deploy/failed/reconciled/lifecycle + timeouts),
  ArtifactDeploymentService (DeployArtifacts now before the best-effort
  stamp, RetryArtifactDeployment, DeploySiteSecrets), InstanceService,
  AreaService, SiteService: post-save LogAsync -> LogAndSaveAsync.
- ManagementActor: AuditAndSaveAsync for the non-configuration handlers
  (API keys, shared schemas, ES methods, data-connection move); move now
  audits the scrubbed public shape (MGT-4) so the fix does not start
  writing protocol credentials into AuditLogEntries.
- HandleCreateInstance no longer stages a second Create row on top of
  InstanceService's own.

Tests: real-context (SQLite) tests per family read the row back through
a second context - DeploymentService, ArtifactDeploymentService,
InstanceService, ManagementActor; each fails against the old code.
Test projects gain a ConfigurationDatabase + EF Sqlite reference.
This commit is contained in:
Joseph Doherty
2026-12-03 09:59:19 -05:00
parent 5469ece012
commit 5ca998dc56
26 changed files with 829 additions and 98 deletions
@@ -737,6 +737,22 @@ public class ManagementActor : ReceiveActor
await auditService.LogAsync(user, action, entityType, entityId, entityName, afterState);
}
/// <summary>
/// Logs AND persists an audit entry, best-effort, for a handler that is NOT a
/// configuration command (code review 2026-12-02 MGT-1).
/// </summary>
/// <remarks>
/// <see cref="AuditAsync"/> only stages the row; for a command in
/// <see cref="IsConfigurationCommand"/> the <c>ConfigurationCommandTransaction</c>'s final
/// save flushes it. A command outside that list runs through plain
/// <c>DispatchCommand</c> with no trailing save, so a staged row there was discarded with
/// the scope (API keys, shared schemas, external-system methods, data-connection move).
/// Such handlers call this AFTER their own save (or after a store call that saves
/// internally); it never throws.
/// </remarks>
private static Task AuditAndSaveAsync(IServiceProvider sp, string user, string action, string entityType, string entityId, string entityName, object? afterState) =>
sp.GetRequiredService<IAuditService>().LogAndSaveAsync(user, action, entityType, entityId, entityName, afterState);
// ========================================================================
// Template handlers
// ========================================================================
@@ -1027,7 +1043,9 @@ public class ManagementActor : ReceiveActor
var svc = sp.GetRequiredService<InstanceService>();
var result = await svc.CreateInstanceAsync(cmd.UniqueName, cmd.TemplateId, cmd.SiteId, cmd.AreaId, user.Username);
if (!result.IsSuccess) throw new ManagementCommandException(result.Error);
await AuditAsync(sp, user.Username, "Create", "Instance", result.Value.Id.ToString(), result.Value.UniqueName, result.Value);
// No AuditAsync here: InstanceService.CreateInstanceAsync audits the Create itself
// (see the AuditAsync contract). Both rows used to be staged and lost (code review
// 2026-12-02 TPL-3); now that the service saves its row, a second row would double-log.
return result.Value;
}
@@ -2378,7 +2396,10 @@ public class ManagementActor : ReceiveActor
conn.SiteId = cmd.TargetSiteId;
await repo.UpdateDataConnectionAsync(conn);
await repo.SaveChangesAsync();
await AuditAsync(sp, user, "Move", "DataConnection", conn.Id.ToString(), conn.Name, conn);
// AuditAndSaveAsync (MGT-1): Move is not a configuration command, so a staged row
// was never saved. The after-state is the scrubbed public shape (MGT-4) — the raw
// entity carries the decrypted protocol configuration, credentials included.
await AuditAndSaveAsync(sp, user, "Move", "DataConnection", conn.Id.ToString(), conn.Name, DataConnectionPublicShape(conn));
return conn;
}
@@ -2520,7 +2541,7 @@ public class ManagementActor : ReceiveActor
await repo.AddExternalSystemMethodAsync(method);
await repo.SaveChangesAsync();
await InvalidateExternalDefinitionCacheAfterCommit(sp);
await AuditAsync(sp, user, "Create", "ExternalSystemMethod", method.Id.ToString(), method.Name, method);
await AuditAndSaveAsync(sp, user, "Create", "ExternalSystemMethod", method.Id.ToString(), method.Name, method);
return method;
}
@@ -2537,7 +2558,7 @@ public class ManagementActor : ReceiveActor
await repo.UpdateExternalSystemMethodAsync(method);
await repo.SaveChangesAsync();
await InvalidateExternalDefinitionCacheAfterCommit(sp);
await AuditAsync(sp, user, "Update", "ExternalSystemMethod", method.Id.ToString(), method.Name, method);
await AuditAndSaveAsync(sp, user, "Update", "ExternalSystemMethod", method.Id.ToString(), method.Name, method);
return method;
}
@@ -2547,7 +2568,7 @@ public class ManagementActor : ReceiveActor
await repo.DeleteExternalSystemMethodAsync(cmd.MethodId);
await repo.SaveChangesAsync();
await InvalidateExternalDefinitionCacheAfterCommit(sp);
await AuditAsync(sp, user, "Delete", "ExternalSystemMethod", cmd.MethodId.ToString(), cmd.MethodId.ToString(), null);
await AuditAndSaveAsync(sp, user, "Delete", "ExternalSystemMethod", cmd.MethodId.ToString(), cmd.MethodId.ToString(), null);
return true;
}
@@ -3031,7 +3052,7 @@ public class ManagementActor : ReceiveActor
var admin = sp.GetRequiredService<IInboundApiKeyAdmin>();
var created = await admin.CreateAsync(cmd.Name, cmd.Methods);
await AuditAsync(sp, user, "Create", "ApiKey", created.KeyId, cmd.Name,
await AuditAndSaveAsync(sp, user, "Create", "ApiKey", created.KeyId, cmd.Name,
new { created.KeyId, cmd.Name });
return new
@@ -3048,7 +3069,7 @@ public class ManagementActor : ReceiveActor
var deleted = await admin.DeleteAsync(cmd.KeyId);
if (!deleted)
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
await AuditAsync(sp, user, "Delete", "ApiKey", cmd.KeyId, cmd.KeyId, null);
await AuditAndSaveAsync(sp, user, "Delete", "ApiKey", cmd.KeyId, cmd.KeyId, null);
return deleted;
}
@@ -3750,7 +3771,7 @@ public class ManagementActor : ReceiveActor
var schema = new SharedSchema { Name = name, Scope = cmd.Scope, SchemaJson = cmd.SchemaJson };
await repo.AddAsync(schema);
await AuditAsync(sp, user, "Create", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope });
await AuditAndSaveAsync(sp, user, "Create", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope });
return schema;
}
@@ -3775,7 +3796,7 @@ public class ManagementActor : ReceiveActor
schema.Scope = cmd.Scope;
schema.SchemaJson = cmd.SchemaJson;
await repo.UpdateAsync(schema);
await AuditAsync(sp, user, "Update", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope });
await AuditAndSaveAsync(sp, user, "Update", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope });
return schema;
}
@@ -3787,7 +3808,7 @@ public class ManagementActor : ReceiveActor
// Site delete handler. Falls back to the id when the row is already absent.
var schema = await repo.GetByIdAsync(cmd.SharedSchemaId);
await repo.DeleteAsync(cmd.SharedSchemaId);
await AuditAsync(sp, user, "Delete", "SharedSchema", cmd.SharedSchemaId.ToString(),
await AuditAndSaveAsync(sp, user, "Delete", "SharedSchema", cmd.SharedSchemaId.ToString(),
schema?.Name ?? cmd.SharedSchemaId.ToString(), null);
return true;
}
@@ -4100,7 +4121,7 @@ public class ManagementActor : ReceiveActor
var updated = await admin.SetEnabledAsync(cmd.KeyId, cmd.IsEnabled);
if (!updated)
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
await AuditAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId,
await AuditAndSaveAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId,
new { cmd.KeyId, cmd.IsEnabled });
return new { cmd.KeyId, cmd.IsEnabled };
}
@@ -4116,7 +4137,7 @@ public class ManagementActor : ReceiveActor
var updated = await admin.SetMethodsAsync(cmd.KeyId, cmd.Methods);
if (!updated)
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
await AuditAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId,
await AuditAndSaveAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId,
new { cmd.KeyId, cmd.Methods });
return new { cmd.KeyId, Methods = cmd.Methods };
}