api

package
v0.0.0-...-fafd483 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 17, 2026 License: AGPL-3.0 Imports: 61 Imported by: 0

Documentation

Overview

Package api — AD / LDAP 域控审计 HTTP handler (EDR-4).

Package api 提供 HTTP API 处理器。

admin_data_config.go 实现数据存储配置相关接口:

  • GET /api/v1/admin/feature-flags 列出 feature_flags
  • PUT /api/v1/admin/feature-flags/:key 更新 flag value
  • GET /api/v1/admin/retention-policies 列出 retention_policies
  • PUT /api/v1/admin/retention-policies/:ch_table 更新保留天数

修改 retention 时会立即下发 ALTER TABLE ... MODIFY TTL 到 CH。

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供配置变更审批 HTTP API (P1-1)。

路由 (RBAC: 仅 ops + admin):

POST   /api/v2/config/change-requests        — 提交变更
GET    /api/v2/config/change-requests        — 列表 (pending / approved / rejected)
GET    /api/v2/config/change-requests/:id    — 详情
POST   /api/v2/config/change-requests/:id/approve  — 审批 (admin/security_lead)
POST   /api/v2/config/change-requests/:id/reject   — 拒绝
POST   /api/v2/config/change-requests/:id/cancel   — 申请人取消
GET    /api/v2/config/change-requests/sensitivity?key=foo  — 查询某 key 所需审批数

流程:

  1. ops 提交 → status=pending
  2. admin/security_lead approve → approved_count++
  3. approved_count >= approval_required_count → status=approved
  4. Worker 周期扫 approved → 应用到 FeatureFlag.Value → status=applied
  5. 任何阶段都写 AuditLog

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api — Honeypot 蜜罐 HTTP handler (C1).

后端架构:

  • HoneypotPolicy: 诱饵投放策略表
  • HoneypotDeploymentRecord: Agent 实际投放的诱饵记录
  • alerts (source=honeypot): 命中告警

UI 概念映射:

  • sensor = 一条已部署的诱饵 (聚合自 HoneypotDeploymentRecord)
  • event = honeypot 告警 (alerts 表过滤)

Package api — host vulnerability pre-check endpoints.

让 agent 在 host 本地查询「已装包列表 + 仓库可用版本」,避免靠 server vuln DB 字符串 直接拼 dnf 命令(多次踩坑:fixed_version="0" / Debian 包给 CentOS / repo 不存在)。

Flow:

UI -> POST /host-vulnerabilities/:id/precheck            (单条)
   -> POST /hosts/:host_id/precheck-all                  (批量该 host unpatched)
   -> dispatcher.SendCommand(agent, DataType 9101)
   -> agent plugin handlePreCheck(已在 plugins/remediation/precheck.go)
   -> agent 上报 DataType 9201 (kind=precheck_result)
   -> agentcenter Service.HandlePreCheckResult
   -> biz.WritePreCheckResult -> host_vulnerabilities.precheck_*
   -> UI 周期 GET 看新状态

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api — MSSP 控制台 HTTP 路由 (A3 审计修复, 对齐 UI api/mssp.ts).

Endpoints (全部走 /api/v2/mssp/):

GET    /dashboard                  控制台汇总
GET    /child-tenants              子租户列表
POST   /child-tenants              新建子租户
GET    /child-tenants/:id          详情
POST   /child-tenants/:id/suspend  暂停
POST   /child-tenants/:id/resume   恢复
GET    /alerts                     横跨子租户告警

严格走 response.go 信封, 不直接 c.JSON.

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api — Prometheus 告警 webhook 接收。

设计:

  • Prometheus 触发告警后通过 webhook (alerting.alertmanagers 配置) POST 到此端点
  • 入 alerts 表(source=prometheus_infra)复用 mxsec 现有告警系统
  • 持久化 / 去重 / 状态机 / UI / notification 全部走现有路径,不重复造轮子

不部署 Alertmanager 的原因(避免组件重叠):

  • alerts 表已有 result_id 唯一索引 + hit_count(去重)
  • notification 系统已有 Lark/Webhook 配置(路由)
  • alert_scheduler 已有 30min repeat(重发)
  • UI 已有列表/确认/趋势(展示)

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api - reports_antivirus_data.go 病毒查杀报告数据装配。

与 reports_edr.go::BuildEDRReportData 同模式:从 MySQL 拉取 antivirus_scan_tasks / antivirus_scan_results / security_db_sync_records 装配为 gin.H 后供 JSON API + PDF 渲染共享,避免数据漂移。

数据源:

  • antivirus_scan_tasks (扫描任务元数据)
  • antivirus_scan_results (检出威胁明细)
  • security_db_sync_records (病毒库同步历史)
  • hosts (主机元数据,补全 hostname/ip)

Package api 提供 HTTP API 处理器

reports_edr.go 实现 EDR 模块的报告聚合 + 高管摘要 endpoint。 与 reports.go 中其他模块同样模式,独立文件避免污染 monolithic reports.go。

数据源:

  • MySQL alerts (source=detection/agent, category 维度告警)
  • MySQL storylines + storyline_events (攻击故事线)
  • 后续可注入 ClickHouse 查询 ebpf_events 原始事件量

Package api - reports_kube_data.go 装配 K8s 容器安全 PDF 报告原始数据。

与 reports_edr.go 同模式:纯数据装配函数,返回 gin.H,供 PDF 渲染层 (biz.RenderKubeReportHTML) 与 JSON API 共享,避免数据漂移。

数据源 (MySQL):

  • kube_clusters (集群拓扑 / 节点 / Pod / Namespace)
  • kube_alarms (运行时告警: 类型 / 严重 / Namespace / Target)
  • kube_baselines (CIS 基线: RBAC / Network / Workload / Pod)
  • kube_baseline_alerts (基线告警: active / resolved / ignored)
  • image_scans (镜像扫描汇总: 高危镜像)
  • image_vulnerabilities (镜像 CVE 详情)

Package api 提供 HTTP API 处理器。

reports_pdf.go 提供报告 PDF 导出 endpoint。

渲染流程 (v2 — server-side template):

client → manager
  ├── BuildEDRReportData (复用 JSON API 同一数据装配函数)
  ├── biz.RenderEDRReportHTML (Go html/template + 内嵌 SVG 图表)
  └── biz.PDFService.RenderHTML (POST Gotenberg /forms/chromium/convert/html)
         → 返回矢量 PDF 字节流

优势 vs 旧 SPA 拉取方式:

  • 无 SPA 登录态依赖(不会被 401 重定向到登录页)
  • 数据装配函数共享,JSON / PDF 数据一致不漂移
  • 报告模板独立维护,不耦合前端 dashboard UI
  • 可被 cron / scheduler 后台调用

Package api - reports_task_data.go 任务报告 (按 task_id 维度) 数据装配。

与 reports.go 的 GetTaskReport / GetExecutiveTaskReport 共享同一份数据源 (scan_tasks / scan_results / hosts / policies),但产出结构面向 PDF 模板, 字段命名与 biz/pdf_render_task.go 中 taskReportView 严格对齐。

PDF 渲染入口 (reports_pdf.go 中的新 handler) 调用本函数获取 gin.H, 然后传给 biz.RenderTaskReportHTML 完成 HTML 字符串渲染。

Package api 提供 HTTP API 处理器

reports_vuln_data.go 为「漏洞管理 PDF 报告」装配原始数据。

与 reports.go 的 GetVulnerabilityReport (JSON API) 互补:

  • JSON API 仅返回 UI 列表所需精简字段
  • PDF 报告需要 8 章节维度(修复进度 / SLA / 情报源 / KEV / 组件 Top 等)

本文件仅装配数据,不修改 reports.go / reports_pdf.go / pdf_render.go。 PDF endpoint 后续在 reports_pdf.go 增加 ExportVulnReportPDF 调用 BuildVulnReportData + RenderVulnReportHTML。

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api — Rootkit / DKOM 检测 HTTP handler (C2).

Package api — CEL 规则沙箱测试 endpoint (B5).

给规则编辑器用: 用户输入 expression + sample event, 立即返编译错误 / 是否命中, 不污染 detection_rules 表, 也不进 Pipeline.

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 HTTP API 处理器

Package api 提供 Manager HTTP API 处理函数

Package api 提供 HTTP API 处理器

Package api — VEX 漏洞利用性声明 HTTP handler (B7).

Route:

GET /api/v1/vex/:product_id?version=X.Y.Z              → 整份 VEX JSON
GET /api/v1/vex/:product_id/cyclonedx?version=X.Y.Z   → CycloneDX VEX 1.5 下载
GET /api/v1/vex/:product_id/csaf?version=X.Y.Z        → CSAF 2.0 下载
GET /api/v1/vex/:product_id/statements                → CVE 声明列表

Index

Constants

View Source
const (
	CodeOK = 0

	CodeInvalidParam  = 40000 // 请求参数错误
	CodeUnauthorized  = 40100 // 未授权 / 认证失败(如用户名或密码错误)
	CodeTokenExpired  = 40101 // 登录已过期 / Token 无效(前端据此跳转登录)
	CodeForbidden     = 40300 // 无权限
	CodeNotFound      = 40400 // 资源不存在
	CodeConflict      = 40900 // 资源冲突
	CodeRateLimited   = 42900 // 请求过于频繁
	CodeInternalError = 50000 // 服务器内部错误
	CodeUnavailable   = 50300 // 服务不可用(降级)
)

统一业务响应码库(HTTP 状态码扩展为 5 位)。

约定:

  • HTTP 层一律 200(业务接口),真正的错误用 body 里的 code 表达。
  • code=0 表示成功;非 0 为业务错误,前缀对齐 HTTP 语义便于阅读。
  • 例外(仍返回真实 HTTP 状态码):/health 等探针、gin panic 兜底、K8s Admission Webhook。

新增错误码时在此登记,并补 codeMessages 默认文案;前后端共同遵循此表。

Variables

View Source
var BuildVersion = "dev"

BuildVersion 构建版本,通过 -ldflags "-X ...api.BuildVersion=x.x.x" 注入

Functions

func BadRequest

func BadRequest(c *gin.Context, message string)

BadRequest 请求参数错误

func BadRequestWithData

func BadRequestWithData(c *gin.Context, message string, data interface{})

BadRequestWithData 请求参数错误(附带 data,如 need_captcha 等前端需要的标志)

func Conflict

func Conflict(c *gin.Context, message string)

Conflict 资源冲突

func Created

func Created(c *gin.Context, data interface{})

Created 创建成功响应

func Forbidden

func Forbidden(c *gin.Context, message string)

Forbidden 禁止访问

func InternalError

func InternalError(c *gin.Context, message string)

InternalError 服务器内部错误

func NotFound

func NotFound(c *gin.Context, message string)

NotFound 资源不存在

func Paginate

func Paginate(query *gorm.DB, page, pageSize int, orderBy string, dest interface{}) (int64, error)

Paginate 对 GORM query 执行分页查询,返回总数和结果切片

func ParsePagination

func ParsePagination(c *gin.Context) (page, pageSize int)

ParsePagination 从请求中解析分页参数,自动校验边界

func RegisterPolicyImportExportRoutes

func RegisterPolicyImportExportRoutes(r *gin.RouterGroup, db *gorm.DB, logger *zap.Logger)

RegisterPolicyImportExportRoutes 注册策略导入导出路由

func ReloadGlobalResolver

func ReloadGlobalResolver()

ReloadGlobalResolver 刷新全局权限缓存;无解析器时安全空操作。

func RoleMiddleware

func RoleMiddleware(allowedRoles ...string) gin.HandlerFunc

RoleMiddleware 角色权限中间件,限制只有指定角色可以访问 必须在 AuthMiddleware 之后使用(依赖 context 中的 "role" 字段)

func ServiceUnavailable

func ServiceUnavailable(c *gin.Context, message string, data interface{})

ServiceUnavailable 服务不可用(用于 /health degraded 等)

可附带 data(健康检查报告)。data 传 nil 时只返 code+message。 例外:保留真实 HTTP 503,供 LB / k8s 探针据状态码摘除降级实例。

func SetGlobalResolver

func SetGlobalResolver(r *PermissionResolver)

SetGlobalResolver 注册全局解析器(路由初始化时调用)。

func Success

func Success(c *gin.Context, data interface{})

Success 成功响应(带数据)

func SuccessMessage

func SuccessMessage(c *gin.Context, message string)

SuccessMessage 成功响应(仅消息)

func SuccessPaginated

func SuccessPaginated(c *gin.Context, total int64, items interface{})

SuccessPaginated 成功响应(分页数据)

func SuccessWithMessage

func SuccessWithMessage(c *gin.Context, message string, data interface{})

SuccessWithMessage 成功响应(带消息和数据)

func TooManyRequests

func TooManyRequests(c *gin.Context, message string)

TooManyRequests 限流响应

func Unauthorized

func Unauthorized(c *gin.Context, message string)

Unauthorized 未授权 / 认证失败(如用户名或密码错误)。不触发前端跳转登录。

func UnauthorizedExpired

func UnauthorizedExpired(c *gin.Context, message string)

UnauthorizedExpired 登录已过期 / Token 无效。前端据 code=40101 跳转登录页。

Types

type ADAuditHandler

type ADAuditHandler struct {
	// contains filtered or unexported fields
}

func NewADAuditHandler

func NewADAuditHandler(db *gorm.DB, logger *zap.Logger) *ADAuditHandler

func (*ADAuditHandler) ListAlerts

func (h *ADAuditHandler) ListAlerts(c *gin.Context)

ListAlerts GET /api/v1/ad-audit/alerts.

func (*ADAuditHandler) ListEvents

func (h *ADAuditHandler) ListEvents(c *gin.Context)

ListEvents GET /api/v1/ad-audit/events.

func (*ADAuditHandler) Stats

func (h *ADAuditHandler) Stats(c *gin.Context)

Stats GET /api/v1/ad-audit/stats.

type APIResponse

type APIResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
}

APIResponse 统一 API 响应结构

type AdminDataConfigHandler

type AdminDataConfigHandler struct {
	// contains filtered or unexported fields
}

AdminDataConfigHandler 数据存储配置处理器。

func NewAdminDataConfigHandler

func NewAdminDataConfigHandler(db *gorm.DB, chConn chdriver.Conn, logger *zap.Logger) *AdminDataConfigHandler

NewAdminDataConfigHandler 创建处理器

func (*AdminDataConfigHandler) ListFeatureFlags

func (h *AdminDataConfigHandler) ListFeatureFlags(c *gin.Context)

ListFeatureFlags 返回所有 feature_flags(按 key 字典序)。

func (*AdminDataConfigHandler) ListRetentionPolicies

func (h *AdminDataConfigHandler) ListRetentionPolicies(c *gin.Context)

ListRetentionPolicies 列出所有保留策略。

func (*AdminDataConfigHandler) UpdateFeatureFlag

func (h *AdminDataConfigHandler) UpdateFeatureFlag(c *gin.Context)

UpdateFeatureFlag 更新 flag value。修改不立即生效,consumer / manager 需重启。

func (*AdminDataConfigHandler) UpdateRetentionPolicy

func (h *AdminDataConfigHandler) UpdateRetentionPolicy(c *gin.Context)

UpdateRetentionPolicy 修改保留天数,立即下发 CH ALTER TABLE MODIFY TTL。 CH 端是元数据操作,秒级完成;旧数据下次 merge 时清理。

type AdminTenantsHandler

type AdminTenantsHandler struct {
	// contains filtered or unexported fields
}

AdminTenantsHandler 平台超管租户管理 API。

