Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

安全审计日志:更新gateway接口文档

hanjiahuiefb3cd097d07
diff --git a/jiuwenswarm/common/audit_emit.py b/jiuwenswarm/common/audit_emit.py
index 1c52ddbedb..26317a8b65 100644
--- a/jiuwenswarm/common/audit_emit.py
+++ b/jiuwenswarm/common/audit_emit.py
@@ -60,6 +60,14 @@ def emit_audit(
except Exception: # noqa: BLE001
pass
+ try:
+ from jiuwenswarm.common.audit_gate import is_audit_config_enabled
+
+ if not is_audit_config_enabled():
+ return
+ except Exception: # noqa: BLE001
+ return
+
try:
from jiuwenswarm.telemetry.audit import audit_claw_log
diff --git a/jiuwenswarm/common/audit_gate.py b/jiuwenswarm/common/audit_gate.py
new file mode 100644
index 0000000000..36cc5dab12
--- /dev/null
+++ b/jiuwenswarm/common/audit_gate.py
@@ -0,0 +1,27 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""审计写出闸门:有库配置才允许 emit。
+
+与 OTEL / telemetry runtime 解耦,避免业务打点与冷加载互相拖依赖。
+"""
+
+from __future__ import annotations
+
+# 仅当 Gateway 本地库存在有效 audit_log_config 并完成 apply 后为 True。
+_audit_config_enabled = False
+
+
+def is_audit_config_enabled() -> bool:
+ """是否已加载有效审计配置(空库 / DELETE 后为 False)。"""
+ return _audit_config_enabled
+
+
+def set_audit_config_enabled(enabled: bool) -> None:
+ """由 ``apply_audit_log_config_payload`` 在有/无库配置时切换写出闸门。"""
+ global _audit_config_enabled
+ _audit_config_enabled = bool(enabled)
+
+
+__all__ = [
+ "is_audit_config_enabled",
+ "set_audit_config_enabled",
+]
diff --git a/jiuwenswarm/gateway/config/audit/access.py b/jiuwenswarm/gateway/config/audit/access.py
index c563baef16..2efd3eb3b3 100644
--- a/jiuwenswarm/gateway/config/audit/access.py
+++ b/jiuwenswarm/gateway/config/audit/access.py
@@ -3,6 +3,9 @@
Gateway 热更与 config_poll 使用 ``service=gateway``;
AgentServer 启动冷加载使用 ``service=agentserver``。
+
+无有效库配置时关闭写出(``set_audit_config_enabled(False)``);
+有 body 落盘并 apply 后打开写出。
"""
from __future__ import annotations
@@ -40,12 +43,15 @@ def apply_audit_log_config_payload(
validate: bool = True,
service: str = SERVICE_GATEWAY,
) -> dict[str, Any]:
- """热加载审计配置。``payload`` 为权威 body(§5.2);None 表示恢复 SDK 默认。"""
+ """热加载审计配置。``payload`` 为权威 body;None 表示清除配置并关闭写出。"""
mgr = get_audit_manager()
process_service = str(service or SERVICE_GATEWAY).strip() or SERVICE_GATEWAY
if payload is None:
mgr.apply_config({"service": process_service})
- return {"ok": True, "source": "default", "service": process_service}
+ from jiuwenswarm.common.audit_gate import set_audit_config_enabled
+
+ set_audit_config_enabled(False)
+ return {"ok": True, "source": "disabled", "service": process_service}
data = _with_process_service(payload, service=process_service)
if validate:
@@ -54,6 +60,9 @@ def apply_audit_log_config_payload(
except SchemaValidationError as exc:
raise ValueError(str(exc)) from exc
mgr.apply_config(data)
+ from jiuwenswarm.common.audit_gate import set_audit_config_enabled
+
+ set_audit_config_enabled(True)
return {"ok": True, "source": "db", "service": process_service}
@@ -115,7 +124,7 @@ async def reload_audit_log_config_from_db(
apply_audit_log_config_payload(None, service=process_service)
except Exception: # noqa: BLE001
pass
- return {"ok": False, "source": "default", "service": process_service}
+ return {"ok": False, "source": "disabled", "service": process_service}
__all__ = [
diff --git "a/jiuwenswarm/gateway/docs/Gateway\345\257\271\346\216\245\347\256\241\347\220\206\351\235\242\346\216\245\345\217\243\346\226\207\346\241\243.md" "b/jiuwenswarm/gateway/docs/Gateway\345\257\271\346\216\245\347\256\241\347\220\206\351\235\242\346\216\245\345\217\243\346\226\207\346\241\243.md"
index 1729f21740..b82f537c74 100644
--- "a/jiuwenswarm/gateway/docs/Gateway\345\257\271\346\216\245\347\256\241\347\220\206\351\235\242\346\216\245\345\217\243\346\226\207\346\241\243.md"
+++ "b/jiuwenswarm/gateway/docs/Gateway\345\257\271\346\216\245\347\256\241\347\220\206\351\235\242\346\216\245\345\217\243\346\226\207\346\241\243.md"
@@ -30,7 +30,7 @@
| Base | `gateway_config_host` | `http://{host}:19002/api/v1` |
| 信封 | `{ code, message, data }` | `{ request_id, ok, data\|error, metadata }` |
| 流式 | 无 SSE 会话流 | 流式仅 SSE |
-| 身份 | HTTP 层无 Web 租户头模型;依赖内网 / TLS(见 §16.7) | 企业推荐 `X-User-Id` / `X-Group-Id` / `X-Bot-Id` 等 |
+| 身份 | HTTP 层无 Web 租户头模型;依赖内网 / TLS(见 §18.7) | 企业推荐 `X-User-Id` / `X-Group-Id` / `X-Bot-Id` 等 |
**交互原则**
@@ -1509,11 +1509,132 @@ HMAC 密钥、Bearer token、长期明文下载凭证不得出现在模板或普
-## 13. 应用配置 — 日志脱敏规则(`log_masking_rule`)
+## 13. 应用配置 — 审计日志(`audit_log_config`)
+单行配置。权威内容在 `body`;Gateway 落盘后本进程热加载,并 `trigger_runtime_config_update`。OTEL 开关与 endpoint 由部署 `OTEL_*` / TelemetryRuntime 决定,**不由本接口驱动**。
+### 13.1 Upsert 审计日志配置
-### 13.0 表结构(`log_masking_rule`)
+- **接口名称**:Upsert 审计日志配置
+- **请求方法**:`PUT`
+- **请求路径**:`/api/v1/audit-log`
+- **请求参数**(Body):
+
+
+| 字段名 | 类型 | 必填 | 说明 |
+| --- | --- | --- | --- |
+| `body` | object | 是 | 完整可下发 payload |
+| `body.format` | object | 是 | 字段清单 |
+| `body.format.schema_version` | string | 是 | 默认 `"1.0.0"` |
+| `body.format.header_fields` | string[] | 是 | 头部属性键 |
+| `body.format.content_fields` | string[] | 是 | 内容属性键 |
+| `body.format.required_fields` | string[] | 是 | 须为 header∪content 子集 |
+| `body.format.placeholder` | string | 否 | 默认 `"-"` |
+| `body.format.timestamp_format` | string | 否 | 默认 `"yyyyMMdd-HH:mm:ss.SSS"` |
+| `body.data_center` | string | 是 | 审计头部 |
+| `body.system_code` | string | 是 | 审计头部 |
+| `body.node` | string | 否 | 审计头部,建议 `IP:PORT` |
+| `source` | string | 否 | 默认 `"manager"` |
+| `revision` | int | 否 | 默认 `1` |
+
+
+顶层 `data_center` / `system_code` / `node` 若传入,可覆盖 `body` 内同名字段。
+
+- **返回参数**:`data` 为落库行(含 `body`)
+- **请求示例**:
+
+```json
+{
+ "body": {
+ "format": {
+ "schema_version": "1.0.0",
+ "header_fields": [
+ "schema_version", "timestamp", "level", "data_center",
+ "system_code", "node", "trace_id", "txn_seq",
+ "pid", "tid", "caller"
+ ],
+ "content_fields": [
+ "UID", "CUSTID", "SRCIP", "DSTIP", "COST",
+ "UA", "EVT", "MSG", "RSPCD", "SUBMDL", "PROC",
+ "SVRNAM", "ACTION", "SANDBOXID", "RESULT"
+ ],
+ "required_fields": [
+ "timestamp", "level", "UID", "CUSTID", "SRCIP", "DSTIP",
+ "RSPCD", "SUBMDL", "PROC"
+ ],
+ "placeholder": "-",
+ "timestamp_format": "yyyyMMdd-HH:mm:ss.SSS"
+ },
+ "data_center": "N",
+ "system_code": "99900180001",
+ "node": "10.0.0.1:8080"
+ },
+ "source": "manager",
+ "revision": 1
+}
+```
+
+- **返回示例**:
+
+```json
+{
+ "code": 200,
+ "message": "success",
+ "data": {
+ "id": 1,
+ "body": {
+ "format": {
+ "schema_version": "1.0.0",
+ "header_fields": ["schema_version", "timestamp", "level", "data_center", "system_code", "node", "trace_id", "txn_seq", "pid", "tid", "caller"],
+ "content_fields": ["UID", "CUSTID", "SRCIP", "DSTIP", "COST", "UA", "EVT", "MSG", "RSPCD", "SUBMDL", "PROC", "SVRNAM", "ACTION", "SANDBOXID", "RESULT"],
+ "required_fields": ["timestamp", "level", "UID", "CUSTID", "SRCIP", "DSTIP", "RSPCD", "SUBMDL", "PROC"],
+ "placeholder": "-",
+ "timestamp_format": "yyyyMMdd-HH:mm:ss.SSS"
+ },
+ "data_center": "N",
+ "system_code": "99900180001",
+ "node": "10.0.0.1:8080"
+ },
+ "source": "manager",
+ "revision": 1
+ }
+}
+```
+
+
+
+### 13.2 删除审计日志配置
+
+- **接口名称**:删除审计日志配置(清除配置并停止写出)
+- **请求方法**:`DELETE`
+- **请求路径**:`/api/v1/audit-log`
+- **请求参数**:`{}`
+- **返回参数**:`data` 为 `null`
+- **请求示例**:
+
+```json
+{}
+```
+
+- **返回示例**:
+
+```json
+{
+ "code": 200,
+ "message": "success",
+ "data": null
+}
+```
+
+---
+
+
+
+## 14. 应用配置 — 日志脱敏规则(`log_masking_rule`)
+
+
+
+### 14.0 表结构(`log_masking_rule`)
| 字段名 | 类型 | 必填 | 说明 |
@@ -1535,7 +1656,7 @@ HMAC 密钥、Bearer token、长期明文下载凭证不得出现在模板或普
-### 13.1 创建日志脱敏规则
+### 14.1 创建日志脱敏规则
- **接口名称**:创建日志脱敏规则
- **请求方法**:`POST`
@@ -1589,7 +1710,7 @@ HMAC 密钥、Bearer token、长期明文下载凭证不得出现在模板或普
-### 13.2 更新日志脱敏规则
+### 14.2 更新日志脱敏规则
- **接口名称**:更新日志脱敏规则
- **请求方法**:`PATCH`
@@ -1620,7 +1741,7 @@ HMAC 密钥、Bearer token、长期明文下载凭证不得出现在模板或普
-### 13.3 删除日志脱敏规则
+### 14.3 删除日志脱敏规则
- **接口名称**:删除日志脱敏规则
- **请求方法**:`DELETE`
@@ -1648,11 +1769,11 @@ HMAC 密钥、Bearer token、长期明文下载凭证不得出现在模板或普
-## 14. 实例数据生命周期
+## 15. 实例数据生命周期
无独立业务表;`purge` 会清理本 Gateway 上已同步的模板 / 资源 / 应用配置等表(含 channel / cron / Manager 公钥等;不可逆)。
-### 14.1 清理实例配置数据
+### 15.1 清理实例配置数据
- **接口名称**:实例数据生命周期(purge)
- **请求方法**:`POST`
@@ -1701,7 +1822,7 @@ HMAC 密钥、Bearer token、长期明文下载凭证不得出现在模板或普
-## 15. Manager 侧调用映射(速查)
+## 16. Manager 侧调用映射(速查)
| Gateway 能力 | Manager 代码位置 |
@@ -1716,6 +1837,7 @@ HMAC 密钥、Bearer token、长期明文下载凭证不得出现在模板或普
| Agent 模板/资源推送 | `core/template/push_agent_template_to_gateway.py` |
| Agent 资源业务 | `core/instance_resource/instance_agent_resource_service.py` |
| 应用配置 | `core/application_config/*.py` |
+| 审计日志配置 | `core/application_config/audit_log_config.py` → `/api/v1/audit-log` |
| 上线全量同步 | `core/instance/instance_data_lifecycle.py` |
| 删实例清理 | `purge_gateway_instance_data` |
@@ -1724,7 +1846,7 @@ HMAC 密钥、Bearer token、长期明文下载凭证不得出现在模板或普
-## 16. 源码索引
+## 17. 源码索引
| 侧 | 路径 |
@@ -1744,14 +1866,14 @@ Gateway OpenAPI:`{gateway_config_host}/docs`。
-## 17. 与旧 Gateway 接口的差异
+## 18. 与旧 Gateway 接口的差异
> 旧实现:`jiuwenswarm/.../packages/jiuwenclaw-ee/gateway/extensions/manager_ws_client`
-> 新实现:`manager_config_receiver`(本文档 §1–§16 所描述的 HTTP Config Receiver)
+> 新实现:`manager_config_receiver`(本文档 §1–§17 所描述的 HTTP Config Receiver)
旧链路是 **Gateway 作为 WebSocket 客户端连上 Manager**,由 Manager 下发 `config.push` 帧;新链路是 **Manager 作为 HTTP 客户端主动调用** Gateway 的 `gateway_config_host`。业务落库语义大体对齐,但传输、寻址、操作编码与能力边界均已切换。
-### 17.1 架构与连接模型
+### 18.1 架构与连接模型
| 维度 | 旧(`manager_ws_client`) | 新(本文档 HTTP) |
@@ -1767,7 +1889,7 @@ Gateway OpenAPI:`{gateway_config_host}/docs`。
-### 17.2 报文形态对比
+### 18.2 报文形态对比
**旧:**`config.push` **帧(示意)**
@@ -1811,7 +1933,7 @@ Content-Type: application/json
-### 17.3 操作编码:`op` → HTTP 方法
+### 18.3 操作编码:`op` → HTTP 方法
| 旧 `op`(payload 内) | 新 HTTP | 说明 |
@@ -1821,12 +1943,12 @@ Content-Type: application/json
| `upsert` | `PUT /api/v1/...` | logging 等单文档配置 |
| `delete` | `DELETE /api/v1/...` 或 `.../{id}` | 无业务字段时 Body `{}` |
| `sync` | **无对等单接口** | 旧版全量对账(upsert 全集 + 删差集);新版由 Manager 上线引导时多次 REST 推送,或 `POST /api/v1/instance-data-lifecycle`(`purge`)清理 |
-| `activate` / `deactivate`(仅 channel) | **本 Receiver 未提供** | 见 §17.5 |
+| `activate` / `deactivate`(仅 channel) | **本 Receiver 未提供** | 见 §18.5 |
-### 17.4 能力映射速查
+### 18.4 能力映射速查
| 旧 `config` key | 旧入口 | 新 HTTP 路径(本文档) |
@@ -1839,6 +1961,7 @@ Content-Type: application/json
| `permissions_config`(旧实例级) | 旧 WS 应用配置 | `/api/v1/permissions-templates`(**改为** `permissions_template` CRUD,见 §8) |
| — | 无 | `/api/v1/mcp-templates`(**新增** `mcp_template` CRUD,见 §9) |
| `logging_config` | `apply_logging_config` | `/api/v1/logging` |
+| — | 无 | `/api/v1/audit-log`(**新增** `audit_log_config`,见 §13) |
| `log_masking_rule` | `apply_log_masking_rule` | `/api/v1/log-masking-rules` |
| `instance_data_lifecycle` | `apply_instance_data_lifecycle` | `/api/v1/instance-data-lifecycle` |
| — | 无 | `/api/v1/agent-templates`(**新增**) |
@@ -1847,7 +1970,7 @@ Content-Type: application/json
-### 17.5 旧有、本文档未覆盖的能力
+### 18.5 旧有、本文档未覆盖的能力
下列 key 仍存在于旧 `manager_ws_client` 路由中,**不在**本 Config Receiver HTTP 文档范围内(去向以当前产品设计为准:策略/映射可能仍在 Manager 侧编排,或改由 Runtime 通道下发):
@@ -1868,7 +1991,7 @@ Content-Type: application/json
-### 17.6 数据模型与实例隔离
+### 18.6 数据模型与实例隔离
| 维度 | 旧 | 新 |
@@ -1880,7 +2003,7 @@ Content-Type: application/json
-### 17.7 安全与副作用
+### 18.7 安全与副作用
| 项 | 旧 | 新 |
@@ -1892,7 +2015,7 @@ Content-Type: application/json
-### 17.8 迁移时注意点
+### 18.8 迁移时注意点
1. **不要把旧** `op` **JSON 原样 POST**:须改成对应 REST 方法与路径;模板 create 的 Body 是资源字段本身,不是 `{ "op":"create", "template":{...} }`。
2. **无** `sync` **单接口**:上线全量对齐改为 Manager 按资源逐条(或批量多次)HTTP 推送;删实例仍用 lifecycle `purge`。
diff --git a/jiuwenswarm/telemetry/audit.py b/jiuwenswarm/telemetry/audit.py
index b0772dbfa9..4fa9e9ea25 100644
--- a/jiuwenswarm/telemetry/audit.py
+++ b/jiuwenswarm/telemetry/audit.py
@@ -11,6 +11,7 @@
- :func:`install_audit_middleware` —— M1 gateway web 全局 HTTP 审计中间件
个人版:打点入口 no-op(``is_enterprise`` 门控);异常只记 warning,不影响业务。
+无 audit_log_config 库配置时:写出关闭(``is_audit_config_enabled``),直至落盘并 apply。
"""
from __future__ import annotations
@@ -21,6 +22,7 @@ from typing import Any
from openjiuwen_runtime.foundation import audit
+from jiuwenswarm.common.audit_gate import is_audit_config_enabled
from jiuwenswarm.edition import is_enterprise
from jiuwenswarm.extensions.identity_provider import IdentityStore
from jiuwenswarm.telemetry import metrics as telemetry_metrics
@@ -124,6 +126,8 @@ def audit_claw_log(
try:
if not is_enterprise():
return
+ if not is_audit_config_enabled():
+ return
ctx = _request_context()
merged_extra: dict[str, Any] = {
"agent_pod": os.getenv("HOSTNAME", ""),
diff --git a/tests/unit_tests/gateway/test_audit_access.py b/tests/unit_tests/gateway/test_audit_access.py
index 2337a06051..f2685ad3dc 100644
--- a/tests/unit_tests/gateway/test_audit_access.py
+++ b/tests/unit_tests/gateway/test_audit_access.py
@@ -12,6 +12,7 @@ from openjiuwen_runtime.foundation.audit import (
reset_audit_manager,
)
+from jiuwenswarm.common.audit_gate import is_audit_config_enabled
from jiuwenswarm.gateway.config.audit.access import (
apply_audit_log_config_payload,
apply_audit_log_config_row,
@@ -68,6 +69,8 @@ def test_apply_payload_sets_gateway_service() -> None:
result = apply_audit_log_config_payload(_sample_body())
assert result["ok"] is True
assert result["service"] == "gateway"
+ assert result["source"] == "db"
+ assert is_audit_config_enabled() is True
cfg = get_audit_manager().config
assert cfg.service == "gateway"
assert cfg.identity.system_code == "JIUWEN"
@@ -95,9 +98,12 @@ def test_apply_row_uses_body() -> None:
assert get_audit_manager().config.identity.system_code == "FROM-ROW"
-def test_apply_none_restores_default_with_gateway_service() -> None:
+def test_apply_none_disables_emit_with_gateway_service() -> None:
apply_audit_log_config_payload(_sample_body(system_code="TMP"))
- apply_audit_log_config_payload(None)
+ assert is_audit_config_enabled() is True
+ result = apply_audit_log_config_payload(None)
+ assert result["source"] == "disabled"
+ assert is_audit_config_enabled() is False
cfg = get_audit_manager().config
assert cfg.service == "gateway"
assert cfg.identity.system_code == "-"
@@ -130,7 +136,26 @@ async def test_reload_from_db_prefers_repository(monkeypatch) -> None:
monkeypatch.setattr("jiuwenswarm.edition.is_enterprise", lambda: True)
result = await reload_audit_log_config_from_db()
assert result["ok"] is True
+ assert result["source"] == "db"
+ assert is_audit_config_enabled() is True
assert get_audit_manager().config.identity.system_code == "COLD"
assert get_audit_manager().config.service == "gateway"
finally:
clear_enterprise_record_repositories()
+
+
+async def test_reload_from_empty_db_disables_emit(monkeypatch) -> None:
+ store = InMemoryPersistentBackend()
+ repo = EnterpriseRecordRepository(store, "audit_log_config", instance_id="")
+ set_enterprise_record_repository("audit_log_config", repo)
+ try:
+ apply_audit_log_config_payload(_sample_body())
+ assert is_audit_config_enabled() is True
+ monkeypatch.setattr("jiuwenswarm.edition.is_enterprise", lambda: True)
+ result = await reload_audit_log_config_from_db()
+ assert result["ok"] is True
+ assert result["source"] == "disabled"
+ assert is_audit_config_enabled() is False
+ finally:
+ clear_enterprise_record_repositories()
diff --git a/tests/unit_tests/gateway/test_audit_emit.py b/tests/unit_tests/gateway/test_audit_emit.py
index 30b22cd0db..7a580daf39 100644
--- a/tests/unit_tests/gateway/test_audit_emit.py
+++ b/tests/unit_tests/gateway/test_audit_emit.py
@@ -15,13 +15,16 @@ from jiuwenswarm.common.audit_emit import (
emit_audit_evt,
emit_audit_ua,
)
+from jiuwenswarm.common.audit_gate import set_audit_config_enabled
@pytest.fixture(autouse=True)
def _audit_memory():
mem = MemoryEmitter()
reset_audit_manager(AuditManager(emitter=mem))
+ set_audit_config_enabled(True)
yield mem
+ set_audit_config_enabled(False)
reset_audit_manager()
@@ -64,6 +67,16 @@ def test_emit_audit_caller_is_business_site(_audit_memory: MemoryEmitter, monkey
assert "audit_claw_log" not in caller
+def test_emit_audit_noop_when_config_disabled(
+ _audit_memory: MemoryEmitter,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
+ set_audit_config_enabled(False)
+ emit_audit_ua(SUBMDL="gateway", PROC="http_agent_send", UA="ok")
+ assert _audit_memory.records == []
+
+
def test_audit_timer_cost_ms() -> None:
with AuditTimer() as t:
pass