# 安全（src/openhuman/security/）

`src/openhuman/security/` 是 **自主核心的信任边界**. 它负责管理自主性/风险策略，决定某个工具调用是否被允许、在宿主支持时约束这些调用的可插拔沙箱后端、每个代理动作的仅追加审计日志、加密密钥存储、控制 RPC 服务器公开绑定的配对守卫，以及 `redact()` 其他所有领域都使用的辅助函数，用于使日志中不包含明文凭据。

它做 **不** 拥有：

* 跨领域的 `EncryptionEngine` ——它位于 `src/openhuman/encryption/`.
* 按通道的凭据存储——它位于 `src/openhuman/credentials/`.

当询问“这个代理动作是否被允许；如果允许，又是如何被限制的？”时，应首先查看此模块。

## 公开表面

| 项                                                                                                                             | 文件           | 用途                                      |
| ----------------------------------------------------------------------------------------------------------------------------- | ------------ | --------------------------------------- |
| `SecurityPolicy`                                                                                                              | `policy.rs`  | 从以下内容组装运行时策略： `AutonomyConfig` + 工作区目录。 |
| `AutonomyLevel` (`受监督` / `半自主` / `自主`)                                                                                        | `policy.rs`  | 三级自主阶梯。                                 |
| `CommandRiskLevel`, `ToolOperation`, `ActionTracker`                                                                          | `policy.rs`  | 风险分类 + 每会话计数。                           |
| `Sandbox` trait， `NoopSandbox`                                                                                                | `traits.rs`  | 可插拔沙箱抽象；每个后端都实现 `Sandbox`.              |
| `create_sandbox(&SecurityConfig) -> Arc<dyn Sandbox>`                                                                         | `detect.rs`  | 在运行时选择主机上可用的最佳后端。                       |
| `pub mod docker / bubblewrap / firejail / landlock`                                                                           | （同级）         | 各后端的实现： `Sandbox`.                      |
| `SecretStore`                                                                                                                 | `secrets.rs` | 使用 XOR / 操作系统钥匙串加密的密钥持久化，并带有往返辅助函数。     |
| `AuditLogger`, `AuditEventType`, `AuditEvent`, `Actor`, `Action`, `ExecutionResult`, `SecurityContext`, `CommandExecutionLog` | `audit.rs`   | 仅追加的审计轨迹。                               |
| `PairingGuard`, `constant_time_eq`, `is_public_bind`                                                                          | `pairing.rs` | 在将 RPC 服务器公开绑定之前进行配对令牌检查。               |
| `redact(value: &str) -> String`                                                                                               | `core.rs`    | 用于日志的统一 4 字符前缀遮盖。                       |
| `security_policy_info() -> RpcOutcome<serde_json::Value>`                                                                     | `ops.rs`     | 用于 doctor / settings 界面的 RPC 处理程序。      |

## 沙箱后端选择

`detect::create_sandbox` 遍历优先级列表并返回 **首个可用的** 主机后端。确切顺序编码在 `detect.rs`；实际中它优先选择可用的最强隔离：

```
                ┌──────────────┐
SecurityConfig ─►│ create_sandbox│
                └──────┬───────┘
                       │ 探测
                       ├─► Docker      （最佳隔离；需要守护进程）
                       ├─► Bubblewrap  （Linux 用户命名空间沙箱）
                       ├─► Firejail    （Linux setuid 沙箱）
                       ├─► Landlock    （Linux LSM；进程内）
                       └─► Noop        （最后手段；仅记录日志）
```

代理永远看不到这个选择——它只是调用 `Sandbox::run(...)` ，其余由当前活动后端处理。每个后端都位于一个同级文件中（`docker.rs`, `bubblewrap.rs`, `firejail.rs`, `landlock.rs`）；noop 回退位于 `traits.rs`.

## 自主阶梯

`AutonomyLevel` 是一个三级阶梯，用于控制策略对工具调用的约束强度：

* **受监督** ——每个更高风险的工具调用都需要一次显式审批往返。
* **半自主** ——低/中风险工具调用可直接通过；更高风险的仍需审批。
* **自主** ——策略允许代理在预算和风险上限内无人值守运行。

`CommandRiskLevel` + `ToolOperation` 对给定的工具调用进行分类； `ActionTracker` 维护策略用来与上限比较的每会话计数。代理运行框架会在每次可执行工具分发前询问 `SecurityPolicy` 以获取决策。

## 审计日志

`audit.rs` 写入一个仅追加的流，内容为 `AuditEvent`个记录，位于工作区目录下。每个可执行工具调用都会连同其 `Actor` （代理/用户）， `Action`, `ExecutionResult`以及 `SecurityContext` （自主级别、沙箱后端等）一起记录下来。该日志是对代理所做之事以及其为何被允许的事后说明。

## 配对守卫

`PairingGuard` （位于 `pairing.rs`）位于 RPC 服务器与任何尝试绑定到非回环地址的行为之间。 `is_public_bind` 检测危险情况； `PairingGuard` 在允许此类绑定之前，需要一个以恒定时间比较的配对令牌（`constant_time_eq`）。这是 iOS / 局域网伴侣配对流程防止未配对对端连接到桌面核心的防护。

## 密钥存储

`SecretStore` （位于 `secrets.rs`）通过静态加密保存每个密钥的机密。在受支持的平台上，加密密钥来自操作系统钥匙串；否则会回退到工作区本地的 XOR 方案（这只是 **混淆，而非安全**，源码中也明确如此说明）。

## `redact()`

`redact(value)` 返回一个统一的 4 字符前缀字符串（例如 `"sk-a"` -> `"sk-a…"`）供日志和错误消息使用。每当机密、凭据、令牌或 PII 字符串即将被格式化进 `log::` / `tracing::` 调用时都应使用它。其他领域会直接调用它—— `credentials/`, `webhooks/`, `composio/`，这些是集成适配器。

## 布局

| 路径                                                            | 角色                                                    |
| ------------------------------------------------------------- | ----------------------------------------------------- |
| `policy.rs`, `policy_tests.rs`                                | `SecurityPolicy`, `AutonomyLevel`，风险分类，动作跟踪。          |
| `traits.rs`                                                   | `Sandbox` trait + `NoopSandbox` 回退。                   |
| `detect.rs`                                                   | `create_sandbox` ——选择最佳可用后端。                          |
| `docker.rs` / `bubblewrap.rs` / `firejail.rs` / `landlock.rs` | 各后端 `Sandbox` 实现。                                     |
| `core.rs`                                                     | `redact()` + 少量共享辅助函数（其自身有 `#[cfg(test)] mod tests`). |
| `audit.rs`                                                    | 仅追加审计日志类型。                                            |
| `secrets.rs`, `secrets_tests.rs`                              | `SecretStore` + 往返测试。                                 |
| `pairing.rs`, `pairing_tests.rs`                              | `PairingGuard` + 恒定时间辅助函数。                            |
| `ops.rs`                                                      | RPC 处理程序（`security_policy_info`).                     |
| `schemas.rs`                                                  | 控制器模式 + 处理程序分发。                                       |
| `mod.rs`                                                      | 对上述公开表面的重新导出。                                         |

## 调用

* `src/openhuman/config/` — `SecurityConfig`, `AutonomyConfig` 用于策略 + 沙箱选择。
* 操作系统级沙箱工具—— `docker`, `bwrap`, `firejail`，Landlock 系统调用（按后端）。
* 工作区文件系统——用于审计日志和密钥存储。

## 由以下调用：

* `src/openhuman/cron/scheduler.rs` ——将 shell 作业封装进 `SecurityPolicy::from_config`.
* `src/openhuman/tools/local_cli.rs`, `tools/ops.rs`，以及大多数 `tools/impl/{system,network,memory,agent}/*.rs` ——每个可执行工具都会查询 `SecurityPolicy`.
* `src/openhuman/tools/impl/network/{curl,http_request,composio}.rs` ——对外发调用进行风险分类。
* `src/openhuman/memory/tools/{store,forget}.rs` ——敏感写入跟踪。
* `src/openhuman/agent/tools/delegate.rs` ——子代理分发需经过自主性门控。
* `src/openhuman/credentials/` ——使用 `SecretStore` 和 `redact`.

## 测试

* 单元： `pairing_tests.rs`, `policy_tests.rs`, `secrets_tests.rs`.
* `core.rs` 有其自己的 `#[cfg(test)] mod tests` ——往返测试 `SecretStore` 加密/解密， `redact()` 用例， `PairingGuard` 默认值。
* 沙箱后端冒烟测试：每个后端文件都有其自己的 `#[cfg(test)]` 在主机上可用二进制文件的代码块。

## 相关

* [`security/README.md`](https://github.com/tinyhumansai/openhuman/blob/main/src/openhuman/security/README.md) ——本页面所镜像的、面向内部受众的权威概览。
* [架构概览](https://github.com/tinyhumansai/openhuman/blob/main/gitbooks/developing/architecture.md) ——更广泛的系统上下文。
* [代理运行框架](/openhuman/zh/kai-fa/architecture/agent-harness.md) ——在这里 `SecurityPolicy` 会在每次工具分发时被查询。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tinyhumans.gitbook.io/openhuman/zh/kai-fa/architecture/security.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
