diff --git a/src/Data/Models/AuditLog.cs b/src/Data/Models/AuditLog.cs index 7d9756a5..f5f01a86 100644 --- a/src/Data/Models/AuditLog.cs +++ b/src/Data/Models/AuditLog.cs @@ -171,7 +171,10 @@ public enum AuditActionType WithdrawalInterceptorConnected, WithdrawalInterceptorDisconnected, WithdrawalAllowedByIntegrator, - WithdrawalBlockedByIntegrator + WithdrawalBlockedByIntegrator, + + // RBF cancellation: a replacement request that sends the funds back to the wallet + RbfCancel } /// diff --git a/src/Pages/AuditTrail.razor b/src/Pages/AuditTrail.razor index 9346f943..c71f3177 100644 --- a/src/Pages/AuditTrail.razor +++ b/src/Pages/AuditTrail.razor @@ -386,6 +386,7 @@ AuditActionType.Approve => Color.Success, AuditActionType.Reject => Color.Warning, AuditActionType.Cancel => Color.Secondary, + AuditActionType.RbfCancel => Color.Secondary, AuditActionType.Login => Color.Primary, AuditActionType.Logout => Color.Secondary, AuditActionType.TwoFactorLogin => Color.Primary, diff --git a/src/Pages/Withdrawals.razor b/src/Pages/Withdrawals.razor index fbada670..b0b8fe3e 100644 --- a/src/Pages/Withdrawals.razor +++ b/src/Pages/Withdrawals.razor @@ -943,13 +943,16 @@ } } + /// The audit action of the bump modal's current operation: an RBF cancellation or a fee bump. + private AuditActionType BumpAuditAction => _bumpIsCancellation ? AuditActionType.RbfCancel : AuditActionType.BumpFee; + private async Task ShowBumpfeeModal(WalletWithdrawalRequest walletWithdrawalRequest, bool cancellation = false) { _bumpIsCancellation = cancellation; if (walletWithdrawalRequest == null) { ToastService.ShowError("Invalid request"); - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, null, "Invalid bump fee request."); + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, null, "Invalid RBF replacement request."); return; } @@ -957,7 +960,7 @@ if (request == null) { ToastService.ShowError("Request not found"); - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, walletWithdrawalRequest, "Withdrawal request not found for bumping."); + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, walletWithdrawalRequest, "Withdrawal request to replace not found."); return; } @@ -965,7 +968,7 @@ if (request.Status != WalletWithdrawalRequestStatus.OnChainConfirmationPending) { ToastService.ShowError("Bumpfee can only be used for transactions that are pending on-chain confirmation."); - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Bump requested for withdrawal not pending on-chain confirmation."); + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, "RBF replacement requested for withdrawal not pending on-chain confirmation."); return; } @@ -980,7 +983,7 @@ catch (Exception) { ToastService.ShowError("Error getting confirmations"); - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Failed to retrieve transaction confirmations for bumping."); + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, "Failed to retrieve transaction confirmations for the RBF replacement."); return; } } @@ -989,7 +992,7 @@ { ToastService.ShowError("Bumpfee can only be used for transactions with no confirmations. " + "This transaction has already been mined."); - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Bump requested for transaction that already has confirmations."); + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, "RBF replacement requested for transaction that already has confirmations."); return; } @@ -997,7 +1000,7 @@ if (!cancellation && request.Changeless && request.WalletWithdrawalRequestDestinations!.Count > 1) { ToastService.ShowError("Fee bumping is not supported for changeless transactions. Please create a new withdrawal with higher fees instead."); - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Bump requested for changeless transaction with multiple outputs."); + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, "Bump requested for changeless transaction with multiple outputs."); return; } @@ -1010,8 +1013,8 @@ catch (Exception ex) { ToastService.ShowError("Error while creating bumpfee modal"); - var message = string.IsNullOrWhiteSpace(ex.Message) ? "Error while creating bump fee modal." : ex.Message; - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, message); + var message = string.IsNullOrWhiteSpace(ex.Message) ? "Error while creating the RBF replacement modal." : ex.Message; + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, message); } } @@ -1106,14 +1109,14 @@ if (newRequest == null || _bumpfeeRef == null) { ToastService.ShowError("Something went wrong"); - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, newRequest, "Invalid bump fee request parameters."); + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, newRequest, "Invalid RBF replacement request parameters."); return; } // The replacement was validated, created and its UTXOs locked by WithdrawalRequestService (see BumpfeeModal). _selectedRequest = newRequest; await _bumpfeeRef.HideModal(); - await LogWithdrawalAuditAsync(newRequest.IsRbfCancellation ? AuditActionType.Cancel : AuditActionType.BumpFee, + await LogWithdrawalAuditAsync(newRequest.IsRbfCancellation ? AuditActionType.RbfCancel : AuditActionType.BumpFee, AuditEventType.Success, newRequest, newRequest.IsRbfCancellation ? "RBF cancellation request created." : "Bump withdrawal request created."); await GetData(); @@ -1134,7 +1137,7 @@ { Logger.LogError(e, "Error while bumping withdrawal request {RequestId}", newRequest?.Id); ToastService.ShowError("Something went wrong"); - await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, newRequest, "Unexpected error while bumping withdrawal."); + await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, newRequest, "Unexpected error while replacing withdrawal."); if (_bumpfeeRef != null) await _bumpfeeRef.HideModal(); } } diff --git a/src/Rpc/NodeGuardService.cs b/src/Rpc/NodeGuardService.cs index 000309d2..ca529726 100644 --- a/src/Rpc/NodeGuardService.cs +++ b/src/Rpc/NodeGuardService.cs @@ -292,6 +292,12 @@ public override async Task RequestWithdrawal(RequestW ServerCallContext context) { WalletWithdrawalRequest? withdrawalRequest = null; + var auditDetails = new + { + request.WalletId, + Destinations = request.Destinations.Select(d => new { d.Address, d.AmountSats }), + request.ReferenceId + }; try { //We get the wallet @@ -375,18 +381,26 @@ await _coinSelectionService.LockUTXOs(utxos, withdrawalRequest, BitcoinRequestType.WalletWithdrawal); } - // Update to refresh from db - withdrawalRequest = await _walletWithdrawalRequestRepository.GetById(withdrawalRequest.Id); + // Update to refresh from db. A missing row keeps the saved instance so the failure handling can still + // cancel and audit it + withdrawalRequest = await _walletWithdrawalRequestRepository.GetById(withdrawalRequest.Id) + ?? throw new InvalidOperationException( + $"Withdrawal request {withdrawalRequest.Id} not found after saving it"); - if (!withdrawalSaved.Item1) + // Template PSBT generation with SIGHASH_ALL + var psbt = await _bitcoinService.GenerateTemplatePSBT(withdrawalRequest); + + // Built before the job is scheduled: once it is, nothing may fail and cancel a request the job will execute + var response = new RequestWithdrawalResponse { - _logger.LogError("Error saving withdrawal request for wallet with id {walletId}", request.WalletId); - throw new RpcException(new Status(StatusCode.Internal, "Error saving withdrawal request for wallet")); - } + IsHotWallet = wallet.IsHotWallet, + Txid = psbt.GetGlobalTransaction().GetHash().ToString(), + RequestId = withdrawalRequest.Id + }; - // Template PSBT generation with SIGHASH_ALL - var psbt = await _bitcoinService.GenerateTemplatePSBT(withdrawalRequest ?? - throw new ArgumentException(nameof(withdrawalRequest))); + // Audited before the hot wallet job is scheduled, so the creation precedes the job's own audits + await _auditService.LogAsync(AuditActionType.Create, AuditEventType.Success, + AuditObjectType.WalletWithdrawalRequest, withdrawalRequest.Id.ToString(), auditDetails); // If the wallet is hot, we send the withdrawal request to the embedded or remote signer if (wallet.IsHotWallet) @@ -397,40 +411,80 @@ await _coinSelectionService.LockUTXOs(utxos, withdrawalRequest, await _scheduler.ScheduleJob(job.Job, job.Trigger); } - var response = new RequestWithdrawalResponse - { - IsHotWallet = wallet.IsHotWallet, - Txid = psbt.GetGlobalTransaction().GetHash().ToString(), - RequestId = withdrawalRequest.Id - }; - return response; } catch (NoUTXOsAvailableException) { - MarkWithdrawalRequestCancelled(withdrawalRequest); + await CancelFailedWithdrawalRequestAsync(withdrawalRequest, AuditActionType.Create, auditDetails, + "No available UTXOs for wallet"); _logger.LogError("No available UTXOs for wallet with id {walletId}", request.WalletId); throw new RpcException(new Status(StatusCode.ResourceExhausted, "No available UTXOs for wallet")); } catch (NotEnoughBalanceInWalletException e) { + await CancelFailedWithdrawalRequestAsync(withdrawalRequest, AuditActionType.Create, auditDetails, e.Message); _logger.LogError(e.Message); throw new RpcException(new Status(StatusCode.ResourceExhausted, e.Message)); } catch (RpcException e) { - MarkWithdrawalRequestCancelled(withdrawalRequest); + await CancelFailedWithdrawalRequestAsync(withdrawalRequest, AuditActionType.Create, auditDetails, + e.Status.Detail); _logger.LogError(e.Message); throw new RpcException(new Status(e.Status.StatusCode, e.Status.Detail)); } catch (Exception e) { - MarkWithdrawalRequestCancelled(withdrawalRequest); + await CancelFailedWithdrawalRequestAsync(withdrawalRequest, AuditActionType.Create, auditDetails, + e.Message); _logger.LogError(e, "Error requesting withdrawal for wallet with id {walletId}", request.WalletId); throw new RpcException(new Status(StatusCode.Internal, "Error requesting withdrawal for wallet")); } } + private Task CancelFailedWithdrawalRequestAsync(WalletWithdrawalRequest? withdrawalRequest, + AuditActionType actionType, object details, string? error) + { + int? persistedRequestId = withdrawalRequest is { Id: > 0 } ? withdrawalRequest.Id : null; + + return FailRequestAndAuditAsync(persistedRequestId, () => MarkWithdrawalRequestCancelled(withdrawalRequest), + actionType, AuditObjectType.WalletWithdrawalRequest, details, error); + } + + /// + /// Audits a failed request and, if it was already persisted, takes it out of the active states with + /// (which also releases its locked UTXOs, held only by active requests), so the + /// request id has a record of why it never went out. Requests refused before being persisted are audited + /// without an id. + /// + /// Runs inside catch blocks, so it never throws: that would replace the error being reported. + private async Task FailRequestAndAuditAsync(int? persistedRequestId, Action markFailed, + AuditActionType actionType, AuditObjectType objectType, object details, string? error) + { + // Separate tries so the failure is audited even if marking the request fails + if (persistedRequestId != null) + { + try + { + markFailed(); + } + catch (Exception e) + { + _logger.LogError(e, "Error marking {ObjectType} {RequestId} as failed", objectType, persistedRequestId); + } + } + + try + { + await _auditService.LogAsync(actionType, AuditEventType.Failure, objectType, + persistedRequestId?.ToString(), new { Request = details, Error = error }); + } + catch (Exception e) + { + _logger.LogError(e, "Error auditing the failure of {ObjectType} {RequestId}", objectType, persistedRequestId); + } + } + private void MarkWithdrawalRequestCancelled(WalletWithdrawalRequest? withdrawalRequest) { if (withdrawalRequest != null) @@ -496,7 +550,10 @@ private readonly record struct ReplacementTarget(int? RequestId, string? TxId) MempoolRecommendedFeesType feeType, decimal? customFeeRate, bool cancellation) { var action = cancellation ? "cancellation" : "fee bump"; + var auditAction = cancellation ? AuditActionType.RbfCancel : AuditActionType.BumpFee; WalletWithdrawalRequest? replacement = null; + // Until the replacement exists, failures can only be tied to the requested target + object auditDetails = new { Target = target.ToString() }; try { var originalRequestId = await ResolveReplacementTargetAsync(target); @@ -505,11 +562,27 @@ private readonly record struct ReplacementTarget(int? RequestId, string? TxId) ? await _withdrawalRequestService.CreateCancelRequestAsync(originalRequestId, feeType, customFeeRate) : await _withdrawalRequestService.CreateBumpRequestAsync(originalRequestId, feeType, customFeeRate); + auditDetails = new { replacement.WalletId, ReplacedRequestId = originalRequestId, replacement.ReferenceId }; + var isHotWallet = replacement.Wallet?.IsHotWallet ?? false; + Task AuditSuccessAsync() + { + return _auditService.LogAsync(auditAction, AuditEventType.Success, + AuditObjectType.WalletWithdrawalRequest, replacement.Id.ToString(), auditDetails); + } - var psbt = isHotWallet - ? await _withdrawalRequestService.ScheduleHotWalletWithdrawalAsync(replacement.Id) - : await _bitcoinService.GenerateTemplatePSBT(replacement); + PSBT psbt; + if (isHotWallet) + { + // Audited once the PSBT exists but before the job is scheduled, so the replacement precedes the job's + // own audits + psbt = await _withdrawalRequestService.ScheduleHotWalletWithdrawalAsync(replacement.Id, AuditSuccessAsync); + } + else + { + psbt = await _bitcoinService.GenerateTemplatePSBT(replacement); + await AuditSuccessAsync(); + } return (replacement.Id, psbt.GetGlobalTransaction().GetHash().ToString(), isHotWallet); } @@ -517,29 +590,30 @@ private readonly record struct ReplacementTarget(int? RequestId, string? TxId) { _logger.LogWarning("RBF {Action} of withdrawal request {Target} refused ({Reason}): {Message}", action, target, e.Reason, e.Message); - MarkWithdrawalRequestCancelled(replacement); + await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, e.Message); throw new RpcException(new Status(ToStatusCode(e.Reason), e.Message)); } catch (NoUTXOsAvailableException) { - MarkWithdrawalRequestCancelled(replacement); + await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, + "No available UTXOs for wallet"); _logger.LogError("No available UTXOs for the RBF {Action} of withdrawal request {Target}", action, target); throw new RpcException(new Status(StatusCode.ResourceExhausted, "No available UTXOs for wallet")); } catch (ShowToUserException e) { - MarkWithdrawalRequestCancelled(replacement); + await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, e.Message); _logger.LogError(e, "Error in the RBF {Action} of withdrawal request {Target}", action, target); throw new RpcException(new Status(StatusCode.FailedPrecondition, e.Message)); } - catch (RpcException) + catch (RpcException e) { - MarkWithdrawalRequestCancelled(replacement); + await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, e.Status.Detail); throw; } catch (Exception e) { - MarkWithdrawalRequestCancelled(replacement); + await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, e.Message); _logger.LogError(e, "Error in the RBF {Action} of withdrawal request {Target}", action, target); throw new RpcException(new Status(StatusCode.Internal, $"Error in the RBF {action} of the withdrawal request")); } @@ -751,38 +825,69 @@ public override async Task GetNodes(GetNodesRequest request, S public override async Task OpenChannel(OpenChannelRequest request, ServerCallContext context) { - var sourceNode = await _nodeRepository.GetByPubkey(request.SourcePubKey); - if (sourceNode == null) + var auditDetails = new { - throw new RpcException(new Status(StatusCode.NotFound, "Source node not found")); - } + request.WalletId, + request.SatsAmount, + request.SourcePubKey, + request.DestinationPubKey + }; - var destNode = await _nodeRepository.GetByPubkey(request.DestinationPubKey); - if (destNode == null) + NodeGuard.Data.Models.Node? sourceNode; + NodeGuard.Data.Models.Node? destNode; + Wallet? wallet; + try { - throw new RpcException(new Status(StatusCode.NotFound, "Destination node not found")); - } + sourceNode = await _nodeRepository.GetByPubkey(request.SourcePubKey); + if (sourceNode == null) + { + throw new RpcException(new Status(StatusCode.NotFound, "Source node not found")); + } - var wallet = await _walletRepository.GetById(request.WalletId); - if (wallet == null) - { - throw new RpcException(new Status(StatusCode.NotFound, "Wallet not found")); - } + destNode = await _nodeRepository.GetByPubkey(request.DestinationPubKey); + if (destNode == null) + { + throw new RpcException(new Status(StatusCode.NotFound, "Destination node not found")); + } - RefuseSparkWallet(wallet); + wallet = await _walletRepository.GetById(request.WalletId); + if (wallet == null) + { + throw new RpcException(new Status(StatusCode.NotFound, "Wallet not found")); + } - if (request.MempoolFeeRate == FEES_TYPE.CustomFee && request.CustomFeeRate == 0) - { - throw new RpcException( - new Status(StatusCode.InvalidArgument, "Mempool fee rate configuration is not valid")); - } + RefuseSparkWallet(wallet); + + if (request.MempoolFeeRate == FEES_TYPE.CustomFee && request.CustomFeeRate == 0) + { + throw new RpcException( + new Status(StatusCode.InvalidArgument, "Mempool fee rate configuration is not valid")); + } - if (request.Changeless && request.UtxosOutpoints.Count == 0) + if (request.Changeless && request.UtxosOutpoints.Count == 0) + { + throw new RpcException(new Status(StatusCode.InvalidArgument, "Changeless channel open requires utxos")); + } + } + catch (Exception e) { - throw new RpcException(new Status(StatusCode.InvalidArgument, "Changeless channel open requires utxos")); + // Nothing is persisted yet, so the refusal is only audited + var error = e is RpcException rpcException ? rpcException.Status.Detail : e.Message; + await _auditService.LogAsync(AuditActionType.Create, AuditEventType.Failure, + AuditObjectType.ChannelOperationRequest, null, new { Request = auditDetails, Error = error }); + + if (e is RpcException) + { + throw; + } + + _logger?.LogError(e, "Error validating channel open request through gRPC"); + throw new RpcException(new Status(StatusCode.Internal, "Error validating the channel open request")); } int requestId; + ChannelOperationRequest? channelOperationRequest = null; + var jobScheduled = false; try { @@ -823,7 +928,7 @@ public override async Task OpenChannel(OpenChannelRequest r throw new RpcException(new Status(StatusCode.NotFound, "Custom fee rate is required")); } - var channelOperationRequest = new ChannelOperationRequest + channelOperationRequest = new ChannelOperationRequest { SatsAmount = request.SatsAmount, Description = $"Channel open from {sourceNode.PubKey} to {destNode.PubKey} (API)", @@ -860,8 +965,7 @@ await _coinSelectionService.LockUTXOs(utxos, channelOperationRequest, (await _lightningService.GenerateTemplatePSBT(channelOperationRequest)); if (templatePsbt == null) { - channelOperationRequest.Status = ChannelOperationRequestStatus.Failed; - _channelOperationRequestRepository.Update(channelOperationRequest); + // The catch below marks the request as failed if (noUtxosAvailable) { _logger?.LogError("No UTXOs available for opening the channel"); @@ -883,20 +987,38 @@ await _coinSelectionService.LockUTXOs(utxos, channelOperationRequest, var retryList = RetriableJob.ParseRetryListFromString(Constants.JOB_RETRY_INTERVAL_LIST_IN_MINUTES); var job = RetriableJob.Create(map, channelOperationRequest.Id.ToString(), retryList); + + // Audited before the job is scheduled, so the creation precedes the job's own audits + await _auditService.LogAsync(AuditActionType.Create, AuditEventType.Success, + AuditObjectType.ChannelOperationRequest, channelOperationRequest.Id.ToString(), auditDetails); + await scheduler.ScheduleJob(job.Job, job.Trigger); + jobScheduled = true; var jobUpdateResult = _channelOperationRequestRepository.Update(channelOperationRequest); + // The job is scheduled and will open the channel, so failing the call here would only make the client + // retry and open a second one if (!jobUpdateResult.Item1) { - _logger?.LogError("Error updating channel operation request, error: {error}", jobUpdateResult.Item2); - throw new RpcException(new Status(StatusCode.Internal, "Error updating channel operation request")); + _logger?.LogError("Error updating channel operation request {RequestId} after scheduling its job: {error}", + channelOperationRequest.Id, jobUpdateResult.Item2); } requestId = channelOperationRequest.Id; } + catch (Exception e) when (jobScheduled) + { + // The job is scheduled and will open the channel, so the request stays active and audited as created. + // Failing the call would only make the client retry and open a second one + _logger?.LogError(e, "Error opening channel through gRPC after scheduling the job of request {RequestId}", + channelOperationRequest!.Id); + requestId = channelOperationRequest.Id; + } catch (Exception e) { + await FailChannelOpenRequestAsync(channelOperationRequest, auditDetails, e.Message); + _logger?.LogError(e, "Error opening channel through gRPC"); throw new RpcException(new Status(StatusCode.Internal, e.Message)); } @@ -908,6 +1030,26 @@ await _coinSelectionService.LockUTXOs(utxos, channelOperationRequest, }; } + private Task FailChannelOpenRequestAsync(ChannelOperationRequest? channelOperationRequest, object details, + string error) + { + int? persistedRequestId = channelOperationRequest is { Id: > 0 } ? channelOperationRequest.Id : null; + + return FailRequestAndAuditAsync(persistedRequestId, () => MarkChannelOperationRequestFailed(channelOperationRequest!), + AuditActionType.Create, AuditObjectType.ChannelOperationRequest, details, error); + } + + private void MarkChannelOperationRequestFailed(ChannelOperationRequest channelOperationRequest) + { + channelOperationRequest.Status = ChannelOperationRequestStatus.Failed; + var (updated, error) = _channelOperationRequestRepository.Update(channelOperationRequest); + if (!updated) + { + _logger?.LogError("Error marking channel operation request {RequestId} as failed: {Error}", + channelOperationRequest.Id, error); + } + } + public override async Task CloseChannel(CloseChannelRequest request, ServerCallContext context) { diff --git a/src/Services/AuditService.cs b/src/Services/AuditService.cs index 3e535e38..3007eda8 100644 --- a/src/Services/AuditService.cs +++ b/src/Services/AuditService.cs @@ -19,6 +19,7 @@ using System.Security.Claims; using System.Text.Json; +using System.Text.Json.Nodes; using NodeGuard.Data.Models; using NodeGuard.Data.Repositories.Interfaces; using NodeGuard.Helpers; @@ -27,6 +28,8 @@ namespace NodeGuard.Services; public class AuditService : IAuditService { + private const string ApiTokenIdKey = "ApiTokenId"; + private readonly IAuditLogRepository _auditLogRepository; private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILogger _logger; @@ -48,8 +51,9 @@ public async Task LogAsync( string? objectId = null, object? details = null) { - var (userId, username, ipAddress) = ExtractContextInfo(); - await LogInternalAsync(actionType, eventType, objectAffected, objectId, userId, username, ipAddress, details); + var (userId, username, ipAddress, contextDetails) = ExtractContextInfo(); + await LogInternalAsync(actionType, eventType, objectAffected, objectId, userId, username, ipAddress, details, + contextDetails); } public async Task LogSystemAsync( @@ -70,11 +74,12 @@ private async Task LogInternalAsync( string? userId, string? username, string? ipAddress, - object? details) + object? details, + IReadOnlyDictionary? contextDetails = null) { try { - var detailsJson = details != null ? JsonSerializer.Serialize(details) : null; + var detailsJson = SerializeDetails(details, contextDetails); // Log to system logger _logger.LogInformation( @@ -113,11 +118,53 @@ private async Task LogInternalAsync( } } - private (string? UserId, string? Username, string? IpAddress) ExtractContextInfo() + /// + /// Serializes the details, adding the request context (the user's roles at the time of the action, or the API + /// token that authenticated a gRPC call) so it can be checked later even if roles or tokens change. Details that + /// are not a JSON object are wrapped under Details and keys supplied by the caller are never overwritten. + /// The context is recorded even when the caller passes no details, so every user audit keeps its roles. + /// + private static string? SerializeDetails(object? details, IReadOnlyDictionary? contextDetails) + { + if (contextDetails == null || contextDetails.Count == 0) + { + return details == null ? null : JsonSerializer.Serialize(details); + } + + var node = details != null ? JsonSerializer.SerializeToNode(details) : new JsonObject(); + var detailsObject = node as JsonObject ?? new JsonObject { ["Details"] = node }; + + foreach (var (key, value) in contextDetails) + { + if (!detailsObject.ContainsKey(key)) + { + detailsObject[key] = value?.DeepClone(); + } + } + + return detailsObject.ToJsonString(); + } + + /// + /// Token names have no length limit, so the name is cut to keep the username within 's + /// 256 characters; otherwise the insert fails and the audit is lost. + /// + private static string FormatApiTokenUsername(AuthenticatedApiToken apiToken) + { + const int usernameMaxLength = 256; + var prefix = $"API token {apiToken.Id} ("; + var maxNameLength = usernameMaxLength - prefix.Length - 1; + var name = apiToken.Name.Length > maxNameLength ? apiToken.Name[..maxNameLength] : apiToken.Name; + return $"{prefix}{name})"; + } + + private (string? UserId, string? Username, string? IpAddress, IReadOnlyDictionary ContextDetails) + ExtractContextInfo() { string? userId = null; string? username = null; string? ipAddress = null; + var contextDetails = new Dictionary(); try { @@ -133,6 +180,18 @@ private async Task LogInternalAsync( username = user.FindFirst(ClaimTypes.Name)?.Value ?? user.FindFirst(ClaimTypes.Email)?.Value ?? user.Identity.Name; + contextDetails["UserRoles"] = new JsonArray(user.FindAll(ClaimTypes.Role) + .Select(c => (JsonNode?)JsonValue.Create(c.Value)).ToArray()); + } + + // gRPC calls are authenticated by an API token instead of a user (see GRPCAuthInterceptor) + if (httpContext.Items.TryGetValue(AuthenticatedApiToken.HttpContextItemKey, out var item) + && item is AuthenticatedApiToken apiToken) + { + // The id keeps tokens sharing a name apart, and the spaces keep it from passing for a username + username ??= FormatApiTokenUsername(apiToken); + contextDetails[ApiTokenIdKey] = apiToken.Id; + contextDetails["ApiTokenName"] = apiToken.Name; } // Extract IP address (considering proxies) @@ -144,6 +203,6 @@ private async Task LogInternalAsync( _logger.LogWarning(ex, "Error extracting context info for audit log"); } - return (userId, username, ipAddress); + return (userId, username, ipAddress, contextDetails); } } diff --git a/src/Services/WithdrawalRequestService.cs b/src/Services/WithdrawalRequestService.cs index 686c9673..3ae44535 100644 --- a/src/Services/WithdrawalRequestService.cs +++ b/src/Services/WithdrawalRequestService.cs @@ -62,8 +62,11 @@ Task CreateCancelRequestAsync(int originalRequestId, Me /// which signs and broadcasts. On failure the replaced request is put back to OnChainConfirmationPending and the /// exception is rethrown; the caller decides what happens to the request itself. /// + /// The hot-wallet request to execute. + /// Runs once the template PSBT exists and the replaced request is marked, right + /// before the job is scheduled, so callers can audit the request ahead of the job's own audits. /// The template PSBT; its global transaction hash is the txid that will be broadcast. - Task ScheduleHotWalletWithdrawalAsync(int requestId); + Task ScheduleHotWalletWithdrawalAsync(int requestId, Func? beforeScheduling = null); /// /// Marks the request replaced by as Bumped (fee bump) or Cancelled (RBF cancellation). @@ -291,7 +294,7 @@ private async Task CreateReplacementAsync(int originalR return await _walletWithdrawalRequestRepository.GetById(replacement.Id) ?? replacement; } - public async Task ScheduleHotWalletWithdrawalAsync(int requestId) + public async Task ScheduleHotWalletWithdrawalAsync(int requestId, Func? beforeScheduling = null) { var request = await _walletWithdrawalRequestRepository.GetById(requestId) ?? throw new InvalidOperationException($"Withdrawal request {requestId} not found"); @@ -333,6 +336,11 @@ public async Task ScheduleHotWalletWithdrawalAsync(int requestId) await MarkOriginalAsReplacedAsync(request); } + if (beforeScheduling != null) + { + await beforeScheduling(); + } + var scheduler = await _schedulerFactory.GetScheduler(); var map = new JobDataMap(); map.Put("withdrawalRequestId", request.Id); diff --git a/src/Shared/TransferFundsModal.razor b/src/Shared/TransferFundsModal.razor index 315733eb..1740bb42 100644 --- a/src/Shared/TransferFundsModal.razor +++ b/src/Shared/TransferFundsModal.razor @@ -461,15 +461,15 @@ _amountToTransfer; await AuditService.LogAsync( AuditActionType.Transfer, AuditEventType.Success, - AuditObjectType.Wallet, - _sourceTransferWallet?.Id.ToString(), + AuditObjectType.WalletWithdrawalRequest, + withdrawalRequest.Id.ToString(), new { + SourceWalletId = _sourceTransferWallet?.Id, SourceWallet = _sourceWalletName, TargetWallet = _targetWalletName, Amount = _amountToTransfer, - AllFunds = _transferAllFunds, - WithdrawalRequestId = withdrawalRequest.Id + AllFunds = _transferAllFunds }); await _multisigTransferModal.ShowModal(); await CloseAndCleanTransferFundsModal(); @@ -515,39 +515,43 @@ _amountToTransfer; var amount = _selectedUTXOs.Count > 0 ? SelectedUTXOsValue() : _amountToTransfer; var withdrawalRequest = await CreateWithdrawalRequestForFunds(_sourceTransferWallet, _targetTransferWallet, amount, _transferAllFunds); - var transferSuccess = await TransferInnerWithdrawalProcess(withdrawalRequest); + bool transferSuccess; + try + { + transferSuccess = await TransferInnerWithdrawalProcess(withdrawalRequest); + } + catch (Exception e) + { + // The request is already saved: fail it so its UTXOs are released and audit why, then let the outer catch toast + withdrawalRequest.Status = WalletWithdrawalRequestStatus.Failed; + var (updated, updateError) = WalletWithdrawalRequestRepository.Update(withdrawalRequest); + if (!updated) + { + Logger.LogError("Error while updating the withdrawal request {RequestId} status to failed: {Error}", withdrawalRequest.Id, updateError); + } + + await AuditService.LogAsync( + AuditActionType.Transfer, + AuditEventType.Failure, + AuditObjectType.WalletWithdrawalRequest, + withdrawalRequest.Id.ToString(), + new { Request = HotWalletTransferAuditDetails(), Error = e.Message }); + throw; + } + // The Success entry is written in CreateJobForFunds, before the job is scheduled if (transferSuccess) { ToastService.ShowSuccess("Funds transferred successfully"); - await AuditService.LogAsync( - AuditActionType.Transfer, - AuditEventType.Success, - AuditObjectType.Wallet, - _sourceTransferWallet?.Id.ToString(), - new - { - SourceWallet = _sourceWalletName, - TargetWallet = _targetWalletName, - Amount = _amountToTransfer, - AllFunds = _transferAllFunds, - WithdrawalRequestId = withdrawalRequest.Id - }); } else { await AuditService.LogAsync( AuditActionType.Transfer, AuditEventType.Failure, - AuditObjectType.Wallet, - _sourceTransferWallet?.Id.ToString(), - new - { - SourceWallet = _sourceWalletName, - TargetWallet = _targetWalletName, - Amount = _amountToTransfer, - WithdrawalRequestId = withdrawalRequest.Id - }); + AuditObjectType.WalletWithdrawalRequest, + withdrawalRequest.Id.ToString(), + HotWalletTransferAuditDetails()); ToastService.ShowError("Error while transferring funds, please contact a superadmin for troubleshooting"); } @@ -628,6 +632,18 @@ _amountToTransfer; return result; } + private object HotWalletTransferAuditDetails() + { + return new + { + SourceWalletId = _sourceTransferWallet?.Id, + SourceWallet = _sourceWalletName, + TargetWallet = _targetWalletName, + Amount = _amountToTransfer, + AllFunds = _transferAllFunds + }; + } + private async Task CreateJobForFunds(WalletWithdrawalRequest withdrawalRequest) { var result = false; @@ -640,6 +656,14 @@ _amountToTransfer; map.Put("withdrawalRequestId", withdrawalRequest.Id); var job = SimpleJob.Create(map, withdrawalRequest.Id.ToString()); + + // Audit before scheduling so the transfer comes before the job's own audits + await AuditService.LogAsync( + AuditActionType.Transfer, + AuditEventType.Success, + AuditObjectType.WalletWithdrawalRequest, + withdrawalRequest.Id.ToString(), + HotWalletTransferAuditDetails()); await scheduler.ScheduleJob(job.Job, job.Trigger); // No write after scheduling: the job may already have moved the request to FinalizingPSBT or broadcast diff --git a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs index d963b27a..34b505ee 100644 --- a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs +++ b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs @@ -134,11 +134,13 @@ public async Task OpenChannel_SourceNodeNotFound_ReturnsNotFoundError() nodeRepositoryMock.Setup(repo => repo.GetByPubkey(sourcePubKey)).ReturnsAsync((Node?)null); nodeRepositoryMock.Setup(repo => repo.GetByPubkey(destPubKey)) .ReturnsAsync(new Node { Id = 2, PubKey = destPubKey }); + var auditService = new Mock(); var service = CreateNodeGuardService( schedulerFactory: schedulerFactoryMock, nodeRepository: nodeRepositoryMock.Object, - channelOperationRequestRepository: channelOperationRequestRepositoryMock.Object); + channelOperationRequestRepository: channelOperationRequestRepositoryMock.Object, + auditService: auditService.Object); var request = new OpenChannelRequest { @@ -155,6 +157,206 @@ public async Task OpenChannel_SourceNodeNotFound_ReturnsNotFoundError() // Assert (await act.Should().ThrowAsync()).Which.Status.StatusCode.Should().Be(StatusCode.NotFound); + auditService.Verify(x => x.LogAsync(AuditActionType.Create, AuditEventType.Failure, + AuditObjectType.ChannelOperationRequest, null, It.IsAny()), Times.Once, + "a refused request is audited even though it was never persisted"); + } + + [Fact] + public async Task OpenChannel_SchedulingFails_MarksTheRequestFailedAndAuditsTheFailure() + { + // Arrange + var nodeRepositoryMock = new Mock(); + var channelOperationRequestRepositoryMock = new Mock(); + var walletRepositoryMock = new Mock(); + var lightningServiceMock = new Mock(); + var auditService = new Mock(); + var calls = new List(); + + nodeRepositoryMock.Setup(repo => repo.GetByPubkey("sourcePubKey")) + .ReturnsAsync(new Node { Id = 1, PubKey = "sourcePubKey" }); + nodeRepositoryMock.Setup(repo => repo.GetByPubkey("destPubKey")) + .ReturnsAsync(new Node { Id = 2, PubKey = "destPubKey" }); + walletRepositoryMock.Setup(repo => repo.GetById(1)).ReturnsAsync(new Wallet { Id = 1 }); + channelOperationRequestRepositoryMock.Setup(repo => repo.AddAsync(It.IsAny())) + .Callback(r => r.Id = 5) + .ReturnsAsync((true, null)); + channelOperationRequestRepositoryMock.Setup(repo => repo.Update(It.IsAny())) + .Returns((true, null)); + lightningServiceMock.Setup(service => service.GenerateTemplatePSBT(It.IsAny())) + .ReturnsAsync((PSBT.Parse(PSBTHex, Network.RegTest), false)); + auditService.Setup(x => x.LogAsync(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((_, e, _, id, _) => + calls.Add($"audit {e} {id}")) + .Returns(Task.CompletedTask); + + var scheduler = new Mock(); + scheduler.Setup(x => x.ScheduleJob(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback(() => calls.Add("schedule")) + .ThrowsAsync(new SchedulerException("boom")); + var schedulerFactory = new Mock(); + schedulerFactory.Setup(x => x.GetScheduler(It.IsAny())).ReturnsAsync(scheduler.Object); + + var service = CreateNodeGuardService( + walletRepository: walletRepositoryMock.Object, + schedulerFactory: schedulerFactory.Object, + nodeRepository: nodeRepositoryMock.Object, + channelOperationRequestRepository: channelOperationRequestRepositoryMock.Object, + lightningService: lightningServiceMock.Object, + auditService: auditService.Object); + + var request = new OpenChannelRequest + { + SourcePubKey = "sourcePubKey", + DestinationPubKey = "destPubKey", + SatsAmount = 10000, + WalletId = 1, + MempoolFeeRate = FEES_TYPE.HourFee + }; + + // Act + var act = () => service.OpenChannel(request, TestServerCallContext.Create()); + + // Assert + await act.Should().ThrowAsync(); + channelOperationRequestRepositoryMock.Verify(repo => repo.Update(It.Is(r => + r.Id == 5 && r.Status == ChannelOperationRequestStatus.Failed)), Times.Once, + "a request that could not be scheduled must not stay pending holding its UTXOs"); + calls.Should().Equal(new[] { "audit Success 5", "schedule", "audit Failure 5" }, + "the creation is audited before the job can run, and the failure after it"); + } + + [Fact] + public async Task OpenChannel_UpdateFailsAfterScheduling_KeepsTheRequestActiveAndReturnsIt() + { + // Arrange + var nodeRepositoryMock = new Mock(); + var channelOperationRequestRepositoryMock = new Mock(); + var walletRepositoryMock = new Mock(); + var lightningServiceMock = new Mock(); + var auditService = new Mock(); + + nodeRepositoryMock.Setup(repo => repo.GetByPubkey("sourcePubKey")) + .ReturnsAsync(new Node { Id = 1, PubKey = "sourcePubKey" }); + nodeRepositoryMock.Setup(repo => repo.GetByPubkey("destPubKey")) + .ReturnsAsync(new Node { Id = 2, PubKey = "destPubKey" }); + walletRepositoryMock.Setup(repo => repo.GetById(1)).ReturnsAsync(new Wallet { Id = 1 }); + channelOperationRequestRepositoryMock.Setup(repo => repo.AddAsync(It.IsAny())) + .Callback(r => r.Id = 5) + .ReturnsAsync((true, null)); + channelOperationRequestRepositoryMock.Setup(repo => repo.Update(It.IsAny())) + .Returns((false, "db down")); + lightningServiceMock.Setup(service => service.GenerateTemplatePSBT(It.IsAny())) + .ReturnsAsync((PSBT.Parse(PSBTHex, Network.RegTest), false)); + + var scheduler = new Mock(); + var schedulerFactory = new Mock(); + schedulerFactory.Setup(x => x.GetScheduler(It.IsAny())).ReturnsAsync(scheduler.Object); + + var service = CreateNodeGuardService( + walletRepository: walletRepositoryMock.Object, + schedulerFactory: schedulerFactory.Object, + nodeRepository: nodeRepositoryMock.Object, + channelOperationRequestRepository: channelOperationRequestRepositoryMock.Object, + lightningService: lightningServiceMock.Object, + auditService: auditService.Object); + + var request = new OpenChannelRequest + { + SourcePubKey = "sourcePubKey", + DestinationPubKey = "destPubKey", + SatsAmount = 10000, + WalletId = 1, + MempoolFeeRate = FEES_TYPE.HourFee + }; + + // Act + var response = await service.OpenChannel(request, TestServerCallContext.Create()); + + // Assert + response.ChannelOperationRequestId.Should().Be(5, + "an error would make the client retry and open a second channel"); + channelOperationRequestRepositoryMock.Verify(repo => repo.Update(It.Is(r => + r.Status == ChannelOperationRequestStatus.Failed)), Times.Never, + "the scheduled job will still open the channel, so its request must stay active"); + auditService.Verify(x => x.LogAsync(It.IsAny(), AuditEventType.Failure, + It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task OpenChannel_LookupThrows_AuditsTheFailureAndReturnsInternal() + { + // Arrange + var nodeRepositoryMock = new Mock(); + nodeRepositoryMock.Setup(repo => repo.GetByPubkey(It.IsAny())) + .ThrowsAsync(new InvalidOperationException("db down")); + var auditService = new Mock(); + + var service = CreateNodeGuardService(nodeRepository: nodeRepositoryMock.Object, + auditService: auditService.Object); + + // Act + var act = () => service.OpenChannel(new OpenChannelRequest + { + SourcePubKey = "sourcePubKey", + DestinationPubKey = "destPubKey", + SatsAmount = 10000, + WalletId = 1 + }, TestServerCallContext.Create()); + + // Assert + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.Internal); + auditService.Verify(x => x.LogAsync(AuditActionType.Create, AuditEventType.Failure, + AuditObjectType.ChannelOperationRequest, null, It.IsAny()), Times.Once); + } + + [Fact] + public async Task OpenChannel_UpdateThrowsAfterScheduling_ReturnsTheRequest() + { + // Arrange + var nodeRepositoryMock = new Mock(); + var channelOperationRequestRepositoryMock = new Mock(); + var walletRepositoryMock = new Mock(); + var lightningServiceMock = new Mock(); + + nodeRepositoryMock.Setup(repo => repo.GetByPubkey("sourcePubKey")) + .ReturnsAsync(new Node { Id = 1, PubKey = "sourcePubKey" }); + nodeRepositoryMock.Setup(repo => repo.GetByPubkey("destPubKey")) + .ReturnsAsync(new Node { Id = 2, PubKey = "destPubKey" }); + walletRepositoryMock.Setup(repo => repo.GetById(1)).ReturnsAsync(new Wallet { Id = 1 }); + channelOperationRequestRepositoryMock.Setup(repo => repo.AddAsync(It.IsAny())) + .Callback(r => r.Id = 5) + .ReturnsAsync((true, null)); + channelOperationRequestRepositoryMock.Setup(repo => repo.Update(It.IsAny())) + .Throws(new InvalidOperationException("db down")); + lightningServiceMock.Setup(service => service.GenerateTemplatePSBT(It.IsAny())) + .ReturnsAsync((PSBT.Parse(PSBTHex, Network.RegTest), false)); + + var scheduler = new Mock(); + var schedulerFactory = new Mock(); + schedulerFactory.Setup(x => x.GetScheduler(It.IsAny())).ReturnsAsync(scheduler.Object); + + var service = CreateNodeGuardService( + walletRepository: walletRepositoryMock.Object, + schedulerFactory: schedulerFactory.Object, + nodeRepository: nodeRepositoryMock.Object, + channelOperationRequestRepository: channelOperationRequestRepositoryMock.Object, + lightningService: lightningServiceMock.Object); + + // Act + var response = await service.OpenChannel(new OpenChannelRequest + { + SourcePubKey = "sourcePubKey", + DestinationPubKey = "destPubKey", + SatsAmount = 10000, + WalletId = 1, + MempoolFeeRate = FEES_TYPE.HourFee + }, TestServerCallContext.Create()); + + // Assert + response.ChannelOperationRequestId.Should().Be(5, + "an error would make the client retry and open a second channel"); } [Fact] @@ -242,7 +444,7 @@ public async Task OpenChannel_ValidRequest_OpensChannelAndReturnsResponse() WalletId = walletId, MempoolFeeRate = FEES_TYPE.HourFee }; - var context = new Mock().Object; + var context = TestServerCallContext.Create(); // Act Func act = async () => await service.OpenChannel(request, context); @@ -334,7 +536,7 @@ public async Task OpenChannel_ValidRequest_OpensChangelessChannelAndReturnsRespo }, MempoolFeeRate = FEES_TYPE.HourFee }; - var context = new Mock().Object; + var context = TestServerCallContext.Create(); // Act Func act = async () => await service.OpenChannel(request, context); @@ -768,6 +970,91 @@ public async Task RequestWithdrawal_WithoutACoinSelectionStrategy_StoresNull() Times.Once); } + [Fact] + public async Task RequestWithdrawal_Success_AuditsTheCreatedRequest() + { + //Arrange + var wallet = InitMockRequestWithdrawal(out var walletRepository, + out var nbxplorerService, + out _, + out _, + out _, + out _, + out _, + out var bitcoinService, + out var walletWithdrawalRequestRepository, out var mockScheduler); + + wallet.IsHotWallet = false; + var auditService = new Mock(); + + var mockNodeGuardService = CreateNodeGuardService( + walletRepository: walletRepository.Object, + walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, + bitcoinService: bitcoinService.Object, + nbXplorerService: nbxplorerService.Object, + schedulerFactory: mockScheduler, + auditService: auditService.Object); + + var requestWithdrawalRequest = new RequestWithdrawalRequest + { + WalletId = wallet.Id, + Description = "Request Withdrawal Audit Test", + Destinations = { new Destination + { + Address = "bcrt1q590shaxaf5u08ml8jwlzghz99dup3z9592vxal", + AmountSats = new Money(1, MoneyUnit.BTC).Satoshi + } + } + }; + //Act + var resp = await mockNodeGuardService.RequestWithdrawal(requestWithdrawalRequest, TestServerCallContext.Create()); + + //Assert + auditService.Verify(x => x.LogAsync(AuditActionType.Create, AuditEventType.Success, + AuditObjectType.WalletWithdrawalRequest, resp.RequestId.ToString(), It.IsAny()), Times.Once); + } + + [Fact] + public async Task RequestWithdrawal_RefreshReturnsNull_CancelsAndAuditsTheSavedRequest() + { + //Arrange + var wallet = InitMockRequestWithdrawal(out var walletRepository, + out var nbxplorerService, + out _, + out _, + out _, + out _, + out _, + out var bitcoinService, + out var walletWithdrawalRequestRepository, out var mockScheduler); + walletWithdrawalRequestRepository.Setup(x => x.AddAsync(It.IsAny())) + .Callback(r => r.Id = 9) + .ReturnsAsync((true, null)); + walletWithdrawalRequestRepository.Setup(x => x.GetById(9)).ReturnsAsync((WalletWithdrawalRequest?)null); + walletWithdrawalRequestRepository.Setup(x => x.Update(It.IsAny())) + .Returns((true, (string?)null)); + var auditService = new Mock(); + + var mockNodeGuardService = CreateNodeGuardService( + walletRepository: walletRepository.Object, + walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, + bitcoinService: bitcoinService.Object, + nbXplorerService: nbxplorerService.Object, + schedulerFactory: mockScheduler, + auditService: auditService.Object); + + //Act + var act = () => mockNodeGuardService.RequestWithdrawal(CreateWithdrawalRequest(wallet.Id, 100), + TestServerCallContext.Create()); + + //Assert + await act.Should().ThrowAsync(); + walletWithdrawalRequestRepository.Verify(x => x.Update(It.Is(r => + r.Id == 9 && r.Status == WalletWithdrawalRequestStatus.Cancelled)), Times.Once); + auditService.Verify(x => x.LogAsync(AuditActionType.Create, AuditEventType.Failure, + AuditObjectType.WalletWithdrawalRequest, "9", It.IsAny()), Times.Once); + } + [Fact] public async Task RequestWithdrawal_NoWallet() { @@ -911,7 +1198,7 @@ public async Task BumpWithdrawal_HotWallet_SchedulesTheReplacementAndReturnsItsT var psbt = SamplePsbt(); var withdrawalRequestService = new Mock(); withdrawalRequestService.Setup(x => x.CreateBumpRequestAsync(10, MempoolRecommendedFeesType.CustomFee, 10m)).ReturnsAsync(bump); - withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11)).ReturnsAsync(psbt); + withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11, It.IsAny?>())).Returns(RunBeforeScheduling(psbt)); var bitcoinService = new Mock(); var mockNodeGuardService = CreateNodeGuardService( @@ -930,7 +1217,7 @@ public async Task BumpWithdrawal_HotWallet_SchedulesTheReplacementAndReturnsItsT resp.RequestId.Should().Be(11); resp.IsHotWallet.Should().BeTrue(); resp.Txid.Should().Be(psbt.GetGlobalTransaction().GetHash().ToString()); - withdrawalRequestService.Verify(x => x.ScheduleHotWalletWithdrawalAsync(11), Times.Once); + withdrawalRequestService.Verify(x => x.ScheduleHotWalletWithdrawalAsync(11, It.IsAny?>()), Times.Once); bitcoinService.Verify(x => x.GenerateTemplatePSBT(It.IsAny()), Times.Never, "the hot-wallet execution (template + job) is the service's job"); } @@ -961,7 +1248,7 @@ public async Task BumpWithdrawal_ColdWallet_GeneratesTheTemplateWithoutSchedulin resp.RequestId.Should().Be(11); resp.IsHotWallet.Should().BeFalse(); resp.Txid.Should().Be(psbt.GetGlobalTransaction().GetHash().ToString()); - withdrawalRequestService.Verify(x => x.ScheduleHotWalletWithdrawalAsync(It.IsAny()), Times.Never, + withdrawalRequestService.Verify(x => x.ScheduleHotWalletWithdrawalAsync(It.IsAny(), It.IsAny?>()), Times.Never, "a cold-wallet bump waits for the approvers' signatures"); } @@ -1006,13 +1293,15 @@ public async Task BumpWithdrawal_SchedulingFails_CancelsTheBumpRequest() var bump = new WalletWithdrawalRequest { Id = 11, Wallet = new Wallet { IsHotWallet = true }, BumpingWalletWithdrawalRequestId = 10 }; var withdrawalRequestService = new Mock(); withdrawalRequestService.Setup(x => x.CreateBumpRequestAsync(10, MempoolRecommendedFeesType.CustomFee, 10m)).ReturnsAsync(bump); - withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11)).ThrowsAsync(new Exception("boom")); + withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11, It.IsAny?>())).ThrowsAsync(new Exception("boom")); var walletWithdrawalRequestRepository = new Mock(); walletWithdrawalRequestRepository.Setup(x => x.Update(It.IsAny())).Returns((true, (string?)null)); + var auditService = new Mock(); var mockNodeGuardService = CreateNodeGuardService( walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, - withdrawalRequestService: withdrawalRequestService.Object); + withdrawalRequestService: withdrawalRequestService.Object, + auditService: auditService.Object); //Act var act = () => mockNodeGuardService.BumpWithdrawal(new BumpWithdrawalRequest @@ -1027,6 +1316,71 @@ public async Task BumpWithdrawal_SchedulingFails_CancelsTheBumpRequest() walletWithdrawalRequestRepository.Verify(x => x.Update(It.Is(r => r.Id == 11 && r.Status == WalletWithdrawalRequestStatus.Cancelled)), Times.Once, "a bump that could not be executed must not stay pending"); + auditService.Verify(x => x.LogAsync(AuditActionType.BumpFee, AuditEventType.Success, + AuditObjectType.WalletWithdrawalRequest, "11", It.IsAny()), Times.Never, + "a replacement is only audited as a success once its PSBT exists"); + auditService.Verify(x => x.LogAsync(AuditActionType.BumpFee, AuditEventType.Failure, + AuditObjectType.WalletWithdrawalRequest, "11", It.IsAny()), Times.Once); + } + + [Fact] + public async Task BumpWithdrawal_CancellingTheFailedBumpThrows_KeepsTheOriginalError() + { + //Arrange + var bump = new WalletWithdrawalRequest { Id = 11, Wallet = new Wallet { IsHotWallet = true }, BumpingWalletWithdrawalRequestId = 10 }; + var withdrawalRequestService = new Mock(); + withdrawalRequestService.Setup(x => x.CreateBumpRequestAsync(10, MempoolRecommendedFeesType.CustomFee, 10m)).ReturnsAsync(bump); + withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11, It.IsAny?>())).ThrowsAsync(new NoUTXOsAvailableException()); + var walletWithdrawalRequestRepository = new Mock(); + walletWithdrawalRequestRepository.Setup(x => x.Update(It.IsAny())) + .Throws(new InvalidOperationException("context disposed")); + + var mockNodeGuardService = CreateNodeGuardService( + walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, + withdrawalRequestService: withdrawalRequestService.Object); + + //Act + var act = () => mockNodeGuardService.BumpWithdrawal(new BumpWithdrawalRequest + { + RequestId = 10, + MempoolFeeRate = FEES_TYPE.CustomFee, + CustomFeeRate = 10, + }, TestServerCallContext.Create()); + + //Assert + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.ResourceExhausted); + } + + [Fact] + public async Task BumpWithdrawal_CancellingTheFailedBumpThrows_StillAuditsTheFailure() + { + //Arrange + var bump = new WalletWithdrawalRequest { Id = 11, Wallet = new Wallet { IsHotWallet = true }, BumpingWalletWithdrawalRequestId = 10 }; + var withdrawalRequestService = new Mock(); + withdrawalRequestService.Setup(x => x.CreateBumpRequestAsync(10, MempoolRecommendedFeesType.CustomFee, 10m)).ReturnsAsync(bump); + withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11, It.IsAny?>())).ThrowsAsync(new Exception("boom")); + var walletWithdrawalRequestRepository = new Mock(); + walletWithdrawalRequestRepository.Setup(x => x.Update(It.IsAny())) + .Throws(new InvalidOperationException("context disposed")); + var auditService = new Mock(); + + var mockNodeGuardService = CreateNodeGuardService( + walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, + withdrawalRequestService: withdrawalRequestService.Object, + auditService: auditService.Object); + + //Act + var act = () => mockNodeGuardService.BumpWithdrawal(new BumpWithdrawalRequest + { + RequestId = 10, + MempoolFeeRate = FEES_TYPE.CustomFee, + CustomFeeRate = 10, + }, TestServerCallContext.Create()); + + //Assert + await act.Should().ThrowAsync(); + auditService.Verify(x => x.LogAsync(AuditActionType.BumpFee, AuditEventType.Failure, + AuditObjectType.WalletWithdrawalRequest, "11", It.IsAny()), Times.Once); } [Fact] @@ -1040,7 +1394,7 @@ public async Task BumpWithdrawal_ByTxId_ResolvesTheRequestToBump() walletWithdrawalRequestRepository.Setup(x => x.GetByTxHash(txId)).ReturnsAsync(original); var withdrawalRequestService = new Mock(); withdrawalRequestService.Setup(x => x.CreateBumpRequestAsync(10, MempoolRecommendedFeesType.CustomFee, 10m)).ReturnsAsync(bump); - withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11)).ReturnsAsync(SamplePsbt()); + withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11, It.IsAny?>())).Returns(RunBeforeScheduling(SamplePsbt())); var mockNodeGuardService = CreateNodeGuardService( walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, @@ -1133,9 +1487,11 @@ public async Task CancelWithdrawal_HotWallet_SchedulesTheReplacementAndReturnsIt var psbt = SamplePsbt(); var withdrawalRequestService = new Mock(); withdrawalRequestService.Setup(x => x.CreateCancelRequestAsync(10, MempoolRecommendedFeesType.CustomFee, 10m)).ReturnsAsync(cancel); - withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11)).ReturnsAsync(psbt); + withdrawalRequestService.Setup(x => x.ScheduleHotWalletWithdrawalAsync(11, It.IsAny?>())).Returns(RunBeforeScheduling(psbt)); + var auditService = new Mock(); - var mockNodeGuardService = CreateNodeGuardService(withdrawalRequestService: withdrawalRequestService.Object); + var mockNodeGuardService = CreateNodeGuardService(withdrawalRequestService: withdrawalRequestService.Object, + auditService: auditService.Object); //Act var resp = await mockNodeGuardService.CancelWithdrawal(new CancelWithdrawalRequest @@ -1151,6 +1507,8 @@ public async Task CancelWithdrawal_HotWallet_SchedulesTheReplacementAndReturnsIt resp.Txid.Should().Be(psbt.GetGlobalTransaction().GetHash().ToString()); withdrawalRequestService.Verify(x => x.CreateBumpRequestAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never, "a cancellation must not be turned into a fee bump"); + auditService.Verify(x => x.LogAsync(AuditActionType.RbfCancel, AuditEventType.Success, + AuditObjectType.WalletWithdrawalRequest, "11", It.IsAny()), Times.Once); } [Fact] @@ -1181,7 +1539,7 @@ public async Task CancelWithdrawal_ByTxId_ResolvesTheRequestToCancel() //Assert resp.RequestId.Should().Be(11); resp.IsHotWallet.Should().BeFalse(); - withdrawalRequestService.Verify(x => x.ScheduleHotWalletWithdrawalAsync(It.IsAny()), Times.Never, + withdrawalRequestService.Verify(x => x.ScheduleHotWalletWithdrawalAsync(It.IsAny(), It.IsAny?>()), Times.Never, "a cold-wallet cancellation waits for the approvers' signatures"); } @@ -1210,6 +1568,20 @@ public async Task CancelWithdrawal_RefusedByTheService_MapsTheReasonToAStatusCod exception.Status.Detail.Should().Be("already mined"); } + /// Stands in for ScheduleHotWalletWithdrawalAsync succeeding: runs the caller's pre-scheduling hook. + private static Func?, Task> RunBeforeScheduling(PSBT psbt) + { + return async (_, beforeScheduling) => + { + if (beforeScheduling != null) + { + await beforeScheduling(); + } + + return psbt; + }; + } + /// A parseable one-in/one-out PSBT; PSBT.FromTransaction refuses a transaction without inputs. private static PSBT SamplePsbt() { diff --git a/test/NodeGuard.Tests/Services/AuditServiceTests.cs b/test/NodeGuard.Tests/Services/AuditServiceTests.cs index 7b9b4f46..55c1260e 100644 --- a/test/NodeGuard.Tests/Services/AuditServiceTests.cs +++ b/test/NodeGuard.Tests/Services/AuditServiceTests.cs @@ -237,6 +237,183 @@ public async Task LogAsync_AutoContext_ExceptionDuringLogging_CatchesAndLogsErro #endregion + [Fact] + public async Task LogAsync_AutoContext_WithUserRoles_AddsRolesToDetails() + { + // Arrange + var httpContext = CreateHttpContextWithUser("user-123", "johndoe"); + var identity = (ClaimsIdentity)httpContext.User.Identity!; + identity.AddClaim(new Claim(ClaimTypes.Role, ApplicationUserRole.FinanceManager.ToString())); + identity.AddClaim(new Claim(ClaimTypes.Role, ApplicationUserRole.NodeManager.ToString())); + _httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContext); + var service = CreateAuditService(); + var captured = CaptureAuditLog(); + + // Act + await service.LogAsync( + AuditActionType.Create, + AuditEventType.Success, + AuditObjectType.WalletWithdrawalRequest, + "1", + new { Amount = 50000 }); + + // Assert + using var details = JsonDocument.Parse(captured().Details!); + details.RootElement.GetProperty("Amount").GetInt32().Should().Be(50000); + details.RootElement.GetProperty("UserRoles").EnumerateArray().Select(e => e.GetString()) + .Should().BeEquivalentTo("FinanceManager", "NodeManager"); + } + + [Fact] + public async Task LogAsync_AutoContext_WithUserAndNoDetails_StillRecordsRoles() + { + // Arrange + var httpContext = CreateHttpContextWithUser("user-123", "johndoe"); + ((ClaimsIdentity)httpContext.User.Identity!).AddClaim(new Claim(ClaimTypes.Role, "FinanceManager")); + _httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContext); + var service = CreateAuditService(); + var captured = CaptureAuditLog(); + + // Act + await service.LogAsync(AuditActionType.Login, AuditEventType.Success, AuditObjectType.User); + + // Assert + using var details = JsonDocument.Parse(captured().Details!); + details.RootElement.GetProperty("UserRoles").EnumerateArray().Select(e => e.GetString()) + .Should().BeEquivalentTo("FinanceManager"); + } + + [Fact] + public async Task LogAsync_AutoContext_WithoutContextAndNoDetails_KeepsDetailsNull() + { + // Arrange + _httpContextAccessorMock.Setup(x => x.HttpContext).Returns(new DefaultHttpContext()); + var service = CreateAuditService(); + var captured = CaptureAuditLog(); + + // Act + await service.LogAsync(AuditActionType.Login, AuditEventType.Failure, AuditObjectType.User); + + // Assert + captured().Details.Should().BeNull(); + } + + [Fact] + public async Task LogAsync_AutoContext_WithLongApiTokenName_TruncatesUsernameToColumnLength() + { + // Arrange + var httpContext = new DefaultHttpContext(); + var longName = new string('x', 500); + httpContext.Items[AuthenticatedApiToken.HttpContextItemKey] = new AuthenticatedApiToken(7, longName); + _httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContext); + var service = CreateAuditService(); + var captured = CaptureAuditLog(); + + // Act + await service.LogAsync(AuditActionType.Create, AuditEventType.Success, AuditObjectType.WalletWithdrawalRequest); + + // Assert + var log = captured(); + log.Username.Should().HaveLength(256).And.StartWith("API token 7 (xxx").And.EndWith("x)"); + using var details = JsonDocument.Parse(log.Details!); + details.RootElement.GetProperty("ApiTokenName").GetString().Should().Be(longName); + } + + [Fact] + public async Task LogAsync_AutoContext_WithNonObjectDetails_WrapsThemAndKeepsRoles() + { + // Arrange + var httpContext = CreateHttpContextWithUser("user-123", "johndoe"); + ((ClaimsIdentity)httpContext.User.Identity!).AddClaim(new Claim(ClaimTypes.Role, "FinanceManager")); + _httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContext); + var service = CreateAuditService(); + var captured = CaptureAuditLog(); + + // Act + await service.LogAsync(AuditActionType.Approve, AuditEventType.Success, AuditObjectType.WalletWithdrawalRequest, + "1", "Withdrawal approved"); + + // Assert + using var details = JsonDocument.Parse(captured().Details!); + details.RootElement.GetProperty("Details").GetString().Should().Be("Withdrawal approved"); + details.RootElement.GetProperty("UserRoles").EnumerateArray().Select(e => e.GetString()) + .Should().BeEquivalentTo("FinanceManager"); + } + + [Fact] + public async Task LogAsync_AutoContext_DoesNotOverwriteCallerSuppliedKeys() + { + // Arrange + var httpContext = CreateHttpContextWithUser("user-123", "johndoe"); + ((ClaimsIdentity)httpContext.User.Identity!).AddClaim(new Claim(ClaimTypes.Role, "FinanceManager")); + _httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContext); + var service = CreateAuditService(); + var captured = CaptureAuditLog(); + + // Act + await service.LogAsync(AuditActionType.Update, AuditEventType.Success, AuditObjectType.User, "2", + new { UserRoles = new[] { "NodeManager" } }); + + // Assert + using var details = JsonDocument.Parse(captured().Details!); + details.RootElement.GetProperty("UserRoles").EnumerateArray().Select(e => e.GetString()) + .Should().BeEquivalentTo("NodeManager"); + } + + [Fact] + public async Task LogAsync_AutoContext_WithApiToken_RecordsTokenAndIpAddress() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("10.0.0.5"); + httpContext.Items[AuthenticatedApiToken.HttpContextItemKey] = new AuthenticatedApiToken(7, "backend"); + _httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContext); + var service = CreateAuditService(); + var captured = CaptureAuditLog(); + + // Act + await service.LogAsync(AuditActionType.Create, AuditEventType.Success, AuditObjectType.WalletWithdrawalRequest, + "1", new { WalletId = 3 }); + + // Assert + var log = captured(); + log.Username.Should().Be("API token 7 (backend)"); + log.UserId.Should().BeNull(); + log.IpAddress.Should().Be("10.0.0.5"); + using var details = JsonDocument.Parse(log.Details!); + details.RootElement.GetProperty("WalletId").GetInt32().Should().Be(3); + details.RootElement.GetProperty("ApiTokenId").GetInt32().Should().Be(7); + details.RootElement.GetProperty("ApiTokenName").GetString().Should().Be("backend"); + } + + [Fact] + public async Task LogAsync_AutoContext_WithApiTokenAndNoDetails_StillRecordsTheTokenId() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.Items[AuthenticatedApiToken.HttpContextItemKey] = new AuthenticatedApiToken(7, "backend"); + _httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContext); + var service = CreateAuditService(); + var captured = CaptureAuditLog(); + + // Act + await service.LogAsync(AuditActionType.Create, AuditEventType.Failure, AuditObjectType.WalletWithdrawalRequest); + + // Assert + using var details = JsonDocument.Parse(captured().Details!); + details.RootElement.GetProperty("ApiTokenId").GetInt32().Should().Be(7); + } + + private Func CaptureAuditLog() + { + AuditLog? captured = null; + _auditLogRepositoryMock + .Setup(x => x.AddAsync(It.IsAny())) + .Callback(log => captured = log) + .ReturnsAsync((true, (string?)null)); + return () => captured ?? throw new InvalidOperationException("No audit log was persisted"); + } + #region LogSystemAsync [Fact] diff --git a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs index 80448162..4aebf1c1 100644 --- a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs +++ b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs @@ -465,6 +465,45 @@ public async Task ScheduleHotWalletWithdrawalAsync_TemplateGenerationFails_Leave _scheduler.Verify(x => x.ScheduleJob(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } + [Fact] + public async Task ScheduleHotWalletWithdrawalAsync_BeforeScheduling_RunsAfterTheTemplateAndBeforeTheJob() + { + HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending); + var events = new List(); + _bitcoin.Setup(x => x.GenerateTemplatePSBT(It.IsAny())) + .Callback(() => events.Add("template")) + .ReturnsAsync(EmptyPsbt()); + _scheduler.Setup(x => x.ScheduleJob(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback(() => events.Add("schedule")) + .ReturnsAsync(DateTimeOffset.UtcNow); + + await CreateService().ScheduleHotWalletWithdrawalAsync(BumpId, () => + { + events.Add("hook"); + return Task.CompletedTask; + }); + + events.Should().Equal("template", "hook", "schedule"); + } + + [Fact] + public async Task ScheduleHotWalletWithdrawalAsync_TemplateGenerationFails_DoesNotRunBeforeScheduling() + { + HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending); + _bitcoin.Setup(x => x.GenerateTemplatePSBT(It.IsAny())) + .ThrowsAsync(new NoUTXOsAvailableException()); + var hookRan = false; + + var act = () => CreateService().ScheduleHotWalletWithdrawalAsync(BumpId, () => + { + hookRan = true; + return Task.CompletedTask; + }); + + await act.Should().ThrowAsync(); + hookRan.Should().BeFalse("a request whose PSBT could not be built must not be audited as a success"); + } + [Fact] public async Task ScheduleHotWalletWithdrawalAsync_ColdWallet_IsRefused() {