# 审计日志对齐规范

## 与 rmdc-audit-log 对齐

所有模块的审计记录必须与 `rmdc-audit-log` 模块的格式保持一致。

## 必须字段

| 字段 | 类型 | 说明 |
|:---|:---|:---|
| id | uint | 审计记录ID |
| user_id | uint | 操作人ID |
| username | string | 操作人用户名 |
| action | string | 操作类型 |
| resource_type | string | 资源类型 |
| resource_id | string | 资源ID |
| details | json | 操作详情 |
| ip_address | string | 客户端IP |
| user_agent | string | 客户端UA |
| timestamp | timestamp | 操作时间 |
| result | string | 操作结果 success/failed |

## 操作类型规范

| 模块 | 操作类型 |
|:---|:---|
| user-auth | USER_LOGIN, USER_LOGOUT, USER_CREATE, USER_UPDATE, USER_DELETE, PASSWORD_CHANGE, PERMISSION_GRANT |
| jenkins-dac | BUILD_TRIGGER, BUILD_CANCEL, PERMISSION_CHANGE |
| exchange-hub | COMMAND_SEND, COMMAND_COMPLETE |
| watchdog | DEPLOYMENT_START, DEPLOYMENT_COMPLETE, TOTP_VERIFY |
| project-mgmt | PROJECT_CREATE, PROJECT_UPDATE, AUTH_GRANT |
| work-procedure | WORKFLOW_CREATE, WORKFLOW_APPROVE, WORKFLOW_REJECT |

## 审计表保护

审计表必须设置以下保护：
1. 禁止 DELETE 操作
2. 禁止 UPDATE 操作（除标记字段外）
3. 定期备份
4. 独立存储（建议）

```sql
-- 创建只允许 INSERT 的触发器
CREATE OR REPLACE FUNCTION prevent_audit_modify()
RETURNS TRIGGER AS $$
BEGIN
    RAISE EXCEPTION 'Audit log modification is not allowed';
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER audit_log_protect
BEFORE UPDATE OR DELETE ON audit_logs
FOR EACH ROW EXECUTE FUNCTION prevent_audit_modify();
```

## 审计记录示例

```go
// user-auth 模块
audit.Record(audit.Entry{
    UserID:       operatorID,
    Username:     operatorName,
    Action:       "USER_CREATE",
    ResourceType: "user",
    ResourceID:   strconv.Itoa(int(newUser.ID)),
    Details: map[string]interface{}{
        "username": newUser.Username,
        "role":     newUser.Role,
    },
    IPAddress: c.ClientIP(),
    UserAgent: c.Request.UserAgent(),
    Result:    "success",
})
```
