Documentation
¶
Overview ¶
Package audit provides command logging and audit trail functionality for the STX Agent system. 审计包提供 STX Agent 系统的命令日志和审计追踪功能。
Package audit provides command logging and audit trail functionality for the STX Agent system. 审计包提供 STX Agent 系统的命令日志和审计追踪功能。
Index ¶
- Constants
- Variables
- func ActionsForGroup(group string) []string
- func BindOperator(c *gin.Context)
- func IsSensitiveKey(key string) bool
- func IsVariablePlaceholder(value string) bool
- func RecordFromGin(c *gin.Context, repo *Repository, userID uint64, ...) error
- func RecordFromGinNoUser(repo *Repository, req *http.Request, userID uint64, ...) error
- func RedactText(value string) string
- func UintID(id uint) string
- func WithCommandMetadata(ctx context.Context, metadata CommandMetadata) context.Context
- type AuditDetails
- type AuditLog
- type AuditLogFilter
- type AuditLogInfo
- type CommandLog
- type CommandLogFilter
- type CommandLogInfo
- type CommandMetadata
- type CommandParameters
- type CommandStatus
- type CreateAuditLogRequest
- type CreateCommandLogRequest
- type GetAuditLogResponse
- type GetCommandLogResponse
- type Handler
- type ListAuditLogsRequest
- type ListAuditLogsResponse
- type ListCommandLogsRequest
- type ListCommandLogsResponse
- type Repository
- func (r *Repository) CountCommandsByRequestIDs(ctx context.Context, requestIDs []string) (map[string]int64, error)
- func (r *Repository) CreateAuditLog(ctx context.Context, log *AuditLog) error
- func (r *Repository) CreateCommandLog(ctx context.Context, log *CommandLog) error
- func (r *Repository) DeleteAuditLog(ctx context.Context, id uint) error
- func (r *Repository) DeleteAuditLogsBefore(ctx context.Context, before interface{}) (int64, error)
- func (r *Repository) DeleteCommandLog(ctx context.Context, id uint) error
- func (r *Repository) DeleteCommandLogsBefore(ctx context.Context, before interface{}) (int64, error)
- func (r *Repository) ExistsByCommandID(ctx context.Context, commandID string) (bool, error)
- func (r *Repository) GetAuditLogByID(ctx context.Context, id uint) (*AuditLog, error)
- func (r *Repository) GetAuditLogByIDForOwner(ctx context.Context, id, ownerUserID uint, includeAll bool) (*AuditLog, error)
- func (r *Repository) GetCommandLogByCommandID(ctx context.Context, commandID string) (*CommandLog, error)
- func (r *Repository) GetCommandLogByID(ctx context.Context, id uint) (*CommandLog, error)
- func (r *Repository) GetCommandLogByIDForOwner(ctx context.Context, id, ownerUserID uint, includeAll bool) (*CommandLog, error)
- func (r *Repository) ListAuditLogs(ctx context.Context, filter *AuditLogFilter) ([]*AuditLog, int64, error)
- func (r *Repository) ListCommandLogs(ctx context.Context, filter *CommandLogFilter) ([]*CommandLog, int64, error)
- func (r *Repository) LookupUsername(ctx context.Context, userID uint) string
- func (r *Repository) UpdateAuditLogDetailsByExecutionID(ctx context.Context, executionID string, extraDetails map[string]any) error
- func (r *Repository) UpdateCommandLog(ctx context.Context, log *CommandLog) error
- func (r *Repository) UpdateCommandLogStatus(ctx context.Context, id uint, updates map[string]interface{}) error
- type UpdateCommandLogRequest
Constants ¶
const ( ErrCodeCommandLogNotFound = 4001 ErrCodeCommandIDDuplicate = 4002 ErrCodeCommandIDEmpty = 4003 ErrCodeAgentIDEmpty = 4004 ErrCodeCommandTypeEmpty = 4005 ErrCodeAuditLogNotFound = 4006 ErrCodeActionEmpty = 4007 ErrCodeResourceTypeEmpty = 4008 )
Error codes for audit and command log operations. 审计和命令日志操作的错误代码。
Variables ¶
var ( // ErrCommandLogNotFound indicates the requested command log does not exist. // ErrCommandLogNotFound 表示请求的命令日志不存在。 ErrCommandLogNotFound = errors.New("audit: command log not found") // ErrCommandIDDuplicate indicates a command log with the same command ID already exists. // ErrCommandIDDuplicate 表示具有相同命令 ID 的命令日志已存在。 ErrCommandIDDuplicate = errors.New("audit: command ID already exists") // ErrCommandIDEmpty indicates the command ID is empty. // ErrCommandIDEmpty 表示命令 ID 为空。 ErrCommandIDEmpty = errors.New("audit: command ID cannot be empty") // ErrAgentIDEmpty indicates the agent ID is empty. // ErrAgentIDEmpty 表示代理 ID 为空。 ErrAgentIDEmpty = errors.New("audit: agent ID cannot be empty") // ErrCommandTypeEmpty indicates the command type is empty. // ErrCommandTypeEmpty 表示命令类型为空。 ErrCommandTypeEmpty = errors.New("audit: command type cannot be empty") // ErrAuditLogNotFound indicates the requested audit log does not exist. // ErrAuditLogNotFound 表示请求的审计日志不存在。 ErrAuditLogNotFound = errors.New("audit: audit log not found") // ErrActionEmpty indicates the action is empty. // ErrActionEmpty 表示操作为空。 ErrActionEmpty = errors.New("audit: action cannot be empty") // ErrResourceTypeEmpty indicates the resource type is empty. // ErrResourceTypeEmpty 表示资源类型为空。 ErrResourceTypeEmpty = errors.New("audit: resource type cannot be empty") )
Error definitions for audit and command log operations. 审计和命令日志操作的错误定义。
Functions ¶
func ActionsForGroup ¶ added in v1.0.0
ActionsForGroup 把界面上的少数操作类别展开成实际写入的 action。 ActionsForGroup expands a small UI action category into the actions that are actually stored.
func BindOperator ¶ added in v1.0.0
BindOperator 把当前登录用户和请求编号写进请求上下文。 同一次 HTTP 操作里下发的 Agent 命令会带上同一个 request_id,审计行才能对上服务器命令。 BindOperator stores the current user and request ID on the request context. Agent commands issued by the same HTTP operation share that request ID with the audit row.
func IsSensitiveKey ¶
IsSensitiveKey 判断字段名是否表示密码、令牌或密钥。 IsSensitiveKey reports whether a field name represents a password, token, or key.
func IsVariablePlaceholder ¶ added in v1.0.0
IsVariablePlaceholder 判断给定值是否为模板变量或占位符表达式(如 {{var}}、${var})。 这类变量引用不应被脱敏替换,因为它们是变量名而非明文凭据。 IsVariablePlaceholder reports whether a value represents a template variable or placeholder.
func RecordFromGin ¶
func RecordFromGin(c *gin.Context, repo *Repository, userID uint64, username, action, resourceType, resourceID, resourceName string, details AuditDetails) error
RecordFromGin writes an audit log entry from an HTTP request (user from session, IP, User-Agent from request). RecordFromGin 根据 HTTP 请求写入审计日志(用户来自 session,IP、User-Agent 来自请求)。 userID and username should be obtained via auth.GetUserIDFromContext(c) and auth.GetUsernameFromContext(c). If repo is nil, the function no-ops and returns nil.
func RecordFromGinNoUser ¶
func RecordFromGinNoUser(repo *Repository, req *http.Request, userID uint64, username, action, resourceType, resourceID, resourceName string, details AuditDetails) error
RecordFromGinNoUser is like RecordFromGin but accepts *http.Request for context (e.g. when no gin context). Prefer RecordFromGin when you have gin.Context.
func RedactText ¶
RedactText 屏蔽 JSON、HOCON 和常见 key=value 文本中的敏感值。 RedactText masks sensitive values in JSON, HOCON, and common key=value text.
func WithCommandMetadata ¶
func WithCommandMetadata(ctx context.Context, metadata CommandMetadata) context.Context
WithCommandMetadata 把 Agent 命令关联信息写入上下文,已有字段不会被空值清掉。 WithCommandMetadata attaches Agent command linkage metadata and keeps existing fields when the new value is empty.
Types ¶
type AuditDetails ¶
type AuditDetails map[string]interface{}
AuditDetails represents the JSON details for an audit log entry. AuditDetails 表示审计日志条目的 JSON 详情。
func RedactDetails ¶
func RedactDetails(details AuditDetails) AuditDetails
RedactDetails 递归屏蔽审计详情中的密码、令牌、密钥和凭证。 RedactDetails recursively masks passwords, tokens, keys, and credentials in audit details.
func (*AuditDetails) Scan ¶
func (d *AuditDetails) Scan(value interface{}) error
Scan implements the sql.Scanner interface for database retrieval. Scan 实现 sql.Scanner 接口用于数据库读取。
type AuditLog ¶
type AuditLog struct {
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
UserID *uint `json:"user_id" gorm:"index"`
Username string `json:"username" gorm:"size:100"`
Action string `json:"action" gorm:"size:50;not null;index"`
ResourceType string `json:"resource_type" gorm:"size:50;not null;index:idx_resource"`
ResourceID string `json:"resource_id" gorm:"size:100;index:idx_resource"`
ResourceName string `json:"resource_name" gorm:"size:200"`
RequestID string `json:"request_id,omitempty" gorm:"size:64;index"`
ExecutionID string `json:"execution_id,omitempty" gorm:"size:36;index"`
CommandID string `json:"command_id,omitempty" gorm:"size:50;index"`
ClientType string `json:"client_type,omitempty" gorm:"size:20;index"`
RiskLevel string `json:"risk_level,omitempty" gorm:"size:4;index"`
ResultStatus string `json:"result_status,omitempty" gorm:"size:32;index"`
// Trigger: "auto" (Agent) or "manual" (user), empty for legacy records.
// Trigger:自动(Agent)或手动(用户),空表示旧数据。
Trigger string `json:"trigger" gorm:"size:20;index"`
Details AuditDetails `json:"details" gorm:"type:json"`
IPAddress string `json:"ip_address" gorm:"size:45"`
UserAgent string `json:"user_agent" gorm:"size:500"`
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;index"`
}
AuditLog represents an audit trail entry for system operations. AuditLog 表示系统操作的审计追踪条目。 Requirements: 10.3, 10.4
func (AuditLog) TableName ¶
TableName specifies the table name for the AuditLog model. TableName 指定 AuditLog 模型的表名。
func (*AuditLog) ToAuditLogInfo ¶
func (a *AuditLog) ToAuditLogInfo() *AuditLogInfo
ToAuditLogInfo converts an AuditLog to AuditLogInfo. ToAuditLogInfo 将 AuditLog 转换为 AuditLogInfo。
type AuditLogFilter ¶
type AuditLogFilter struct {
UserID *uint `json:"user_id"`
Username string `json:"username"`
Action string `json:"action"`
// ActionGroup 是界面上的操作类别,展开后过滤多个 action。
// ActionGroup is a UI action category that filters several stored actions.
ActionGroup string `json:"-"`
ResourceType string `json:"resource_type"`
ResourceID string `json:"resource_id"`
RequestID string `json:"request_id"`
ExecutionID string `json:"execution_id"`
CommandID string `json:"command_id"`
ClientType string `json:"client_type"`
ResultStatus string `json:"result_status"`
IncludeAll bool `json:"-"`
// Trigger filters by trigger column: "auto" (agent) or "manual" (user).
// Trigger 按 trigger 字段过滤:auto(Agent 自动)或 manual(手动)。
Trigger string `json:"trigger"`
StartTime *time.Time `json:"start_time"`
EndTime *time.Time `json:"end_time"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
AuditLogFilter represents filter criteria for querying audit logs. AuditLogFilter 表示查询审计日志的过滤条件。 Requirements: 10.4
type AuditLogInfo ¶
type AuditLogInfo struct {
ID uint `json:"id"`
UserID *uint `json:"user_id"`
Username string `json:"username"`
Action string `json:"action"`
ResourceType string `json:"resource_type"`
ResourceID string `json:"resource_id"`
ResourceName string `json:"resource_name"`
RequestID string `json:"request_id,omitempty"`
ExecutionID string `json:"execution_id,omitempty"`
CommandID string `json:"command_id,omitempty"`
ClientType string `json:"client_type,omitempty"`
RiskLevel string `json:"risk_level,omitempty"`
ResultStatus string `json:"result_status,omitempty"`
Trigger string `json:"trigger"` // "auto" | "manual" | ""
Details AuditDetails `json:"details"`
IPAddress string `json:"ip_address"`
UserAgent string `json:"user_agent"`
CreatedAt time.Time `json:"created_at"`
// CommandCount 是同一次请求下发到 Agent 的命令数,只在列表接口填充。
// CommandCount is the number of Agent commands from the same request. Only list responses fill it.
CommandCount int `json:"command_count,omitempty"`
}
AuditLogInfo represents audit log information for API responses. AuditLogInfo 表示 API 响应的审计日志信息。
type CommandLog ¶
type CommandLog struct {
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
CommandID string `json:"command_id" gorm:"size:50;uniqueIndex;not null"`
RequestID string `json:"request_id,omitempty" gorm:"size:64;index"`
ExecutionID string `json:"execution_id,omitempty" gorm:"size:36;index"`
AgentID string `json:"agent_id" gorm:"size:100;not null;index"`
HostID *uint `json:"host_id" gorm:"index"`
CommandType string `json:"command_type" gorm:"size:30;not null"`
ClientType string `json:"client_type,omitempty" gorm:"size:20;index"`
// DisplayCommand 保存经过脱敏、适合审计展示的实际命令或 Agent 操作说明。
// DisplayCommand stores a redacted command or Agent action description suitable for audit display.
DisplayCommand string `json:"display_command,omitempty" gorm:"type:text"`
Parameters CommandParameters `json:"parameters" gorm:"type:json"`
Status CommandStatus `json:"status" gorm:"size:20;not null;index"`
Progress int `json:"progress" gorm:"default:0"`
// Output 存储命令执行的原始内容输出,兼容 SQLite/MySQL/PostgreSQL。
// Output stores the raw command execution output, compatible with SQLite/MySQL/PostgreSQL.
Output string `json:"output" gorm:"type:text"`
Error string `json:"error" gorm:"type:text"`
StartedAt *time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;index"`
CreatedBy *uint `json:"created_by"`
}
CommandLog represents a record of command execution by an Agent. CommandLog 表示 Agent 执行命令的记录。 Requirements: 10.1, 10.3
func (CommandLog) TableName ¶
func (CommandLog) TableName() string
TableName specifies the table name for the CommandLog model. TableName 指定 CommandLog 模型的表名。
func (*CommandLog) ToCommandLogInfo ¶
func (c *CommandLog) ToCommandLogInfo() *CommandLogInfo
ToCommandLogInfo converts a CommandLog to CommandLogInfo. ToCommandLogInfo 将 CommandLog 转换为 CommandLogInfo。
type CommandLogFilter ¶
type CommandLogFilter struct {
CommandID string `json:"command_id"`
AgentID string `json:"agent_id"`
HostID *uint `json:"host_id"`
CommandType string `json:"command_type"`
Status CommandStatus `json:"status"`
StartTime *time.Time `json:"start_time"`
EndTime *time.Time `json:"end_time"`
CreatedBy *uint `json:"created_by"`
RequestID string `json:"request_id"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
CommandLogFilter represents filter criteria for querying command logs. CommandLogFilter 表示查询命令日志的过滤条件。
type CommandLogInfo ¶
type CommandLogInfo struct {
ID uint `json:"id"`
CommandID string `json:"command_id"`
RequestID string `json:"request_id,omitempty"`
ExecutionID string `json:"execution_id,omitempty"`
AgentID string `json:"agent_id"`
HostID *uint `json:"host_id"`
CommandType string `json:"command_type"`
ClientType string `json:"client_type,omitempty"`
DisplayCommand string `json:"display_command,omitempty"`
Parameters CommandParameters `json:"parameters"`
Status CommandStatus `json:"status"`
Progress int `json:"progress"`
Output string `json:"output"`
Error string `json:"error"`
StartedAt *time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
CreatedAt time.Time `json:"created_at"`
CreatedBy *uint `json:"created_by"`
}
CommandLogInfo represents command log information for API responses. CommandLogInfo 表示 API 响应的命令日志信息。
type CommandMetadata ¶
type CommandMetadata struct {
RequestID string
ExecutionID string
OwnerUserID uint
OwnerUsername string
ClientType string
}
CommandMetadata 保存 Agent 命令与用户请求、公共执行之间的关联。 CommandMetadata stores links between an Agent command, the user request, and the shared execution.
func CommandMetadataFromContext ¶
func CommandMetadataFromContext(ctx context.Context) CommandMetadata
CommandMetadataFromContext 从上下文读取 Agent 命令关联信息。 CommandMetadataFromContext reads Agent command linkage metadata from a context.
type CommandParameters ¶
type CommandParameters map[string]interface{}
CommandParameters represents the JSON parameters for a command. CommandParameters 表示命令的 JSON 参数。
func RedactParameters ¶
func RedactParameters(parameters CommandParameters) CommandParameters
RedactParameters 递归屏蔽 Agent 命令参数中的敏感值。 RedactParameters recursively masks sensitive values in Agent command parameters.
func (*CommandParameters) Scan ¶
func (p *CommandParameters) Scan(value interface{}) error
Scan implements the sql.Scanner interface for database retrieval. Scan 实现 sql.Scanner 接口用于数据库读取。
type CommandStatus ¶
type CommandStatus string
CommandStatus represents the execution status of a command. CommandStatus 表示命令的执行状态。
const ( // CommandStatusPending indicates the command is waiting to be executed. // CommandStatusPending 表示命令正在等待执行。 CommandStatusPending CommandStatus = "pending" // CommandStatusRunning indicates the command is currently executing. // CommandStatusRunning 表示命令正在执行中。 CommandStatusRunning CommandStatus = "running" // CommandStatusSuccess indicates the command completed successfully. // CommandStatusSuccess 表示命令执行成功。 CommandStatusSuccess CommandStatus = "success" // CommandStatusFailed indicates the command execution failed. // CommandStatusFailed 表示命令执行失败。 CommandStatusFailed CommandStatus = "failed" // CommandStatusCancelled indicates the command was cancelled. // CommandStatusCancelled 表示命令已被取消。 CommandStatusCancelled CommandStatus = "cancelled" )
type CreateAuditLogRequest ¶
type CreateAuditLogRequest struct {
UserID *uint `json:"user_id"`
Username string `json:"username" binding:"max=100"`
Action string `json:"action" binding:"required,max=50"`
ResourceType string `json:"resource_type" binding:"required,max=50"`
ResourceID string `json:"resource_id" binding:"max=100"`
ResourceName string `json:"resource_name" binding:"max=200"`
Details AuditDetails `json:"details"`
IPAddress string `json:"ip_address" binding:"max=45"`
UserAgent string `json:"user_agent" binding:"max=500"`
}
CreateAuditLogRequest represents a request to create a new audit log. CreateAuditLogRequest 表示创建新审计日志的请求。
type CreateCommandLogRequest ¶
type CreateCommandLogRequest struct {
CommandID string `json:"command_id" binding:"required,max=50"`
AgentID string `json:"agent_id" binding:"required,max=100"`
HostID *uint `json:"host_id"`
CommandType string `json:"command_type" binding:"required,max=30"`
Parameters CommandParameters `json:"parameters"`
CreatedBy *uint `json:"created_by"`
}
CreateCommandLogRequest represents a request to create a new command log. CreateCommandLogRequest 表示创建新命令日志的请求。
type GetAuditLogResponse ¶
type GetAuditLogResponse struct {
ErrorMsg string `json:"error_msg"`
Data *AuditLogInfo `json:"data"`
}
GetAuditLogResponse represents the response for getting an audit log. GetAuditLogResponse 表示获取审计日志详情的响应。
type GetCommandLogResponse ¶
type GetCommandLogResponse struct {
ErrorMsg string `json:"error_msg"`
Data *CommandLogInfo `json:"data"`
}
GetCommandLogResponse represents the response for getting a command log. GetCommandLogResponse 表示获取命令日志详情的响应。
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler provides HTTP handlers for audit and command log operations. Handler 提供审计和命令日志操作的 HTTP 处理器。
func NewHandler ¶
func NewHandler(repo *Repository) *Handler
NewHandler creates a new Handler instance. NewHandler 创建一个新的 Handler 实例。
func (*Handler) GetAuditLog ¶
GetAuditLog handles GET /api/v1/audit-logs/:id - gets an audit log by ID. GetAuditLog 处理 GET /api/v1/audit-logs/:id - 根据 ID 获取审计日志详情。 @Tags audit @Produce json @Param id path int true "审计日志ID" @Success 200 {object} GetAuditLogResponse @Router /api/v1/audit-logs/{id} [get] Requirements: 10.4
func (*Handler) GetCommandLog ¶
GetCommandLog handles GET /api/v1/commands/:id - gets a command log by ID. GetCommandLog 处理 GET /api/v1/commands/:id - 根据 ID 获取命令日志详情。 @Tags audit @Produce json @Param id path int true "命令日志ID" @Success 200 {object} GetCommandLogResponse @Router /api/v1/commands/{id} [get] Requirements: 10.1
func (*Handler) ListAuditLogs ¶
ListAuditLogs handles GET /api/v1/audit-logs - lists audit logs with filtering and pagination. ListAuditLogs 处理 GET /api/v1/audit-logs - 获取审计日志列表(支持过滤和分页)。 @Tags audit @Param request query ListAuditLogsRequest true "查询参数" @Produce json @Success 200 {object} ListAuditLogsResponse @Router /api/v1/audit-logs [get] Requirements: 10.4
func (*Handler) ListCommandLogs ¶
ListCommandLogs handles GET /api/v1/commands - lists command logs with filtering and pagination. ListCommandLogs 处理 GET /api/v1/commands - 获取命令日志列表(支持过滤和分页)。 @Tags audit @Param request query ListCommandLogsRequest true "查询参数" @Produce json @Success 200 {object} ListCommandLogsResponse @Router /api/v1/commands [get] Requirements: 10.1, 10.4
type ListAuditLogsRequest ¶
type ListAuditLogsRequest struct {
Current int `json:"current" form:"current" binding:"min=1"`
Size int `json:"size" form:"size" binding:"min=1,max=100"`
UserID *uint `json:"user_id" form:"user_id"`
Username string `json:"username" form:"username"`
Action string `json:"action" form:"action"`
ActionGroup string `json:"action_group" form:"action_group"`
ResourceType string `json:"resource_type" form:"resource_type"`
ResourceID string `json:"resource_id" form:"resource_id"`
RequestID string `json:"request_id" form:"request_id"`
ExecutionID string `json:"execution_id" form:"execution_id"`
CommandID string `json:"command_id" form:"command_id"`
ClientType string `json:"client_type" form:"client_type"`
ResultStatus string `json:"result_status" form:"result_status"`
Trigger string `json:"trigger" form:"trigger"` // "auto" | "manual"
StartTime string `json:"start_time" form:"start_time"`
EndTime string `json:"end_time" form:"end_time"`
}
ListAuditLogsRequest represents the request for listing audit logs. ListAuditLogsRequest 表示获取审计日志列表的请求。
type ListAuditLogsResponse ¶
type ListAuditLogsResponse struct {
ErrorMsg string `json:"error_msg"`
Data *struct {
Total int64 `json:"total"`
Logs []*AuditLogInfo `json:"logs"`
} `json:"data"`
}
ListAuditLogsResponse represents the response for listing audit logs. ListAuditLogsResponse 表示获取审计日志列表的响应。
type ListCommandLogsRequest ¶
type ListCommandLogsRequest struct {
Current int `json:"current" form:"current" binding:"min=1"`
Size int `json:"size" form:"size" binding:"min=1,max=100"`
CommandID string `json:"command_id" form:"command_id"`
AgentID string `json:"agent_id" form:"agent_id"`
HostID *uint `json:"host_id" form:"host_id"`
CommandType string `json:"command_type" form:"command_type"`
RequestID string `json:"request_id" form:"request_id"`
Status CommandStatus `json:"status" form:"status"`
StartTime string `json:"start_time" form:"start_time"`
EndTime string `json:"end_time" form:"end_time"`
}
ListCommandLogsRequest represents the request for listing command logs. ListCommandLogsRequest 表示获取命令日志列表的请求。
type ListCommandLogsResponse ¶
type ListCommandLogsResponse struct {
ErrorMsg string `json:"error_msg"`
Data *struct {
Total int64 `json:"total"`
Commands []*CommandLogInfo `json:"commands"`
} `json:"data"`
}
ListCommandLogsResponse represents the response for listing command logs. ListCommandLogsResponse 表示获取命令日志列表的响应。
type Repository ¶
type Repository struct {
// contains filtered or unexported fields
}
Repository provides data access operations for CommandLog and AuditLog entities. Repository 提供 CommandLog 和 AuditLog 实体的数据访问操作。
func NewRepository ¶
func NewRepository(db *gorm.DB) *Repository
NewRepository creates a new Repository instance. NewRepository 创建一个新的 Repository 实例。
func (*Repository) CountCommandsByRequestIDs ¶ added in v1.0.0
func (r *Repository) CountCommandsByRequestIDs(ctx context.Context, requestIDs []string) (map[string]int64, error)
CountCommandsByRequestIDs 统计每个请求编号下的 Agent 命令数。 CountCommandsByRequestIDs counts Agent commands grouped by request ID.
func (*Repository) CreateAuditLog ¶
func (r *Repository) CreateAuditLog(ctx context.Context, log *AuditLog) error
CreateAuditLog creates a new audit log record in the database. CreateAuditLog 在数据库中创建新的审计日志记录。 Requirements: 10.3
func (*Repository) CreateCommandLog ¶
func (r *Repository) CreateCommandLog(ctx context.Context, log *CommandLog) error
CreateCommandLog creates a new command log record in the database. CreateCommandLog 在数据库中创建新的命令日志记录。 Returns ErrCommandIDDuplicate if a command log with the same command ID already exists. 如果具有相同命令 ID 的命令日志已存在,则返回 ErrCommandIDDuplicate。 Requirements: 10.1
func (*Repository) DeleteAuditLog ¶
func (r *Repository) DeleteAuditLog(ctx context.Context, id uint) error
DeleteAuditLog removes an audit log record from the database. DeleteAuditLog 从数据库中删除审计日志记录。 Returns ErrAuditLogNotFound if the audit log does not exist. 如果审计日志不存在,则返回 ErrAuditLogNotFound。
func (*Repository) DeleteAuditLogsBefore ¶
func (r *Repository) DeleteAuditLogsBefore(ctx context.Context, before interface{}) (int64, error)
DeleteAuditLogsBefore deletes audit logs created before the specified time. DeleteAuditLogsBefore 删除指定时间之前创建的审计日志。 This is useful for implementing log retention policies. 这对于实现日志保留策略很有用。 Requirements: 10.5
func (*Repository) DeleteCommandLog ¶
func (r *Repository) DeleteCommandLog(ctx context.Context, id uint) error
DeleteCommandLog removes a command log record from the database. DeleteCommandLog 从数据库中删除命令日志记录。 Returns ErrCommandLogNotFound if the command log does not exist. 如果命令日志不存在,则返回 ErrCommandLogNotFound。
func (*Repository) DeleteCommandLogsBefore ¶
func (r *Repository) DeleteCommandLogsBefore(ctx context.Context, before interface{}) (int64, error)
DeleteCommandLogsBefore deletes command logs created before the specified time. DeleteCommandLogsBefore 删除指定时间之前创建的命令日志。 This is useful for implementing log retention policies. 这对于实现日志保留策略很有用。
func (*Repository) ExistsByCommandID ¶
ExistsByCommandID checks if a command log with the given command ID exists. ExistsByCommandID 检查具有给定命令 ID 的命令日志是否存在。
func (*Repository) GetAuditLogByID ¶
GetAuditLogByID retrieves an audit log by its ID. GetAuditLogByID 通过 ID 获取审计日志。 Returns ErrAuditLogNotFound if the audit log does not exist. 如果审计日志不存在,则返回 ErrAuditLogNotFound。
func (*Repository) GetAuditLogByIDForOwner ¶
func (r *Repository) GetAuditLogByIDForOwner(ctx context.Context, id, ownerUserID uint, includeAll bool) (*AuditLog, error)
GetAuditLogByIDForOwner 按用户归属读取审计记录,管理员可查看全部。 GetAuditLogByIDForOwner loads an audit entry under owner scope, while administrators may view all entries.
func (*Repository) GetCommandLogByCommandID ¶
func (r *Repository) GetCommandLogByCommandID(ctx context.Context, commandID string) (*CommandLog, error)
GetCommandLogByCommandID retrieves a command log by its command ID. GetCommandLogByCommandID 通过命令 ID 获取命令日志。 Returns ErrCommandLogNotFound if the command log does not exist. 如果命令日志不存在,则返回 ErrCommandLogNotFound。
func (*Repository) GetCommandLogByID ¶
func (r *Repository) GetCommandLogByID(ctx context.Context, id uint) (*CommandLog, error)
GetCommandLogByID retrieves a command log by its ID. GetCommandLogByID 通过 ID 获取命令日志。 Returns ErrCommandLogNotFound if the command log does not exist. 如果命令日志不存在,则返回 ErrCommandLogNotFound。
func (*Repository) GetCommandLogByIDForOwner ¶
func (r *Repository) GetCommandLogByIDForOwner(ctx context.Context, id, ownerUserID uint, includeAll bool) (*CommandLog, error)
GetCommandLogByIDForOwner 按用户归属读取命令日志,管理员可查看全部。 GetCommandLogByIDForOwner loads a command log under owner scope, while administrators may view all entries.
func (*Repository) ListAuditLogs ¶
func (r *Repository) ListAuditLogs(ctx context.Context, filter *AuditLogFilter) ([]*AuditLog, int64, error)
ListAuditLogs retrieves audit logs based on filter criteria with pagination. ListAuditLogs 根据过滤条件和分页获取审计日志列表。 Returns the list of audit logs and total count. 返回审计日志列表和总数。 Requirements: 10.4 - Supports filtering by time range, action type, user, and host. 需求: 10.4 - 支持按时间范围、操作类型、用户和主机过滤。
func (*Repository) ListCommandLogs ¶
func (r *Repository) ListCommandLogs(ctx context.Context, filter *CommandLogFilter) ([]*CommandLog, int64, error)
ListCommandLogs retrieves command logs based on filter criteria with pagination. ListCommandLogs 根据过滤条件和分页获取命令日志列表。 Returns the list of command logs and total count. 返回命令日志列表和总数。 Requirements: 10.1, 10.4
func (*Repository) LookupUsername ¶ added in v1.0.0
func (r *Repository) LookupUsername(ctx context.Context, userID uint) string
LookupUsername 按用户 ID 读取登录名,供审计补齐操作人。表不存在或查不到时返回空。 LookupUsername loads the login name for an audit actor. It returns empty when the user table or row is missing.
func (*Repository) UpdateAuditLogDetailsByExecutionID ¶ added in v1.0.0
func (r *Repository) UpdateAuditLogDetailsByExecutionID(ctx context.Context, executionID string, extraDetails map[string]any) error
UpdateAuditLogDetailsByExecutionID 合并更新指定 execution_id 对应审计记录的 Details 字段。 UpdateAuditLogDetailsByExecutionID merges new key-value pairs into Details for audit logs matching execution_id.
func (*Repository) UpdateCommandLog ¶
func (r *Repository) UpdateCommandLog(ctx context.Context, log *CommandLog) error
UpdateCommandLog updates an existing command log record. UpdateCommandLog 更新现有的命令日志记录。 Returns ErrCommandLogNotFound if the command log does not exist. 如果命令日志不存在,则返回 ErrCommandLogNotFound。
func (*Repository) UpdateCommandLogStatus ¶
func (r *Repository) UpdateCommandLogStatus(ctx context.Context, id uint, updates map[string]interface{}) error
UpdateCommandLogStatus updates the status and related fields of a command log. UpdateCommandLogStatus 更新命令日志的状态和相关字段。 Returns ErrCommandLogNotFound if the command log does not exist. 如果命令日志不存在,则返回 ErrCommandLogNotFound。
type UpdateCommandLogRequest ¶
type UpdateCommandLogRequest struct {
Status *CommandStatus `json:"status"`
Progress *int `json:"progress"`
Output *string `json:"output"`
Error *string `json:"error"`
StartedAt *time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
}
UpdateCommandLogRequest represents a request to update a command log. UpdateCommandLogRequest 表示更新命令日志的请求。