Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,5 +121,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
public DbSet<APIToken> ApiTokens { get; set; }

public DbSet<SwapOut> SwapOuts { get; set; }

public DbSet<AuditLog> AuditLogs { get; set; }
}
}
187 changes: 187 additions & 0 deletions src/Data/Models/AuditLog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/*
* NodeGuard
* Copyright (C) 2023 Elenpay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace NodeGuard.Data.Models;

/// <summary>
/// Represents an audit log entry for tracking user actions and system events
/// </summary>
public class AuditLog
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

/// <summary>
/// Timestamp when the audit event occurred
/// </summary>
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow;

/// <summary>
/// The type of action that was performed
/// </summary>
public AuditActionType ActionType { get; set; }

/// <summary>
/// The result/outcome of the action
/// </summary>
public AuditEventType EventType { get; set; }

/// <summary>
/// The ID of the user who performed the action (nullable for system actions)
/// </summary>
[MaxLength(450)]
public string? UserId { get; set; }

/// <summary>
/// The username of the user who performed the action
/// </summary>
[MaxLength(256)]
public string? Username { get; set; }

/// <summary>
/// The IP address from which the action was performed
/// </summary>
[MaxLength(45)]
public string? IpAddress { get; set; }

/// <summary>
/// The type of object that was affected by the action
/// </summary>
public AuditObjectType ObjectAffected { get; set; }

/// <summary>
/// The ID of the object that was affected (e.g., wallet ID, channel ID)
/// </summary>
[MaxLength(450)]
public string? ObjectId { get; set; }

/// <summary>
/// Additional details about the action in JSON format
/// </summary>
public string? Details { get; set; }
}

/// <summary>
/// Types of actions that can be audited
/// </summary>
public enum AuditActionType
{
// CRUD Operations
Create,
Update,
Delete,

// Approval/Rejection
Approve,
Reject,
Cancel,

// Authentication
Login,
Logout,
TwoFactorLogin,
LoginWithRecoveryCode,

// 2FA Management
TwoFactorEnabled,
TwoFactorDisabled,
TwoFactorReset,
GenerateRecoveryCodes,

// Password Management
ChangePassword,
SetPassword,
ResetPassword,

// User Management
LockUser,
UnlockUser,
UpdateRoles,

// Wallet Operations
Transfer,
Import,
Finalise,
Rescan,
FreezeUTXO,
UnfreezeUTXO,
AddKey,

// Channel Operations
Close,
ForceClose,
MarkAsClosed,
EnableLiquidityManagement,
DisableLiquidityManagement,

// API Token Operations
Block,
Unblock,

// Swap Operations
SwapOut,
SwapIn,

// Node Operations
AddNode,
UpdateNode,
DeleteNode,

// Internal Wallet
GenerateInternalWallet,

// Withdrawal Operations
BumpFee,

// Signing
Sign
}

/// <summary>
/// Types of event outcomes
/// </summary>
public enum AuditEventType
{
Success,
Failure,
Attempt
}

/// <summary>
/// Types of objects that can be affected by audited actions
/// </summary>
public enum AuditObjectType
{
User,
Wallet,
Channel,
ChannelOperationRequest,
WalletWithdrawalRequest,
Node,
APIToken,
SwapOut,
LiquidityRule,
Key,
UTXO,
InternalWallet,
Session
}
110 changes: 110 additions & 0 deletions src/Data/Repositories/AuditLogRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* NodeGuard
* Copyright (C) 2023 Elenpay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/

using Microsoft.EntityFrameworkCore;
using NodeGuard.Data.Models;
using NodeGuard.Data.Repositories.Interfaces;

namespace NodeGuard.Data.Repositories;

public class AuditLogRepository : IAuditLogRepository
{
private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;
private readonly ILogger<AuditLogRepository> _logger;

public AuditLogRepository(IDbContextFactory<ApplicationDbContext> dbContextFactory, ILogger<AuditLogRepository> logger)
{
_dbContextFactory = dbContextFactory;
_logger = logger;
}

public async Task<(bool, string?)> AddAsync(AuditLog auditLog)
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();

try
{
auditLog.Timestamp = DateTimeOffset.UtcNow;
await dbContext.AuditLogs.AddAsync(auditLog);
await dbContext.SaveChangesAsync();
return (true, null);
}
catch (Exception e)
{
_logger.LogError(e, "Error adding audit log entry");
return (false, e.Message);
}
}

public async Task<(List<AuditLog>, int)> GetPaginatedAsync(
int page,
int pageSize,
AuditActionType? actionType = null,
AuditEventType? eventType = null,
AuditObjectType? objectType = null,
string? userId = null,
DateTimeOffset? fromDate = null,
DateTimeOffset? toDate = null)
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();

var query = dbContext.AuditLogs.AsQueryable();

if (actionType.HasValue)
query = query.Where(a => a.ActionType == actionType.Value);

if (eventType.HasValue)
query = query.Where(a => a.EventType == eventType.Value);

if (objectType.HasValue)
query = query.Where(a => a.ObjectAffected == objectType.Value);

if (!string.IsNullOrEmpty(userId))
query = query.Where(a => a.UserId == userId);

if (fromDate.HasValue)
query = query.Where(a => a.Timestamp >= fromDate.Value);

if (toDate.HasValue)
query = query.Where(a => a.Timestamp <= toDate.Value);

var totalCount = await query.CountAsync();

var results = await query
.OrderByDescending(a => a.Timestamp)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();

return (results, totalCount);
}

public async Task<int> DeleteOlderThanAsync(DateTimeOffset cutoffDate)
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();

var count = await dbContext.AuditLogs
.Where(a => a.Timestamp < cutoffDate)
.ExecuteDeleteAsync();

_logger.LogInformation("Deleted {Count} audit log entries older than {CutoffDate}", count, cutoffDate);

return count;
}
}
48 changes: 48 additions & 0 deletions src/Data/Repositories/Interfaces/IAuditLogRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* NodeGuard
* Copyright (C) 2023 Elenpay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/

using NodeGuard.Data.Models;

namespace NodeGuard.Data.Repositories.Interfaces;

public interface IAuditLogRepository
{
/// <summary>
/// Add a new audit log entry
/// </summary>
Task<(bool, string?)> AddAsync(AuditLog auditLog);

/// <summary>
/// Get paginated audit logs with optional filtering
/// </summary>
Task<(List<AuditLog>, int)> GetPaginatedAsync(
int page,
int pageSize,
AuditActionType? actionType = null,
AuditEventType? eventType = null,
AuditObjectType? objectType = null,
string? userId = null,
DateTimeOffset? fromDate = null,
DateTimeOffset? toDate = null);

/// <summary>
/// Delete audit logs older than the specified date
/// </summary>
Task<int> DeleteOlderThanAsync(DateTimeOffset cutoffDate);
}
Loading
Loading