路径: /api/v2/admin/tenants/* 鉴权: tenant.AdminMiddleware() (必须 IsPlatformAdmin=true)

详见 docs/multi-tenant.md §4 + docs/api-reference.md

func NewAdminTenantsHandler

func NewAdminTenantsHandler(db *gorm.DB, logger *zap.Logger) *AdminTenantsHandler

NewAdminTenantsHandler 构造租户管理 handler。

func (*AdminTenantsHandler) CreateTenant

func (h *AdminTenantsHandler) CreateTenant(c *gin.Context)

CreateTenant POST /api/v2/admin/tenants

创建新租户。仅平台超管可调用。

func (*AdminTenantsHandler) GetTenant

func (h *AdminTenantsHandler) GetTenant(c *gin.Context)

GetTenant GET /api/v2/admin/tenants/:id

func (*AdminTenantsHandler) ListTenants

func (h *AdminTenantsHandler) ListTenants(c *gin.Context)

ListTenants GET /api/v2/admin/tenants

平台超管查看所有租户列表。普通用户被 AdminMiddleware 拦截。

func (*AdminTenantsHandler) ResumeTenant

func (h *AdminTenantsHandler) ResumeTenant(c *gin.Context)

ResumeTenant POST /api/v2/admin/tenants/:id/resume

func (*AdminTenantsHandler) SuspendTenant

func (h *AdminTenantsHandler) SuspendTenant(c *gin.Context)

SuspendTenant POST /api/v2/admin/tenants/:id/suspend

暂停租户(行级软封禁,不删除数据)。

type AgentHandler

type AgentHandler struct {
	// contains filtered or unexported fields
}

AgentHandler 是 Agent 安装脚本 API 处理器

func NewAgentHandler

func NewAgentHandler(logger *zap.Logger, serverHost, httpAddress string) *AgentHandler

NewAgentHandler 创建 Agent 安装脚本处理器

func (*AgentHandler) InstallScript

func (h *AgentHandler) InstallScript(c *gin.Context)

InstallScript 返回 Linux 安装脚本 GET /agent/install.sh

func (*AgentHandler) UninstallScript

func (h *AgentHandler) UninstallScript(c *gin.Context)

UninstallScript 返回 Linux 卸载脚本 GET /agent/uninstall.sh

type AlertAnalysisHandler

type AlertAnalysisHandler struct {
	// contains filtered or unexported fields
}

AlertAnalysisHandler LLM 告警分析 API 处理器 (P1-10: 异步队列模式).

原 AnalyzeAlert 同步调 LLM 30s 阻塞 gin worker → 改为入队 + 轮询模式:

  1. POST /analyze → 返 task_id, 后台 goroutine 跑 LLM
  2. GET /analyze/:task_id → 返结果或 pending 状态

任务结果存内存 cache, 上限 1000 条. 限并发 LLM 调用 4 个 (sem).

func NewAlertAnalysisHandler

func NewAlertAnalysisHandler(db *gorm.DB, logger *zap.Logger, cfg *config.Config) *AlertAnalysisHandler

NewAlertAnalysisHandler 创建告警分析处理器

func (*AlertAnalysisHandler) AnalyzeAlert

func (h *AlertAnalysisHandler) AnalyzeAlert(c *gin.Context)

AnalyzeAlert P1-10: 入队 + 立刻返 task_id. POST /api/v1/alerts/:id/analyze

func (*AlertAnalysisHandler) GetAnalysisResult

func (h *AlertAnalysisHandler) GetAnalysisResult(c *gin.Context)

GetAnalysisResult P1-10: 客户端轮询查结果. GET /api/v1/alerts/analysis/:task_id

type AlertContextHandler

type AlertContextHandler struct {
	// contains filtered or unexported fields
}

AlertContextHandler 告警溯源上下文 API 处理器

func NewAlertContextHandler

func NewAlertContextHandler(db *gorm.DB, chConn chdriver.Conn, logger *zap.Logger) *AlertContextHandler

NewAlertContextHandler 创建告警溯源处理器

func (*AlertContextHandler) GetAlertContext

func (h *AlertContextHandler) GetAlertContext(c *gin.Context)

GetAlertContext 获取告警溯源上下文 GET /api/v1/alerts/:id/context

type AlertWhitelistHandler

type AlertWhitelistHandler struct {
	// contains filtered or unexported fields
}

AlertWhitelistHandler 告警白名单 API 处理器

func NewAlertWhitelistHandler

func NewAlertWhitelistHandler(db *gorm.DB, logger *zap.Logger) *AlertWhitelistHandler

NewAlertWhitelistHandler 创建告警白名单 API 处理器

func (*AlertWhitelistHandler) CreateWhitelist

func (h *AlertWhitelistHandler) CreateWhitelist(c *gin.Context)

CreateWhitelist 创建白名单条目 POST /api/v1/alerts/whitelist

func (*AlertWhitelistHandler) DeleteWhitelist

func (h *AlertWhitelistHandler) DeleteWhitelist(c *gin.Context)

DeleteWhitelist 删除白名单条目 DELETE /api/v1/alerts/whitelist/:id

func (*AlertWhitelistHandler) ListWhitelist

func (h *AlertWhitelistHandler) ListWhitelist(c *gin.Context)

ListWhitelist 获取白名单列表 GET /api/v1/alerts/whitelist

func (*AlertWhitelistHandler) UpdateWhitelist

func (h *AlertWhitelistHandler) UpdateWhitelist(c *gin.Context)

UpdateWhitelist 更新白名单条目 PUT /api/v1/alerts/whitelist/:id

type AlertsHandler

type AlertsHandler struct {
	// contains filtered or unexported fields
}

AlertsHandler 告警管理 API 处理器

func NewAlertsHandler

func NewAlertsHandler(db *gorm.DB, logger *zap.Logger) *AlertsHandler

NewAlertsHandler 创建告警管理 API 处理器

func (*AlertsHandler) BatchDeleteAlerts

func (h *AlertsHandler) BatchDeleteAlerts(c *gin.Context)

BatchDeleteAlerts 批量删除告警 POST /api/v1/alerts/batch/delete

func (*AlertsHandler) BatchIgnoreAlerts

func (h *AlertsHandler) BatchIgnoreAlerts(c *gin.Context)

BatchIgnoreAlerts 批量忽略告警 POST /api/v1/alerts/batch/ignore

func (*AlertsHandler) BatchResolveAlerts

func (h *AlertsHandler) BatchResolveAlerts(c *gin.Context)

BatchResolveAlerts 批量解决告警 POST /api/v1/alerts/batch/resolve

func (*AlertsHandler) GetAlert

func (h *AlertsHandler) GetAlert(c *gin.Context)

GetAlert 获取告警详情 GET /api/v1/alerts/:id

func (*AlertsHandler) GetAlertStatistics

func (h *AlertsHandler) GetAlertStatistics(c *gin.Context)

GetAlertStatistics 获取告警统计 GET /api/v1/alerts/statistics 优化:2 条 GROUP BY 替代 8 条独立 COUNT

func (*AlertsHandler) IgnoreAlert

func (h *AlertsHandler) IgnoreAlert(c *gin.Context)

IgnoreAlert 忽略告警 POST /api/v1/alerts/:id/ignore

func (*AlertsHandler) ListAlerts

func (h *AlertsHandler) ListAlerts(c *gin.Context)

ListAlerts 获取告警列表 GET /api/v1/alerts

func (*AlertsHandler) ResolveAlert

func (h *AlertsHandler) ResolveAlert(c *gin.Context)

ResolveAlert 解决告警 POST /api/v1/alerts/:id/resolve

type AnomalyHandler

type AnomalyHandler struct {
	// contains filtered or unexported fields
}

AnomalyHandler handles ML anomaly detection API requests.

func NewAnomalyHandler

func NewAnomalyHandler(db *gorm.DB, logger *zap.Logger) *AnomalyHandler

NewAnomalyHandler creates a new anomaly detection handler.

func (*AnomalyHandler) GetAnomalyStats

func (h *AnomalyHandler) GetAnomalyStats(c *gin.Context)

GetAnomalyStats returns anomaly alert statistics. GET /api/v1/anomalies/stats

性能:原 5 query 串行 ~0.76s,合并 3 COUNT 为 1 个 conditional aggregate + 2 个 GROUP BY 并发,~50-100ms。

func (*AnomalyHandler) ListAnomalies

func (h *AnomalyHandler) ListAnomalies(c *gin.Context)

ListAnomalies returns paginated ML anomaly alerts. GET /api/v1/anomalies?host_id=xxx&alert_type=isolation_forest&severity=critical&status=open&page=1&page_size=20

func (*AnomalyHandler) ResolveAnomaly

func (h *AnomalyHandler) ResolveAnomaly(c *gin.Context)

ResolveAnomaly updates the status of an anomaly alert. PUT /api/v1/anomalies/:id/resolve

type AntivirusHandler

type AntivirusHandler struct {
	// contains filtered or unexported fields
}

AntivirusHandler 病毒查杀 API 处理器

func NewAntivirusHandler

func NewAntivirusHandler(db *gorm.DB, logger *zap.Logger, virusDBUpdater *biz.VirusDBUpdater, acDispatcher *sd.ACDispatcher) *AntivirusHandler

NewAntivirusHandler 创建病毒查杀处理器

func (*AntivirusHandler) CancelTask

func (h *AntivirusHandler) CancelTask(c *gin.Context)

CancelTask 取消扫描任务 POST /api/v1/antivirus/tasks/:id/cancel

func (*AntivirusHandler) CreateTask

func (h *AntivirusHandler) CreateTask(c *gin.Context)

CreateTask 创建扫描任务 POST /api/v1/antivirus/tasks

func (*AntivirusHandler) DeleteFileResult

func (h *AntivirusHandler) DeleteFileResult(c *gin.Context)

DeleteFileResult 删除威胁文件 POST /api/v1/antivirus/results/:id/delete-file

func (*AntivirusHandler) DeleteTask

func (h *AntivirusHandler) DeleteTask(c *gin.Context)

DeleteTask 删除扫描任务 DELETE /api/v1/antivirus/tasks/:id

func (*AntivirusHandler) GetResult

func (h *AntivirusHandler) GetResult(c *gin.Context)

GetResult 获取扫描结果详情 GET /api/v1/antivirus/results/:id

func (*AntivirusHandler) GetStatistics

func (h *AntivirusHandler) GetStatistics(c *gin.Context)

GetStatistics 获取病毒查杀统计概览 GET /api/v1/antivirus/statistics

func (*AntivirusHandler) GetTask

func (h *AntivirusHandler) GetTask(c *gin.Context)

GetTask 获取扫描任务详情 GET /api/v1/antivirus/tasks/:id

func (*AntivirusHandler) GetVirusDBHistory

func (h *AntivirusHandler) GetVirusDBHistory(c *gin.Context)

GetVirusDBHistory 获取病毒库同步历史记录 GET /api/v1/antivirus/virus-db/history

func (*AntivirusHandler) GetVirusDBStatus

func (h *AntivirusHandler) GetVirusDBStatus(c *gin.Context)

GetVirusDBStatus 获取病毒库最新同步状态 GET /api/v1/antivirus/virus-db/status

func (*AntivirusHandler) IgnoreResult

func (h *AntivirusHandler) IgnoreResult(c *gin.Context)

IgnoreResult 忽略威胁 POST /api/v1/antivirus/results/:id/ignore

func (*AntivirusHandler) ListResults

func (h *AntivirusHandler) ListResults(c *gin.Context)

ListResults 获取扫描结果列表 GET /api/v1/antivirus/results

func (*AntivirusHandler) ListTasks

func (h *AntivirusHandler) ListTasks(c *gin.Context)

ListTasks 获取扫描任务列表 GET /api/v1/antivirus/tasks

func (*AntivirusHandler) QuarantineResult

func (h *AntivirusHandler) QuarantineResult(c *gin.Context)

QuarantineResult 隔离威胁文件 POST /api/v1/antivirus/results/:id/quarantine

func (*AntivirusHandler) TriggerVirusDBSync

func (h *AntivirusHandler) TriggerVirusDBSync(c *gin.Context)

TriggerVirusDBSync 手动触发病毒库同步 POST /api/v1/antivirus/virus-db/sync

type AssetCollectionStatus

type AssetCollectionStatus struct {
	HostID          string               `json:"host_id,omitempty"`
	Scope           string               `json:"scope"`
	HasData         bool                 `json:"has_data"`
	LastCollectedAt string               `json:"last_collected_at,omitempty"`
	Level           string               `json:"level,omitempty"`
	Message         string               `json:"message,omitempty"`
	Collector       AssetCollectorStatus `json:"collector"`
}

type AssetCollectorStatus

type AssetCollectorStatus struct {
	Version         string `json:"version,omitempty"`
	ConfigEnabled   bool   `json:"config_enabled"`
	PackageUploaded bool   `json:"package_uploaded"`
	PackagePath     string `json:"package_path,omitempty"`
	HostStatus      string `json:"host_status,omitempty"`
	HostVersion     string `json:"host_version,omitempty"`
}

type AssetHistoryPoint

type AssetHistoryPoint struct {
	Timestamp  string          `json:"timestamp"`
	Total      int64           `json:"total"`
	DeltaTotal int64           `json:"delta_total"`
	Statistics AssetStatistics `json:"statistics"`
}

type AssetHistoryResult

type AssetHistoryResult struct {
	Scope             string              `json:"scope"`
	HostID            string              `json:"host_id,omitempty"`
	BusinessLine      string              `json:"business_line,omitempty"`
	TotalSnapshots    int                 `json:"total_snapshots"`
	LatestCollectedAt string              `json:"latest_collected_at,omitempty"`
	Points            []AssetHistoryPoint `json:"points"`
}

type AssetOverview

type AssetOverview struct {
	Scope             string  `json:"scope"`
	TotalHosts        int64   `json:"total_hosts"`
	CoveredHosts      int64   `json:"covered_hosts"`
	UncoveredHosts    int64   `json:"uncovered_hosts"`
	OnlineHosts       int64   `json:"online_hosts"`
	OfflineHosts      int64   `json:"offline_hosts"`
	BusinessLineCount int64   `json:"business_line_count"`
	CoverageRate      float64 `json:"coverage_rate"`
	LastCollectedAt   string  `json:"last_collected_at,omitempty"`
}

type AssetRelationApp

type AssetRelationApp struct {
	AppType    string `json:"app_type"`
	AppName    string `json:"app_name"`
	Version    string `json:"version"`
	Port       int    `json:"port"`
	ConfigPath string `json:"config_path"`
}

type AssetRelationChange

type AssetRelationChange struct {
	EventID    string `json:"event_id"`
	FilePath   string `json:"file_path"`
	ChangeType string `json:"change_type"`
	Severity   string `json:"severity"`
	Category   string `json:"category,omitempty"`
	DetectedAt string `json:"detected_at"`
}

type AssetRelationConfidence

type AssetRelationConfidence struct {
	Level     string   `json:"level"`
	MatchedBy []string `json:"matched_by,omitempty"`
}

type AssetRelationContainer

type AssetRelationContainer struct {
	ContainerID   string `json:"container_id"`
	ContainerName string `json:"container_name"`
	Image         string `json:"image"`
	Runtime       string `json:"runtime"`
	Status        string `json:"status"`
}

type AssetRelationHost

type AssetRelationHost struct {
	HostID        string            `json:"host_id"`
	Hostname      string            `json:"hostname"`
	IPv4          model.StringArray `json:"ipv4,omitempty"`
	BusinessLine  string            `json:"business_line,omitempty"`
	Status        string            `json:"status,omitempty"`
	AgentVersion  string            `json:"agent_version,omitempty"`
	RuntimeType   string            `json:"runtime_type,omitempty"`
	LastHeartbeat string            `json:"last_heartbeat,omitempty"`
}

type AssetRelationItem

type AssetRelationItem struct {
	Host            AssetRelationHost            `json:"host"`
	Process         AssetRelationProcess         `json:"process"`
	Ports           []AssetRelationPort          `json:"ports,omitempty"`
	Apps            []AssetRelationApp           `json:"apps,omitempty"`
	Software        []AssetRelationSoftware      `json:"software,omitempty"`
	Services        []AssetRelationService       `json:"services,omitempty"`
	Container       *AssetRelationContainer      `json:"container,omitempty"`
	Confidence      AssetRelationConfidence      `json:"confidence"`
	Risks           AssetRelationRiskSummary     `json:"risks"`
	Vulnerabilities []AssetRelationVulnerability `json:"vulnerabilities,omitempty"`
	RecentChanges   []AssetRelationChange        `json:"recent_changes,omitempty"`
	RelatedKinds    []string                     `json:"related_kinds"`
	RelationScore   int                          `json:"relation_score"`
}

type AssetRelationPort

type AssetRelationPort struct {
	Protocol string `json:"protocol"`
	Port     int    `json:"port"`
	State    string `json:"state"`
}

type AssetRelationProcess

type AssetRelationProcess struct {
	PID         string `json:"pid"`
	PPID        string `json:"ppid"`
	Exe         string `json:"exe"`
	Cmdline     string `json:"cmdline"`
	Username    string `json:"username"`
	ContainerID string `json:"container_id,omitempty"`
	CollectedAt string `json:"collected_at,omitempty"`
}

type AssetRelationRiskSummary

type AssetRelationRiskSummary struct {
	ExposedPortCount   int    `json:"exposed_port_count"`
	VulnerabilityCount int    `json:"vulnerability_count"`
	FIMChangeCount     int    `json:"fim_change_count"`
	LastChangedAt      string `json:"last_changed_at,omitempty"`
}

type AssetRelationService

type AssetRelationService struct {
	ServiceName string `json:"service_name"`
	ServiceType string `json:"service_type"`
	Status      string `json:"status"`
	Enabled     bool   `json:"enabled"`
}

type AssetRelationSoftware

type AssetRelationSoftware struct {
	Name         string `json:"name"`
	Version      string `json:"version"`
	PackageType  string `json:"package_type"`
	Architecture string `json:"architecture"`
}

type AssetRelationVulnerability

type AssetRelationVulnerability struct {
	CVEID          string `json:"cve_id"`
	Severity       string `json:"severity"`
	Component      string `json:"component"`
	Status         string `json:"status"`
	CurrentVersion string `json:"current_version,omitempty"`
	FixedVersion   string `json:"fixed_version,omitempty"`
}

type AssetRelationsResult

type AssetRelationsResult struct {
	Scope        string              `json:"scope"`
	HostID       string              `json:"host_id,omitempty"`
	BusinessLine string              `json:"business_line,omitempty"`
	Total        int                 `json:"total"`
	Items        []AssetRelationItem `json:"items"`
}

type AssetStatistics

type AssetStatistics struct {
	Processes         int64 `json:"processes"`
	Ports             int64 `json:"ports"`
	Users             int64 `json:"users"`
	Software          int64 `json:"software"`
	Containers        int64 `json:"containers"`
	Apps              int64 `json:"apps"`
	NetworkInterfaces int64 `json:"network_interfaces"`
	Volumes           int64 `json:"volumes"`
	Kmods             int64 `json:"kmods"`
	Services          int64 `json:"services"`
	Crons             int64 `json:"crons"`
}

type AssetTopItem

type AssetTopItem struct {
	Name  string `json:"name"`
	Value int64  `json:"value"`
}

type AssetsHandler

type AssetsHandler struct {
	// contains filtered or unexported fields
}

AssetsHandler 是资产数据 API 处理器

func NewAssetsHandler

func NewAssetsHandler(db *gorm.DB, logger *zap.Logger) *AssetsHandler

NewAssetsHandler 创建资产处理器

func (*AssetsHandler) ExportAssets

func (h *AssetsHandler) ExportAssets(c *gin.Context)

ExportAssets 导出资产数据 GET /api/v1/assets/export?type=processes|ports|users|software|containers|apps|network-interfaces|volumes|kmods|services|crons&format=csv|json&host_id=xxx

func (*AssetsHandler) ExportSBOM

func (h *AssetsHandler) ExportSBOM(c *gin.Context)

ExportSBOM 导出 CycloneDX v1.5 SBOM GET /api/v1/assets/sbom?host_id=xxx

host_id 必填:不传时全量导出 5w 软件包 + 5w 漏洞,响应体 14MB+,严重拖累 MySQL + 网关 + 客户端 IO,且全集群 SBOM 业务意义不大(SBOM 单元应是单主机/容器)。

func (*AssetsHandler) GetCollectionStatus

func (h *AssetsHandler) GetCollectionStatus(c *gin.Context)

GetCollectionStatus 获取资产采集状态 GET /api/v1/assets/status?host_id=xxx

func (*AssetsHandler) GetHistory

func (h *AssetsHandler) GetHistory(c *gin.Context)

GetHistory 获取资产历史快照 GET /api/v1/assets/history?host_id=xxx&business_line=xxx

func (*AssetsHandler) GetOverview

func (h *AssetsHandler) GetOverview(c *gin.Context)

GetOverview 获取资产总览信息 GET /api/v1/assets/overview?host_id=xxx

func (*AssetsHandler) GetRelations

func (h *AssetsHandler) GetRelations(c *gin.Context)

GetRelations 获取资产关系视图 GET /api/v1/assets/relations?host_id=xxx&business_line=xxx

func (*AssetsHandler) GetStatistics

func (h *AssetsHandler) GetStatistics(c *gin.Context)

GetStatistics 获取资产统计信息 GET /api/v1/assets/statistics?host_id=xxx

func (*AssetsHandler) GetTopN

func (h *AssetsHandler) GetTopN(c *gin.Context)

GetTopN 获取资产 TopN 聚合 GET /api/v1/assets/top?type=processes&limit=5&host_id=xxx

func (*AssetsHandler) ListApps

func (h *AssetsHandler) ListApps(c *gin.Context)

ListApps 获取应用列表 GET /api/v1/assets/apps

func (*AssetsHandler) ListContainers

func (h *AssetsHandler) ListContainers(c *gin.Context)

ListContainers 获取容器列表 GET /api/v1/assets/containers

func (*AssetsHandler) ListCrons

func (h *AssetsHandler) ListCrons(c *gin.Context)

ListCrons 获取定时任务列表 GET /api/v1/assets/crons

func (*AssetsHandler) ListKmods

func (h *AssetsHandler) ListKmods(c *gin.Context)

ListKmods 获取内核模块列表 GET /api/v1/assets/kmods

func (*AssetsHandler) ListNetInterfaces

func (h *AssetsHandler) ListNetInterfaces(c *gin.Context)

ListNetInterfaces 获取网络接口列表 GET /api/v1/assets/network-interfaces

func (*AssetsHandler) ListPorts

func (h *AssetsHandler) ListPorts(c *gin.Context)

ListPorts 获取端口列表 GET /api/v1/assets/ports

func (*AssetsHandler) ListProcesses

func (h *AssetsHandler) ListProcesses(c *gin.Context)

ListProcesses 获取进程列表 GET /api/v1/assets/processes

func (*AssetsHandler) ListServices

func (h *AssetsHandler) ListServices(c *gin.Context)

ListServices 获取系统服务列表 GET /api/v1/assets/services

func (*AssetsHandler) ListSoftware

func (h *AssetsHandler) ListSoftware(c *gin.Context)

ListSoftware 获取软件包列表 GET /api/v1/assets/software

func (*AssetsHandler) ListUsers

func (h *AssetsHandler) ListUsers(c *gin.Context)

ListUsers 获取账户列表 GET /api/v1/assets/users

func (*AssetsHandler) ListVolumes

func (h *AssetsHandler) ListVolumes(c *gin.Context)

ListVolumes 获取磁盘列表 GET /api/v1/assets/volumes

type AuditEvent

type AuditEvent = model.AuditEvent

AuditEvent K8s Audit Event 简化结构

type AuditEventList

type AuditEventList = model.AuditEventList

AuditEventList K8s Audit EventList

type AuditLogHandler

type AuditLogHandler struct {
	// contains filtered or unexported fields
}

AuditLogHandler 操作审计日志 API 处理器

func NewAuditLogHandler

func NewAuditLogHandler(db *gorm.DB, logger *zap.Logger) *AuditLogHandler

NewAuditLogHandler 创建审计日志 API 处理器

func (*AuditLogHandler) ListAuditLogs

func (h *AuditLogHandler) ListAuditLogs(c *gin.Context)

ListAuditLogs 获取审计日志列表 GET /api/v1/audit-logs

type AuditObjectRef

type AuditObjectRef = model.AuditObjectRef

AuditObjectRef Audit 事件中的对象引用

type AuditUser

type AuditUser = model.AuditUser

AuditUser Audit 事件中的用户信息

type AuthHandler

type AuthHandler struct {
	// contains filtered or unexported fields
}

AuthHandler 是认证 API 处理器

func NewAuthHandler

func NewAuthHandler(db *gorm.DB, logger *zap.Logger, secret []byte) *AuthHandler

NewAuthHandler 创建认证处理器

func (*AuthHandler) AuthMiddleware

func (h *AuthHandler) AuthMiddleware() gin.HandlerFunc

AuthMiddleware JWT 认证中间件

func (*AuthHandler) ChangePassword

func (h *AuthHandler) ChangePassword(c *gin.Context)

ChangePassword 修改当前用户密码 POST /api/v1/auth/change-password

func (*AuthHandler) EnableJWTBlacklist

func (h *AuthHandler) EnableJWTBlacklist(rdb *redis.Client)

EnableJWTBlacklist 启用登出 JWT 黑名单(需 Redis)。rdb 为 nil 时不启用。

func (*AuthHandler) GetCaptcha

func (h *AuthHandler) GetCaptcha(c *gin.Context)

GetCaptcha 生成图形验证码 GET /api/v1/auth/captcha

func (*AuthHandler) GetCurrentUser

func (h *AuthHandler) GetCurrentUser(c *gin.Context)

GetCurrentUser 获取当前用户信息 GET /api/v1/auth/me

func (*AuthHandler) Login

func (h *AuthHandler) Login(c *gin.Context)

Login 用户登录 POST /api/v1/auth/login

func (*AuthHandler) LoginPrecheck

func (h *AuthHandler) LoginPrecheck(c *gin.Context)

LoginPrecheck 返回该用户名+设备当前是否需要图形验证码,供前端决定是否展示验证码。 POST /api/v1/auth/login-precheck

func (*AuthHandler) Logout

func (h *AuthHandler) Logout(c *gin.Context)

Logout 用户登出 POST /api/v1/auth/logout

JWT 无状态,登出本质是客户端删 token。启用黑名单后额外把 token jti 写 Redis (TTL=剩余有效期),令该 token 在到期前即失效,避免登出后 token 仍可用。

type BDEBaselineHandler

type BDEBaselineHandler struct {
	// contains filtered or unexported fields
}

BDEBaselineHandler BDE 基线管理 API 处理器

func NewBDEBaselineHandler

func NewBDEBaselineHandler(db *gorm.DB, logger *zap.Logger) *BDEBaselineHandler

NewBDEBaselineHandler 创建 BDE 基线管理 API 处理器

func (*BDEBaselineHandler) GetBaselineStats

func (h *BDEBaselineHandler) GetBaselineStats(c *gin.Context)

GetBaselineStats 基线引擎统计概览

func (*BDEBaselineHandler) ListBaselineStates

func (h *BDEBaselineHandler) ListBaselineStates(c *gin.Context)

ListBaselineStates 查看所有主机基线学习状态

func (*BDEBaselineHandler) ListBehaviorAlerts

func (h *BDEBaselineHandler) ListBehaviorAlerts(c *gin.Context)

ListBehaviorAlerts 查看行为异常告警列表

type BackupsHandler

type BackupsHandler struct {
	// contains filtered or unexported fields
}

BackupsHandler 配置备份 API 处理器

func NewBackupsHandler

func NewBackupsHandler(db *gorm.DB, logger *zap.Logger) *BackupsHandler

NewBackupsHandler 创建备份处理器

func (*BackupsHandler) CreateBackup

func (h *BackupsHandler) CreateBackup(c *gin.Context)

CreateBackup 创建备份 POST /api/v1/system/backups

func (*BackupsHandler) DeleteBackup

func (h *BackupsHandler) DeleteBackup(c *gin.Context)

DeleteBackup 删除备份 DELETE /api/v1/system/backups/:id

func (*BackupsHandler) DownloadBackup

func (h *BackupsHandler) DownloadBackup(c *gin.Context)

DownloadBackup 下载备份文件 GET /api/v1/system/backups/:id/download

func (*BackupsHandler) GetBackupConfig

func (h *BackupsHandler) GetBackupConfig(c *gin.Context)

GetBackupConfig 获取自动备份配置 GET /api/v1/system/backup-config

func (*BackupsHandler) ListBackups

func (h *BackupsHandler) ListBackups(c *gin.Context)

ListBackups 获取备份列表 GET /api/v1/system/backups

func (*BackupsHandler) RestoreBackup

func (h *BackupsHandler) RestoreBackup(c *gin.Context)

RestoreBackup 恢复备份 POST /api/v1/system/backups/:id/restore

func (*BackupsHandler) UpdateBackupConfig

func (h *BackupsHandler) UpdateBackupConfig(c *gin.Context)

UpdateBackupConfig 更新自动备份配置 PUT /api/v1/system/backup-config

type BatchAlertRequest

type BatchAlertRequest struct {
	IDs    []uint `json:"ids" binding:"required"`
	Reason string `json:"reason"`
}

BatchAlertRequest 批量操作请求

type BatchDeleteQuarantineRequest

type BatchDeleteQuarantineRequest struct {
	IDs []uint `json:"ids" binding:"required,min=1"`
}

BatchDeleteRequest 批量删除请求

type BusinessLineListItem

type BusinessLineListItem struct {
	model.BusinessLine
	HostCount int `json:"host_count"`
}

BusinessLineListItem 业务线列表项(包含主机数量)

type BusinessLinesHandler

type BusinessLinesHandler struct {
	// contains filtered or unexported fields
}

BusinessLinesHandler 是业务线管理 API 处理器

func NewBusinessLinesHandler

func NewBusinessLinesHandler(db *gorm.DB, logger *zap.Logger) *BusinessLinesHandler

NewBusinessLinesHandler 创建业务线处理器

func (*BusinessLinesHandler) CreateBusinessLine

func (h *BusinessLinesHandler) CreateBusinessLine(c *gin.Context)

CreateBusinessLine 创建业务线 POST /api/v1/business-lines

func (*BusinessLinesHandler) DeleteBusinessLine

func (h *BusinessLinesHandler) DeleteBusinessLine(c *gin.Context)

DeleteBusinessLine 删除业务线 DELETE /api/v1/business-lines/:id

func (*BusinessLinesHandler) GetBusinessLine

func (h *BusinessLinesHandler) GetBusinessLine(c *gin.Context)

GetBusinessLine 获取业务线详情 GET /api/v1/business-lines/:id

func (*BusinessLinesHandler) ListBusinessLines

func (h *BusinessLinesHandler) ListBusinessLines(c *gin.Context)

ListBusinessLines 获取业务线列表 GET /api/v1/business-lines

func (*BusinessLinesHandler) UpdateBusinessLine

func (h *BusinessLinesHandler) UpdateBusinessLine(c *gin.Context)

UpdateBusinessLine 更新业务线 PUT /api/v1/business-lines/:id

type CategoryStats

type CategoryStats struct {
	Category     string  `json:"category"`      // 类别英文标识
	CategoryName string  `json:"category_name"` // 类别中文名称
	TotalChecks  int64   `json:"total_checks"`  // 总检查项
	PassedChecks int64   `json:"passed_checks"` // 通过项
	FailedChecks int64   `json:"failed_checks"` // 失败项
	PassRate     float64 `json:"pass_rate"`     // 通过率
}

CategoryStats 类别统计(用于报告摘要)

type ChangePasswordRequest

type ChangePasswordRequest struct {
	OldPassword string `json:"old_password" binding:"required"`
	NewPassword string `json:"new_password" binding:"required,min=8"`
}

ChangePasswordRequest 修改密码请求

type Claims

type Claims struct {
	Username        string `json:"username"`
	Role            string `json:"role"`
	TenantID        string `json:"tenant_id,omitempty"`
	IsPlatformAdmin bool   `json:"is_platform_admin,omitempty"`
	jwt.RegisteredClaims
}

Claims JWT Claims

v2.0 加入 TenantID / IsPlatformAdmin 字段以支持多租户。 旧版 token(仅 Username / Role)解析后 TenantID 自动回填 model.DefaultTenantID, 保证升级期间已下发的 token 仍然有效。

type ComplianceCoverage

type ComplianceCoverage struct {
	BaselineSource  string   `json:"baseline_source"`  // 基线来源
	CoveredAreas    []string `json:"covered_areas"`    // 覆盖领域
	UncoveredAreas  []string `json:"uncovered_areas"`  // 未覆盖领域
	ImprovementNote string   `json:"improvement_note"` // 改进建议
}

ComplianceCoverage 合规与基线覆盖说明

type ComponentsHandler

type ComponentsHandler struct {
	// contains filtered or unexported fields
}

ComponentsHandler 组件管理 API 处理器

func NewComponentsHandler

func NewComponentsHandler(db *gorm.DB, logger *zap.Logger, cfg *config.Config, uploadDir, urlPrefix string) *ComponentsHandler

NewComponentsHandler 创建组件管理处理器

func (*ComponentsHandler) BroadcastPluginConfigs

func (h *ComponentsHandler) BroadcastPluginConfigs(c *gin.Context)

BroadcastPluginConfigs 手动广播插件配置 POST /api/v1/components/plugins/broadcast

func (*ComponentsHandler) CheckAgentUpdate

func (h *ComponentsHandler) CheckAgentUpdate(c *gin.Context)

CheckAgentUpdate 检查 Agent 是否有可用更新 (无需认证,供 Agent CLI 调用) GET /api/v1/agent/update-check?arch=amd64&current_version=1.0.0&pkg_type=rpm

func (*ComponentsHandler) CreateComponent

func (h *ComponentsHandler) CreateComponent(c *gin.Context)

CreateComponent 创建组件 POST /api/v1/components

func (*ComponentsHandler) DeleteComponent

func (h *ComponentsHandler) DeleteComponent(c *gin.Context)

DeleteComponent 删除组件 DELETE /api/v1/components/:id

func (*ComponentsHandler) DeletePackage

func (h *ComponentsHandler) DeletePackage(c *gin.Context)

DeletePackage 删除包 DELETE /api/v1/packages/:id

func (*ComponentsHandler) DeleteVersion

func (h *ComponentsHandler) DeleteVersion(c *gin.Context)

DeleteVersion 删除版本 DELETE /api/v1/components/:id/versions/:version_id

func (*ComponentsHandler) DownloadAgentPackage

func (h *ComponentsHandler) DownloadAgentPackage(c *gin.Context)

DownloadAgentPackage 下载 Agent 安装包 (无需认证) GET /api/v1/agent/download/:pkg_type/:arch

func (*ComponentsHandler) DownloadDependencyPackage

func (h *ComponentsHandler) DownloadDependencyPackage(c *gin.Context)

DownloadDependencyPackage 下载第三方依赖包(无需认证,Agent 直接下载) GET /api/v1/dependency/download/:name?arch=amd64 从 DB 查询 category=dependency 的组件 → 最新版本 → 对应 arch 的 tgz 包

func (*ComponentsHandler) DownloadPluginPackage

func (h *ComponentsHandler) DownloadPluginPackage(c *gin.Context)

DownloadPluginPackage 下载插件包 (供 Agent 调用) GET /api/v1/plugins/download/:name

func (*ComponentsHandler) GetComponent

func (h *ComponentsHandler) GetComponent(c *gin.Context)

GetComponent 获取组件详情 GET /api/v1/components/:id

func (*ComponentsHandler) GetPluginSyncStatus

func (h *ComponentsHandler) GetPluginSyncStatus(c *gin.Context)

GetPluginSyncStatus 获取插件同步状态 GET /api/v1/components/plugin-status

func (*ComponentsHandler) GetPushRecord

func (h *ComponentsHandler) GetPushRecord(c *gin.Context)

GetPushRecord 获取推送记录详情 GET /api/v1/components/push-records/:id

func (*ComponentsHandler) GetVersion

func (h *ComponentsHandler) GetVersion(c *gin.Context)

GetVersion 获取版本详情 GET /api/v1/components/:id/versions/:version_id

func (*ComponentsHandler) ListComponents

func (h *ComponentsHandler) ListComponents(c *gin.Context)

ListComponents 获取组件列表 GET /api/v1/components

func (*ComponentsHandler) ListPushRecords

func (h *ComponentsHandler) ListPushRecords(c *gin.Context)

ListPushRecords 获取推送记录列表 GET /api/v1/components/push-records

func (*ComponentsHandler) ListVersions

func (h *ComponentsHandler) ListVersions(c *gin.Context)

ListVersions 获取组件的版本列表 GET /api/v1/components/:id/versions

func (*ComponentsHandler) PushAgentUpdate

func (h *ComponentsHandler) PushAgentUpdate(c *gin.Context)

PushAgentUpdate 手动推送 Agent 更新 POST /api/v1/components/agent/push-update

func (*ComponentsHandler) ReleaseVersion

func (h *ComponentsHandler) ReleaseVersion(c *gin.Context)

ReleaseVersion 发布新版本(仅创建版本记录,包文件单独上传) POST /api/v1/components/:id/versions

func (*ComponentsHandler) SetLatestVersion

func (h *ComponentsHandler) SetLatestVersion(c *gin.Context)

SetLatestVersion 设置为最新版本 PUT /api/v1/components/:id/versions/:version_id/set-latest

func (*ComponentsHandler) SyncAllPluginsToLatest

func (h *ComponentsHandler) SyncAllPluginsToLatest(c *gin.Context)

SyncAllPluginsToLatest 同步所有插件配置到最新版本 POST /api/v1/components/plugins/sync-latest

func (*ComponentsHandler) UploadPackage

func (h *ComponentsHandler) UploadPackage(c *gin.Context)

UploadPackage 上传包文件到指定版本 POST /api/v1/components/:id/versions/:version_id/packages

type ConfigChangeRequestHandler

type ConfigChangeRequestHandler struct {
	// contains filtered or unexported fields
}

ConfigChangeRequestHandler 配置变更审批 handler.

func NewConfigChangeRequestHandler

func NewConfigChangeRequestHandler(db *gorm.DB, logger *zap.Logger) *ConfigChangeRequestHandler

NewConfigChangeRequestHandler 构造。

func (*ConfigChangeRequestHandler) Approve

func (h *ConfigChangeRequestHandler) Approve(c *gin.Context)

Approve 审批通过。

如果 approved_count >= approval_required_count → 进 approved 状态。 单个审批人不能重复审批 (Approvers 字段 contains 检查)。

func (*ConfigChangeRequestHandler) Cancel

func (h *ConfigChangeRequestHandler) Cancel(c *gin.Context)

Cancel 申请人主动取消 (仅 pending 状态可取消)。

func (*ConfigChangeRequestHandler) Create

func (h *ConfigChangeRequestHandler) Create(c *gin.Context)

Create 提交配置变更请求。

func (*ConfigChangeRequestHandler) Get

Get 详情。

func (*ConfigChangeRequestHandler) GetSensitivity

func (h *ConfigChangeRequestHandler) GetSensitivity(c *gin.Context)

GetSensitivity 查询某 key 所需审批数。

GET /api/v2/config/change-requests/sensitivity?key=mode.global
→ {key: "mode.global", required_approval_count: 2, sensitive: true}

func (*ConfigChangeRequestHandler) List

List 列出变更请求 (按状态过滤可选)。

func (*ConfigChangeRequestHandler) Reject

func (h *ConfigChangeRequestHandler) Reject(c *gin.Context)

Reject 拒绝。

type ConfirmFIMEventRequest

type ConfirmFIMEventRequest struct {
	Reason         string `json:"reason"`
	UpdateBaseline bool   `json:"update_baseline"`
}

ConfirmFIMEventRequest 确认 FIM 事件请求

type CreateAntivirusTaskRequest

type CreateAntivirusTaskRequest struct {
	Name      string   `json:"name" binding:"required"`
	ScanType  string   `json:"scanType" binding:"required,oneof=quick full custom"`
	ScanPaths []string `json:"scanPaths"`
	HostIDs   []string `json:"hostIds" binding:"required,min=1"`
}

CreateAntivirusTaskRequest 创建扫描任务请求

type CreateBusinessLineRequest

type CreateBusinessLineRequest struct {
	Name        string `json:"name" binding:"required"` // 业务线名称
	Code        string `json:"code" binding:"required"` // 业务线代码
	Description string `json:"description"`             // 描述
	Owner       string `json:"owner"`                   // 负责人
	Contact     string `json:"contact"`                 // 联系方式
	Enabled     bool   `json:"enabled"`                 // 是否启用
}

CreateBusinessLineRequest 创建业务线请求

type CreateChangeRequestRequest

type CreateChangeRequestRequest struct {
	TargetTable   string `json:"target_table" binding:"required"` // feature_flags / kube_clusters / system_config
	TargetKey     string `json:"target_key" binding:"required"`
	ProposedValue string `json:"proposed_value" binding:"required"`
	Reason        string `json:"reason" binding:"required,min=10"` // 至少 10 字符 (审计要求)
}

CreateChangeRequestRequest 提交变更请求体。

type CreateComponentRequest

type CreateComponentRequest struct {
	Name        string `json:"name" binding:"required"`     // 组件名称
	Category    string `json:"category" binding:"required"` // 分类: agent, plugin
	Description string `json:"description"`                 // 描述
}

CreateComponentRequest 创建组件请求

type CreateFIMPolicyRequest

type CreateFIMPolicyRequest struct {
	Name                 string             `json:"name" binding:"required"`
	Description          string             `json:"description"`
	WatchPaths           model.WatchPaths   `json:"watch_paths" binding:"required"`
	ExcludePaths         model.StringArray  `json:"exclude_paths"`
	CheckIntervalHours   int                `json:"check_interval_hours"`
	TargetType           string             `json:"target_type"`
	TargetConfig         model.TargetConfig `json:"target_config"`
	EscalationTimeoutMin *int               `json:"escalation_timeout_min"`
	Enabled              *bool              `json:"enabled"`
}

CreateFIMPolicyRequest 创建 FIM 策略请求

type CreateFIMTaskRequest

type CreateFIMTaskRequest struct {
	PolicyID     string             `json:"policy_id" binding:"required"`
	TargetType   string             `json:"target_type"`
	TargetConfig model.TargetConfig `json:"target_config"`
}

CreateFIMTaskRequest 创建 FIM 任务请求

type CreateFixTaskRequest

type CreateFixTaskRequest struct {
	// 方式1:直接指定扫描结果的复合键(推荐,精确指定要修复的项)
	ResultKeys []ScanResultKey `json:"result_keys"`

	// 方式2:指定主机和规则ID
	HostIDs    []string `json:"host_ids"`
	RuleIDs    []string `json:"rule_ids"`
	Severities []string `json:"severities"`

	// 方式3:使用筛选条件(用于全选所有筛选结果)
	UseFilters   bool   `json:"use_filters"`
	BusinessLine string `json:"business_line"`
}

CreateFixTaskRequest 创建修复任务请求

type CreateNotificationRequest

type CreateNotificationRequest struct {
	Name           string                   `json:"name" binding:"required"`
	Description    string                   `json:"description"`
	NotifyCategory model.NotifyCategory     `json:"notify_category" binding:"required"`
	Enabled        bool                     `json:"enabled"`
	Type           model.NotificationType   `json:"type" binding:"required"`
	Severities     []string                 `json:"severities"`
	Scope          model.NotificationScope  `json:"scope" binding:"required"`
	ScopeValue     model.ScopeValueData     `json:"scope_value"`
	FrontendURL    string                   `json:"frontend_url"`
	Config         model.NotificationConfig `json:"config" binding:"required"`
}

CreateNotificationRequest 创建通知请求

type CreatePolicyGroupRequest

type CreatePolicyGroupRequest struct {
	ID          string `json:"id"`
	Name        string `json:"name" binding:"required"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
	Color       string `json:"color"`
	SortOrder   int    `json:"sort_order"`
	Enabled     *bool  `json:"enabled"`
}

CreatePolicyGroupRequest 创建策略组请求

type CreatePolicyRequest

type CreatePolicyRequest struct {
	ID             string                `json:"id" binding:"required"`
	Name           string                `json:"name" binding:"required"`
	Version        string                `json:"version"`
	Description    string                `json:"description"`
	OSFamily       []string              `json:"os_family"`
	OSVersion      string                `json:"os_version"`
	OSRequirements []model.OSRequirement `json:"os_requirements"` // 详细 OS 版本要求
	RuntimeTypes   []string              `json:"runtime_types"`   // 适用的运行时类型:["vm", "docker", "k8s"]
	Enabled        bool                  `json:"enabled"`
	GroupID        string                `json:"group_id"`
	Rules          []*RuleData           `json:"rules"`
}

CreatePolicyRequest 创建策略请求

type CreateRuleRequest

type CreateRuleRequest struct {
	RuleID      string            `json:"rule_id" binding:"required"`
	Category    string            `json:"category"`
	Title       string            `json:"title" binding:"required"`
	Description string            `json:"description"`
	Severity    string            `json:"severity"`
	Enabled     *bool             `json:"enabled"` // 可选,默认为 true
	CheckConfig model.CheckConfig `json:"check_config"`
	FixConfig   model.FixConfig   `json:"fix_config"`
}

CreateRuleRequest 创建规则请求

type CreateSensorReq

type CreateSensorReq struct {
	HostID   string `json:"host_id" binding:"required"`
	Kind     string `json:"kind" binding:"required"` // ssh | http | file_decoy
	BindAddr string `json:"bind_addr"`
}

CreateSensorReq 部署诱饵请求.

type CreateTaskRequest

type CreateTaskRequest struct {
	Name      string                 `json:"name" binding:"required"`
	Type      string                 `json:"type" binding:"required"`
	Targets   map[string]interface{} `json:"targets" binding:"required"`
	PolicyID  string                 `json:"policy_id"`  // 兼容旧版本:单策略
	PolicyIDs []string               `json:"policy_ids"` // 新版本:多策略
	RuleIDs   []string               `json:"rule_ids"`
	Schedule  map[string]interface{} `json:"schedule"`
}

CreateTaskRequest 创建任务请求

type CreateTenantRequest

type CreateTenantRequest struct {
	ID          string `json:"id" binding:"required,min=2,max=64"`
	Name        string `json:"name" binding:"required,min=1,max=255"`
	Type        string `json:"type" binding:"omitempty,oneof=standalone mssp_parent mssp_child internal"`
	ParentID    string `json:"parent_id"`
	DefaultMode string `json:"default_mode" binding:"omitempty,oneof=observe protect"`
	QuotaAgents int    `json:"quota_agents"`
}

CreateTenantRequest POST /api/v2/admin/tenants 请求体。

type CreateUserRequest

type CreateUserRequest struct {
	Username string `json:"username" binding:"required,min=3,max=64"`
	Password string `json:"password" binding:"required,min=8"`
	Email    string `json:"email" binding:"omitempty,email"`
	Role     string `json:"role" binding:"required,oneof=admin user"`
	Status   string `json:"status" binding:"omitempty,oneof=active inactive"`
}

CreateUserRequest 创建用户请求

type CreateWhitelistRequest

type CreateWhitelistRequest struct {
	Name         string `json:"name" binding:"required"`
	RuleID       string `json:"rule_id"`
	HostID       string `json:"host_id"`
	Category     string `json:"category"`
	Severity     string `json:"severity"`
	SourceIPCIDR string `json:"source_ip_cidr"` // 源 IP CIDR(供 ScanDetector 等使用)
	Reason       string `json:"reason"`
}

CreateWhitelistRequest 创建白名单请求

type DashboardHandler

type DashboardHandler struct {
	// contains filtered or unexported fields
}

DashboardHandler 是 Dashboard API 处理器

func NewDashboardHandler

func NewDashboardHandler(db *gorm.DB, logger *zap.Logger, chConn chdriver.Conn, redisClient *redis.Client, acRegistry *sd.Registry, promClient *prometheus.Client) *DashboardHandler

NewDashboardHandler 创建 Dashboard 处理器

func (*DashboardHandler) GetDashboardStats

func (h *DashboardHandler) GetDashboardStats(c *gin.Context)

GetDashboardStats 获取 Dashboard 统计数据 GET /api/v1/dashboard/stats

type DependencyHandler

type DependencyHandler struct {
	// contains filtered or unexported fields
}

DependencyHandler 处理依赖管理相关 API

func NewDependencyHandler

func NewDependencyHandler(db *gorm.DB, logger *zap.Logger, acDispatcher *sd.ACDispatcher) *DependencyHandler

NewDependencyHandler 创建 DependencyHandler

func (*DependencyHandler) Install

func (h *DependencyHandler) Install(c *gin.Context)

Install godoc POST /api/v1/hosts/dependency/install 向指定主机批量安装/卸载/查询依赖状态

func (*DependencyHandler) Status

func (h *DependencyHandler) Status(c *gin.Context)

Status godoc POST /api/v1/hosts/dependency/status 向指定主机查询依赖状态(通过 Agent 执行 status 命令)

type DetectionRulesHandler

type DetectionRulesHandler struct {
	// contains filtered or unexported fields
}

DetectionRulesHandler 检测规则管理 API 处理器

func NewDetectionRulesHandler

func NewDetectionRulesHandler(db *gorm.DB, logger *zap.Logger) *DetectionRulesHandler

NewDetectionRulesHandler 创建检测规则处理器

func (*DetectionRulesHandler) CreateRule

func (h *DetectionRulesHandler) CreateRule(c *gin.Context)

CreateRule 创建检测规则 POST /api/v1/detection-rules

func (*DetectionRulesHandler) DeleteRule

func (h *DetectionRulesHandler) DeleteRule(c *gin.Context)

DeleteRule 删除检测规则(内置规则不可删除,只能禁用) DELETE /api/v1/detection-rules/:id

func (*DetectionRulesHandler) GetCategories

func (h *DetectionRulesHandler) GetCategories(c *gin.Context)

GetCategories 获取规则分类列表 GET /api/v1/detection-rules/categories

func (*DetectionRulesHandler) GetMitreIDs

func (h *DetectionRulesHandler) GetMitreIDs(c *gin.Context)

GetMitreIDs 获取去重的 MITRE ATT&CK ID 列表 GET /api/v1/detection-rules/mitre-ids

func (*DetectionRulesHandler) GetRule

func (h *DetectionRulesHandler) GetRule(c *gin.Context)

GetRule 获取单条检测规则 GET /api/v1/detection-rules/:id

func (*DetectionRulesHandler) GetStatistics

func (h *DetectionRulesHandler) GetStatistics(c *gin.Context)

GetStatistics 获取规则统计 GET /api/v1/detection-rules/statistics

func (*DetectionRulesHandler) ListRules

func (h *DetectionRulesHandler) ListRules(c *gin.Context)

ListRules 获取检测规则列表 GET /api/v1/detection-rules

func (*DetectionRulesHandler) ToggleRule

func (h *DetectionRulesHandler) ToggleRule(c *gin.Context)

ToggleRule 启用/禁用检测规则 POST /api/v1/detection-rules/:id/toggle

func (*DetectionRulesHandler) UpdateRule

func (h *DetectionRulesHandler) UpdateRule(c *gin.Context)

UpdateRule 更新检测规则 PUT /api/v1/detection-rules/:id

type DiscoveryHandler

type DiscoveryHandler struct {
	// contains filtered or unexported fields
}

DiscoveryHandler 处理 AC 注册/心跳/注销 和服务发现查询

func NewDiscoveryHandler

func NewDiscoveryHandler(registry *sd.Registry, logger *zap.Logger) *DiscoveryHandler

NewDiscoveryHandler 创建 DiscoveryHandler

func (*DiscoveryHandler) Deregister

func (h *DiscoveryHandler) Deregister(c *gin.Context)

Deregister godoc DELETE /api/v1/internal/ac/deregister AC 优雅关闭时主动注销(Manager 不等探测超时即可感知)

func (*DiscoveryHandler) Heartbeat

func (h *DiscoveryHandler) Heartbeat(c *gin.Context)

Heartbeat godoc POST /api/v1/internal/ac/heartbeat AC 每 30s 上报一次心跳和连接数

func (*DiscoveryHandler) ListACInstances

func (h *DiscoveryHandler) ListACInstances(c *gin.Context)

ListACInstances godoc GET /api/v1/discovery/agentcenter 返回所有健康 AC 实例列表(Agent 侧服务发现 / 运维监控用)

func (*DiscoveryHandler) Register

func (h *DiscoveryHandler) Register(c *gin.Context)

Register godoc POST /api/v1/internal/ac/register AC 启动时向 Manager 注册自身

type EDREventStats

type EDREventStats struct {
	Total uint64 `json:"total"`
	// 按事件类型统计
	ProcessExec    uint64 `json:"process_exec"`
	FileOpen       uint64 `json:"file_open"`
	NetworkConnect uint64 `json:"network_connect"`
	// 按 DataType 统计
	ByDataType map[int32]uint64 `json:"by_data_type"`
	// Top 10 主机
	TopHosts []EDRHostEventCount `json:"top_hosts"`
	// Top 10 可执行文件
	TopExes []EDRExeCount `json:"top_exes"`
	// 趋势(按小时)
	Trend []EDREventTrendPoint `json:"trend"`
}

EDREventStats EDR 事件统计

type EDREventTrendPoint

type EDREventTrendPoint struct {
	Time  string `json:"time"`
	Count uint64 `json:"count"`
}

EDREventTrendPoint 趋势数据点

type EDREventsHandler

type EDREventsHandler struct {
	// contains filtered or unexported fields
}

EDREventsHandler EDR 事件查询处理器(数据源:ClickHouse ebpf_events)

func NewEDREventsHandler

func NewEDREventsHandler(logger *zap.Logger, chConn chdriver.Conn, redisClient *redis.Client) *EDREventsHandler

NewEDREventsHandler 创建 EDR 事件处理器 chConn 为 nil 时返回空数据;redisClient 为 nil 时 stats 不走 cache(每次实时计算)

func (*EDREventsHandler) GetEDREventDetail

func (h *EDREventsHandler) GetEDREventDetail(c *gin.Context)

GetEDREventDetail 单条 EDR 事件完整详情。 GET /api/v1/edr/events/detail?host_id=&timestamp=&pid=

列表已返回 8 关键列(lite),详情字段(cmdline / parent_exe / local_addr / protocol / uid / gid / return_code) 走此 endpoint 单独 lazy fetch。host_id + timestamp + pid 复合定位单行,主键命中 <10ms。

func (*EDREventsHandler) GetEDREventStats

func (h *EDREventsHandler) GetEDREventStats(c *gin.Context)

GetEDREventStats 获取 EDR 事件统计 GET /api/v1/edr/events/stats

性能策略:

  1. Redis cache 60s TTL,warm hit <10ms(stats 5 个 GROUP BY 在 1 分钟内变化幅度可忽略)
  2. 5 个 CH 聚合查询并发执行(冷查),总延迟 ≈ max(各 query) ≈ stats_top_hosts (~1.9s)
  3. cache miss / 失败时 fall back 实时计算

func (*EDREventsHandler) ListEDREvents

func (h *EDREventsHandler) ListEDREvents(c *gin.Context)

ListEDREvents 获取 EDR 事件列表 GET /api/v1/edr/events

type EDRExeCount

type EDRExeCount struct {
	Exe   string `json:"exe"`
	Count uint64 `json:"count"`
}

EDRExeCount 可执行文件事件数

type EDRHostEventCount

type EDRHostEventCount struct {
	HostID   string `json:"host_id"`
	Hostname string `json:"hostname"`
	Count    uint64 `json:"count"`
}

EDRHostEventCount 主机事件数

type ExecutiveReportMeta

type ExecutiveReportMeta struct {
	ReportID     string `json:"report_id"`     // 报告编号
	ReportTitle  string `json:"report_title"`  // 报告标题
	GeneratedAt  string `json:"generated_at"`  // 生成时间
	CompanyName  string `json:"company_name"`  // 公司名称
	BaselineType string `json:"baseline_type"` // 基线类型
	CheckTarget  string `json:"check_target"`  // 检查对象描述
}

ExecutiveReportMeta 管理层报告元数据

type ExecutiveSummary

type ExecutiveSummary struct {
	OverallConclusion   string  `json:"overall_conclusion"`   // 总体结论
	CheckScope          string  `json:"check_scope"`          // 检查范围描述
	ComplianceRate      float64 `json:"compliance_rate"`      // 合规率
	HasCriticalRisk     bool    `json:"has_critical_risk"`    // 是否存在严重风险
	HasHighRisk         bool    `json:"has_high_risk"`        // 是否存在高危风险
	ConclusionStatement string  `json:"conclusion_statement"` // 结论陈述
	CoverageNote        string  `json:"coverage_note"`        // 覆盖范围说明
}

ExecutiveSummary 执行摘要

type ExecutiveTaskReport

type ExecutiveTaskReport struct {
	Meta           ExecutiveReportMeta      `json:"meta"`
	Summary        ExecutiveSummary         `json:"summary"`
	TaskInfo       TaskReportSummary        `json:"task_info"`
	Statistics     TaskReportStatistics     `json:"statistics"`
	CategoryStats  []CategoryStats          `json:"category_stats"` // 按类别统计(含通过率)
	SecurityScore  SecurityScore            `json:"security_score"`
	HostDetails    []HostCheckDetail        `json:"host_details"`
	RiskItems      []RiskItem               `json:"risk_items"`
	FailedRules    []FailedRuleSummary      `json:"failed_rules"`
	Coverage       ComplianceCoverage       `json:"coverage"`
	Recommendation ManagementRecommendation `json:"recommendation"`
}

ExecutiveTaskReport 管理层任务报告(完整版)

type FIMBaselinesHandler

type FIMBaselinesHandler struct {
	// contains filtered or unexported fields
}

FIMBaselinesHandler FIM 基线管理处理器

func NewFIMBaselinesHandler

func NewFIMBaselinesHandler(db *gorm.DB, logger *zap.Logger) *FIMBaselinesHandler

NewFIMBaselinesHandler 创建 FIM 基线处理器

func (*FIMBaselinesHandler) ApproveBaseline

func (h *FIMBaselinesHandler) ApproveBaseline(c *gin.Context)

ApproveBaseline 审批基线

func (*FIMBaselinesHandler) BatchApproveBaselines

func (h *FIMBaselinesHandler) BatchApproveBaselines(c *gin.Context)

BatchApproveBaselines 批量审批基线

func (*FIMBaselinesHandler) GetBaseline

func (h *FIMBaselinesHandler) GetBaseline(c *gin.Context)

GetBaseline 获取基线详情(含条目分页)

func (*FIMBaselinesHandler) ListBaselines

func (h *FIMBaselinesHandler) ListBaselines(c *gin.Context)

ListBaselines 获取基线列表

func (*FIMBaselinesHandler) RejectBaseline

func (h *FIMBaselinesHandler) RejectBaseline(c *gin.Context)

RejectBaseline 拒绝基线(删除候选基线及其条目)

type FIMEventStats

type FIMEventStats struct {
	Total    int64 `json:"total"`
	Pending  int64 `json:"pending"`
	Critical int64 `json:"critical"`
	High     int64 `json:"high"`
	Medium   int64 `json:"medium"`
	Low      int64 `json:"low"`
	// 按变更类型统计
	Added   int64 `json:"added"`
	Removed int64 `json:"removed"`
	Changed int64 `json:"changed"`
	// 按分类统计
	ByCategory map[string]int64 `json:"by_category"`
	// Top 主机
	TopHosts []FIMHostEventCount `json:"top_hosts"`
	// 趋势数据
	Trend []FIMEventTrendPoint `json:"trend"`
}

FIMEventStats FIM 事件统计响应

type FIMEventTrendPoint

type FIMEventTrendPoint struct {
	Date  string `json:"date"`
	Count int64  `json:"count"`
}

FIMEventTrendPoint 事件趋势数据点

type FIMEventsHandler

type FIMEventsHandler struct {
	// contains filtered or unexported fields
}

FIMEventsHandler FIM 事件处理器

func NewFIMEventsHandler

func NewFIMEventsHandler(db *gorm.DB, logger *zap.Logger, chConn chdriver.Conn) *FIMEventsHandler

NewFIMEventsHandler 创建 FIM 事件处理器 chConn 可为 nil;为 nil 时退化为纯 MySQL 查询

func (*FIMEventsHandler) BatchConfirmFIMEvents

func (h *FIMEventsHandler) BatchConfirmFIMEvents(c *gin.Context)

BatchConfirmFIMEvents 批量确认 FIM 事件

func (*FIMEventsHandler) ConfirmFIMEvent

func (h *FIMEventsHandler) ConfirmFIMEvent(c *gin.Context)

ConfirmFIMEvent 确认 FIM 事件为合法变更

func (*FIMEventsHandler) GetFIMEvent

func (h *FIMEventsHandler) GetFIMEvent(c *gin.Context)

GetFIMEvent 获取单个 FIM 事件详情(始终走 MySQL,CH 无主键 event_id)

func (*FIMEventsHandler) GetFIMEventStats

func (h *FIMEventsHandler) GetFIMEventStats(c *gin.Context)

GetFIMEventStats 获取 FIM 事件统计 ClickHouse 可用时从 CH 查询(支持大数据量聚合);否则 fallback MySQL

func (*FIMEventsHandler) ListFIMEvents

func (h *FIMEventsHandler) ListFIMEvents(c *gin.Context)

ListFIMEvents 获取 FIM 事件列表 ClickHouse 可用时优先从 CH 查询(低延迟、支持大数据量);否则 fallback MySQL

type FIMHostEventCount

type FIMHostEventCount struct {
	HostID   string `json:"host_id"`
	Hostname string `json:"hostname"`
	Count    int64  `json:"count"`
}

FIMHostEventCount 主机事件数统计

type FIMPoliciesHandler

type FIMPoliciesHandler struct {
	// contains filtered or unexported fields
}

FIMPoliciesHandler FIM 策略管理处理器

func NewFIMPoliciesHandler

func NewFIMPoliciesHandler(db *gorm.DB, logger *zap.Logger) *FIMPoliciesHandler

NewFIMPoliciesHandler 创建 FIM 策略处理器

func (*FIMPoliciesHandler) CreateFIMPolicy

func (h *FIMPoliciesHandler) CreateFIMPolicy(c *gin.Context)

CreateFIMPolicy 创建 FIM 策略

func (*FIMPoliciesHandler) DeleteFIMPolicy

func (h *FIMPoliciesHandler) DeleteFIMPolicy(c *gin.Context)

DeleteFIMPolicy 删除 FIM 策略

func (*FIMPoliciesHandler) GetFIMPolicy

func (h *FIMPoliciesHandler) GetFIMPolicy(c *gin.Context)

GetFIMPolicy 获取单个 FIM 策略

func (*FIMPoliciesHandler) ListFIMPolicies

func (h *FIMPoliciesHandler) ListFIMPolicies(c *gin.Context)

ListFIMPolicies 获取 FIM 策略列表

func (*FIMPoliciesHandler) UpdateFIMPolicy

func (h *FIMPoliciesHandler) UpdateFIMPolicy(c *gin.Context)

UpdateFIMPolicy 更新 FIM 策略

type FIMTasksHandler

type FIMTasksHandler struct {
	// contains filtered or unexported fields
}

FIMTasksHandler FIM 任务管理处理器

func NewFIMTasksHandler

func NewFIMTasksHandler(db *gorm.DB, logger *zap.Logger) *FIMTasksHandler

NewFIMTasksHandler 创建 FIM 任务处理器

func (*FIMTasksHandler) CreateFIMTask

func (h *FIMTasksHandler) CreateFIMTask(c *gin.Context)

CreateFIMTask 创建 FIM 任务

func (*FIMTasksHandler) GetFIMTask

func (h *FIMTasksHandler) GetFIMTask(c *gin.Context)

GetFIMTask 获取单个 FIM 任务详情

func (*FIMTasksHandler) ListFIMTasks

func (h *FIMTasksHandler) ListFIMTasks(c *gin.Context)

ListFIMTasks 获取 FIM 任务列表

func (*FIMTasksHandler) RunFIMTask

func (h *FIMTasksHandler) RunFIMTask(c *gin.Context)

RunFIMTask 执行 FIM 任务(标记为 running,实际调度由 AgentCenter 处理)

type FailedRuleSummary

type FailedRuleSummary struct {
	RuleID        string   `json:"rule_id"`
	Title         string   `json:"title"`
	Severity      string   `json:"severity"`
	Category      string   `json:"category"`
	AffectedHosts []string `json:"affected_hosts"`
	AffectedCount int      `json:"affected_count"`
	FixSuggestion string   `json:"fix_suggestion"`
	Expected      string   `json:"expected"`
}

FailedRuleSummary 失败规则汇总

type FixHandler

type FixHandler struct {
	// contains filtered or unexported fields
}

FixHandler 是基线修复 API 处理器

func NewFixHandler

func NewFixHandler(db *gorm.DB, logger *zap.Logger, acDispatcher *sd.ACDispatcher) *FixHandler

NewFixHandler 创建修复处理器

func (*FixHandler) CancelFixTask

func (h *FixHandler) CancelFixTask(c *gin.Context)

CancelFixTask 取消修复任务

func (*FixHandler) CreateFixTask

func (h *FixHandler) CreateFixTask(c *gin.Context)

CreateFixTask 创建修复任务

func (*FixHandler) DeleteFixTask

func (h *FixHandler) DeleteFixTask(c *gin.Context)

DeleteFixTask 删除修复任务

func (*FixHandler) GetFixResults

func (h *FixHandler) GetFixResults(c *gin.Context)

GetFixResults 获取修复结果

func (*FixHandler) GetFixTask

func (h *FixHandler) GetFixTask(c *gin.Context)

GetFixTask 获取修复任务详情

func (*FixHandler) GetFixTaskHostStatus

func (h *FixHandler) GetFixTaskHostStatus(c *gin.Context)

GetFixTaskHostStatus 获取修复任务主机状态列表

func (*FixHandler) GetFixableItems

func (h *FixHandler) GetFixableItems(c *gin.Context)

GetFixableItems 获取可修复项列表

func (*FixHandler) ListFixTasks

func (h *FixHandler) ListFixTasks(c *gin.Context)

ListFixTasks 获取修复任务列表

type FixResultResponse

type FixResultResponse struct {
	model.FixResult
	Hostname string `json:"hostname"`
	Title    string `json:"title"`
}

FixResultResponse 修复结果响应

type FixableItemResponse

type FixableItemResponse struct {
	TaskID        string `json:"task_id"`
	HostID        string `json:"host_id"`
	Hostname      string `json:"hostname"`
	IP            string `json:"ip"`
	BusinessLine  string `json:"business_line"`
	RuleID        string `json:"rule_id"`
	Title         string `json:"title"`
	Category      string `json:"category"`
	Severity      string `json:"severity"`
	FixSuggestion string `json:"fix_suggestion"`
	FixCommand    string `json:"fix_command"`
	Actual        string `json:"actual"`
	Expected      string `json:"expected"`
	HasFix        bool   `json:"has_fix"`
}

FixableItemResponse 可修复项响应

type HealthHandler

type HealthHandler struct {
	// contains filtered or unexported fields
}

HealthHandler 是健康检查 API 处理器

func NewHealthHandler

func NewHealthHandler(db *gorm.DB, logger *zap.Logger) *HealthHandler

NewHealthHandler 创建健康检查处理器

func (*HealthHandler) Health

func (h *HealthHandler) Health(c *gin.Context)

Health 健康检查端点 GET /health

func (*HealthHandler) Version

func (h *HealthHandler) Version(c *gin.Context)

Version GET /api/v1/system/version 返回 manager 构建版本(外部健康检查 / 监控轮询用)

type HealthResponse

type HealthResponse struct {
	Status    string            `json:"status"`            // 总体状态: "ok" 或 "degraded"
	Timestamp string            `json:"timestamp"`         // 检查时间戳
	Checks    map[string]string `json:"checks"`            // 各项检查结果
	Version   string            `json:"version,omitempty"` // 版本信息(可选)
}

HealthResponse 健康检查响应

type HoneypotHandler

type HoneypotHandler struct {
	// contains filtered or unexported fields
}

func NewHoneypotHandler

func NewHoneypotHandler(db *gorm.DB, logger *zap.Logger) *HoneypotHandler

func (*HoneypotHandler) CreateSensor

func (h *HoneypotHandler) CreateSensor(c *gin.Context)

CreateSensor 创建/部署一个诱饵 (写 deployment 记录). POST /api/v1/v2/honeypot/sensors

func (*HoneypotHandler) ListEvents

func (h *HoneypotHandler) ListEvents(c *gin.Context)

ListEvents 列出蜜罐告警 (alerts 表 source=honeypot). GET /api/v1/v2/honeypot/events

func (*HoneypotHandler) ListSensors

func (h *HoneypotHandler) ListSensors(c *gin.Context)

ListSensors 列出诱饵传感器 (聚合 HoneypotDeploymentRecord). GET /api/v1/v2/honeypot/sensors

func (*HoneypotHandler) StopSensor

func (h *HoneypotHandler) StopSensor(c *gin.Context)

StopSensor 停止一个诱饵 (删除 deployment 记录). POST /api/v1/v2/honeypot/sensors/:id/stop

type HostCheckDetail

type HostCheckDetail struct {
	HostID        string  `json:"host_id"`
	Hostname      string  `json:"hostname"`
	IP            string  `json:"ip"`
	OSFamily      string  `json:"os_family"`
	PassedCount   int64   `json:"passed_count"`
	FailedCount   int64   `json:"failed_count"`
	WarningCount  int64   `json:"warning_count"`
	NACount       int64   `json:"na_count"`
	Score         float64 `json:"score"`
	Status        string  `json:"status"` // pass/warning/fail
	CriticalFails int64   `json:"critical_fails"`
	HighFails     int64   `json:"high_fails"`
}

HostCheckDetail 主机检查明细

type HostIsolationHandler

type HostIsolationHandler struct {
	// contains filtered or unexported fields
}

HostIsolationHandler handles host network isolation API requests.

func NewHostIsolationHandler

func NewHostIsolationHandler(db *gorm.DB, logger *zap.Logger, acDispatcher *sd.ACDispatcher) *HostIsolationHandler

NewHostIsolationHandler creates a new host isolation handler.

func (*HostIsolationHandler) GetIsolationStatus

func (h *HostIsolationHandler) GetIsolationStatus(c *gin.Context)

GetIsolationStatus returns the isolation status of a host. GET /api/v1/hosts/:host_id/isolation-status

func (*HostIsolationHandler) IsolateHost

func (h *HostIsolationHandler) IsolateHost(c *gin.Context)

IsolateHost enables network isolation on a host. POST /api/v1/hosts/isolate

func (*HostIsolationHandler) ListIsolations

func (h *HostIsolationHandler) ListIsolations(c *gin.Context)

ListIsolations returns all isolation records with pagination. GET /api/v1/hosts/isolations?status=active&page=1&page_size=20

func (*HostIsolationHandler) ReleaseHost

func (h *HostIsolationHandler) ReleaseHost(c *gin.Context)

ReleaseHost removes network isolation from a host. POST /api/v1/hosts/release

type HostListItem

type HostListItem struct {
	model.Host
	BaselineScore    int     `json:"baseline_score"`
	BaselinePassRate float64 `json:"baseline_pass_rate"`
}

HostListItem 主机列表项(包含基线得分)

type HostPluginResponse

type HostPluginResponse struct {
	ID            uint   `json:"id"`
	Name          string `json:"name"`
	Version       string `json:"version"`
	Status        string `json:"status"`
	StartTime     string `json:"start_time,omitempty"`
	UpdatedAt     string `json:"updated_at"`
	LatestVersion string `json:"latest_version"`
	NeedUpdate    bool   `json:"need_update"`
}

HostPluginResponse 主机插件响应

type HostRiskDistribution

type HostRiskDistribution struct {
	Critical int64 `json:"critical"` // 存在严重风险基线的主机数
	High     int64 `json:"high"`     // 存在高危风险基线的主机数
	Medium   int64 `json:"medium"`   // 存在中危风险基线的主机数
	Low      int64 `json:"low"`      // 存在低危风险基线的主机数
}

HostRiskDistribution 主机基线风险分布统计(按严重程度)

type HostRiskStatistics

type HostRiskStatistics struct {
	// 安全告警统计
	Alerts struct {
		Total    int64 `json:"total"`    // 未处理告警总数
		Critical int64 `json:"critical"` // 严重
		High     int64 `json:"high"`     // 高危
		Medium   int64 `json:"medium"`   // 中危
		Low      int64 `json:"low"`      // 低危
	} `json:"alerts"`
	// 漏洞风险统计
	Vulnerabilities struct {
		Total    int64 `json:"total"`    // 未处理高可利用漏洞总数
		Critical int64 `json:"critical"` // 严重
		High     int64 `json:"high"`     // 高危
		Medium   int64 `json:"medium"`   // 中危
		Low      int64 `json:"low"`      // 低危
	} `json:"vulnerabilities"`
	// 基线风险统计
	Baseline struct {
		Total    int64 `json:"total"`    // 待加固基线总数
		Critical int64 `json:"critical"` // 严重(基线中通常没有critical,但保留字段)
		High     int64 `json:"high"`     // 高危
		Medium   int64 `json:"medium"`   // 中危
		Low      int64 `json:"low"`      // 低危
	} `json:"baseline"`
}

HostRiskStatistics 主机风险统计

type HostStatusDistribution

type HostStatusDistribution struct {
	Running      int64 `json:"running"`       // 运行中
	Abnormal     int64 `json:"abnormal"`      // 运行异常
	Offline      int64 `json:"offline"`       // 离线
	NotInstalled int64 `json:"not_installed"` // 未安装
	Uninstalled  int64 `json:"uninstalled"`   // 已卸载
}

HostStatusDistribution 主机状态分布统计

type HostVulnPreCheckHandler

type HostVulnPreCheckHandler struct {
	// contains filtered or unexported fields
}

HostVulnPreCheckHandler 主机漏洞预检 API

func NewHostVulnPreCheckHandler

func NewHostVulnPreCheckHandler(db *gorm.DB, logger *zap.Logger, dispatcher *sd.ACDispatcher) *HostVulnPreCheckHandler

func (*HostVulnPreCheckHandler) CreateForAllOnline

func (h *HostVulnPreCheckHandler) CreateForAllOnline(c *gin.Context)

CreateForAllOnline 全集群所有 online 主机的 unpatched 漏洞批量 pre-check POST /api/v1/host-vulnerabilities/precheck-all-online

与 CreateForHostAll 同样的过滤条件(unchecked / failed / >24h stale), 区别是遍历所有 online host。Admin 权限保护以避免普通用户打满集群。

单 host 单次 dispatch ≤ maxBatchPerHost;超出部分留给下轮 cron(每 6h)。

func (*HostVulnPreCheckHandler) CreateForHostAll

func (h *HostVulnPreCheckHandler) CreateForHostAll(c *gin.Context)

CreateForHostAll 该 host 全部 unpatched 漏洞批量 pre-check POST /api/v1/hosts/:host_id/precheck-all

func (*HostVulnPreCheckHandler) CreateForHostVuln

func (h *HostVulnPreCheckHandler) CreateForHostVuln(c *gin.Context)

CreateForHostVuln 单条 host_vulnerability pre-check POST /api/v1/host-vulnerabilities/:id/precheck

type HostsHandler

type HostsHandler struct {
	// contains filtered or unexported fields
}

HostsHandler 是主机管理 API 处理器

func NewHostsHandler

func NewHostsHandler(db *gorm.DB, logger *zap.Logger, scoreCache *biz.BaselineScoreCache, metricsService *biz.MetricsService) *HostsHandler

NewHostsHandler 创建主机处理器

func (*HostsHandler) BatchDeleteHost

func (h *HostsHandler) BatchDeleteHost(c *gin.Context)

BatchDeleteHost 批量删除主机 POST /api/v1/hosts/batch-delete

func (*HostsHandler) BatchUpdateBusinessLine

func (h *HostsHandler) BatchUpdateBusinessLine(c *gin.Context)

BatchUpdateBusinessLine 批量更新主机业务线 POST /api/v1/hosts/batch-update-business-line

func (*HostsHandler) BatchUpdateTags

func (h *HostsHandler) BatchUpdateTags(c *gin.Context)

BatchUpdateTags 批量更新主机标签 POST /api/v1/hosts/batch-update-tags

func (*HostsHandler) DeleteHost

func (h *HostsHandler) DeleteHost(c *gin.Context)

DeleteHost 删除主机 DELETE /api/v1/hosts/:host_id

func (*HostsHandler) GetHost

func (h *HostsHandler) GetHost(c *gin.Context)

GetHost 获取主机详情 GET /api/v1/hosts/:host_id

func (*HostsHandler) GetHostMetrics

func (h *HostsHandler) GetHostMetrics(c *gin.Context)

GetHostMetrics 获取主机监控数据 GET /api/v1/hosts/:host_id/metrics

func (*HostsHandler) GetHostPlugins

func (h *HostsHandler) GetHostPlugins(c *gin.Context)

GetHostPlugins 获取主机插件列表 GET /api/v1/hosts/:host_id/plugins

func (*HostsHandler) GetHostRiskDistribution

func (h *HostsHandler) GetHostRiskDistribution(c *gin.Context)

GetHostRiskDistribution 获取主机基线风险分布(按严重程度) GET /api/v1/hosts/risk-distribution 优化:单次 GROUP BY 替代 4 条 DISTINCT 查询

func (*HostsHandler) GetHostRiskStatistics

func (h *HostsHandler) GetHostRiskStatistics(c *gin.Context)

GetHostRiskStatistics 获取主机风险统计 GET /api/v1/hosts/:host_id/risk-statistics

func (*HostsHandler) GetHostStatusDistribution

func (h *HostsHandler) GetHostStatusDistribution(c *gin.Context)

GetHostStatusDistribution 获取主机状态分布 GET /api/v1/hosts/status-distribution

func (*HostsHandler) GetRestartRecords

func (h *HostsHandler) GetRestartRecords(c *gin.Context)

GetRestartRecords 获取 Agent 重启记录 GET /api/v1/hosts/restart-records

func (*HostsHandler) ListHosts

func (h *HostsHandler) ListHosts(c *gin.Context)

ListHosts 获取主机列表 GET /api/v1/hosts

func (*HostsHandler) RestartAgent

func (h *HostsHandler) RestartAgent(c *gin.Context)

RestartAgent 重启 Agent POST /api/v1/hosts/restart-agent

func (*HostsHandler) UpdateHostBusinessLine

func (h *HostsHandler) UpdateHostBusinessLine(c *gin.Context)

UpdateHostBusinessLine 更新主机业务线 PUT /api/v1/hosts/:host_id/business-line

func (*HostsHandler) UpdateHostTags

func (h *HostsHandler) UpdateHostTags(c *gin.Context)

UpdateHostTags 更新主机标签 PUT /api/v1/hosts/:host_id/tags

type HuntingHandler

type HuntingHandler struct {
	// contains filtered or unexported fields
}

HuntingHandler 威胁狩猎 API 处理器

func NewHuntingHandler

func NewHuntingHandler(db *gorm.DB, chConn chdriver.Conn, logger *zap.Logger) *HuntingHandler

NewHuntingHandler 创建威胁狩猎 API 处理器

func (*HuntingHandler) CreateSavedQuery

func (h *HuntingHandler) CreateSavedQuery(c *gin.Context)

CreateSavedQuery 保存狩猎查询 POST /api/v1/hunting/queries

func (*HuntingHandler) DeleteSavedQuery

func (h *HuntingHandler) DeleteSavedQuery(c *gin.Context)

DeleteSavedQuery 删除保存的狩猎查询 DELETE /api/v1/hunting/queries/:id

func (*HuntingHandler) ExecuteQuery

func (h *HuntingHandler) ExecuteQuery(c *gin.Context)

ExecuteQuery 执行 MQL 查询 POST /api/v1/hunting/query

func (*HuntingHandler) ListSavedQueries

func (h *HuntingHandler) ListSavedQueries(c *gin.Context)

ListSavedQueries 获取保存的狩猎查询列表 GET /api/v1/hunting/queries

type ImageScansHandler

type ImageScansHandler struct {
	// contains filtered or unexported fields
}

ImageScansHandler 镜像扫描 API 处理器

func NewImageScansHandler

func NewImageScansHandler(db *gorm.DB, logger *zap.Logger) *ImageScansHandler

NewImageScansHandler 创建处理器

func (*ImageScansHandler) CreateRegistry

func (h *ImageScansHandler) CreateRegistry(c *gin.Context)

CreateRegistry 添加 Registry

func (*ImageScansHandler) DeleteRegistry

func (h *ImageScansHandler) DeleteRegistry(c *gin.Context)

DeleteRegistry 删除 Registry

func (*ImageScansHandler) GetScan

func (h *ImageScansHandler) GetScan(c *gin.Context)

GetScan 扫描详情

func (*ImageScansHandler) GetScanVulns

func (h *ImageScansHandler) GetScanVulns(c *gin.Context)

GetScanVulns 镜像漏洞列表

func (*ImageScansHandler) ListRegistries

func (h *ImageScansHandler) ListRegistries(c *gin.Context)

ListRegistries Registry 列表

func (*ImageScansHandler) ListScans

func (h *ImageScansHandler) ListScans(c *gin.Context)

ListScans 扫描记录列表

func (*ImageScansHandler) ScanImage

func (h *ImageScansHandler) ScanImage(c *gin.Context)

ScanImage 触发镜像扫描

func (*ImageScansHandler) ScanRegistryImages

func (h *ImageScansHandler) ScanRegistryImages(c *gin.Context)

ScanRegistryImages 触发 Registry 批量扫描

func (*ImageScansHandler) UpdateRegistry

func (h *ImageScansHandler) UpdateRegistry(c *gin.Context)

UpdateRegistry 更新 Registry

type InspectionHandler

type InspectionHandler struct {
	// contains filtered or unexported fields
}

InspectionHandler 运维巡检 API 处理器

func NewInspectionHandler

func NewInspectionHandler(db *gorm.DB, logger *zap.Logger) *InspectionHandler

NewInspectionHandler 创建巡检处理器

func (*InspectionHandler) GetOverview

func (h *InspectionHandler) GetOverview(c *gin.Context)

GetOverview 获取巡检概览 GET /api/v1/inspection/overview

type InspectionHostItem

type InspectionHostItem struct {
	HostID         string            `json:"host_id"`
	Hostname       string            `json:"hostname"`
	IPv4           model.StringArray `json:"ipv4"`
	Status         model.HostStatus  `json:"status"`
	AgentVersion   string            `json:"agent_version"`
	AgentStartTime *model.LocalTime  `json:"agent_start_time"`
	SystemBootTime *model.LocalTime  `json:"system_boot_time"`
	LastHeartbeat  *model.LocalTime  `json:"last_heartbeat"`
	OSFamily       string            `json:"os_family"`
	OSVersion      string            `json:"os_version"`
	Arch           string            `json:"arch"`
	RuntimeType    string            `json:"runtime_type"`
	BusinessLine   string            `json:"business_line"`
	Plugins        []PluginStatus    `json:"plugins"`
}

InspectionHostItem 巡检主机项

type InspectionOverviewResponse

type InspectionOverviewResponse struct {
	Summary              InspectionSummary    `json:"summary"`
	LatestAgentVersion   string               `json:"latest_agent_version"`
	LatestPluginVersions map[string]string    `json:"latest_plugin_versions"`
	Hosts                []InspectionHostItem `json:"hosts"`
}

InspectionOverviewResponse 巡检概览响应

type InspectionSummary

type InspectionSummary struct {
	TotalHosts          int `json:"total_hosts"`
	OnlineHosts         int `json:"online_hosts"`
	OfflineHosts        int `json:"offline_hosts"`
	AgentOutdatedCount  int `json:"agent_outdated_count"`
	PluginErrorCount    int `json:"plugin_error_count"`
	PluginOutdatedCount int `json:"plugin_outdated_count"`
}

InspectionSummary 巡检统计摘要

type KubeAlarmHandler

type KubeAlarmHandler struct {
	// contains filtered or unexported fields
}

KubeAlarmHandler 容器告警 API Handler

func NewKubeAlarmHandler

func NewKubeAlarmHandler(db *gorm.DB, logger *zap.Logger) *KubeAlarmHandler

NewKubeAlarmHandler 创建容器告警 Handler

func (*KubeAlarmHandler) BatchIgnoreAlarms

func (h *KubeAlarmHandler) BatchIgnoreAlarms(c *gin.Context)

BatchIgnoreAlarms 批量忽略告警

func (*KubeAlarmHandler) BatchProcessAlarms

func (h *KubeAlarmHandler) BatchProcessAlarms(c *gin.Context)

BatchProcessAlarms 批量处理告警

func (*KubeAlarmHandler) ListAlarms

func (h *KubeAlarmHandler) ListAlarms(c *gin.Context)

ListAlarms 告警列表(含统计)

func (*KubeAlarmHandler) ProcessAlarm

func (h *KubeAlarmHandler) ProcessAlarm(c *gin.Context)

ProcessAlarm 处理单个告警

type KubeAuditHandler

type KubeAuditHandler struct {
	// contains filtered or unexported fields
}

KubeAuditHandler K8s Audit Webhook 接收端

func NewKubeAuditHandler

func NewKubeAuditHandler(db *gorm.DB, logger *zap.Logger, alarmService *kube.KubeAlarmService) *KubeAuditHandler

NewKubeAuditHandler 创建 Audit Webhook Handler

func (*KubeAuditHandler) ReceiveAuditWebhook

func (h *KubeAuditHandler) ReceiveAuditWebhook(c *gin.Context)

ReceiveAuditWebhook 接收 K8s apiserver 的 audit webhook 回调

type KubeBaselineAlertHandler

type KubeBaselineAlertHandler struct {
	// contains filtered or unexported fields
}

KubeBaselineAlertHandler 容器基线告警 API Handler

func NewKubeBaselineAlertHandler

func NewKubeBaselineAlertHandler(db *gorm.DB, logger *zap.Logger) *KubeBaselineAlertHandler

NewKubeBaselineAlertHandler 创建容器基线告警 Handler

func (*KubeBaselineAlertHandler) BatchIgnoreAlerts

func (h *KubeBaselineAlertHandler) BatchIgnoreAlerts(c *gin.Context)

BatchIgnoreAlerts 批量忽略基线告警

func (*KubeBaselineAlertHandler) IgnoreAlert

func (h *KubeBaselineAlertHandler) IgnoreAlert(c *gin.Context)

IgnoreAlert 忽略基线告警

func (*KubeBaselineAlertHandler) ListAlerts

func (h *KubeBaselineAlertHandler) ListAlerts(c *gin.Context)

ListAlerts 基线告警列表

type KubeBaselineHandler

type KubeBaselineHandler struct {
	// contains filtered or unexported fields
}

KubeBaselineHandler 基线检查 API Handler

func NewKubeBaselineHandler

func NewKubeBaselineHandler(db *gorm.DB, logger *zap.Logger, checker *biz.KubeBaselineChecker) *KubeBaselineHandler

NewKubeBaselineHandler 创建基线检查 Handler

func (*KubeBaselineHandler) GetBaselineDetail

func (h *KubeBaselineHandler) GetBaselineDetail(c *gin.Context)

GetBaselineDetail 基线检查项详情

func (*KubeBaselineHandler) ListBaseline

func (h *KubeBaselineHandler) ListBaseline(c *gin.Context)

ListBaseline 基线检查列表(含统计)

func (*KubeBaselineHandler) RunBaselineCheck

func (h *KubeBaselineHandler) RunBaselineCheck(c *gin.Context)

RunBaselineCheck 执行基线检查

type KubeBaselineRulesHandler

type KubeBaselineRulesHandler struct {
	// contains filtered or unexported fields
}

KubeBaselineRulesHandler 容器基线规则管理 API Handler

func NewKubeBaselineRulesHandler

func NewKubeBaselineRulesHandler(db *gorm.DB, logger *zap.Logger, checker *biz.KubeBaselineChecker, ruleEngine *kube.KubeRuleEngine) *KubeBaselineRulesHandler

NewKubeBaselineRulesHandler 创建基线规则管理 Handler

func (*KubeBaselineRulesHandler) CreateExpressionTemplate

func (h *KubeBaselineRulesHandler) CreateExpressionTemplate(c *gin.Context)

CreateExpressionTemplate 新增表达式模板 POST /api/v1/kube/baseline-rules/expression-templates

func (*KubeBaselineRulesHandler) CreateRule

func (h *KubeBaselineRulesHandler) CreateRule(c *gin.Context)

CreateRule 新增基线规则 POST /api/v1/kube/baseline-rules

func (*KubeBaselineRulesHandler) DeleteExpressionTemplate

func (h *KubeBaselineRulesHandler) DeleteExpressionTemplate(c *gin.Context)

DeleteExpressionTemplate 删除表达式模板 DELETE /api/v1/kube/baseline-rules/expression-templates/:id

func (*KubeBaselineRulesHandler) DeleteRule

func (h *KubeBaselineRulesHandler) DeleteRule(c *gin.Context)

DeleteRule 删除基线规则 DELETE /api/v1/kube/baseline-rules/:id

func (*KubeBaselineRulesHandler) ExportRules

func (h *KubeBaselineRulesHandler) ExportRules(c *gin.Context)

ExportRules 导出规则为 JSON GET /api/v1/kube/baseline-rules/export

func (*KubeBaselineRulesHandler) GetExpressionTemplates

func (h *KubeBaselineRulesHandler) GetExpressionTemplates(c *gin.Context)

GetExpressionTemplates 获取 CEL 表达式模板列表 GET /api/v1/kube/baseline-rules/expression-templates

func (*KubeBaselineRulesHandler) GetRule

func (h *KubeBaselineRulesHandler) GetRule(c *gin.Context)

GetRule 获取单条基线规则 GET /api/v1/kube/baseline-rules/:id

func (*KubeBaselineRulesHandler) ImportRules

func (h *KubeBaselineRulesHandler) ImportRules(c *gin.Context)

ImportRules 导入规则 POST /api/v1/kube/baseline-rules/import

func (*KubeBaselineRulesHandler) ListRules

func (h *KubeBaselineRulesHandler) ListRules(c *gin.Context)

ListRules 基线规则列表 GET /api/v1/kube/baseline-rules

func (*KubeBaselineRulesHandler) ToggleRule

func (h *KubeBaselineRulesHandler) ToggleRule(c *gin.Context)

ToggleRule 启用/禁用切换 PUT /api/v1/kube/baseline-rules/:id/toggle

func (*KubeBaselineRulesHandler) UpdateExpressionTemplate

func (h *KubeBaselineRulesHandler) UpdateExpressionTemplate(c *gin.Context)

UpdateExpressionTemplate 编辑表达式模板 PUT /api/v1/kube/baseline-rules/expression-templates/:id

func (*KubeBaselineRulesHandler) UpdateRule

func (h *KubeBaselineRulesHandler) UpdateRule(c *gin.Context)

UpdateRule 编辑基线规则 PUT /api/v1/kube/baseline-rules/:id

func (*KubeBaselineRulesHandler) ValidateExpression

func (h *KubeBaselineRulesHandler) ValidateExpression(c *gin.Context)

ValidateExpression 验证 CEL 表达式 POST /api/v1/kube/baseline-rules/validate-expression

type KubeClusterHandler

type KubeClusterHandler struct {
	// contains filtered or unexported fields
}

KubeClusterHandler 集群管理 API Handler

func NewKubeClusterHandler

func NewKubeClusterHandler(db *gorm.DB, logger *zap.Logger, kubeClient *biz.KubeClientManager, cfg *config.Config, consumerManager *gcppubsub.ConsumerManager) *KubeClusterHandler

NewKubeClusterHandler 创建集群管理 Handler

func (*KubeClusterHandler) CreateCluster

func (h *KubeClusterHandler) CreateCluster(c *gin.Context)

CreateCluster 接入集群

func (*KubeClusterHandler) DeleteCluster

func (h *KubeClusterHandler) DeleteCluster(c *gin.Context)

DeleteCluster 删除集群

func (*KubeClusterHandler) DeleteGCPConfig

func (h *KubeClusterHandler) DeleteGCPConfig(c *gin.Context)

DeleteGCPConfig 清除集群的 GCP Pub/Sub 配置

func (*KubeClusterHandler) GetCluster

func (h *KubeClusterHandler) GetCluster(c *gin.Context)

GetCluster 集群详情(含实时 K8s 数据)

func (*KubeClusterHandler) GetClusterNodes

func (h *KubeClusterHandler) GetClusterNodes(c *gin.Context)

GetClusterNodes Node 列表(实时查 K8s API)

func (*KubeClusterHandler) GetClusterPods

func (h *KubeClusterHandler) GetClusterPods(c *gin.Context)

GetClusterPods Pod 列表(实时查 K8s API,支持分页和过滤)

func (*KubeClusterHandler) GetClusterWorkloads

func (h *KubeClusterHandler) GetClusterWorkloads(c *gin.Context)

GetClusterWorkloads Workload 列表(实时查 K8s API)

func (*KubeClusterHandler) ListClusters

func (h *KubeClusterHandler) ListClusters(c *gin.Context)

ListClusters 集群列表

func (*KubeClusterHandler) RegenerateAuditToken

func (h *KubeClusterHandler) RegenerateAuditToken(c *gin.Context)

RegenerateAuditToken 重新生成集群的 audit_token

func (*KubeClusterHandler) UpdateCluster

func (h *KubeClusterHandler) UpdateCluster(c *gin.Context)

UpdateCluster 更新集群

func (*KubeClusterHandler) UpdateGCPConfig

func (h *KubeClusterHandler) UpdateGCPConfig(c *gin.Context)

UpdateGCPConfig 配置集群的 GCP Pub/Sub 参数

type KubeEventHandler

type KubeEventHandler struct {
	// contains filtered or unexported fields
}

KubeEventHandler 容器安全事件 API Handler

func NewKubeEventHandler

func NewKubeEventHandler(db *gorm.DB, logger *zap.Logger) *KubeEventHandler

NewKubeEventHandler 创建容器安全事件 Handler

func (*KubeEventHandler) HandleEvent

func (h *KubeEventHandler) HandleEvent(c *gin.Context)

HandleEvent 处理单个事件

func (*KubeEventHandler) ListEvents

func (h *KubeEventHandler) ListEvents(c *gin.Context)

ListEvents 事件列表

type KubeStatsHandler

type KubeStatsHandler struct {
	// contains filtered or unexported fields
}

KubeStatsHandler 容器安全统计 API Handler

func NewKubeStatsHandler

func NewKubeStatsHandler(db *gorm.DB, logger *zap.Logger) *KubeStatsHandler

NewKubeStatsHandler 创建统计 Handler

func (*KubeStatsHandler) GetAlarmTrend

func (h *KubeStatsHandler) GetAlarmTrend(c *gin.Context)

GetAlarmTrend 告警趋势(最近 N 天每天的告警数量)

func (*KubeStatsHandler) GetSummary

func (h *KubeStatsHandler) GetSummary(c *gin.Context)

GetSummary 容器安全概览统计

type KubeWhitelistHandler

type KubeWhitelistHandler struct {
	// contains filtered or unexported fields
}

KubeWhitelistHandler 容器告警白名单 API Handler

func NewKubeWhitelistHandler

func NewKubeWhitelistHandler(db *gorm.DB, logger *zap.Logger) *KubeWhitelistHandler

NewKubeWhitelistHandler 创建白名单 Handler

func (*KubeWhitelistHandler) CreateWhitelist

func (h *KubeWhitelistHandler) CreateWhitelist(c *gin.Context)

CreateWhitelist 创建白名单

func (*KubeWhitelistHandler) DeleteWhitelist

func (h *KubeWhitelistHandler) DeleteWhitelist(c *gin.Context)

DeleteWhitelist 删除白名单

func (*KubeWhitelistHandler) ListWhitelist

func (h *KubeWhitelistHandler) ListWhitelist(c *gin.Context)

ListWhitelist 白名单列表

func (*KubeWhitelistHandler) UpdateWhitelist

func (h *KubeWhitelistHandler) UpdateWhitelist(c *gin.Context)

UpdateWhitelist 更新白名单

type ListAlertsRequest

type ListAlertsRequest struct {
	Page         int    `form:"page" binding:"omitempty,min=1"`
	PageSize     int    `form:"page_size" binding:"omitempty,min=1,max=100"`
	Status       string `form:"status"`   // active, resolved, ignored
	Severity     string `form:"severity"` // critical, high, medium, low
	HostID       string `form:"host_id"`
	RuleID       string `form:"rule_id"`
	Category     string `form:"category"`
	AlertType    string `form:"alert_type"`    // baseline, runtime, agent, vulnerability, fim, virus, kube
	Keyword      string `form:"keyword"`       // 搜索标题或描述
	ResultID     string `form:"result_id"`     // 根据 result_id 查询
	RuntimeType  string `form:"runtime_type"`  // vm, docker, k8s
	BusinessLine string `form:"business_line"` // 按业务线过滤
	MitreID      string `form:"mitre_id"`      // 按 MITRE ATT&CK ID 过滤
	StartTime    string `form:"start_time"`    // 时间范围起 (RFC3339)
	EndTime      string `form:"end_time"`      // 时间范围止 (RFC3339)
}

ListAlertsRequest 获取告警列表请求

type ListAuditLogsRequest

type ListAuditLogsRequest struct {
	Page         int    `form:"page" binding:"omitempty,min=1"`
	PageSize     int    `form:"page_size" binding:"omitempty,min=1,max=100"`
	Username     string `form:"username"`
	Action       string `form:"action"`        // POST/PUT/DELETE
	ResourceType string `form:"resource_type"` // hosts/policies 等
	StartTime    string `form:"start_time"`    // 2006-01-02 15:04:05
	EndTime      string `form:"end_time"`
}

ListAuditLogsRequest 查询审计日志列表请求

type ListUsersRequest

type ListUsersRequest struct {
	Page     int    `form:"page" binding:"omitempty,min=1"`
	PageSize int    `form:"page_size" binding:"omitempty,min=1,max=100"`
	Username string `form:"username"`
	Role     string `form:"role"`
	Status   string `form:"status"`
}

ListUsersRequest 用户列表请求

type ListUsersResponse

type ListUsersResponse struct {
	Total int64        `json:"total"`
	Items []model.User `json:"items"`
}

ListUsersResponse 用户列表响应

type ListWhitelistRequest

type ListWhitelistRequest struct {
	Page     int    `form:"page" binding:"omitempty,min=1"`
	PageSize int    `form:"page_size" binding:"omitempty,min=1,max=100"`
	Keyword  string `form:"keyword"`
}

ListWhitelistRequest 查询白名单列表请求

type LoginPrecheckRequest

type LoginPrecheckRequest struct {
	Username string `json:"username" binding:"required"`
	DeviceID string `json:"device_id"`
}

LoginPrecheckRequest 登录预检请求

type LoginRequest

type LoginRequest struct {
	Username    string `json:"username" binding:"required"`
	Password    string `json:"password" binding:"required"`
	CaptchaID   string `json:"captcha_id"`
	CaptchaCode string `json:"captcha_code"`
	DeviceID    string `json:"device_id"` // 浏览器本地生成的设备标识,用于可信设备判定
}

LoginRequest 登录请求 CaptchaID/CaptchaCode 改为可选:仅在风控判定需要验证码时才校验。

type LoginResponse

type LoginResponse struct {
	Token string `json:"token"`
	User  struct {
		Username string `json:"username"`
		Role     string `json:"role"`
	} `json:"user"`
}

LoginResponse 登录响应

type MSSPHandler

type MSSPHandler struct {
	// contains filtered or unexported fields
}

MSSPHandler 多租户托管 console.

func NewMSSPHandler

func NewMSSPHandler(svc *mssp.Service, logger *zap.Logger) *MSSPHandler

NewMSSPHandler 构造.

func (*MSSPHandler) CreateChildTenant

func (h *MSSPHandler) CreateChildTenant(c *gin.Context)

CreateChildTenant POST /mssp/child-tenants.

func (*MSSPHandler) CrossTenantAlerts

func (h *MSSPHandler) CrossTenantAlerts(c *gin.Context)

CrossTenantAlerts GET /mssp/alerts.

func (*MSSPHandler) Dashboard

func (h *MSSPHandler) Dashboard(c *gin.Context)

Dashboard GET /mssp/dashboard.

func (*MSSPHandler) GetChildTenant

func (h *MSSPHandler) GetChildTenant(c *gin.Context)

GetChildTenant GET /mssp/child-tenants/:id.

func (*MSSPHandler) ListChildTenants

func (h *MSSPHandler) ListChildTenants(c *gin.Context)

ListChildTenants GET /mssp/child-tenants.

func (*MSSPHandler) ResumeChildTenant

func (h *MSSPHandler) ResumeChildTenant(c *gin.Context)

ResumeChildTenant POST /mssp/child-tenants/:id/resume.

func (*MSSPHandler) SuspendChildTenant

func (h *MSSPHandler) SuspendChildTenant(c *gin.Context)

SuspendChildTenant POST /mssp/child-tenants/:id/suspend.

type ManagementRecommendation

type ManagementRecommendation struct {
	OverallAssessment string   `json:"overall_assessment"` // 总体评估
	ActionSuggestions []string `json:"action_suggestions"` // 行动建议
	Disclaimer        string   `json:"disclaimer"`         // 声明
}

ManagementRecommendation 管理建议

type MemoryThreatHandler

type MemoryThreatHandler struct {
	// contains filtered or unexported fields
}

MemoryThreatHandler 内存威胁 API 处理器

func NewMemoryThreatHandler

func NewMemoryThreatHandler(db *gorm.DB, logger *zap.Logger) *MemoryThreatHandler

NewMemoryThreatHandler 创建内存威胁 API 处理器

func (*MemoryThreatHandler) GetMemoryThreatStats

func (h *MemoryThreatHandler) GetMemoryThreatStats(c *gin.Context)

GetMemoryThreatStats 内存威胁统计概览

性能:原 4 个 COUNT 串行 ~1s,合并成 1 个 SELECT 多个 conditional aggregate + 1 个 GROUP BY,2 query 并发后 ~50-100ms。

func (*MemoryThreatHandler) ListMemoryThreats

func (h *MemoryThreatHandler) ListMemoryThreats(c *gin.Context)

ListMemoryThreats 查看内存威胁列表

func (*MemoryThreatHandler) ResolveMemoryThreat

func (h *MemoryThreatHandler) ResolveMemoryThreat(c *gin.Context)

ResolveMemoryThreat 标记内存威胁为已处理

type MigrationHandler

type MigrationHandler struct {
	// contains filtered or unexported fields
}

MigrationHandler 迁移助手 API 处理器

func NewMigrationHandler

func NewMigrationHandler(db *gorm.DB, logger *zap.Logger) *MigrationHandler

NewMigrationHandler 创建迁移处理器

func (*MigrationHandler) CancelJob

func (h *MigrationHandler) CancelJob(c *gin.Context)

CancelJob 取消运行中的迁移任务 POST /api/v1/system/migration/jobs/:id/cancel

func (*MigrationHandler) GetJob

func (h *MigrationHandler) GetJob(c *gin.Context)

GetJob 获取迁移任务详情 GET /api/v1/system/migration/jobs/:id

func (*MigrationHandler) ListJobs

func (h *MigrationHandler) ListJobs(c *gin.Context)

ListJobs 列出历史迁移任务 GET /api/v1/system/migration/jobs

func (*MigrationHandler) StartJob

func (h *MigrationHandler) StartJob(c *gin.Context)

StartJob 创建并启动迁移任务 POST /api/v1/system/migration/jobs

func (*MigrationHandler) TestConnection

func (h *MigrationHandler) TestConnection(c *gin.Context)

TestConnection 测试与 MVP1 的连接 POST /api/v1/system/migration/test-connection

type MonitorHandler

type MonitorHandler struct {
	// contains filtered or unexported fields
}

MonitorHandler 是系统监控 API 处理器

func NewMonitorHandler

func NewMonitorHandler(cfg *config.Config, db *gorm.DB, chConn chdriver.Conn, promClient *prometheus.Client, acRegistry *sd.Registry, logger *zap.Logger, redisClient *redis.Client) *MonitorHandler

NewMonitorHandler 创建 MonitorHandler

func (*MonitorHandler) AckServiceAlert

func (h *MonitorHandler) AckServiceAlert(c *gin.Context)

AckServiceAlert 确认服务告警 POST /api/v1/monitor/service-alerts/:id/ack

func (*MonitorHandler) GetHostMonitor

func (h *MonitorHandler) GetHostMonitor(c *gin.Context)

GetHostMonitor godoc GET /api/v1/monitor/host?range=1h|6h|24h 返回全局主机资源使用概览 + 时间序列趋势(聚合所有在线 Agent 上报数据)

func (*MonitorHandler) GetSLO

func (h *MonitorHandler) GetSLO(c *gin.Context)

GetSLO godoc GET /api/v1/monitor/slo?range=30d

返回各服务的可用性(uptime ratio)+ Error Budget(剩余可允许的不可用时间)。 默认目标 SLO 99.9% (允许 30 天内停机 43min)。

func (*MonitorHandler) GetServiceAlerts

func (h *MonitorHandler) GetServiceAlerts(c *gin.Context)

GetServiceAlerts 获取服务告警列表 GET /api/v1/monitor/service-alerts

func (*MonitorHandler) GetServiceHistory

func (h *MonitorHandler) GetServiceHistory(c *gin.Context)

GetServiceHistory godoc GET /api/v1/monitor/services/:name/history?range=1h|6h|24h&metric=cpu|memory|qps|p99|error_rate|goroutines|fds|gc_pause_p99

返回指定服务+指标的时间序列。基于 Prometheus range query。 不缓存(用户主动刷新趋势图),但 Prometheus 自身 scrape interval 决定数据粒度。

func (*MonitorHandler) GetServicesMonitor

func (h *MonitorHandler) GetServicesMonitor(c *gin.Context)

type NetworkBlockHandler

type NetworkBlockHandler struct {
	// contains filtered or unexported fields
}

NetworkBlockHandler 网络阻断 API 处理器

func NewNetworkBlockHandler

func NewNetworkBlockHandler(db *gorm.DB, logger *zap.Logger, acDispatcher *sd.ACDispatcher) *NetworkBlockHandler

NewNetworkBlockHandler 创建网络阻断处理器

func (*NetworkBlockHandler) CreateRule

func (h *NetworkBlockHandler) CreateRule(c *gin.Context)

CreateRule 创建阻断规则 POST /api/v1/network-block/rules

func (*NetworkBlockHandler) DeleteRule

func (h *NetworkBlockHandler) DeleteRule(c *gin.Context)

DeleteRule 删除阻断规则记录 DELETE /api/v1/network-block/rules/:id

func (*NetworkBlockHandler) ListRules

func (h *NetworkBlockHandler) ListRules(c *gin.Context)

ListRules 查询阻断规则列表 GET /api/v1/network-block/rules?host_id=xxx&status=active&page=1&page_size=20

func (*NetworkBlockHandler) RemoveRule

func (h *NetworkBlockHandler) RemoveRule(c *gin.Context)

RemoveRule 移除阻断规则(解除阻断) POST /api/v1/network-block/rules/:id/remove

type NotificationsHandler

type NotificationsHandler struct {
	// contains filtered or unexported fields
}

NotificationsHandler 通知管理 API 处理器

func NewNotificationsHandler

func NewNotificationsHandler(db *gorm.DB, logger *zap.Logger) *NotificationsHandler

NewNotificationsHandler 创建通知处理器

func (*NotificationsHandler) CreateNotification

func (h *NotificationsHandler) CreateNotification(c *gin.Context)

CreateNotification 创建通知 POST /api/v1/notifications

func (*NotificationsHandler) DeleteNotification

func (h *NotificationsHandler) DeleteNotification(c *gin.Context)

DeleteNotification 删除通知 DELETE /api/v1/notifications/:id

func (*NotificationsHandler) GetNotification

func (h *NotificationsHandler) GetNotification(c *gin.Context)

GetNotification 获取通知详情 GET /api/v1/notifications/:id

func (*NotificationsHandler) ListNotifications

func (h *NotificationsHandler) ListNotifications(c *gin.Context)

ListNotifications 获取通知列表 GET /api/v1/notifications

func (*NotificationsHandler) TestNotification

func (h *NotificationsHandler) TestNotification(c *gin.Context)

TestNotification 测试通知 POST /api/v1/notifications/test

func (*NotificationsHandler) UpdateNotification

func (h *NotificationsHandler) UpdateNotification(c *gin.Context)

UpdateNotification 更新通知 PUT /api/v1/notifications/:id

type PaginatedData

type PaginatedData struct {
	Total int64       `json:"total"`
	Items interface{} `json:"items"`
}

PaginatedData 分页数据结构

type PermissionResolver

type PermissionResolver struct {
	// contains filtered or unexported fields
}

PermissionResolver 让 role_permissions 表真正参与放行判定(纵向越权防护)。

缓存 role -> {permCode} 集合,避免每请求查库;UpdateRolePermissions 后调 Reload 失效刷新。 admin 角色拥有全部权限,直接放行。

func NewPermissionResolver

func NewPermissionResolver(db *gorm.DB, logger *zap.Logger) *PermissionResolver

NewPermissionResolver 构造并立即加载一次缓存。

func (*PermissionResolver) EnforceWritePermissions

func (r *PermissionResolver) EnforceWritePermissions() gin.HandlerFunc

EnforceWritePermissions 是挂在 apiV1Auth 组上的中间件: 对写操作按所属模块校验当前角色是否拥有对应权限 code,缺失则 403。 读操作(GET/HEAD/OPTIONS)与未登记模块放行。admin 角色恒通过。

func (*PermissionResolver) Has

func (r *PermissionResolver) Has(role, code string) bool

Has 判断角色是否拥有某权限 code。admin 恒为 true。

func (*PermissionResolver) Reload

func (r *PermissionResolver) Reload() error

Reload 从 role_permissions 全量重建缓存。

type PluginStatus

type PluginStatus struct {
	Name          string `json:"name"`
	Version       string `json:"version"`
	Status        string `json:"status"`
	LatestVersion string `json:"latest_version"`
	NeedUpdate    bool   `json:"need_update"`
}

PluginStatus 插件状态

type PluginsHandler

type PluginsHandler struct {
	// contains filtered or unexported fields
}

PluginsHandler 处理插件相关请求

func NewPluginsHandler

func NewPluginsHandler(logger *zap.Logger, pluginsDir string) *PluginsHandler

NewPluginsHandler 创建 PluginsHandler 实例

func (*PluginsHandler) DownloadPlugin

func (h *PluginsHandler) DownloadPlugin(c *gin.Context)

DownloadPlugin 下载插件文件 GET /api/v1/plugins/download/:name 支持 ?arch=amd64|arm64 参数指定架构

func (*PluginsHandler) ListPlugins

func (h *PluginsHandler) ListPlugins(c *gin.Context)

ListPlugins 列出可用插件 GET /api/v1/plugins

type PoliciesHandler

type PoliciesHandler struct {
	// contains filtered or unexported fields
}

PoliciesHandler 是策略管理 API 处理器

func NewPoliciesHandler

func NewPoliciesHandler(db *gorm.DB, logger *zap.Logger) *PoliciesHandler

NewPoliciesHandler 创建策略处理器

func (*PoliciesHandler) BatchDelete

func (h *PoliciesHandler) BatchDelete(c *gin.Context)

BatchDelete 批量删除策略

func (*PoliciesHandler) BatchEnableDisable

func (h *PoliciesHandler) BatchEnableDisable(c *gin.Context)

BatchEnableDisable 批量启用/禁用策略

func (*PoliciesHandler) BatchExport

func (h *PoliciesHandler) BatchExport(c *gin.Context)

BatchExport 批量导出策略

func (*PoliciesHandler) CreatePolicy

func (h *PoliciesHandler) CreatePolicy(c *gin.Context)

CreatePolicy 创建策略 POST /api/v1/policies

func (*PoliciesHandler) DeletePolicy

func (h *PoliciesHandler) DeletePolicy(c *gin.Context)

DeletePolicy 删除策略 DELETE /api/v1/policies/:policy_id

func (*PoliciesHandler) GetPolicy

func (h *PoliciesHandler) GetPolicy(c *gin.Context)

GetPolicy 获取策略详情 GET /api/v1/policies/:policy_id

func (*PoliciesHandler) GetPolicyStatistics

func (h *PoliciesHandler) GetPolicyStatistics(c *gin.Context)

GetPolicyStatistics 获取策略统计信息 GET /api/v1/policies/:policy_id/statistics

func (*PoliciesHandler) ListPolicies

func (h *PoliciesHandler) ListPolicies(c *gin.Context)

ListPolicies 获取策略列表 GET /api/v1/policies

func (*PoliciesHandler) UpdatePolicy

func (h *PoliciesHandler) UpdatePolicy(c *gin.Context)

UpdatePolicy 更新策略 PUT /api/v1/policies/:policy_id

type PolicyExportFormat

type PolicyExportFormat struct {
	ID          string             `json:"id"`
	Name        string             `json:"name"`
	Version     string             `json:"version"`
	Description string             `json:"description"`
	OSFamily    []string           `json:"os_family"`
	OSVersion   string             `json:"os_version,omitempty"`
	Enabled     bool               `json:"enabled"`
	Rules       []RuleExportFormat `json:"rules"`
}

PolicyExportFormat 策略导出格式(匹配 JSON 配置文件格式)

type PolicyGroupsHandler

type PolicyGroupsHandler struct {
	// contains filtered or unexported fields
}

PolicyGroupsHandler 是策略组管理 API 处理器

func NewPolicyGroupsHandler

func NewPolicyGroupsHandler(db *gorm.DB, logger *zap.Logger) *PolicyGroupsHandler

NewPolicyGroupsHandler 创建策略组处理器

func (*PolicyGroupsHandler) CreatePolicyGroup

func (h *PolicyGroupsHandler) CreatePolicyGroup(c *gin.Context)

CreatePolicyGroup 创建策略组 POST /api/v1/policy-groups

func (*PolicyGroupsHandler) DeletePolicyGroup

func (h *PolicyGroupsHandler) DeletePolicyGroup(c *gin.Context)

DeletePolicyGroup 删除策略组 DELETE /api/v1/policy-groups/:id

func (*PolicyGroupsHandler) GetPolicyGroup

func (h *PolicyGroupsHandler) GetPolicyGroup(c *gin.Context)

GetPolicyGroup 获取策略组详情 GET /api/v1/policy-groups/:id

func (*PolicyGroupsHandler) GetPolicyGroupStatistics

func (h *PolicyGroupsHandler) GetPolicyGroupStatistics(c *gin.Context)

GetPolicyGroupStatistics 获取策略组统计信息 GET /api/v1/policy-groups/:id/statistics

func (*PolicyGroupsHandler) ListPolicyGroups

func (h *PolicyGroupsHandler) ListPolicyGroups(c *gin.Context)

ListPolicyGroups 获取策略组列表 GET /api/v1/policy-groups

func (*PolicyGroupsHandler) UpdatePolicyGroup

func (h *PolicyGroupsHandler) UpdatePolicyGroup(c *gin.Context)

UpdatePolicyGroup 更新策略组 PUT /api/v1/policy-groups/:id

type PolicyImportExportHandler

type PolicyImportExportHandler struct {
	// contains filtered or unexported fields
}

PolicyImportExportHandler 策略导入导出处理器

func NewPolicyImportExportHandler

func NewPolicyImportExportHandler(db *gorm.DB, logger *zap.Logger) *PolicyImportExportHandler

NewPolicyImportExportHandler 创建策略导入导出处理器

func (*PolicyImportExportHandler) ExportAllPolicies

func (h *PolicyImportExportHandler) ExportAllPolicies(c *gin.Context)

ExportAllPolicies 导出所有策略

func (*PolicyImportExportHandler) ExportPolicy

func (h *PolicyImportExportHandler) ExportPolicy(c *gin.Context)

ExportPolicy 导出单个策略

func (*PolicyImportExportHandler) ImportPolicy

func (h *PolicyImportExportHandler) ImportPolicy(c *gin.Context)

ImportPolicy 导入策略

type PrometheusAlertsHandler

type PrometheusAlertsHandler struct {
	// contains filtered or unexported fields
}

PrometheusAlertsHandler 接收 Prometheus alerting webhook

func NewPrometheusAlertsHandler

func NewPrometheusAlertsHandler(db *gorm.DB, logger *zap.Logger) *PrometheusAlertsHandler

NewPrometheusAlertsHandler 构造

func (*PrometheusAlertsHandler) Ingest

func (h *PrometheusAlertsHandler) Ingest(c *gin.Context)

Ingest 处理 Prometheus 告警 webhook。

POST /api/v1/internal/alerts/prometheus

行为:

  • status=firing → upsert alert 记录(status=active,命中次数+1)
  • status=resolved → 更新 alert 记录 status=resolved + resolved_at

type QuarantineHandler

type QuarantineHandler struct {
	// contains filtered or unexported fields
}

QuarantineHandler 文件隔离箱 API 处理器

func NewQuarantineHandler

func NewQuarantineHandler(db *gorm.DB, logger *zap.Logger) *QuarantineHandler

NewQuarantineHandler 创建文件隔离箱处理器

func (*QuarantineHandler) BatchDelete

func (h *QuarantineHandler) BatchDelete(c *gin.Context)

BatchDelete 批量永久删除隔离文件 POST /api/v1/quarantine/files/batch-delete

func (*QuarantineHandler) DeleteFile

func (h *QuarantineHandler) DeleteFile(c *gin.Context)

DeleteFile 永久删除隔离文件 DELETE /api/v1/quarantine/files/:id

func (*QuarantineHandler) GetFile

func (h *QuarantineHandler) GetFile(c *gin.Context)

GetFile 获取隔离文件详情 GET /api/v1/quarantine/files/:id

func (*QuarantineHandler) GetStatistics

func (h *QuarantineHandler) GetStatistics(c *gin.Context)

GetStatistics 获取隔离箱统计 GET /api/v1/quarantine/statistics

func (*QuarantineHandler) ListFiles

func (h *QuarantineHandler) ListFiles(c *gin.Context)

ListFiles 获取隔离文件列表 GET /api/v1/quarantine/files

func (*QuarantineHandler) RestoreFile

func (h *QuarantineHandler) RestoreFile(c *gin.Context)

RestoreFile 恢复隔离文件 POST /api/v1/quarantine/files/:id/restore

type RBACHandler

type RBACHandler struct {
	// contains filtered or unexported fields
}

RBACHandler 权限管理 API 处理器

func NewRBACHandler

func NewRBACHandler(db *gorm.DB, logger *zap.Logger) *RBACHandler

NewRBACHandler 创建权限管理处理器

func (*RBACHandler) GetRolePermissions

func (h *RBACHandler) GetRolePermissions(c *gin.Context)

GetRolePermissions 获取指定角色的权限码列表 GET /api/v1/rbac/roles/:role/permissions

func (*RBACHandler) ListPermissions

func (h *RBACHandler) ListPermissions(c *gin.Context)

ListPermissions 获取所有权限定义 GET /api/v1/rbac/permissions

func (*RBACHandler) ListRoles

func (h *RBACHandler) ListRoles(c *gin.Context)

ListRoles 获取所有角色及其权限 GET /api/v1/rbac/roles

func (*RBACHandler) UpdateRolePermissions

func (h *RBACHandler) UpdateRolePermissions(c *gin.Context)

UpdateRolePermissions 更新指定角色的权限 PUT /api/v1/rbac/roles/:role/permissions

type RejectRequest

type RejectRequest struct {
	Reason string `json:"reason" binding:"required,min=5"`
}

RejectRequest 拒绝请求体。

type ReleaseVersionRequest

type ReleaseVersionRequest struct {
	Version   string `json:"version" binding:"required"` // 版本号
	Changelog string `json:"changelog"`                  // 更新日志
	SetLatest bool   `json:"set_latest"`                 // 是否设为最新版本
	Force     bool   `json:"force"`                      // 是否强制覆盖已存在的版本
}

ReleaseVersionRequest 发布版本请求

type RemediationHandler

type RemediationHandler struct {
	// contains filtered or unexported fields
}

RemediationHandler 漏洞修复 API 处理器

func NewRemediationHandler

func NewRemediationHandler(db *gorm.DB, logger *zap.Logger) *RemediationHandler

NewRemediationHandler 创建修复处理器

func (*RemediationHandler) GetAdvice

func (h *RemediationHandler) GetAdvice(c *gin.Context)

GetAdvice 获取漏洞修复建议 GET /api/v1/vulnerabilities/:id/advice

func (*RemediationHandler) GetRemediationStats

func (h *RemediationHandler) GetRemediationStats(c *gin.Context)

GetRemediationStats 获取修复统计概览 GET /api/v1/vulnerabilities/stats/remediation

func (*RemediationHandler) GetRemediationTrend

func (h *RemediationHandler) GetRemediationTrend(c *gin.Context)

GetRemediationTrend 获取修复趋势 GET /api/v1/vulnerabilities/stats/trend

func (*RemediationHandler) PatchVulnerability

func (h *RemediationHandler) PatchVulnerability(c *gin.Context)

PatchVulnerability 标记漏洞已修复 POST /api/v1/vulnerabilities/:id/patch

func (*RemediationHandler) VerifyRemediation

func (h *RemediationHandler) VerifyRemediation(c *gin.Context)

VerifyRemediation 验证漏洞修复(比对主机当前版本) POST /api/v1/vulnerabilities/:id/verify

func (*RemediationHandler) VerifyTask

func (h *RemediationHandler) VerifyTask(c *gin.Context)

VerifyTask 验证修复任务的结果 POST /api/v1/remediation-tasks/:id/verify

type RemediationPoliciesHandler

type RemediationPoliciesHandler struct {
	// contains filtered or unexported fields
}

RemediationPoliciesHandler 修复策略 API 处理器

func NewRemediationPoliciesHandler

func NewRemediationPoliciesHandler(db *gorm.DB, logger *zap.Logger, remExecutor *biz.RemediationExecutor) *RemediationPoliciesHandler

NewRemediationPoliciesHandler 创建处理器

func (*RemediationPoliciesHandler) CreatePolicy

func (h *RemediationPoliciesHandler) CreatePolicy(c *gin.Context)

CreatePolicy 创建修复策略

func (*RemediationPoliciesHandler) DeletePolicy

func (h *RemediationPoliciesHandler) DeletePolicy(c *gin.Context)

DeletePolicy 删除修复策略

func (*RemediationPoliciesHandler) ExecutePolicy

func (h *RemediationPoliciesHandler) ExecutePolicy(c *gin.Context)

ExecutePolicy 执行修复策略

func (*RemediationPoliciesHandler) GetPolicy

func (h *RemediationPoliciesHandler) GetPolicy(c *gin.Context)

GetPolicy 策略详情

func (*RemediationPoliciesHandler) ListExecutions

func (h *RemediationPoliciesHandler) ListExecutions(c *gin.Context)

ListExecutions 查询修复策略的执行历史

func (*RemediationPoliciesHandler) ListPolicies

func (h *RemediationPoliciesHandler) ListPolicies(c *gin.Context)

ListPolicies 策略列表

func (*RemediationPoliciesHandler) PreviewPolicy

func (h *RemediationPoliciesHandler) PreviewPolicy(c *gin.Context)

PreviewPolicy 预览策略影响范围

func (*RemediationPoliciesHandler) UpdatePolicy

func (h *RemediationPoliciesHandler) UpdatePolicy(c *gin.Context)

UpdatePolicy 更新修复策略

type RemediationTaskVerifyHandler

type RemediationTaskVerifyHandler struct {
	// contains filtered or unexported fields
}

ConfirmExecuted P5.6: user 点 "确认已执行" 后触发复测 POST /api/v1/remediation-tasks/:id/confirm-executed 仅 status=success_pending_verify 可调用;成功后 status→main_verifying,触发 pre-check

func NewRemediationTaskVerifyHandler

func NewRemediationTaskVerifyHandler(db *gorm.DB, logger *zap.Logger, dispatcher biz.PreCheckDispatcher) *RemediationTaskVerifyHandler

func (*RemediationTaskVerifyHandler) ConfirmExecuted

func (h *RemediationTaskVerifyHandler) ConfirmExecuted(c *gin.Context)

type RemediationTasksHandler

type RemediationTasksHandler struct {
	// contains filtered or unexported fields
}

RemediationTasksHandler 修复任务 API 处理器

func NewRemediationTasksHandler

func NewRemediationTasksHandler(db *gorm.DB, logger *zap.Logger) *RemediationTasksHandler

NewRemediationTasksHandler 创建修复任务处理器

func (*RemediationTasksHandler) BatchCancel

func (h *RemediationTasksHandler) BatchCancel(c *gin.Context)

BatchCancel 批量取消修复任务 POST /api/v1/remediation-tasks/batch-cancel

func (*RemediationTasksHandler) BatchConfirm

func (h *RemediationTasksHandler) BatchConfirm(c *gin.Context)

BatchConfirm 批量确认修复任务 POST /api/v1/remediation-tasks/batch-confirm

func (*RemediationTasksHandler) BatchCreate

func (h *RemediationTasksHandler) BatchCreate(c *gin.Context)

BatchCreate 批量创建修复任务(按漏洞) POST /api/v1/remediation-tasks/batch

func (*RemediationTasksHandler) BatchRetry

func (h *RemediationTasksHandler) BatchRetry(c *gin.Context)

BatchRetry 批量重试失败的修复任务 POST /api/v1/remediation-tasks/batch-retry

func (*RemediationTasksHandler) CancelTask

func (h *RemediationTasksHandler) CancelTask(c *gin.Context)

CancelTask 取消修复任务 POST /api/v1/remediation-tasks/:id/cancel

func (*RemediationTasksHandler) ConfirmTask

func (h *RemediationTasksHandler) ConfirmTask(c *gin.Context)

ConfirmTask 用户确认执行修复任务 POST /api/v1/remediation-tasks/:id/confirm

func (*RemediationTasksHandler) CreateForHost

func (h *RemediationTasksHandler) CreateForHost(c *gin.Context)

CreateForHost 单 host 批量创建修复任务 POST /api/v1/remediation-tasks/host-batch body: {hostId, vulnIds?: [], allUnpatched?: bool}

  • vulnIds 模式:为指定 host 的子集 vuln 创建任务
  • allUnpatched 模式:为指定 host 的全部 unpatched vuln 创建任务(忽略 vulnIds)

func (*RemediationTasksHandler) CreateTask

func (h *RemediationTasksHandler) CreateTask(c *gin.Context)

CreateTask 创建修复任务 POST /api/v1/remediation-tasks

func (*RemediationTasksHandler) GetTask

func (h *RemediationTasksHandler) GetTask(c *gin.Context)

GetTask 获取修复任务详情 GET /api/v1/remediation-tasks/:id

func (*RemediationTasksHandler) GetTaskStats

func (h *RemediationTasksHandler) GetTaskStats(c *gin.Context)

GetTaskStats 获取修复任务统计 GET /api/v1/remediation-tasks/stats

func (*RemediationTasksHandler) ListEvents

func (h *RemediationTasksHandler) ListEvents(c *gin.Context)

ListEvents GET /api/v1/remediation-tasks/:id/events 返回指定 task 的全量 lifecycle events,按 sequence 升序。

func (*RemediationTasksHandler) ListTasks

func (h *RemediationTasksHandler) ListTasks(c *gin.Context)

ListTasks 查询修复任务列表 GET /api/v1/remediation-tasks

func (*RemediationTasksHandler) RetryTask

func (h *RemediationTasksHandler) RetryTask(c *gin.Context)

RetryTask 重试失败的修复任务 POST /api/v1/remediation-tasks/:id/retry

func (*RemediationTasksHandler) StreamEvents

func (h *RemediationTasksHandler) StreamEvents(c *gin.Context)

StreamEvents GET /api/v1/remediation-tasks/:id/events/stream SSE 实时推送 lifecycle events,UI 订阅显示 11 state 实时转换。

客户端约定:

  • text/event-stream 协议
  • 每条 event 形如 data: {json}\n\n
  • heartbeat 每 30s 发 `:` 注释行保持连接
  • 连接超时 5 分钟(防泄漏,UI 自动重连)

type ReportPDFHandler

type ReportPDFHandler struct {
	// contains filtered or unexported fields
}

ReportPDFHandler 处理报告 PDF 导出。

func NewReportPDFHandler

func NewReportPDFHandler(gotenbergURL string, rh *ReportsHandler, uploadStatic, uploadDir, httpPrefix string, logger *zap.Logger) *ReportPDFHandler

NewReportPDFHandler 创建处理器。

gotenbergURL 为空时 HasGotenberg 返回 false,导出接口直接报错。 uploadStatic/uploadDir 用于把 site_config.site_logo URL 解析为本地文件。

func (*ReportPDFHandler) ExportAntivirusReportPDF

func (h *ReportPDFHandler) ExportAntivirusReportPDF(c *gin.Context)

ExportAntivirusReportPDF GET /api/v1/reports/antivirus/pdf?start_time=&end_time=

func (*ReportPDFHandler) ExportEDRReportPDF

func (h *ReportPDFHandler) ExportEDRReportPDF(c *gin.Context)

ExportEDRReportPDF GET /api/v1/reports/edr/pdf?start_time=&end_time=&landscape=

func (*ReportPDFHandler) ExportKubeReportPDF

func (h *ReportPDFHandler) ExportKubeReportPDF(c *gin.Context)

ExportKubeReportPDF GET /api/v1/reports/kube/pdf?start_time=&end_time=

func (*ReportPDFHandler) ExportTaskReportPDF

func (h *ReportPDFHandler) ExportTaskReportPDF(c *gin.Context)

ExportTaskReportPDF GET /api/v1/reports/task/:task_id/pdf

func (*ReportPDFHandler) ExportVulnReportPDF

func (h *ReportPDFHandler) ExportVulnReportPDF(c *gin.Context)

ExportVulnReportPDF GET /api/v1/reports/vulnerability/pdf?start_time=&end_time=

type ReportsHandler

type ReportsHandler struct {
	// contains filtered or unexported fields
}

ReportsHandler 是报表 API 处理器

func NewReportsHandler

func NewReportsHandler(db *gorm.DB, logger *zap.Logger) *ReportsHandler

NewReportsHandler 创建报表处理器

func (*ReportsHandler) BuildAntivirusReportData

func (h *ReportsHandler) BuildAntivirusReportData(startTime, endTime time.Time) gin.H

BuildAntivirusReportData 装配病毒查杀报告原始数据。

输出 gin.H 字段:meta / summary / trend / taskStats / severityDistribution / threatTypeDistribution / topThreats / topAffectedHosts / recentTasks / engine / improvements。

与 GetAntivirusReport handler 中相同维度的统计逻辑保持一致, 但额外补充了 PDF 报告所需的:任务状态分布、扫描类型分布、 周期趋势对比、引擎/病毒库版本、近期任务列表、近期同步记录。

func (*ReportsHandler) BuildEDRReportData

func (h *ReportsHandler) BuildEDRReportData(startTime, endTime time.Time) gin.H

BuildEDRReportData 装配 EDR 报告原始数据。 PDF 渲染路径与 JSON API 共享同一份装配函数,避免数据漂移。

性能:13 个 block 串行约 11s,并发后 ~ max(各 block) ≈ 2-3s。 顶层 errgroup 让 MySQL/CH 各自调度,大幅减少端到端 latency。

func (*ReportsHandler) BuildKubeReportData

func (h *ReportsHandler) BuildKubeReportData(startTime, endTime time.Time) gin.H

BuildKubeReportData 装配 K8s 容器安全报告原始数据。

不存盘、不写日志,纯数据组装;调用方负责 saveGeneratedReport / Success(c,…)。 与 GetKubeReport (reports.go) 共享数据源但格式适配 PDF 模板。

func (*ReportsHandler) BuildTaskReportData

func (h *ReportsHandler) BuildTaskReportData(taskID string) gin.H

BuildTaskReportData 装配任务报告原始数据。

参数 taskID 是 scan_tasks.task_id 主键。 返回 gin.H — 若任务不存在,返回 nil(调用方需判空后写错误响应)。

PDF 渲染路径与 GetTaskReport JSON API 共享主体逻辑,避免数据漂移; 但此处额外计算了 PDF 模板需要的衍生字段(duration、failure_rate、 host_status_classification、retry_hosts、critical_suggestions 等)。

func (*ReportsHandler) BuildVulnReportData

func (h *ReportsHandler) BuildVulnReportData(startTime, endTime time.Time) gin.H

BuildVulnReportData 装配漏洞管理报告原始数据,供 PDF 渲染消费。

PDF / JSON / 后台调度可复用同一份装配函数避免数据漂移。 内部所有 query 失败均给安全默认值,不抛错。

func (*ReportsHandler) DeleteGeneratedReport

func (h *ReportsHandler) DeleteGeneratedReport(c *gin.Context)

DeleteGeneratedReport 删除已保存的报告 DELETE /api/v1/reports/generated/:id

func (*ReportsHandler) GetAntivirusExecutiveReport

func (h *ReportsHandler) GetAntivirusExecutiveReport(c *gin.Context)

GetAntivirusExecutiveReport 获取病毒查杀 Executive 报告 GET /api/v1/reports/antivirus/:task_id/executive

func (*ReportsHandler) GetAntivirusReport

func (h *ReportsHandler) GetAntivirusReport(c *gin.Context)

GetAntivirusReport 获取病毒查杀报告 GET /api/v1/reports/antivirus

func (*ReportsHandler) GetBaselineScoreTrend

func (h *ReportsHandler) GetBaselineScoreTrend(c *gin.Context)

GetBaselineScoreTrend 获取基线得分趋势 GET /api/v1/reports/baseline-score-trend

func (*ReportsHandler) GetCheckResultTrend

func (h *ReportsHandler) GetCheckResultTrend(c *gin.Context)

GetCheckResultTrend 获取检查结果趋势 GET /api/v1/reports/check-result-trend

func (*ReportsHandler) GetEDRExecutiveReport

func (h *ReportsHandler) GetEDRExecutiveReport(c *gin.Context)

GetEDRExecutiveReport 生成 EDR 高管摘要(精简 1 页) GET /api/v1/reports/edr/executive?start_time=&end_time=

func (*ReportsHandler) GetEDRReport

func (h *ReportsHandler) GetEDRReport(c *gin.Context)

GetEDRReport 生成 EDR 模块聚合报告 GET /api/v1/reports/edr?start_time=&end_time=

报告含 13 个章节,覆盖告警概览、严重程度分布、规则/主机 Top N、 MITRE 矩阵、故事线统计、误报抑制统计、周期趋势对比等。 加 60s Redis cache:报表数据 1 分钟内不变,降低 13 章节 query 重复成本。

func (*ReportsHandler) GetExecutiveTaskReport

func (h *ReportsHandler) GetExecutiveTaskReport(c *gin.Context)

GetExecutiveTaskReport 获取管理层任务报告(面向非技术管理者的专业报告) GET /api/v1/reports/task/:task_id/executive

func (*ReportsHandler) GetGeneratedReport

func (h *ReportsHandler) GetGeneratedReport(c *gin.Context)

GetGeneratedReport 获取已保存的报告详情 GET /api/v1/reports/generated/:id

func (*ReportsHandler) GetKubeExecutiveReport

func (h *ReportsHandler) GetKubeExecutiveReport(c *gin.Context)

GetKubeExecutiveReport 获取容器安全 Executive 报告 GET /api/v1/reports/kube/executive

func (*ReportsHandler) GetKubeReport

func (h *ReportsHandler) GetKubeReport(c *gin.Context)

GetKubeReport 获取容器安全报告 GET /api/v1/reports/kube

func (*ReportsHandler) GetRemediationExecutiveReport

func (h *ReportsHandler) GetRemediationExecutiveReport(c *gin.Context)

GetRemediationExecutiveReport 获取漏洞修复 Executive 报告(可导出 PDF) GET /api/v1/reports/remediation/executive

func (*ReportsHandler) GetStats

func (h *ReportsHandler) GetStats(c *gin.Context)

GetStats 获取报表统计数据 GET /api/v1/reports/stats

func (*ReportsHandler) GetTaskHostDetail

func (h *ReportsHandler) GetTaskHostDetail(c *gin.Context)

GetTaskHostDetail 获取主机在任务中的详细检查结果 GET /api/v1/reports/task/:task_id/host/:host_id

func (*ReportsHandler) GetTaskReport

func (h *ReportsHandler) GetTaskReport(c *gin.Context)

GetTaskReport 获取任务报告 GET /api/v1/reports/task/:task_id

func (*ReportsHandler) GetTopFailedRules

func (h *ReportsHandler) GetTopFailedRules(c *gin.Context)

GetTopFailedRules 获取 Top N 失败检查项 GET /api/v1/reports/top-failed-rules

func (*ReportsHandler) GetTopRiskHosts

func (h *ReportsHandler) GetTopRiskHosts(c *gin.Context)

GetTopRiskHosts 获取 Top N 风险主机 GET /api/v1/reports/top-risk-hosts

func (*ReportsHandler) GetVulnerabilityExecutiveReport

func (h *ReportsHandler) GetVulnerabilityExecutiveReport(c *gin.Context)

GetVulnerabilityExecutiveReport 获取漏洞管理 Executive 报告 GET /api/v1/reports/vulnerability/executive

func (*ReportsHandler) GetVulnerabilityReport

func (h *ReportsHandler) GetVulnerabilityReport(c *gin.Context)

GetVulnerabilityReport 获取漏洞管理报告 GET /api/v1/reports/vulnerability

func (*ReportsHandler) ListGeneratedReports

func (h *ReportsHandler) ListGeneratedReports(c *gin.Context)

ListGeneratedReports 获取已保存的报告列表 GET /api/v1/reports/generated

func (*ReportsHandler) SetClickHouse

func (h *ReportsHandler) SetClickHouse(conn chdriver.Conn)

SetClickHouse 启动时注入 CH 连接,启用各 *Report 的 CH 查询路径。

func (*ReportsHandler) SetRedis

func (h *ReportsHandler) SetRedis(c *redis.Client)

SetRedis 启动时注入 Redis client,启用报表 cache。

type ResolveAlertRequest

type ResolveAlertRequest struct {
	Reason string `json:"reason"` // 解决原因
}

ResolveAlertRequest 解决告警请求

type ResolveReq

type ResolveReq struct {
	Note string `json:"note"`
}

ResolveReq POST /api/v1/rootkit/findings/:id/resolve.

type RestartAgentRequest

type RestartAgentRequest struct {
	HostIDs []string `json:"host_ids"` // 为空表示全部在线主机
}

RestartAgentRequest Agent 重启请求

type ResultsHandler

type ResultsHandler struct {
	// contains filtered or unexported fields
}

ResultsHandler 是检测结果 API 处理器

func NewResultsHandler

func NewResultsHandler(db *gorm.DB, logger *zap.Logger) *ResultsHandler

NewResultsHandler 创建结果处理器

func (*ResultsHandler) ExportHostBaselineResults

func (h *ResultsHandler) ExportHostBaselineResults(c *gin.Context)

ExportHostBaselineResults 导出主机基线检查结果 GET /api/v1/results/host/:host_id/export?format=markdown|excel

func (*ResultsHandler) GetHostBaselineScore

func (h *ResultsHandler) GetHostBaselineScore(c *gin.Context)

GetHostBaselineScore 获取主机基线得分 GET /api/v1/results/host/:host_id/score

func (*ResultsHandler) GetHostBaselineSummary

func (h *ResultsHandler) GetHostBaselineSummary(c *gin.Context)

GetHostBaselineSummary 获取主机基线摘要(按严重级别统计) GET /api/v1/results/host/:host_id/summary

func (*ResultsHandler) GetResult

func (h *ResultsHandler) GetResult(c *gin.Context)

GetResult 获取检测结果详情 GET /api/v1/results/detail?task_id=xxx&host_id=xxx&rule_id=xxx

func (*ResultsHandler) ListResults

func (h *ResultsHandler) ListResults(c *gin.Context)

ListResults 获取检测结果列表 GET /api/v1/results

type RiskItem

type RiskItem struct {
	Category       string `json:"category"`       // 风险类别
	Description    string `json:"description"`    // 风险描述(自然语言)
	Impact         string `json:"impact"`         // 可能影响
	Severity       string `json:"severity"`       // 风险等级
	SeverityLabel  string `json:"severity_label"` // 风险等级中文
	Recommendation string `json:"recommendation"` // 整改建议方向
	AffectedCount  int    `json:"affected_count"` // 影响数量
}

RiskItem 风险项

type RootkitHandler

type RootkitHandler struct {
	// contains filtered or unexported fields
}

func NewRootkitHandler

func NewRootkitHandler(db *gorm.DB, logger *zap.Logger) *RootkitHandler

func (*RootkitHandler) ListFindings

func (h *RootkitHandler) ListFindings(c *gin.Context)

ListFindings GET /api/v1/rootkit/findings.

func (*RootkitHandler) Resolve

func (h *RootkitHandler) Resolve(c *gin.Context)

Resolve 标记一条 finding 为已处理.

func (*RootkitHandler) TriggerScan

func (h *RootkitHandler) TriggerScan(c *gin.Context)

TriggerScan 下发一次扫描 (异步, 完成后 Agent 上报落 RootkitFinding 表).

注: 实际下发通道在 v2.2 接入 ACDispatcher; 当前返回 accepted + 最新一次扫描快照. POST /api/v1/rootkit/scan

type RuleData

type RuleData struct {
	RuleID      string            `json:"rule_id" binding:"required"`
	Category    string            `json:"category"`
	Title       string            `json:"title" binding:"required"`
	Description string            `json:"description"`
	Severity    string            `json:"severity"`
	CheckConfig model.CheckConfig `json:"check_config"`
	FixConfig   model.FixConfig   `json:"fix_config"`
}

RuleData 规则数据

type RuleExportFormat

type RuleExportFormat struct {
	RuleID      string                 `json:"rule_id"`
	Category    string                 `json:"category"`
	Title       string                 `json:"title"`
	Description string                 `json:"description"`
	Severity    string                 `json:"severity"`
	Check       map[string]interface{} `json:"check"`
	Fix         map[string]interface{} `json:"fix"`
}

RuleExportFormat 规则导出格式

type RuleSandboxHandler

type RuleSandboxHandler struct {
	// contains filtered or unexported fields
}

RuleSandboxHandler 沙箱测试.

func NewRuleSandboxHandler

func NewRuleSandboxHandler(logger *zap.Logger) *RuleSandboxHandler

NewRuleSandboxHandler 构造.

func (*RuleSandboxHandler) Test

func (h *RuleSandboxHandler) Test(c *gin.Context)

Test POST /api/v2/rules/test.

不存表, 仅瞬时编译评估返回结果.

type RulesHandler

type RulesHandler struct {
	// contains filtered or unexported fields
}

RulesHandler 是规则管理 API 处理器

func NewRulesHandler

func NewRulesHandler(db *gorm.DB, logger *zap.Logger) *RulesHandler

NewRulesHandler 创建规则处理器

func (*RulesHandler) CreateRule

func (h *RulesHandler) CreateRule(c *gin.Context)

CreateRule 创建规则 POST /api/v1/policies/:policy_id/rules

func (*RulesHandler) DeleteRule

func (h *RulesHandler) DeleteRule(c *gin.Context)

DeleteRule 删除规则 DELETE /api/v1/rules/:rule_id

func (*RulesHandler) GetRule

func (h *RulesHandler) GetRule(c *gin.Context)

GetRule 获取规则详情 GET /api/v1/rules/:rule_id

func (*RulesHandler) ListRules

func (h *RulesHandler) ListRules(c *gin.Context)

ListRules 获取策略的规则列表 GET /api/v1/policies/:policy_id/rules

func (*RulesHandler) UpdateRule

func (h *RulesHandler) UpdateRule(c *gin.Context)

UpdateRule 更新规则 PUT /api/v1/rules/:rule_id

type SBOMImportHandler

type SBOMImportHandler struct {
	// contains filtered or unexported fields
}

SBOMImportHandler SBOM 导入 API 处理器

func NewSBOMImportHandler

func NewSBOMImportHandler(db *gorm.DB, logger *zap.Logger) *SBOMImportHandler

NewSBOMImportHandler 创建处理器

func (*SBOMImportHandler) GetProject

func (h *SBOMImportHandler) GetProject(c *gin.Context)

GetProject 项目组件 + 漏洞详情

func (*SBOMImportHandler) ImportSBOM

func (h *SBOMImportHandler) ImportSBOM(c *gin.Context)

ImportSBOM 上传 SBOM 文件

func (*SBOMImportHandler) ListProjects

func (h *SBOMImportHandler) ListProjects(c *gin.Context)

ListProjects SBOM 项目列表

type ScanResultKey

type ScanResultKey struct {
	TaskID string `json:"task_id"`
	HostID string `json:"host_id"`
	RuleID string `json:"rule_id"`
}

ScanResultKey 标识一条扫描结果的复合键

type ScanSchedulesHandler

type ScanSchedulesHandler struct {
	// contains filtered or unexported fields
}

ScanSchedulesHandler 扫描计划 API 处理器

func NewScanSchedulesHandler

func NewScanSchedulesHandler(db *gorm.DB, logger *zap.Logger, scheduler *biz.ScanScheduler) *ScanSchedulesHandler

NewScanSchedulesHandler 创建处理器

func (*ScanSchedulesHandler) CreateSchedule

func (h *ScanSchedulesHandler) CreateSchedule(c *gin.Context)

CreateSchedule 创建扫描计划

func (*ScanSchedulesHandler) DeleteSchedule

func (h *ScanSchedulesHandler) DeleteSchedule(c *gin.Context)

DeleteSchedule 删除扫描计划

func (*ScanSchedulesHandler) GetExecution

func (h *ScanSchedulesHandler) GetExecution(c *gin.Context)

GetExecution 查询单次执行详情(含新增漏洞、受影响主机)

func (*ScanSchedulesHandler) ListExecutions

func (h *ScanSchedulesHandler) ListExecutions(c *gin.Context)

ListExecutions 查询扫描计划的执行历史

func (*ScanSchedulesHandler) ListSchedules

func (h *ScanSchedulesHandler) ListSchedules(c *gin.Context)

ListSchedules 扫描计划列表

func (*ScanSchedulesHandler) ToggleSchedule

func (h *ScanSchedulesHandler) ToggleSchedule(c *gin.Context)

ToggleSchedule 启用/禁用扫描计划

func (*ScanSchedulesHandler) UpdateSchedule

func (h *ScanSchedulesHandler) UpdateSchedule(c *gin.Context)

UpdateSchedule 更新扫描计划

type SecurityScore

type SecurityScore struct {
	Score            float64 `json:"score"`             // 综合安全评分 (0-100)
	Grade            string  `json:"grade"`             // 安全等级 (优秀/良好/一般/较差)
	GradeColor       string  `json:"grade_color"`       // 等级颜色
	ScoreExplanation string  `json:"score_explanation"` // 评分说明
	SecurityNote     string  `json:"security_note"`     // 安全提示
}

SecurityScore 安全评分

type SetTenantModeRequest

type SetTenantModeRequest struct {
	Mode string `json:"mode" binding:"required,oneof=observe protect"`
}

SetTenantModeRequest POST /api/v2/admin/tenants/:id/mode 请求体。

type StorylineHandler

type StorylineHandler struct {
	// contains filtered or unexported fields
}

StorylineHandler 攻击故事线 API 处理器

storyline_events 数据可能在 MySQL 或 ClickHouse,按 feature_flag.data_source. storyline_events 决定读路径。chConn 为 nil 时强制走 MySQL。

func NewStorylineHandler

func NewStorylineHandler(db *gorm.DB, logger *zap.Logger) *StorylineHandler

NewStorylineHandler 创建攻击故事线 API 处理器

func (*StorylineHandler) GetStoryline

func (h *StorylineHandler) GetStoryline(c *gin.Context)

GetStoryline 获取故事线详情(含事件时间线,分页)

单 storyline 的 events 可达数万级(EDR ebpf 全量关联),全量返回 JSON 体积过大导致浏览器解析+渲染卡死。改用分页:默认 page=1 page_size=100, 上限 500;UI 增量加载。

func (*StorylineHandler) GetStorylineStats

func (h *StorylineHandler) GetStorylineStats(c *gin.Context)

GetStorylineStats 故事线统计概览

func (*StorylineHandler) ListStorylines

func (h *StorylineHandler) ListStorylines(c *gin.Context)

ListStorylines 查看攻击故事线列表

func (*StorylineHandler) ResolveStoryline

func (h *StorylineHandler) ResolveStoryline(c *gin.Context)

ResolveStoryline 标记故事线为已处理

func (*StorylineHandler) SetClickHouse

func (h *StorylineHandler) SetClickHouse(conn chdriver.Conn)

SetClickHouse 启动时注入 CH 连接。

type SystemConfigHandler

type SystemConfigHandler struct {
	// contains filtered or unexported fields
}

SystemConfigHandler 是系统配置 API 处理器

func NewSystemConfigHandler

func NewSystemConfigHandler(db *gorm.DB, logger *zap.Logger, uploadDir, staticPath string) *SystemConfigHandler

NewSystemConfigHandler 创建系统配置处理器 uploadDir: 文件系统路径,用于存储上传的文件(例如:./uploads) staticPath: HTTP 访问路径,用于通过 HTTP 访问上传的文件(例如:/uploads)

func (*SystemConfigHandler) GetAlertConfig

func (h *SystemConfigHandler) GetAlertConfig(c *gin.Context)

GetAlertConfig 获取告警配置 GET /api/v1/system-config/alert

func (*SystemConfigHandler) GetKubernetesImageConfig

func (h *SystemConfigHandler) GetKubernetesImageConfig(c *gin.Context)

GetKubernetesImageConfig 获取 Kubernetes 镜像配置 GET /api/v1/system-config/kubernetes-image

func (h *SystemConfigHandler) GetLogo(c *gin.Context)

GetLogo 获取 Logo 文件 GET /api/v1/system-config/logo/:filename

func (*SystemConfigHandler) GetSiteConfig

func (h *SystemConfigHandler) GetSiteConfig(c *gin.Context)

GetSiteConfig 获取站点配置 GET /api/v1/system-config/site

func (*SystemConfigHandler) UpdateAlertConfig

func (h *SystemConfigHandler) UpdateAlertConfig(c *gin.Context)

UpdateAlertConfig 更新告警配置 PUT /api/v1/system-config/alert

func (*SystemConfigHandler) UpdateKubernetesImageConfig

func (h *SystemConfigHandler) UpdateKubernetesImageConfig(c *gin.Context)

UpdateKubernetesImageConfig 更新 Kubernetes 镜像配置 PUT /api/v1/system-config/kubernetes-image

func (*SystemConfigHandler) UpdateSiteConfig

func (h *SystemConfigHandler) UpdateSiteConfig(c *gin.Context)

UpdateSiteConfig 更新站点配置 PUT /api/v1/system-config/site

func (h *SystemConfigHandler) UploadLogo(c *gin.Context)

UploadLogo 上传 Logo POST /api/v1/system-config/upload-logo

type SystemModeHandler

type SystemModeHandler struct {
	// contains filtered or unexported fields
}

SystemModeHandler 提供 /api/v2/system/mode 与 /api/v2/admin/tenants/:id/mode API。

设计文档: docs/operating-modes.md §5 切换流程

4 级覆盖优先级 (高 → 低): 规则级 > 主机标签级 > 租户级 > 全局默认。 本 handler 暂只暴露租户级 + 全局默认查询/切换, 主机标签级与规则级通过 baseline/rule API 改 (后续 PR)。

func NewSystemModeHandler

func NewSystemModeHandler(db *gorm.DB, logger *zap.Logger, resolver *mode.MemoryResolver) *SystemModeHandler

NewSystemModeHandler 构造 mode handler。

func (*SystemModeHandler) GetCurrentMode

func (h *SystemModeHandler) GetCurrentMode(c *gin.Context)

GetCurrentMode GET /api/v2/system/mode

返回当前生效的 mode 决策 (按当前 token 的 tenant)。 平台超管返回全局视图。

func (*SystemModeHandler) ListTenantModes

func (h *SystemModeHandler) ListTenantModes(c *gin.Context)

ListTenantModes GET /api/v2/admin/tenants/modes

列出所有租户的当前 mode 与 quota (仅平台超管)。

func (*SystemModeHandler) SetTenantMode

func (h *SystemModeHandler) SetTenantMode(c *gin.Context)

SetTenantMode POST /api/v2/admin/tenants/:id/mode

仅平台超管可调用。租户级切换 → MemoryResolver + tenants 表持久化。 protect 切换前应该做 6 门槛准入校验 (PR 留 hook,本 PR 暂仅记录 audit 警告)。

type TaskReportStatistics

type TaskReportStatistics struct {
	TotalChecks   int64            `json:"total_checks"`
	PassedChecks  int64            `json:"passed_checks"`
	FailedChecks  int64            `json:"failed_checks"`
	WarningChecks int64            `json:"warning_checks"`
	NAChecks      int64            `json:"na_checks"`
	PassRate      float64          `json:"pass_rate"`
	BySeverity    map[string]int64 `json:"by_severity"`
	ByCategory    map[string]int64 `json:"by_category"`
}

TaskReportStatistics 任务报告统计

type TaskReportSummary

type TaskReportSummary struct {
	TaskID      string     `json:"task_id"`
	TaskName    string     `json:"task_name"`
	PolicyID    string     `json:"policy_id"`    // 兼容旧版本
	PolicyIDs   []string   `json:"policy_ids"`   // 新版本:多策略ID
	PolicyName  string     `json:"policy_name"`  // 策略名称(多策略时显示数量)
	PolicyNames []string   `json:"policy_names"` // 新版本:策略名称列表
	ExecutedAt  *time.Time `json:"executed_at"`
	CompletedAt *time.Time `json:"completed_at"`
	HostCount   int        `json:"host_count"`
	RuleCount   int        `json:"rule_count"`
	Status      string     `json:"status"`
}

TaskReportSummary 任务报告概要

type TaskResponse

type TaskResponse struct {
	model.ScanTask
	TargetHosts        []string `json:"target_hosts"`         // 目标主机 ID 列表
	MatchedHostCount   int      `json:"matched_host_count"`   // 匹配的主机数量(在线)
	TotalHostCount     int      `json:"total_host_count"`     // 总目标主机数量(包括离线)
	TotalRuleCount     int      `json:"total_rule_count"`     // 关联策略的规则总数
	ExpectedCheckCount int      `json:"expected_check_count"` // 预期检查项总数(在线主机数 × 规则数)
}

TaskResponse 任务响应(包含计算字段)

type TasksHandler

type TasksHandler struct {
	// contains filtered or unexported fields
}

TasksHandler 是任务管理 API 处理器

func NewTasksHandler

func NewTasksHandler(db *gorm.DB, logger *zap.Logger, acDispatcher *sd.ACDispatcher) *TasksHandler

NewTasksHandler 创建任务处理器

func (*TasksHandler) CancelTask

func (h *TasksHandler) CancelTask(c *gin.Context)

CancelTask 取消任务 POST /api/v1/tasks/:task_id/cancel

func (*TasksHandler) CreateTask

func (h *TasksHandler) CreateTask(c *gin.Context)

CreateTask 创建扫描任务 POST /api/v1/tasks

func (*TasksHandler) DeleteTask

func (h *TasksHandler) DeleteTask(c *gin.Context)

DeleteTask 删除任务 DELETE /api/v1/tasks/:task_id

func (*TasksHandler) GetTask

func (h *TasksHandler) GetTask(c *gin.Context)

GetTask 获取任务详情 GET /api/v1/tasks/:task_id

func (*TasksHandler) GetTaskHostStatus

func (h *TasksHandler) GetTaskHostStatus(c *gin.Context)

GetTaskHostStatus 获取任务的主机执行状态 GET /api/v1/tasks/:task_id/host-status

func (*TasksHandler) ListTasks

func (h *TasksHandler) ListTasks(c *gin.Context)

ListTasks 获取任务列表 GET /api/v1/tasks

func (*TasksHandler) RunTask

func (h *TasksHandler) RunTask(c *gin.Context)

RunTask 执行任务 POST /api/v1/tasks/:task_id/run

type TestNotificationRequest

type TestNotificationRequest struct {
	Type           model.NotificationType   `json:"type" binding:"required"`
	Config         model.NotificationConfig `json:"config" binding:"required"`
	FrontendURL    string                   `json:"frontend_url"`    // 可选,用于测试跳转链接
	NotificationID *uint                    `json:"notification_id"` // 可选,如果提供则使用完整的通知配置
	NotifyCategory model.NotifyCategory     `json:"notify_category"` // 可选,指定测试的通知类别
}

TestNotificationRequest 测试通知请求

type ThreatIntelHandler

type ThreatIntelHandler struct {
	// contains filtered or unexported fields
}

ThreatIntelHandler 威胁情报 API

func NewThreatIntelHandler

func NewThreatIntelHandler(service *biz.ThreatIntel, redisClient *redis.Client, logger *zap.Logger) *ThreatIntelHandler

NewThreatIntelHandler 创建威胁情报 handler

func (*ThreatIntelHandler) CheckIOC

func (h *ThreatIntelHandler) CheckIOC(c *gin.Context)

CheckIOC 检查单个值是否命中 IOC

func (*ThreatIntelHandler) GetIOCStats

func (h *ThreatIntelHandler) GetIOCStats(c *gin.Context)

GetIOCStats 获取 IOC 统计概览

func (*ThreatIntelHandler) GetSyncHistory

func (h *ThreatIntelHandler) GetSyncHistory(c *gin.Context)

GetSyncHistory 获取威胁情报同步历史记录 GET /api/v1/threat-intel/sync-history

func (*ThreatIntelHandler) GetSyncStatus

func (h *ThreatIntelHandler) GetSyncStatus(c *gin.Context)

GetSyncStatus 获取威胁情报最新同步状态 GET /api/v1/threat-intel/sync-status

func (*ThreatIntelHandler) ListIOCs

func (h *ThreatIntelHandler) ListIOCs(c *gin.Context)

ListIOCs 列出指定类型的 IOC

func (*ThreatIntelHandler) TriggerSync

func (h *ThreatIntelHandler) TriggerSync(c *gin.Context)

TriggerSync 手动触发 IOC 同步

type TopFailedRule

type TopFailedRule struct {
	RuleID        string `json:"rule_id"`
	Title         string `json:"title"`
	Severity      string `json:"severity"`
	Category      string `json:"category"`
	AffectedHosts int    `json:"affected_hosts"`
}

TopFailedRule Top 失败检查项

type TopRiskHost

type TopRiskHost struct {
	HostID        string  `json:"host_id"`
	Hostname      string  `json:"hostname"`
	IP            string  `json:"ip"`
	OSFamily      string  `json:"os_family"`
	Score         float64 `json:"score"`
	FailCount     int     `json:"fail_count"`
	CriticalCount int     `json:"critical_count"`
	HighCount     int     `json:"high_count"`
}

TopRiskHost Top 风险主机

type TriggerScanReq

type TriggerScanReq struct {
	HostID string `json:"host_id" binding:"required"`
}

TriggerScanReq POST /api/v1/rootkit/scan.

type UpdateAlertConfigRequest

type UpdateAlertConfigRequest struct {
	RepeatAlertInterval   int  `json:"repeat_alert_interval" binding:"required,min=1"`
	EnablePeriodicSummary bool `json:"enable_periodic_summary"`
}

UpdateAlertConfigRequest 更新告警配置请求

type UpdateBusinessLineRequest

type UpdateBusinessLineRequest struct {
	Name        string `json:"name"`        // 业务线名称
	Description string `json:"description"` // 描述
	Owner       string `json:"owner"`       // 负责人
	Contact     string `json:"contact"`     // 联系方式
	Enabled     *bool  `json:"enabled"`     // 是否启用
}

UpdateBusinessLineRequest 更新业务线请求

type UpdateFeatureFlagRequest

type UpdateFeatureFlagRequest struct {
	Value string `json:"value" binding:"required"`
}

UpdateFeatureFlagRequest 更新请求体。

type UpdateHostBusinessLineRequest

type UpdateHostBusinessLineRequest struct {
	BusinessLine string `json:"business_line"` // 业务线代码(空字符串表示取消绑定)
}

UpdateHostBusinessLineRequest 更新主机业务线请求

type UpdateKubernetesImageConfigRequest

type UpdateKubernetesImageConfigRequest struct {
	Repository     string   `json:"repository" binding:"required"`
	Versions       []string `json:"versions" binding:"required"`
	DefaultVersion string   `json:"default_version" binding:"required"`
}

UpdateKubernetesImageConfigRequest 更新 Kubernetes 镜像配置请求

type UpdateNotificationRequest

type UpdateNotificationRequest struct {
	Name           string                    `json:"name"`
	Description    string                    `json:"description"`
	NotifyCategory model.NotifyCategory      `json:"notify_category"`
	Enabled        *bool                     `json:"enabled"`
	Type           model.NotificationType    `json:"type"`
	Severities     []string                  `json:"severities"`
	Scope          model.NotificationScope   `json:"scope"`
	ScopeValue     *model.ScopeValueData     `json:"scope_value"`
	FrontendURL    string                    `json:"frontend_url"`
	Config         *model.NotificationConfig `json:"config"`
}

UpdateNotificationRequest 更新通知请求

type UpdatePolicyGroupRequest

type UpdatePolicyGroupRequest struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
	Color       string `json:"color"`
	SortOrder   *int   `json:"sort_order"`
	Enabled     *bool  `json:"enabled"`
}

UpdatePolicyGroupRequest 更新策略组请求

type UpdatePolicyRequest

type UpdatePolicyRequest struct {
	Name           string                `json:"name"`
	Version        string                `json:"version"`
	Description    string                `json:"description"`
	OSFamily       []string              `json:"os_family"`
	OSVersion      string                `json:"os_version"`
	OSRequirements []model.OSRequirement `json:"os_requirements"` // 详细 OS 版本要求
	RuntimeTypes   []string              `json:"runtime_types"`   // 适用的运行时类型
	Enabled        *bool                 `json:"enabled"`
	GroupID        *string               `json:"group_id"`
	Rules          []*RuleData           `json:"rules"`
}

UpdatePolicyRequest 更新策略请求

type UpdateRetentionPolicyRequest

type UpdateRetentionPolicyRequest struct {
	RetentionDays int `json:"retention_days" binding:"required,min=1,max=3650"`
}

UpdateRetentionPolicyRequest 更新请求体。

type UpdateRolePermissionsRequest

type UpdateRolePermissionsRequest struct {
	Permissions []string `json:"permissions" binding:"required"`
}

UpdateRolePermissionsRequest 更新角色权限请求

type UpdateRuleRequest

type UpdateRuleRequest struct {
	Category    string             `json:"category"`
	Title       string             `json:"title"`
	Description string             `json:"description"`
	Severity    string             `json:"severity"`
	Enabled     *bool              `json:"enabled"` // 可选,更新启用状态
	CheckConfig *model.CheckConfig `json:"check_config"`
	FixConfig   *model.FixConfig   `json:"fix_config"`
}

UpdateRuleRequest 更新规则请求

type UpdateSiteConfigRequest

type UpdateSiteConfigRequest struct {
	SiteName   string  `json:"site_name"`   // 站点名称(必填,手动验证)
	SiteDomain string  `json:"site_domain"` // 前端访问域名(可选)
	BackendURL string  `json:"backend_url"` // 后端接口地址(必填)
}

UpdateSiteConfigRequest 更新站点配置请求

type UpdateUserRequest

type UpdateUserRequest struct {
	Password string `json:"password" binding:"omitempty,min=8"`
	Email    string `json:"email" binding:"omitempty,email"`
	Role     string `json:"role" binding:"omitempty,oneof=admin user"`
	Status   string `json:"status" binding:"omitempty,oneof=active inactive"`
}

UpdateUserRequest 更新用户请求

type UpdateWhitelistRequest

type UpdateWhitelistRequest struct {
	Name         string `json:"name" binding:"required"`
	RuleID       string `json:"rule_id"`
	HostID       string `json:"host_id"`
	Category     string `json:"category"`
	Severity     string `json:"severity"`
	SourceIPCIDR string `json:"source_ip_cidr"`
	Reason       string `json:"reason"`
}

UpdateWhitelistRequest 更新白名单请求

type UsersHandler

type UsersHandler struct {
	// contains filtered or unexported fields
}

UsersHandler 是用户管理 API 处理器

func NewUsersHandler

func NewUsersHandler(db *gorm.DB, logger *zap.Logger) *UsersHandler

NewUsersHandler 创建用户管理处理器

func (*UsersHandler) CreateUser

func (h *UsersHandler) CreateUser(c *gin.Context)

CreateUser 创建用户 POST /api/v1/users

func (*UsersHandler) DeleteUser

func (h *UsersHandler) DeleteUser(c *gin.Context)

DeleteUser 删除用户 DELETE /api/v1/users/:id

func (*UsersHandler) GetUser

func (h *UsersHandler) GetUser(c *gin.Context)

GetUser 获取用户详情 GET /api/v1/users/:id

func (*UsersHandler) ListUsers

func (h *UsersHandler) ListUsers(c *gin.Context)

ListUsers 获取用户列表 GET /api/v1/users

func (*UsersHandler) UpdateUser

func (h *UsersHandler) UpdateUser(c *gin.Context)

UpdateUser 更新用户 PUT /api/v1/users/:id

type VEXHandler

type VEXHandler struct {
	// contains filtered or unexported fields
}

func NewVEXHandler

func NewVEXHandler(db *gorm.DB, logger *zap.Logger) *VEXHandler

func (*VEXHandler) ExportCSAF

func (h *VEXHandler) ExportCSAF(c *gin.Context)

ExportCSAF 下载 CSAF 2.0 JSON. GET /api/v1/vex/:product_id/csaf?version=X.Y.Z

func (*VEXHandler) ExportCycloneDX

func (h *VEXHandler) ExportCycloneDX(c *gin.Context)

ExportCycloneDX 下载 CycloneDX VEX 1.5 JSON. GET /api/v1/vex/:product_id/cyclonedx?version=X.Y.Z

func (*VEXHandler) GetDocument

func (h *VEXHandler) GetDocument(c *gin.Context)

GetDocument 返回完整 VEX 文档. GET /api/v1/vex/:product_id?version=X.Y.Z

func (*VEXHandler) ListStatements

func (h *VEXHandler) ListStatements(c *gin.Context)

ListStatements 返回 CVE 声明列表 (与 GetDocument.Statements 等价, 提供独立端点便于分页). GET /api/v1/vex/:product_id/statements

type VulnBulletinsHandler

type VulnBulletinsHandler struct {
	// contains filtered or unexported fields
}

VulnBulletinsHandler 漏洞通报 API

func NewVulnBulletinsHandler

func NewVulnBulletinsHandler(db *gorm.DB, logger *zap.Logger) *VulnBulletinsHandler

NewVulnBulletinsHandler 创建漏洞通报 Handler

func (*VulnBulletinsHandler) AcknowledgeBulletin

func (h *VulnBulletinsHandler) AcknowledgeBulletin(c *gin.Context)

AcknowledgeBulletin 确认通报

func (*VulnBulletinsHandler) BatchBulletins

func (h *VulnBulletinsHandler) BatchBulletins(c *gin.Context)

BatchBulletins 批量操作

func (*VulnBulletinsHandler) GetBulletin

func (h *VulnBulletinsHandler) GetBulletin(c *gin.Context)

GetBulletin 通报详情

func (*VulnBulletinsHandler) GetBulletinConfig

func (h *VulnBulletinsHandler) GetBulletinConfig(c *gin.Context)

GetBulletinConfig 获取通报配置

func (*VulnBulletinsHandler) GetBulletinStatistics

func (h *VulnBulletinsHandler) GetBulletinStatistics(c *gin.Context)

GetBulletinStatistics 通报统计

func (*VulnBulletinsHandler) IgnoreBulletin

func (h *VulnBulletinsHandler) IgnoreBulletin(c *gin.Context)

IgnoreBulletin 忽略通报

func (*VulnBulletinsHandler) ListBulletins

func (h *VulnBulletinsHandler) ListBulletins(c *gin.Context)

ListBulletins 通报列表

func (*VulnBulletinsHandler) ReopenBulletin

func (h *VulnBulletinsHandler) ReopenBulletin(c *gin.Context)

ReopenBulletin 重新打开通报

func (*VulnBulletinsHandler) ResolveBulletin

func (h *VulnBulletinsHandler) ResolveBulletin(c *gin.Context)

ResolveBulletin 修复通报

func (*VulnBulletinsHandler) UpdateBulletinConfig

func (h *VulnBulletinsHandler) UpdateBulletinConfig(c *gin.Context)

UpdateBulletinConfig 更新通报配置

type VulnCacheHandler

type VulnCacheHandler struct {
	// contains filtered or unexported fields
}

VulnCacheHandler 漏洞库缓存 API 处理器

func NewVulnCacheHandler

func NewVulnCacheHandler(db *gorm.DB, logger *zap.Logger) *VulnCacheHandler

NewVulnCacheHandler 创建处理器

func (*VulnCacheHandler) GetImportHistory

func (h *VulnCacheHandler) GetImportHistory(c *gin.Context)

GetImportHistory 导入历史

func (*VulnCacheHandler) GetStats

func (h *VulnCacheHandler) GetStats(c *gin.Context)

GetStats 缓存统计

func (*VulnCacheHandler) ImportDB

func (h *VulnCacheHandler) ImportDB(c *gin.Context)

ImportDB 上传离线数据包

func (*VulnCacheHandler) PurgeExpired

func (h *VulnCacheHandler) PurgeExpired(c *gin.Context)

PurgeExpired 清理过期缓存

type VulnDataSourcesHandler

type VulnDataSourcesHandler struct {
	// contains filtered or unexported fields
}

VulnDataSourcesHandler 漏洞数据源 admin 配置 API。

func NewVulnDataSourcesHandler

func NewVulnDataSourcesHandler(db *gorm.DB, logger *zap.Logger) *VulnDataSourcesHandler

NewVulnDataSourcesHandler 构造。

func (*VulnDataSourcesHandler) List

func (h *VulnDataSourcesHandler) List(c *gin.Context)

List GET /api/v1/vuln-data-sources 列出全部 source + 启用状态 + 上次同步信息。

func (*VulnDataSourcesHandler) TestConnection

func (h *VulnDataSourcesHandler) TestConnection(c *gin.Context)

TestConnection POST /api/v1/vuln-data-sources/:id/test 测试 source 上游可达性(HEAD 请求 base_url,60s 超时)。

func (*VulnDataSourcesHandler) TriggerSync

func (h *VulnDataSourcesHandler) TriggerSync(c *gin.Context)

TriggerSync POST /api/v1/vuln-data-sources/:id/sync 手动触发单源同步(异步)。

func (*VulnDataSourcesHandler) Update

func (h *VulnDataSourcesHandler) Update(c *gin.Context)

Update PUT /api/v1/vuln-data-sources/:id 更新 enabled / base_url。

type VulnSyncHandler

type VulnSyncHandler struct {
	// contains filtered or unexported fields
}

VulnSyncHandler 漏洞数据多源同步 admin API。

func NewVulnSyncHandler

func NewVulnSyncHandler(db *gorm.DB, logger *zap.Logger) *VulnSyncHandler

NewVulnSyncHandler 构造默认 handler。

func (*VulnSyncHandler) SyncAdvisories

func (h *VulnSyncHandler) SyncAdvisories(c *gin.Context)

SyncAdvisories POST /api/v1/vulnerabilities/advisory-sync

触发 advisory.Coordinator 拉取 RHSA/Rocky/USN/Debian/OSV,按 OS 精确匹配 入库 + soft-update 现有 host_vulnerabilities。

入参(可选):

{ "since": "2024-01-01", "truncate": false }

truncate=true 时先清空 vulnerabilities + host_vulnerabilities(仅 dev 验收使用)。

type VulnerabilitiesHandler

type VulnerabilitiesHandler struct {
	// contains filtered or unexported fields
}

VulnerabilitiesHandler 漏洞管理 API 处理器

func NewVulnerabilitiesHandler

func NewVulnerabilitiesHandler(db *gorm.DB, logger *zap.Logger) *VulnerabilitiesHandler

NewVulnerabilitiesHandler 创建漏洞处理器

func (*VulnerabilitiesHandler) ExportByOwner

func (h *VulnerabilitiesHandler) ExportByOwner(c *gin.Context)

ExportByOwner 按修复责任方导出漏洞 CSV GET /api/v1/vulnerabilities/export-by-owner?fix_owner=dev[&asset_type=app&business_line=G02&severity=critical,high]

业务场景:漏洞分级分类后,需把工作量分派到对应团队:

  • ops/sre/dba: OS / middleware 漏洞 → 直接 dnf update
  • dev: app/language_dep → 业务程序 rebuild,需要 binary_path + module + fix_version
  • image_maintainer: container/image → 镜像 rebuild,需要 image_id

导出列:host_id, hostname, ip, business_line, business_owner, business_contact,

cve, severity, cvss, cwe_category, asset_type, vuln_category,
component, current, fixed, restart_action, message

func (*VulnerabilitiesHandler) GetAssetTypeStats

func (h *VulnerabilitiesHandler) GetAssetTypeStats(c *gin.Context)

GetAssetTypeStats 按 asset_type × severity 统计漏洞数(host 维度) GET /api/v1/vulnerabilities/stats/asset-type?host_id=...&business_line=...

返回结构:

{
  "asset_types": [
    {"asset_type":"os","critical":0,"high":0,"medium":1,"low":0,"total":1},
    {"asset_type":"app","critical":8,"high":12,"medium":30,"low":2,"total":52},
    ...
  ],
  "fix_owners": [...同样结构 by fix_owner...]
}

UI 主机详情漏洞 tab 用此 endpoint 渲染分类徽章 + 切换 tab 内容。

func (*VulnerabilitiesHandler) GetPriorityStats

func (h *VulnerabilitiesHandler) GetPriorityStats(c *gin.Context)

GetPriorityStats 漏洞优先级分布统计 GET /api/v1/vulnerabilities/stats/priority

func (*VulnerabilitiesHandler) GetScanHistory

func (h *VulnerabilitiesHandler) GetScanHistory(c *gin.Context)

GetScanHistory 获取漏洞扫描历史记录 GET /api/v1/vulnerabilities/scan-history

func (*VulnerabilitiesHandler) GetScanHistoryDetail

func (h *VulnerabilitiesHandler) GetScanHistoryDetail(c *gin.Context)

GetScanHistoryDetail 获取单条扫描记录详情(含本次新增的漏洞列表) GET /api/v1/vulnerabilities/scan-history/:id

func (*VulnerabilitiesHandler) GetScanStatus

func (h *VulnerabilitiesHandler) GetScanStatus(c *gin.Context)

GetScanStatus 获取漏洞扫描最新同步状态 GET /api/v1/vulnerabilities/scan-status

func (*VulnerabilitiesHandler) GetScanTask

func (h *VulnerabilitiesHandler) GetScanTask(c *gin.Context)

GetScanTask 查单个扫描任务进度 GET /api/v1/vulnerabilities/scan-tasks/:task_id

func (*VulnerabilitiesHandler) GetVulnerability

func (h *VulnerabilitiesHandler) GetVulnerability(c *gin.Context)

GetVulnerability 获取单个漏洞详情 GET /api/v1/vulnerabilities/:id

func (*VulnerabilitiesHandler) IgnoreVulnerability

func (h *VulnerabilitiesHandler) IgnoreVulnerability(c *gin.Context)

IgnoreVulnerability 忽略漏洞 POST /api/v1/vulnerabilities/:id/ignore

func (*VulnerabilitiesHandler) ListScanTasks

func (h *VulnerabilitiesHandler) ListScanTasks(c *gin.Context)

ListScanTasks 列出扫描任务(按 created_at 降序) GET /api/v1/vulnerabilities/scan-tasks?status=running&limit=20

func (*VulnerabilitiesHandler) ListVulnerabilities

func (h *VulnerabilitiesHandler) ListVulnerabilities(c *gin.Context)

func (*VulnerabilitiesHandler) TriggerScan

func (h *VulnerabilitiesHandler) TriggerScan(c *gin.Context)

TriggerScan 触发漏洞扫描 POST /api/v1/vulnerabilities/scan

兼容两种参数:

旧: { scan_type: "full_scan" | "incremental_scan" } → 等价 scope=global
新: { scope: "global"|"hosts"|"business_line", host_ids: [], business_line: "" }

当 scope 字段存在时以 scope 为准(新字段优先)。

func (*VulnerabilitiesHandler) TriggerSync

func (h *VulnerabilitiesHandler) TriggerSync(c *gin.Context)

TriggerSync 触发漏洞库同步(仅同步 NVD + Red Hat 数据,不执行主机扫描) POST /api/v1/vulnerabilities/sync

func (*VulnerabilitiesHandler) UnignoreVulnerability

func (h *VulnerabilitiesHandler) UnignoreVulnerability(c *gin.Context)

UnignoreVulnerability 取消忽略漏洞 POST /api/v1/vulnerabilities/:id/unignore

func (*VulnerabilitiesHandler) UpdateCategoryOverride

func (h *VulnerabilitiesHandler) UpdateCategoryOverride(c *gin.Context)

ListVulnerabilities 获取漏洞列表 GET /api/v1/vulnerabilities UpdateCategoryOverride PUT /api/v1/vulnerabilities/:id/category admin 手动覆盖漏洞分类 / 重启动作(auto categorize 错时的兜底)。 body: {vuln_category_override?: string, restart_action_override?: string} 空字符串 = 清除 override 回归 auto

Directories

Path Synopsis
Package admission 实现 K8s ValidatingAdmissionWebhook v1。
Package admission 实现 K8s ValidatingAdmissionWebhook v1。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL