Compare commits

..
13 Commits
Author SHA1 Message Date
kory 650dc7186e docs: document constrained diagnostic mode
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:34:30 +08:00
kory 5e6281ae99 feat: add constrained read-only diagnostics 2026-10-02 14:32:40 +08:00
kory 2a072f9cc9 fix: detach local sessions from request context
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:18:24 +08:00
kory 4e016fd3ba docs: record streamable http compatibility gap
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:14:26 +08:00
kory 343708eebe fix: repair session API and local session fallback
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:10:56 +08:00
kory 583b27fb5c fix: expose write_file and document one-click operations
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:07:11 +08:00
kory cc99022215 docs: restore established documentation format
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:01:14 +08:00
kory 71a596a556 docs: synchronize architecture deployment and MCP documentation
Release / Build & Release (push) Canceled after 0s
2026-10-02 13:53:00 +08:00
kory b9f7197ec7 docs: add v2.1 security hardening spec
Release / Build & Release (push) Canceled after 0s
2026-10-02 13:44:07 +08:00
kory 9fbb2bd80a fix: bridge panel admin authorization 2026-10-02 13:36:25 +08:00
kory 556870b594 feat: complete dc tool pool and final production build
Release / Build & Release (push) Canceled after 0s
2026-10-02 13:24:37 +08:00
kory 38382d2486 chore: include complete dc refactor implementation and audits
Release / Build & Release (push) Canceled after 0s
2026-10-02 13:23:30 +08:00
kory 192969d7f6 feat: finalize dc dual-channel security rollout 2026-10-02 13:23:25 +08:00
53 changed files with 7143 additions and 841 deletions
+172 -182
View File
@@ -2,12 +2,11 @@
# VPS-Commander
**面向 AI Agent (ChatGPT / Claude / MCP) 与个人运维的高性能、极轻量、多节点私有基础设施调度中枢**
**面向 AI Agent、MCP 与个人运维的高性能、轻量、多节点私有基础设施调度中枢**
[![Go Version](https://img.shields.io/badge/Go-1.22+-00ADD8?style=flat&logo=go)](https://golang.org)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Architecture](https://img.shields.io/badge/Arch-Linux%20AMD64%20%7C%20ARM64-orange)](#)
[![Memory Footprint](https://img.shields.io/badge/Memory-Hub%20%E2%89%A4%2025MB%20%7C%20Agent%20%E2%89%A4%2012MB-brightgreen)](#)
</div>
@@ -15,210 +14,201 @@
## 🌟 核心特性
- ⚡ **极致轻量,极低常驻**:纯 Go 原生编写,静态无依赖编译。Hub 核心管理进程物理常驻内存(RSS)稳定在 **15MB** 左右;受控端 Agent 内存占用仅 **7~11MB**,小内存 VPS 零负担。
- 🤖 **原生 AI 友好 (ChatGPT Actions & MCP 双协议)**:
- **OpenAPI 3.1.0 标准**:开箱即用支持 ChatGPT Custom GPTs / Claude Actions。
- **MCP (Model Context Protocol)**:内置兼容 SSE 与 JSON-RPC 标准,支持 Cursor、Windsurf、Claude Desktop 等客户端。
- **OAuth 2.0 / Bearer 认证**:支持公开客户端授权与 Bearer API Key 访问控制。
- 🌐 **多节点集群架构 (Hub & Agent)**:
- 单中心 Hub 统一管理多台受控 VPS。
- 远程 Agent 节点通过标准 WebSocket (WSS) 主动建立安全长连接回连,天然穿透 NAT 与内网,无需受控端暴露端口。
- 🛡️ **严格安全防护与权限闭环**:
- **零参数泄露**:全面封禁 CLI 敏感传参,凭据由 `0600` 环境变量接管,避免 `/proc/*/cmdline` 泄密。
- **完整审计追溯**:内置本地 SQLite 存储,全量记录调用者 IP、下发节点、指令内容、退出码及精确执行耗时。
- **执行隔离与超时回收**:内置上下文超时控制,强制清理孤儿进程,彻底杜绝僵尸进程。
- 📊 **实时节点资源画像 (Node Profiling & Role)**:
- **原生零依赖深度采集**:直接读取 Linux 内核指标,实时监控物理 CPU 核心数与瞬时负载、真实可用内存(`MemAvailable`)与 Swap、根分区磁盘占用、IO 压力指数(内核原生 PSI / Loadavg)及 Docker 守护进程运行状态。
- **动态角色标签**:支持节点角色分工(如 `CONTROL` 控制中枢、`APPLICATION` 应用节点、`DATABASE` 等),为 AI Agent 自动化调度部署决策提供全维度实时依据。
- 🛡️ **设备生命周期管理与防重连黑名单**:
- 支持管理员在 Web 控制台一键注销并强制断开指定受控节点。
- 持久化吊销拦截(Revocation List),彻底杜绝被下线 Agent 因 Systemd 自动重启而死灰复燃。
- 本地主控节点(Local)强制安全锁,防误操作防护。
- 🖥️ **内嵌极简 Web 管理面板**:
- 静态单页面(SPA)采用 Go `embed` 完整打包进二进制文件,单文件独立运行,无需安装 Node.js、Nginx 或外部静态资源 CDN。
- **工程级双态主题**:纯手绘 SVG 极简几何微图标(太阳/弦月),支持深曜蓝黑与柔和浅灰白一键切换,完美适配系统偏好且零 FOUC 白屏闪烁。
- **全端响应式**:彻底适配手机移动端(≤680px),宽表独立触控滑动,长节点名自动断行不穿透。
- ⚡ **轻量单体部署**:纯 Go 原生编译,Hub、Agent、MCP stdio 均可独立部署。
- 🤖 **原生 AI / MCP 接入**:提供 HTTP API、MCP SSE、stdio 以及 Agent WebSocket,多种客户端可以共用同一套安全模型。
- 🌐 **Hub & Agent 双通道架构**:Hub 负责控制与授权,Agent 通过 WSS 主动回连,不要求远端开放入站管理端口。
- 🛡️ **认证与授权分离**:HTTP/MCP 使用 Bearer API Key;Agent 使用每设备独立 Credential;Tool Registry + Security Snapshot 实现 Low / Medium / High 风险门禁。
- 📋 **完整审计链**:SQLite 持久化设备、凭据哈希、策略版本、操作审计与 Webhook 配置。
- 🧩 **多节点能力聚合**:文件、Shell、进程、Session、Agent MCP 等能力由 Hub 统一调度。
- 🖥️ **内嵌 Web 管理面板**:Go embed 打包,无需 Node.js 运行时。
---
## 🏗️ 架构概览
## 🏁 研发最初目标
VPS-Commander 最初并不是一个简单的远程 Shell 工具,而是为 AI Agent 建立一个**用户自己控制的私有化 Linux 运维控制面**。
### 1.1 私有化
- 运维请求通过用户自己的 Hub 和 VPS 节点完成。
- 不依赖第三方运维 Relay。
- 凭据、策略和审计数据由用户自己的基础设施控制。
### 1.2 Host-centric 运维
- 全局 Shell。
- 全局文件读写。
- 进程与长任务 Session。
- 远程 Agent MCP。
### 1.3 多节点统一调度
- 一个 Hub 管理多个 VPS。
- 使用节点名称选择目标。
- 节点离线后保留设备身份与持久化状态。
### 1.4 AI 原生接口
- HTTP API。
- MCP。
- OpenAPI 契约。
- Web 管理面板。
---
## 🏗️ 当前总体架构
```text
+-----------------------------------+
| OpenAI ChatGPT / AI Agents |
+-----------------+-----------------+
| HTTPS / MCP SSE / WSS
v
+-----------------------------------+
| 反向代理 / SSL 终止 (Lucky/Nginx)|
+-----------------+-----------------+
| 127.0.0.1:9521
v
+-------------------------------------------------------------+
| VPS-Commander Hub |
| - OpenAPI 3.1 & MCP 路由引擎 |
| - OAuth / Bearer 鉴权与 Session 会话 |
| - 本地 SQLite 审计数据库 (commander.db) |
| - 内嵌 Web 管理面板 (SPA) |
+--------------+-------------------------------+--------------+
| |
(本地执行通道) (WebSocket RPC 长连接通道)
| |
v v
+--------------------+ +--------------------+
| 宿主机 (Local) | | 受控 VPS (Agent) |
| uname / sh / 文件 | | vps-commander-a |
+--------------------+ +--------------------+
+--------------------------------------+
| AI / MCP Client / Web Panel |
+------------------+-------------------+
| HTTPS / MCP / WSS
v
+--------------------------------------+
| Reverse Proxy / TLS |
+------------------+-------------------+
| 127.0.0.1:9521
v
+-----------------------------------------------------------+
| VPS-Commander Hub |
|-----------------------------------------------------------|
| Auth / API / MCP / Web Panel |
| Security Snapshot / Tool Registry / Audit |
| Cluster Router / Session / Rate Limiter |
+----------------------+-------------------+---------------+
| |
Local Executor Agent WSS
| |
v v
Hub 本机 Remote VPS
|
Host Executor
File / Shell / Process
```
---
## 🚀 极速一键部署与平滑升级
## 🔐 当前安全模型
### 1. 一键全自动安装 (推荐)
无论是在受控端 VPS 还是中心端,只需一行命令即可交互式安装与启动:
### 1. Client Authentication
`Authorization: Bearer <API_KEY>` 是 HTTP / MCP 的主要客户端认证方式。
```bash
bash <(curl -fsSLk https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh)
```
- **安装 Agent (受控 VPS)**:输入 Hub 的 WSS 地址与通信密钥,全自动配置开机自启并秒级连入集群。
- **安装 Hub (中心服务端)**:自动生成安全 API Key / Web 面板密码并以 Systemd 托管常驻。
### 2. Agent Authentication
每个 Agent 使用独立的 `VPS_COMMANDER_AGENT_TOKEN`。
Hub SQLite 只保存 Credential Hash,不保存明文 Token。
### 2. 受控端 Agent 一键平滑升级 (免重输配置)
当新版本发布后,无需重新配置通信密钥或重新安装,在任意受控机上直接运行升级脚本:
### 3. Authorization
Tool Registry 首先确定操作风险:
```bash
curl -fsSLk https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | bash
```
- 自动检测并拉取 GitHub 最新版本架构包(AMD64 / ARM64);
- 自动备份旧版本二进制(`.bak`);
- 升级异常(校验失败或无法启动)时**自动秒级回滚**,保证节点永不失联。
| 风险 | 典型能力 |
| :--- | :--- |
| Low | 读取、搜索、设备/进程观察 |
| Medium | 文件修改、目录创建/移动、Agent MCP |
| High | Shell、进程启动、交互、终止 |
未知设备、未知身份或策略无法解析时不得获得 High 权限。
### 4. Shared Secret
生产环境已经关闭 Cluster Secret / Shared Secret fallback。
---
## 🛠️ 手动编译部署
## 🤖 当前 MCP 能力
### 1. Hub 服务端部署
目前共 **12 个 MCP Tools**:
在中心管理机上部署 Hub:
```bash
# 1. 编译二进制
make linux-amd64
# 2. 安装二进制文件
install -d -m 0750 /opt/vps-commander/data /etc/vps-commander
install -m 0755 bin/vps-commander-hub-linux-amd64 /opt/vps-commander/vps-commander-hub
# 3. 创建环境变量配置 (注意保护权限)
cat << 'ENV' > /etc/vps-commander/hub.env
VPS_COMMANDER_API_KEY=your_secure_api_key_here
VPS_COMMANDER_CLUSTER_SECRET=your_cluster_sync_secret_here
VPS_COMMANDER_WEB_PASSWORD=your_web_panel_password_here
ENV
chmod 0600 /etc/vps-commander/hub.env
# 4. 配置并启动 Systemd 服务
cp deploy/vps-commander-hub.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now vps-commander-hub
```
### 2. 远程 VPS Agent 受控端部署
在需要受控的远程 VPS 机器上执行:
```bash
# 1. 下载或拷贝 agent 二进制至远程机器
install -d -m 0750 /etc/vps-commander /opt/vps-commander
install -m 0755 vps-commander-agent-linux-amd64 /opt/vps-commander/vps-commander-agent
# 2. 配置 Agent 环境变量
cat << 'ENV' > /etc/vps-commander/agent.env
VPS_COMMANDER_HUB_WS_URL=wss://your-domain.com/agent/ws
VPS_COMMANDER_AGENT_NAME=vps-us-node01
VPS_COMMANDER_CLUSTER_SECRET=your_cluster_sync_secret_here
ENV
chmod 0600 /etc/vps-commander/agent.env
# 3. 配置并启动 Systemd 服务
cp deploy/vps-commander-agent.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now vps-commander-agent
```
Agent 启动后会通过 WSS 自动连入 Hub,在 Hub 管理面板与 `/api/v1/devices` 接口中实时显示为 `online`。
---
## 🤖 接入 ChatGPT (新版插件 Apps & MCP 模式)
当前 ChatGPT 已升级为以 **插件 / 应用 (Apps & MCP)** 规范连接外部服务。VPS-Commander 原生内置完整的 **MCP SSE + OAuth2** 协议支持,无需部署额外适配层。
### 接入配置步骤:
1. **进入 ChatGPT 插件/应用配置页**:
- 打开 ChatGPT -> **Settings (设置)** -> **Apps & Integrations (应用与集成) / Plugins** -> **Create / Add App (添加应用)**。
2. **连接方式选择 MCP**:
- 连接协议选择 **MCP (Model Context Protocol)** 或 **Server-Sent Events (SSE)**。
- **MCP Server URL**:填入 Hub 的 SSE 统一入口:
```text
https://your-domain.com/mcp/sse
```
3. **身份认证 (Authentication)**:
- **方式 A (OAuth 2.0 自动授权,推荐)**:
- Hub 内置了标准 RFC 8414 OAuth Metadata (`/.well-known/oauth-authorization-server`);
- 授权端点与 Token 端点由 ChatGPT 自动识别,一键点击「Authorize」即可完成免密安全绑定。
- **方式 B (Bearer API Key)**:
- 若选择 API Key,填入 Hub 环境变量 `VPS_COMMANDER_API_KEY` 即可。
4. **自动发现 4 大运维工具**:
- 握手成功后,ChatGPT 会自动加载并列出 4 个原生运维工具:
- `list_devices`:列出受控节点、CPU/内存/磁盘剩余绝对值及 Docker 状态;
- `exec_command`:在目标机器(如 `m4-live-agent`)执行 Shell 指令;
- `read_file`:分页读取目标文件;
- `write_file`:远程编辑或创建文件。
---
### 传统客户端支持 (Claude Desktop / Cursor / VS Code)
支持通过本地 stdio 二进制连接 Hub:
```json
{
"mcpServers": {
"vps-commander": {
"command": "/path/to/vps-commander-mcp-stdio-linux-amd64",
"args": [
"-hub", "https://your-domain.com",
"-key", "YOUR_API_KEY"
]
}
}
}
```
---
## 📊 接口与能力一览
| 接口路径 | 方法 | 功能描述 |
| Tool | Risk | 功能 |
| :--- | :--- | :--- |
| `/api/v1/devices` | `GET` | 列出集群中所有受控设备状态与**实时资源画像 (CPU/Mem/Disk/IO PSI/Docker/Role)** |
| `/panel/api/devices` | `DELETE` | 【管理员】注销并踢出指定受控节点,持久化写入防重连黑名单 |
| `/api/v1/exec` | `POST` | 在指定受控节点执行任意 Shell 指令(支持超时截断) |
| `/api/v1/file/read` | `POST` | 安全分页读取目标机器上的文件内容(防内存溢出) |
| `/api/v1/file/write` | `POST` | 向目标机器指定路径覆写或创建文件 |
| `/mcp/sse` | `GET` | MCP 协议长连接事件流通道 |
| `/panel/login` | `GET/POST`| 内嵌 Web 运维管理控制台 |
| `list_devices` | Low | 节点列表与状态 |
| `exec_command` | High | Shell 执行 |
| `read_file` | Low | 分页读取文件 |
| `read_multiple_files` | Low | 批量读取文件 |
| `create_directory` | Medium | 创建目录 |
| `move_file` | Medium | 移动/重命名 |
| `list_processes` | Low | 进程观察 |
| `edit_block` | Medium | 原子文本修改 |
| `write_file` | Medium | 创建/覆写文件 |
| `list_agent_mcp` | Low | 查看 Agent MCP |
| `call_agent_mcp` | Medium | 调用 Agent MCP |
远程 MCP 当前使用 **legacy HTTP + SSE**;本地客户端使用 stdio。
Streamable HTTP 作为下一阶段 transport 演进方向。
---
## 📊 HTTP / Web 能力
| 接口 | 方法 | 功能 |
| :--- | :--- | :--- |
| `/api/v1/devices` | GET | 设备状态与资源画像 |
| `/api/v1/exec` | POST | 远程 Shell |
| `/api/v1/file/read` | POST | 文件读取 |
| `/api/v1/file/list` | POST | 目录列表 |
| `/api/v1/file/info` | POST | 文件信息 |
| `/api/v1/file/search` | POST | 文件搜索 |
| `/api/v1/file/write` | POST | 文件写入 |
| `/api/v1/devices/file/edit_block` | POST | 安全块编辑 |
| `/api/v1/process/session` | POST | Session 操作 |
| `/api/v1/mcp/*` | GET/POST/DELETE | MCP 服务管理与调用 |
| `/api/v1/security/*` | GET/POST | 安全策略 |
| `/api/v1/notifications/webhook*` | GET/POST/DELETE | Webhook |
| `/agent/ws` | WebSocket | Agent 长连接 |
| `/panel/*` | GET/POST | Web 管理面板 |
---
## 🚀 生产部署
Hub:
```text
/opt/vps-commander/vps-commander-hub
/etc/vps-commander/hub.env
/opt/vps-commander/data/commander.db
127.0.0.1:9521
```
Agent:
```text
/opt/vps-commander/vps-commander-agent
/etc/vps-commander/agent.env
wss://vpstool.kory.kdns.fr/agent/ws
```
Agent 只主动连接 Hub,不需要公网入站端口。
生产发布顺序:
`backup → clean build → 单节点灰度 → Hub restart recovery → rolling Agent → MCP/security/audit 验收`。
---
## 🚀 一键安装与升级
### 一键安装
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh | sudo bash
```
安装脚本自动识别 `amd64/arm64` 并进入 Hub / Agent 安装流程。
### 一键升级 Agent
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | sudo bash
```
升级脚本下载目标 Release、校验文件大小、备份旧版本并在启动失败时自动回滚。
生产环境的 Agent 凭据以独立设备凭据为准;不要将 Cluster Secret 作为长期生产凭据重新启用。
---
## 📄 文档索引
- [生产部署指南与运维手册](deploy/README.md)
- [系统架构与安全设计说明](docs/ARCHITECTURE.md)
- [研发设计规范与内存基线](docs/DEV_SPEC.md)
- [阶段验收标准与门禁用例矩阵](docs/ACCEPTANCE_CRITERIA.md)
- [MCP 客户端接入协议文档](docs/MCP_INTEGRATION.md)
- [文档基线与全局索引](docs/DOCUMENTATION_BASELINE_20261002.md)
- [系统架构与开发设计规范](docs/ARCHITECTURE.md)
- [研发与协议规范](docs/DEV_SPEC.md)
- [MCP 接入指南](docs/MCP_INTEGRATION.md)
- [生产部署与运维指南](deploy/README.md)
- [发布验收标准](docs/ACCEPTANCE_CRITERIA.md)
- [项目进度与路线图](docs/PROGRESS_TRACKING.md)
- [v2.1 安全加固规范](docs/VPS_COMMANDER_V2_1_SECURITY_HARDENING_SPEC.md)
---
+177 -5
View File
@@ -23,7 +23,7 @@ import (
func main() {
hub := flag.String("hub", "", "Hub WebSocket URL")
name := flag.String("name", "", "device name")
token := flag.String("token", os.Getenv("VPS_COMMANDER_CLUSTER_SECRET"), "cluster secret")
token := flag.String("token", firstNonEmpty(os.Getenv("VPS_COMMANDER_AGENT_TOKEN"), os.Getenv("VPS_COMMANDER_CLUSTER_SECRET")), "agent credential")
insecure := flag.Bool("insecure", false, "skip TLS verification")
flag.Parse()
if *hub == "" || *name == "" || *token == "" {
@@ -74,7 +74,7 @@ func run(hub, name, token string, insecure bool) error {
// 初始握手附带画像
initProf := sysinfo.Collect("APPLICATION")
if err := writeJSON(cluster.Message{Event: "hello", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &initProf, TS: time.Now().Unix()}); err != nil {
if err := writeJSON(cluster.Message{Event: "hello", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &initProf, TS: time.Now().Unix(), ProtocolVersion: "2", AgentVersion: "2.0", Capabilities: []string{"read_file", "read_multiple_files", "list_directory", "get_file_info", "start_search", "get_more_search_results", "list_processes", "list_sessions", "read_process_output", "edit_block", "write_file", "create_directory", "move_file", "exec_command", "start_process", "interact_with_process", "kill_process", "force_terminate", "mcp_call", "mcp_list", "mcp_test"}}); err != nil {
return err
}
@@ -94,6 +94,20 @@ func run(hub, name, token string, insecure bool) error {
}
}()
sessions := executor.NewSessionManager(16)
go func() {
t := time.NewTicker(1 * time.Minute)
defer t.Stop()
for {
select {
case <-t.C:
sessions.Cleanup()
case <-stopPing:
return
}
}
}()
for {
var msg cluster.Message
if err := c.ReadJSON(&msg); err != nil {
@@ -128,16 +142,27 @@ func run(hub, name, token string, insecure bool) error {
continue
}
go func(msg cluster.Message) {
if err := handle(writeJSON, exec, mcpRuntime, msg); err != nil {
if err := handle(writeJSON, exec, mcpRuntime, sessions, msg); err != nil {
log.Printf("request %s failed: %v", msg.ID, err)
_ = c.Close()
_ = sendError(writeJSON, msg.ID, err)
}
}(msg)
}
}
func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRuntime *cluster.MCPRuntime, msg cluster.Message) error {
func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRuntime *cluster.MCPRuntime, sessions *executor.SessionManager, msg cluster.Message) error {
switch msg.Action {
case "diagnostic_command":
var p executor.DiagnosticRequest
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
v, err := executor.Diagnostic(context.Background(), p)
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
case "mcp_list":
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: mcpRuntime.List()})
case "mcp_test":
@@ -176,6 +201,134 @@ func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRunti
return nil
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: map[string]any{"server": p.Server, "tool": p.Tool, "result": result, "duration_ms": duration}})
case "start_process":
var p cluster.StartProcessPayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
if p.SessionID == "" || p.Command == "" {
return sendError(writeJSON, msg.ID, errors.New("session_id and command required"))
}
s, err := sessions.Start(context.Background(), p.SessionID, p.Command, p.Workdir, p.Owner, p.RingCapacity)
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: map[string]any{"session_id": s.ID, "started_at": s.StartedAt.Unix()}})
case "read_process_output":
var p struct {
SessionID string `json:"session_id"`
Owner string `json:"owner"`
}
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
s, ok := sessions.Get(p.SessionID)
if !ok {
return sendError(writeJSON, msg.ID, errors.New("session not found"))
}
if !s.Authorized(p.Owner) {
return sendError(writeJSON, msg.ID, errors.New("session ownership denied"))
}
code, done, _ := s.Status()
out, errout := s.Output()
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: cluster.ProcessOutputPayload{SessionID: p.SessionID, Stdout: out, Stderr: errout, ExitCode: code, Running: !done}})
case "interact_with_process":
var p cluster.ProcessInputPayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
s, ok := sessions.Get(p.SessionID)
if !ok {
return sendError(writeJSON, msg.ID, errors.New("session not found"))
}
if !s.Authorized(p.Owner) {
return sendError(writeJSON, msg.ID, errors.New("session ownership denied"))
}
if err := s.Stdin([]byte(p.Data)); err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success"})
case "force_terminate":
var p struct {
SessionID string `json:"session_id"`
Owner string `json:"owner"`
}
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
ss, ok := sessions.Get(p.SessionID)
if !ok {
return sendError(writeJSON, msg.ID, errors.New("session not found"))
}
if !ss.Authorized(p.Owner) {
return sendError(writeJSON, msg.ID, errors.New("session ownership denied"))
}
if err := sessions.Stop(p.SessionID, true); err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success"})
case "list_sessions":
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: sessions.List()})
case "read_multiple_files":
var p cluster.ReadMultipleFilesPayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: executor.ReadMultipleFiles(p.Paths, p.Limit)})
case "create_directory":
var p cluster.CreateDirectoryPayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
if err := executor.CreateDirectory(p.Path); err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success"})
case "move_file":
var p cluster.MoveFilePayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
if err := executor.MoveFile(p.Source, p.Destination); err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success"})
case "list_processes":
v, err := executor.ListProcesses()
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
case "list_directory":
var p cluster.ListDirectoryPayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
v, err := executor.ListDirectory(p.Path, p.Recursive, p.MaxEntries)
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
case "get_file_info":
var p cluster.FileInfoPayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
v, err := executor.GetFileInfo(p.Path)
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
case "start_search":
var p cluster.SearchPayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
v, err := executor.Search(context.Background(), p.Root, p.Query, p.MaxResults)
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
case "exec":
var p cluster.ExecPayload
if err := decodePayload(msg.Payload, &p); err != nil {
@@ -223,6 +376,16 @@ func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRunti
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: map[string]any{"content": string(buf[:n]), "bytes": n, "total_size": info.Size(), "has_more": p.Offset+int64(n) < info.Size(), "eof": eof}})
case "edit_block":
var p cluster.EditBlockPayload
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
res, err := executor.EditBlock(p.Path, p.OldText, p.NewText)
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: res})
case "file_write":
var p cluster.FileWritePayload
if err := decodePayload(msg.Payload, &p); err != nil {
@@ -251,3 +414,12 @@ func decodePayload(v any, out any) error {
func sendError(writeJSON func(cluster.Message) error, id string, err error) error {
return writeJSON(cluster.Message{ID: id, Status: "error", Error: err.Error()})
}
func firstNonEmpty(vs ...string) string {
for _, v := range vs {
if v != "" {
return v
}
}
return ""
}
+26 -8
View File
@@ -37,8 +37,12 @@ func main() {
apiKey := os.Getenv("VPS_COMMANDER_API_KEY")
clusterSecret := os.Getenv("VPS_COMMANDER_CLUSTER_SECRET")
webPassword := os.Getenv("VPS_COMMANDER_WEB_PASSWORD")
if apiKey == "" || clusterSecret == "" || webPassword == "" {
log.Fatal("VPS_COMMANDER_API_KEY, VPS_COMMANDER_CLUSTER_SECRET and VPS_COMMANDER_WEB_PASSWORD are required via environment")
adminToken := os.Getenv("VPS_COMMANDER_ADMIN_TOKEN")
if adminToken == "" {
adminToken = webPassword
}
if apiKey == "" || webPassword == "" {
log.Fatal("VPS_COMMANDER_API_KEY and VPS_COMMANDER_WEB_PASSWORD are required via environment")
}
authManager := auth.NewManager(apiKey)
store, err := storage.Open(*dbPath)
@@ -57,12 +61,19 @@ func main() {
notificationManager.Start()
defer notificationManager.Stop()
s := &api.Server{
Auth: authManager,
Exec: executor.Local{MaxOutput: 1024 * 1024},
Cluster: cluster.NewManager(clusterSecret, store),
Store: store,
LocalName: local,
Notify: notificationManager,
Auth: authManager,
Exec: executor.Local{MaxOutput: 1024 * 1024},
Cluster: cluster.NewManager(clusterSecret, store),
Store: store,
LocalName: local,
Notify: notificationManager,
AdminToken: adminToken,
ExecLimiter: make(chan struct{}, 32),
SearchLimiter: make(chan struct{}, 8),
LocalSessions: executor.NewSessionManager(0),
}
if err := s.LoadSecurityPolicySnapshot(); err != nil {
log.Fatalf("load security policy snapshot: %v", err)
}
// MCP Server instance
@@ -111,6 +122,13 @@ func main() {
IdleTimeout: 90 * time.Second,
}
log.Printf("vps-commander-hub listening on %s as %s", *addr, local)
go func() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for range ticker.C {
s.LocalSessions.Cleanup()
}
}()
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
+7
View File
@@ -100,6 +100,13 @@ func (h *HubRemoteBackend) ReadFile(ctx context.Context, clientIP, device, path
return res, err
}
func (h *HubRemoteBackend) EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error) {
payload := map[string]any{"device": device, "path": path, "old_text": oldText, "new_text": newText}
var res any
err := h.post("/api/v1/devices/file/edit_block", payload, &res)
return res, err
}
func (h *HubRemoteBackend) WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error) {
payload := map[string]any{
"device": device,
+171 -74
View File
@@ -1,79 +1,139 @@
# VPS-Commander 部署与运维指南
本文档介绍 VPS-Commander 的生产环境部署架构、配置规范与运维操作。
本文档介绍 VPS-Commander 当前生产环境部署架构、凭据规范、Agent 接入、升级与回滚流程。
---
## 一、 系统架构与端口规划
## 一、系统架构与端口规划
- **Hub 服务端**:统一监听本地 `127.0.0.1:9521`,不对公网直接暴露端口。
- **反向代理 (Lucky)**:
- 域名:`https://vpstool.kory.kdns.fr`
- 转发目标:`http://127.0.0.1:9521`
- 核心要求:开启 **WebSocket Upgrade** 支持,转发透传所有子路径(`/.well-known/*`、`/oauth/*`、`/mcp/*`、`/api/v1/*`、`/agent/ws`、`/panel/*`)。
- SSL 终止于反代层,反代自动携带 `X-Forwarded-Proto: https` 头以保障 Cookie 的 `Secure` 属性。
- **Agent 客户端**:
- 运行于受控的远程 VPS 机器上。
- 通过公网 WSS 长连接主动回连 Hub:`wss://vpstool.kory.kdns.fr/agent/ws`。
- **Hub 服务端**:监听 `127.0.0.1:9521`,不直接暴露公网。
- **反向代理**:公网 HTTPS/WSS 入口为 `https://vpstool.kory.kdns.fr`。
- **Agent 客户端**:通过 `wss://vpstool.kory.kdns.fr/agent/ws` 主动回连 Hub。
反代必须支持:
- WebSocket Upgrade;
- `/agent/ws`;
- `/mcp/*`;
- `/api/v1/*`;
- `/panel/*`;
- `/.well-known/*`;
- `/oauth/*`。
---
## 二、 凭据安全规范(强制要求)
## 二、凭据安全规范(强制要求)
1. **绝对禁止命令行参数传密**:
- 二进制不再支持 `--api-key`、`--cluster-secret`、`--web-password` 命令行参数。
- 彻底杜绝在 `/proc/*/cmdline` 和 `ps aux` 中泄露明文密码。
2. **凭据存储位置与权限**:
- 凭据文件保存在 `/etc/vps-commander/hub.env` 与 `/etc/vps-commander/agent.env`。
- 权限必须严格设置为 `0600`(仅 root 可读写)。
### 2.1 Hub 凭据
Hub 使用:
- `VPS_COMMANDER_API_KEY`;
- `VPS_COMMANDER_WEB_PASSWORD`。
生产环境不再依赖 `VPS_COMMANDER_CLUSTER_SECRET` 作为 Agent 身份 fallback。
### 2.2 Agent 凭据
每台 Agent 使用独立:
`VPS_COMMANDER_AGENT_TOKEN`。
Hub SQLite 仅保存 Credential Hash。
### 2.3 文件权限
```bash
chmod 0600 /etc/vps-commander/hub.env
chmod 0600 /etc/vps-commander/agent.env
```
### 2.4 v2.1 安全要求
当前 v2.0 代码仍兼容旧的 `-token` 参数;下一版本要求 Secret 不出现在 argv / `/proc/*/cmdline`,优先使用 systemd EnvironmentFile / LoadCredential。
---
## 三、 Hub 服务端部署步骤
## 三、一键安装与升级
### 1. 编译并安装二进制
### 3.1 一键安装
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh | sudo bash
```
脚本自动识别 `amd64/arm64`,并进入 Hub / Agent 安装流程。
- Hub:自动生成 API Key 与 Web 面板密码。
- Agent:输入 Hub WSS 地址、节点名称和独立 Agent Token。
- 生产环境不再要求 Cluster Secret 作为长期凭据。
### 3.2 一键升级 Agent
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | sudo bash
```
升级流程:
```text
下载 Release
↓
临时文件完整性检查
↓
备份当前 Agent
↓
原子替换
↓
systemd restart
↓
健康检查
├─ 成功 → 删除备份
└─ 失败 → 自动恢复旧版本
```
### 3.3 手工安装
如果需要固定版本、离线部署或灰度验证,再使用下面的手工安装流程。
---
## 四、Hub 服务端部署步骤
### 4.1 编译
```bash
cd /root/.openclaw/workspace/vps-commander
go test ./...
go test -race ./...
git diff --check
make clean
make linux-amd64
```
发布前必须确认:
```text
vcs.modified=false
vcs.revision=<release commit>
```
### 4.2 安装
```bash
install -d -m 0750 /opt/vps-commander/data /etc/vps-commander
install -m 0755 bin/vps-commander-hub-linux-amd64 /opt/vps-commander/vps-commander-hub
```
### 2. 配置环境变量文件 (`/etc/vps-commander/hub.env`)
### 4.3 配置
```bash
cat << 'ENV' > /etc/vps-commander/hub.env
VPS_COMMANDER_API_KEY=your_generated_api_key_here
VPS_COMMANDER_CLUSTER_SECRET=your_generated_cluster_secret_here
VPS_COMMANDER_WEB_PASSWORD=your_generated_web_password_here
VPS_COMMANDER_API_KEY=your_secure_api_key
VPS_COMMANDER_WEB_PASSWORD=your_web_password
ENV
chmod 0600 /etc/vps-commander/hub.env
```
### 3. 配置 Systemd 托管 (`/etc/systemd/system/vps-commander-hub.service`)
### 4.4 Systemd
```ini
[Unit]
Description=VPS-Commander Hub
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/vps-commander
EnvironmentFile=-/etc/vps-commander/hub.env
ExecStart=/opt/vps-commander/vps-commander-hub -addr 127.0.0.1:9521 -db /opt/vps-commander/data/commander.db
Restart=always
RestartSec=3s
KillSignal=SIGTERM
TimeoutStopSec=10s
LimitNOFILE=65536
Environment=GOGC=50
[Install]
WantedBy=multi-user.target
```
### 4. 启动服务
### 4.5 启动
```bash
systemctl daemon-reload
systemctl enable --now vps-commander-hub
@@ -82,62 +142,99 @@ systemctl status vps-commander-hub
---
## 四、 远程 Agent 节点部署步骤
## 五、远程 Agent 节点部署步骤
若要将其他 VPS 纳入受控列表,在该远程 VPS 上执行:
### 5.1 安装二进制
```bash
install -d -m 0750 /etc/vps-commander /opt/vps-commander
install -m 0755 vps-commander-agent-linux-amd64 /opt/vps-commander/vps-commander-agent
```
### 1. 安装 Agent 二进制
将编译生成的 `bin/vps-commander-agent-linux-amd64`(或 ARM64 版本)上传至目标 VPS 的 `/opt/vps-commander/vps-commander-agent` 并赋予执行权限 `chmod +x`。
### 2. 配置 Agent 环境变量 (`/etc/vps-commander/agent.env`)
### 5.2 配置
```bash
install -d -m 0750 /etc/vps-commander
cat << 'ENV' > /etc/vps-commander/agent.env
VPS_COMMANDER_HUB_WS_URL=wss://vpstool.kory.kdns.fr/agent/ws
VPS_COMMANDER_AGENT_NAME=vps-node-01
VPS_COMMANDER_CLUSTER_SECRET=与Hub相同的CLUSTER_SECRET
VPS_COMMANDER_AGENT_TOKEN=<per-device-token>
ENV
chmod 0600 /etc/vps-commander/agent.env
```
### 3. 配置 Systemd 托管 (`/etc/systemd/system/vps-commander-agent.service`)
### 5.3 Systemd
```ini
[Unit]
Description=VPS-Commander Agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/vps-commander
EnvironmentFile=-/etc/vps-commander/agent.env
ExecStart=/opt/vps-commander/vps-commander-agent -hub ${VPS_COMMANDER_HUB_WS_URL} -name ${VPS_COMMANDER_AGENT_NAME}
Restart=always
RestartSec=3s
KillSignal=SIGTERM
TimeoutStopSec=10s
LimitNOFILE=65536
Environment=GOGC=50
[Install]
WantedBy=multi-user.target
```
### 4. 启动并连入集群
当前 v2.0 生产迁移阶段可兼容显式 token;v2.1 发布后必须改为不出现在 ExecStart 的方式。
### 5.4 启动
```bash
systemctl daemon-reload
systemctl enable --now vps-commander-agent
systemctl status vps-commander-agent
```
启动后,Hub 控制面板与 `/api/v1/devices` 接口将立即展示该节点并标记为 `online`。
Agent 启动后主动连接 Hub,并在设备列表中显示为 `online`。
---
## 五、 控制面板与 Actions 使用
## 六、控制面板与 MCP 使用
1. **管理后台地址**:`https://vpstool.kory.kdns.fr/panel/login`
2. **后台功能**:
- **设备看板**:查看所有在线/离线节点、系统架构与延迟。
- **快速控制台**:直接在网页端向指定节点执行 Shell 指令。
- **审计日志**:实时监控 GPT 与用户的全部执行调用、命令详情与耗时。
- **Actions 向导**:一键复制 Schema 地址、System Prompt 与 API 密钥。
### 6.1 管理面板
`https://vpstool.kory.kdns.fr/panel/login`
面板包含设备状态、安全策略、操作控制、审计和相关管理功能。
### 6.2 MCP
远程入口:
`https://vpstool.kory.kdns.fr/mcp/sse`
本地 stdio 使用 `vps-commander-mcp-stdio`。
当前共 12 个 MCP tools,详见 `docs/MCP_INTEGRATION.md`。
---
## 七、生产升级流程
```text
Backup
↓
Clean Build
↓
Single-node Gray Release
↓
Hub Restart Recovery
↓
Rolling Agent
↓
MCP / Security / Audit Smoke Test
↓
Full Acceptance
```
任一节点断联、权限绕过、Credential 泄露或协议不兼容,立即停止发布并回滚。
---
## 八、日常运维检查
```bash
systemctl status vps-commander-hub
journalctl -u vps-commander-hub -n 100
curl -fsS http://127.0.0.1:9521/healthz
```
集群可通过 Web Panel、`/api/v1/devices` 或 MCP `list_devices` 检查。
---
## 九、当前生产审计提示
2026-10-02 审计发现生产 Hub / Agent 曾由 `vcs.modified=true` 的工作树构建。
因此生产现场二进制不能直接视为当前 HEAD 的可复现产物。
下一次正式发布必须 clean rebuild,并重新部署与验证。
+9 -14
View File
@@ -72,15 +72,15 @@ install_agent() {
read -rp "请输入本节点名称 (默认: ${DEFAULT_NAME}): " AGENT_NAME
AGENT_NAME=${AGENT_NAME:-${DEFAULT_NAME}}
read -rp "请输入 Cluster Secret (集群通信密钥): " CLUSTER_SECRET
while [ -z "$CLUSTER_SECRET" ]; do
read -rp "Cluster Secret 不能为空,请重新输入: " CLUSTER_SECRET
read -rp "请输入 Agent 独立凭据 Token: " AGENT_TOKEN
while [ -z "$AGENT_TOKEN" ]; do
read -rp "Agent Token 不能为空,请重新输入: " AGENT_TOKEN
done
cat << ENV > "${CONF_DIR}/agent.env"
VPS_COMMANDER_HUB_WS_URL=${HUB_WS}
VPS_COMMANDER_AGENT_NAME=${AGENT_NAME}
VPS_COMMANDER_CLUSTER_SECRET=***
VPS_COMMANDER_AGENT_TOKEN=${AGENT_TOKEN}
ENV
chmod 0600 "${CONF_DIR}/agent.env"
@@ -133,23 +133,19 @@ install_hub() {
read -rp "请输入监听端口 (默认 9521): " HUB_PORT
HUB_PORT=${HUB_PORT:-9521}
GEN_API_KEY=*** -c 24 /dev/urandom | xxd -p)
GEN_SECRET=*** -c 24 /dev/urandom | xxd -p)
GEN_API_KEY=$(head -c 24 /dev/urandom | xxd -p)
GEN_PASS=$(head -c 16 /dev/urandom | xxd -p)
read -rp "请输入 API Key (默认随机生成): " API_KEY
API_KEY=***
read -rp "请输入 Cluster Secret (默认随机生成): " CLUSTER_SECRET
CLUSTER_SECRET=${CLUS…RET}
API_KEY=${API_KEY:-$GEN_API_KEY}
read -rp "请输入 Web 管理面板密码 (默认随机生成): " WEB_PASS
WEB_PASS=${WEB_PASS:-$GEN_PASS}
cat << ENV > "${CONF_DIR}/hub.env"
VPS_COMMANDER_API_KEY=***
VPS_COMMANDER_CLUSTER_SECRET=***
VPS_COMMANDER_WEB_PASSWORD=***
VPS_COMMANDER_API_KEY=${API_KEY}
VPS_COMMANDER_WEB_PASSWORD=${WEB_PASS}
ENV
ENV
chmod 0600 "${CONF_DIR}/hub.env"
@@ -185,7 +181,6 @@ SVC
echo -e "\n================== Hub 配置凭据 =================="
echo -e "监听地址: 127.0.0.1:${HUB_PORT}"
echo -e "API Key: ${API_KEY}"
echo -e "Cluster Secret: ${CLUSTER_SECRET}"
echo -e "Web 面板密码: ${WEB_PASS}"
echo -e "==================================================\n"
warn "请妥善保管上述凭据,反代请将域名反代至 127.0.0.1:${HUB_PORT}"
+118 -37
View File
@@ -1,50 +1,131 @@
# VPS-Commander 验收审核标准与收尾门禁规范 (Quality Gate & Acceptance Criteria)
# VPS-Commander 阶段验收标准与发布门禁用例矩阵
> 本规范由架构与质量负责人(OpenClaw)制定并执行最终裁决。
> 任何交付代码必须满足以下全量准入与准出指标方可判定为验收通过(Release Ready)。
本文档定义当前 v2.0 生产架构的发布门禁,并为 v2.1 安全加固预留验收项。
---
## 一、 核心门禁四不原则(强制一票否决项)
## 一、构建与版本一致性
1. **绝对无外部公网中转**:任何网络交互(除与 OpenAI 官方通信外)严禁经过第三方 Relay 服务器,必须 100% 走私有域名直连。
2. **绝对零残留孤儿进程**:执行任何命令、超时中断或连接断开后,后台不得产生僵尸进程或孤儿子进程。
3. **绝对无未授权越权**:所有非公共接口必须强制 Bearer Token / Cluster Secret 校验,缺失或错误凭证必须严厉返回 HTTP 401,严禁静默放行。
4. **内存超标即挂**:Hub 静态常驻物理内存不得突破 **25 MB**,Agent 客户端常驻物理内存不得突破 **12 MB**;10MB 为优化目标。
### 1.1 基础测试
```bash
go test ./...
go test -race ./...
git diff --check
```
### 1.2 生产构建
- Git 工作树必须 clean。
- `vcs.modified=false`。
- `vcs.revision` 必须等于 release commit。
- AMD64 / ARM64 编译成功。
---
## 二、 详细验收测试用例矩阵 (12 项全绿门禁)
## 二、Hub / Agent 集群验收
| 用例 ID | 验证模块 | 测试动作与输入 | 预期结果与合格标准 | 验证方式 |
| :--- | :--- | :--- | :--- | :--- |
| **TC-01** | **OpenAPI 规范合法性** | `GET /openapi.json` | 格式符合 OpenAPI 3.1.0 标准,包含 servers URL、4 个标准 path、安全定义为 `bearerAuth`(HTTP Bearer),可通过 Swagger / OpenAI Actions 校验无报错。 | 机器静态校验 |
| **TC-02** | **未授权拦截** | 无 Token 请求 `/api/v1/exec` | 立即返回 HTTP 401 Unauthorized,响应体包含 `{"error": "Unauthorized"}`,不触发任何底层 bash。 | `curl -i` 验证 |
| **TC-03** | **本地基础命令执行** | `POST /api/v1/exec` (`{"device":"local","command":"uname -a"}`) | 返回 exit_code: 0,stdout 正确包含 Linux 内核信息,duration_ms > 0 且合理。 | 实测响应校验 |
| **TC-04** | **命令超时与进程回收** | 执行 `sleep 10`,设置 `timeout: 2` | 命令在 2 秒后强制终止,返回超时错误,且检查系统进程树确认 `sleep` 进程彻底消失,无僵尸残留。 | `ps -ef` 核查 |
| **TC-05** | **文件分页读取防爆** | 读取 10MB 文本文件,设置 `limit: 1024` | 仅返回前 1024 字节内容,返回 `total_size` 与 `has_more: true`,严禁一次性将全文件读入内存。 | 接口响应验证 |
| **TC-06** | **文件安全覆写** | `POST /api/v1/file/write` 写入 `/tmp/vps_cmd_test.txt` | 文件内容精确写入,权限正常,支持覆盖写入。 | 本地文件比对 |
| **TC-07** | **Agent 握手与注册** | 启动 Agent 连入 Hub WSS | Hub 面板与 `GET /api/v1/devices` 瞬间显示该设备为 `online`,展示正确 IP 与内核信息。 | 状态机校验 |
| **TC-08** | **心跳保活与离线感知** | 模拟杀死 Agent 进程 | 经过 2 个心跳周期(~60s)后,Hub 自动将该节点状态变更为 `offline`,不发生 panic。 | 节点状态监听 |
| **TC-09** | **跨节点路由下发** | `POST /api/v1/exec` (`{"device":"hwsg","command":"uptime"}`) | Hub 正确通过 WebSocket 寻址到远程 Agent,Agent 执行并原路返回,耗时增加在 RTT 合理范围内。 | 跨机实测 |
| **TC-10** | **Web 管理面板嵌入** | 浏览器直接访问 `GET /` | 页面秒开,设备列表、ChatGPT 向导、审计日志正常渲染,无任何外部 CDN 404,无 node 构建产物遗留。 | 浏览器/Headless 验证 |
| **TC-11** | **审计日志完备性** | 执行一次正常命令与一次失败命令 | 查询 SQLite `audit_logs` 表,两条记录均完整存在(含 IP、设备、指令、退出码、耗时),字段无空缺。 | SQLite 查询比对 |
| **TC-12** | **内存基线压测** | 连续并发执行 100 次 `ps aux` | 压测结束后,Hub RSS 必须 ≤ 25MB;20MB 为优化目标。压测结束后应回落并稳定,无持续增长趋势。 | `ps -eo rss` 采样 |
| 项目 | 验收标准 |
| :--- | :--- |
| Hub | 监听 `127.0.0.1:9521` |
| Agent | 5 个远程节点可正常回连 |
| Restart | Hub 重启后 Agent 自动恢复 |
| Identity | Credential 与设备身份一致 |
| Unknown | 未知设备必须 fail-closed |
---
## 三、 严格收尾与交付规范 (Sign-off Checklist)
## 三、认证与授权验收
GPT 完成开发提交代码后,由我执行以下严苛收尾工作:
1. **代码审计 (Code Review)**:
- 检查并发安全性(互斥锁 `sync.RWMutex` 是否合理、Channel 是否有阻塞泄漏风险)。
- 检查外部输入 Shell 命令的执行上下文,是否存在注入或不可控行为。
2. **构建与打包 (Clean Build)**:
- 生成标准的 `Makefile`,支持编译 Linux AMD64/ARM64 静态无依赖产物。
- 清理所有中间编译缓存与临时测试文件。
3. **部署托管与 Systemd 固化**:
- 为 Hub 编写规范的 `vps-commander-hub.service`。
- Lucky 反代添加规则及 SSL 校验。
4. **终验报告与归档**:
- 输出完整的《VPS-Commander 最终验收合格报告》。
- 将完整配置参数与使用说明同步至长期记忆 `MEMORY.md`。
- Bearer API Key 正常。
- URL token (`?token` / `?key` / `?api_key`) 必须拒绝。
- 每设备 Credential 独立。
- Shared Secret fallback 关闭。
- Panel Admin Token 不进入浏览器。
- Tool Registry 风险等级一致。
- Policy version 不允许回退。
---
## 四、MCP 验收矩阵
| Tool | Risk | 基础用例 |
| :--- | :--- | :--- |
| `list_devices` | Low | 返回设备列表 |
| `exec_command` | High | `echo/true` |
| `read_file` | Low | 读取 `/etc/hostname` |
| `read_multiple_files` | Low | 批量读取临时文件 |
| `create_directory` | Medium | 创建临时目录 |
| `move_file` | Medium | 移动临时文件 |
| `list_processes` | Low | 返回进程 |
| `edit_block` | Medium | 唯一匹配修改 |
| `write_file` | Medium | 写入临时文件 |
| `list_agent_mcp` | Low | 查询 Agent MCP |
| `call_agent_mcp` | Medium | 调用无害 Agent MCP |
必须同时验证:
- Medium 策略可以阻断 Medium 工具。
- Medium 策略可以阻断 High 工具。
- MCP 与 HTTP 使用同一授权逻辑。
- `call_agent_mcp` 无旁路。
---
## 五、文件与 Session 验收
### 5.1 edit_block
- old_text 唯一匹配。
- generation check。
- atomic write。
- fsync。
- 失败不破坏原文件。
### 5.2 Session
- Hard TTL。
- Idle TTL。
- Ring Buffer 上限。
- 总 buffer 上限。
- 并发访问安全。
- kill 只能作用于 Session 内部 process handle。
---
## 六、API Regression
必须覆盖:
- `/api/v1/devices`
- `/api/v1/exec`
- file read/list/info/search/write
- edit_block
- process/session
- MCP services/list/call/test
- security settings
- webhook
- Panel
- Agent WebSocket
---
## 七、发布停止条件
出现以下任一情况立即停止发布:
- Agent 断联。
- 未授权请求成功。
- unknown device 获得 High。
- MCP 存在旁路。
- Token 出现在 argv。
- 审计丢失。
- dirty binary。
- Policy version 回退。
- Session 资源无限增长。
---
## 八、v2.1 验收预留
### P0
- EffectiveRisk 完全 fail-closed。
- Agent Credential 不进入 argv / cmdline。
### P1
- Principal / Operator。
- Session Owner 强隔离。
- principal → credential → session → device → operation 审计链。
+180 -127
View File
@@ -1,148 +1,201 @@
# VPS-Commander(自托管私有化多节点运维管家)架构与开发设计规范
## 1. 项目立项背景与目标
## 一、项目立项背景与目标
### 1.1 背景与痛点
- 当前市面方案(如 Desktop Commander)严重依赖公共第三方中继(SaaS Relay),存在严重的命令与数据泄漏风险、Token 明文暴露风险以及第三方额度/速率限制。
- 现有纯开发网关(如 CodePier)采用项目目录沙箱隔离,无法进行系统级运维(如查看全局进程、管理 Lucky/Docker、修改全盘系统配置等),且不支持 ChatGPT 原生 Actions 插件生态。
- 早期方案过度依赖第三方 Relay,控制面与节点执行面边界不清。
- 单机开发网关通常存在项目目录沙箱,无法覆盖完整 Host-centric 运维。
- AI Agent 需要的不只是 Shell,而是节点发现、文件、进程、Session、MCP 和审计的一体化控制面。
### 1.2 核心目标
- **100% 私有化部署**:数据仅在 OpenAI 官方服务器和用户私有 VPS 之间传输,零第三方中转。
- **全权宿主运维 (Host-centric)**:提供全局 Shell、进程管理、文件读写能力。
- **多节点别名调度**:通过单一 Hub 统一管理多台 VPS/客户端节点,支持在 ChatGPT 中通过自然语言昵称(如 "hwsg"、"wjyhk")随时切换目标节点。
- **原生 ChatGPT 插件集成**:提供标准 OpenAPI 3.1 规范与 Actions 端点,在 ChatGPT 手机端/网页端呈现为原生交互卡片。
- **超轻量 Go 架构**:Hub 常驻 RSS 目标 ≤ 20MB、硬上限 25MB;Agent 常驻 RSS 目标 ≤ 10MB、硬上限 12MB。
- **100% 私有化控制面**:Hub、Agent、SQLite 与反向代理均由用户控制。
- **Host-centric 运维**:Shell、文件、进程、Session、远程 MCP。
- **多节点统一调度**:一个 Hub 管理多个 VPS,节点状态持久化。
- **AI 原生接入**:HTTP、MCP、stdio、Web 管理面板。
- **安全闭环**:认证、风险授权、资源限制、审计、可回滚发布。
---
## 2. 总体架构设计
## 二、总体架构设计
```text
[ 用户在 ChatGPT APP / Web 端发指令 ]
│
▼ (HTTPS POST + Bearer API Key)
[ 用户私有域名反代 (Lucky SSL) ]
│
▼ (反向代理至 127.0.0.1:28800)
┌────────────────────────────────────────────────────────┐
│ VPS-Commander Hub (中央管理网关) │
│ │
│ ├─ OpenAPI / Actions Engine (/openapi.json, /api/v1) │
│ ├─ 鉴权与安全过滤中间件 (Auth Middleware) │
│ ├─ 设备拓扑注册表 (Device Registry & State Machine) │
│ ├─ 审计日志存储 (SQLite: audit.db) │
│ └─ 路由分发器 (Router Dispatcher) │
└───────────┬────────────────────────────────┬───────────┘
│ │
(本地进程直连: target="local") (安全 WebSocket 长连接 / mTLS)
│ │
▼ ▼
[ 本机 Local Executor ] [ 远程 Agent (Node: hwsg) ]
- bash -c ... - Client Agent Daemon
- 文件/进程直接操作 - 接收 JSON-RPC 指令并执行
[ AI / MCP Client / Web Panel ]
│
▼ HTTPS / MCP
[ Reverse Proxy / TLS ]
│
▼ 127.0.0.1:9521
┌──────────────────────────────────────────────┐
│ VPS-Commander Hub │
│----------------------------------------------│
│ Auth / API / MCP / Web Panel │
│ Policy Snapshot / Tool Registry │
│ Cluster Router / Session / Rate Limit │
│ SQLite / Audit / Webhook │
└──────────────┬───────────────────┬───────────┘
│ │
Local Executor Agent WSS
│ │
▼ ▼
Hub 本机 Remote VPS
│
Host Executor
Shell / File / Process
```
### 2.1 控制通道
AI / MCP / HTTP 请求进入 Hub,由 Hub 完成认证、设备解析、风险判断和路由。
### 2.2 节点通道
Agent 主动通过 WSS 回连 Hub,负责设备注册、状态、能力协商及 RPC 请求/响应。
两条通道共享同一设备身份、策略和审计上下文,不允许出现 MCP 或 Agent MCP 绕过 Hub 授权的旁路。
---
## 三、Hub 与 Agent 通信规范
### 3.1 Agent 注册与鉴权
- Agent 连接:`wss://<hub>/agent/ws`。
- 使用每设备独立 Credential。
- Hub 从已认证 Credential 建立 Canonical Device Identity。
- 客户端自报 `device/name` 不能成为授权身份来源。
- 生产不再使用 Cluster Secret fallback。
### 3.2 协议握手
握手包含:
- Protocol Version;
- AgentVersion;
- Capabilities;
- Per-device Credential。
### 3.3 RPC
Hub 将经过授权的操作转换为 Agent RPC。
Agent 返回结果后,Hub 完成审计并将结果返回 HTTP/MCP 调用方。
---
## 四、安全与权限模型
### 4.1 认证
- HTTP / MCP:Bearer API Key。
- Web Panel:Panel Session,服务端内部 bridge Admin Token。
- Agent:per-device credential。
### 4.2 Tool Risk Registry
| 风险 | 典型操作 |
| :--- | :--- |
| Low | read_file、read_multiple_files、list_directory、file_info、search、list_processes |
| Medium | edit_block、write_file、create_directory、move_file、mcp_call |
| Low | diagnostic_command:严格白名单只读诊断(Docker、systemd、journal、网络监听、磁盘、内存、uptime) |
| High | exec_command、start_process、interact_with_process、kill_process、force_terminate |
### 4.3 Policy Snapshot
- 安全策略持久化到 SQLite。
- 每次更新生成单调递增 version。
- Hub 请求路径读取内存 Snapshot。
- 未知、未注册、凭据错误或身份无法解析的设备必须 deny。
- GlobalRisk 不得让未知设备获得 High。
v2.1 将彻底清理 `EffectiveRisk` 中仍存在的 GlobalRisk fallback。
---
## 五、Session 与执行安全
### 5.1 Session 资源限制
- Ring Buffer 默认 2MB。
- 总 Session buffer 上限 8MB。
- Hard TTL 30 分钟。
- Idle TTL 10 分钟。
- LastAccess 自动刷新。
- 过期与空闲 Session 自动清理。
### 5.2 进程生命周期
kill / terminate 使用 Session 内部进程句柄,不接受客户端任意 PID 作为授权对象。
### 5.3 文件修改
`edit_block` 使用唯一匹配、generation check、临时文件、fsync、atomic rename 和权限保留,失败时不破坏原文件。
---
## 六、MCP 架构
当前 MCP 共 12 个工具:
1. `list_devices`
2. `exec_command`
3. `read_file`
4. `read_multiple_files`
5. `create_directory`
6. `move_file`
7. `list_processes`
8. `diagnostic_command`:严格白名单的只读系统诊断;
8. `edit_block`
9. `write_file`
10. `list_agent_mcp`
11. `call_agent_mcp`
`call_agent_mcp` 必须经过 MCP risk gate,不允许成为远程 Agent 的权限旁路。
当前远程 transport 为 legacy HTTP + SSE,本地客户端为 stdio;Streamable HTTP 属于后续演进。
---
## 七、项目工程结构与技术选型
- **语言**:Go。
- **存储**:SQLite。
- **HTTP**:标准库。
- **Web**:Go embed。
- **节点通信**:WebSocket。
```text
cmd/
├── hub/
├── agent/
└── mcp-stdio/
internal/
├── api/
├── auth/
├── cluster/
├── executor/
├── mcp/
├── model/
├── notify/
├── security/
├── storage/
└── web/
```
---
## 3. 核心接口与协议规范 (OpenAPI 3.1)
## 八、生产部署边界
ChatGPT Actions 识别的标准接口集合:
- Hub:`127.0.0.1:9521`。
- 公网由 Reverse Proxy 终止 TLS。
- Agent 仅出站连接 Hub。
- 数据库:`/opt/vps-commander/data/commander.db`。
- systemd:`vps-commander-hub.service` / `vps-commander-agent.service`。
### 3.1 `/api/v1/devices` (GET)
- **说明**:获取当前所有在线/受管设备列表及健康状态。
- **返回**:`[{"name": "wjyhk", "is_local": true, "status": "online"}, {"name": "hwsg", "status": "online"}]`
### 3.2 `/api/v1/exec` (POST)
- **说明**:在指定节点执行 Shell 命令。
- **请求体**:
```json
{
"device": "hwsg", // 节点昵称,缺省默认 local / wjyhk
"command": "free -h", // 要执行的命令
"workdir": "/root", // 可选工作目录
"timeout": 30 // 超时时间(秒)
}
```
- **响应体**:
```json
{
"device": "hwsg",
"exit_code": 0,
"stdout": "...",
"stderr": "",
"duration_ms": 120
}
```
### 3.3 `/api/v1/fs/read` (POST)
- **说明**:受控读取指定设备的文件内容。
- **参数**:`device`, `path`, `offset_bytes`, `limit_bytes`(防止大文件撑爆模型上下文)。
### 3.4 `/api/v1/fs/write` (POST)
- **说明**:在指定设备创建或覆写文件。
- **参数**:`device`, `path`, `content`。
升级必须执行:
1. backup;
2. clean build;
3. 单节点灰度;
4. Hub restart recovery;
5. rolling Agent;
6. MCP/security/audit 验收。
---
## 4. Hub 与 Agent 节点通信规范
## 九、v2.1 演进方向
1. **Agent 注册与鉴权**:
- Agent 启动时通过 `wss://hub.domain.com/agent/ws` 发起长连接。
- 握手使用 `Authorization: Bearer <cluster-secret>` Header;Cluster Secret 不进入 URL。
- 握手成功后,Hub 内存注册表更新该设备为 `online`,并启动双向 Heartbeat ping/pong(30s 周期)。
### 9.1 P0
- EffectiveRisk 完全 fail-closed。
- Agent Credential 不进入 argv / cmdline。
2. **指令下发 (JSON-RPC)**:
- Hub 收到 ChatGPT 请求 ➡️ 生成 `task_id` ➡️ 通过 WS 发送 `{"action": "exec", "task_id": "...", "command": "..."}`。
- Agent 执行完毕后返回 `{"task_id": "...", "result": {...}}`。
- Hub 审计日志落库后返回给 ChatGPT。
---
## 5. 项目工程结构与技术选型
- **开发语言**:Go 1.22+(高性能、低内存、单二进制交叉编译友好)
- **Web 框架**:Gin 或纯标准库 `net/http` + `gorilla/websocket`
- **存储**:SQLite (纯粹用于审计日志与持久化配置)
```
vps-commander/
├── cmd/
│ ├── hub/ # 中央控制网关主入口
│ └── agent/ # 节点客户端主入口
├── internal/
│ ├── api/ # ChatGPT Actions HTTP 接口
│ ├── auth/ # Bearer Token 与 Secret 鉴权
│ ├── cluster/ # 节点连接池、心跳与 WebSocket 管理
│ ├── executor/ # 本地/远程执行器抽象
│ └── storage/ # 审计日志与设备配置持久化
├── web/ # 极简设备状态面板(纯 HTML/CSS 嵌入二进制)
├── openapi/ # 供 ChatGPT 导入的 openapi.json
├── Makefile # 多架构编译 (linux/amd64, linux/arm64)
└── README.md # 部署与 ChatGPT 配置指南
```
---
## 6. Hub Web 控制面板设计规范
### 6.1 定位与设计原则
- **极简独立**:前端采用纯 HTML5 + TailwindCSS/原生CSS + Vanilla JS,不引入复杂 node 构建工具链,通过 Go 1.16+ `embed.FS` 直接打包进单一二进制产物。
- **开箱即用**:零外部静态资源依赖,访问 `https://hub.yourdomain.com/` 即可直接加载。
- **低资源消耗**:Web 面板由 Hub 服务原生托管,静态文件常驻开销基本为零。
### 6.2 核心功能模块
1. **设备看板 (Device Overview)**
- 受管设备列表:别名(Alias)、当前状态(Online/Offline)、系统架构与内核、IP 地址、最后心跳(Heartbeat)。
- 快速连接指引:点击“添加节点”,自动生成带 Token 的单行一键安装/运行命令(如 `curl -sL https://... | bash -s -- --hub=... --token=...`)。
- 设备启停与踢出操作:支持在面板主动注销失效/弃用节点。
2. **ChatGPT Actions 配置与向导中心**
- 托管与展示 `/openapi.json` 规范预览。
- 提供专属 API Key 生成、轮换与撤销功能。
- 提供直接导入 ChatGPT Custom GPT 的一键复制 Schema 按钮与预设 System Prompt 建议。
3. **实时操作审计与日志 (Audit Log)**
- 记录来源(ChatGPT / Web 手动)、目标设备、动作(exec / file_read / file_write)、执行内容、执行耗时、退出码与结果摘要。
- 支持按设备、关键字实时搜索过滤。
4. **Web 快速调试终端 (Quick Terminal / Console)**
- 提供快速测试输入框,选择目标设备后可直接输入命令测试执行并查看即时输出,无需打开 ChatGPT 即可验证节点联通性。
### 9.2 P1
- Principal / Operator Identity。
- Session Owner 强隔离。
- principal → credential → session → device → operation 完整审计链。
+129
View File
@@ -0,0 +1,129 @@
# vps-commander 生产 Bug Hunt 报告(2026-10-02)
- **测试人**:安全测试员(独立 bug hunt)
- **测试时间**:2026-10-02 13:36–13:50(+08)
- **测试对象**:生产 Hub(wjyhk,13:36:06 重启)+ 6 节点 Agent
- **测试方式**:只读探测 + 无害命令(echo/true),未写生产文件、未改配置、未重启服务、未碰 commander.db
- **结论**:发现 **4 个 bug**,最高严重度 **高**。另有若干“未发现问题”的项如实记录。
---
## 【标题】生产 Agent 二进制构建自脏工作树,缺失已提交代码
**【严重度:高】**
**【复现步骤】**
1. 在 wjyhk 执行 `go version -m /opt/vps-commander/vps-commander-agent`,观察 `vcs.revision=a5620cb` 且 `vcs.modified=true`。
2. 对比源码:`git show a5620cb:cmd/agent/main.go` 的 action switch 只有 6 个 case(mcp_list/mcp_test/mcp_call/exec/file_read/file_write),无 session 相关、无 `read_multiple_files`。
3. 但生产 Agent 实际能处理 `start_process`(session 功能可用),说明二进制内容无法从任何 commit 还原——是脏树构建。
4. Hub 同样 `vcs.modified=true`(13:36 重部署的二进制,revision=556870b)。
**【证据】**
```
build vcs.revision=a5620cb9c4d3570cf5ce2abe8772ef4e3b91bd76
build vcs.time=2026-10-01T16:45:10Z
build vcs.modified=true
```
各节点 Agent md5 一致(35e965a9),均为同一脏构建,于 13:22 统一重启部署。
**【影响分析】**
- 生产二进制不可复现:出问题时无法用 `git checkout <rev> && go build` 还原现场,排障与回滚失去基准。
- 脏构建内容未知:`read_multiple_files` 在源码 192969d 中已加入 Agent,但生产 Agent 不支持(见 Bug #3),说明构建时的脏树处于部分完成状态,**可能还缺失其他已提交的安全修复**,需逐项核对。
- **建议**:从干净 HEAD 重新构建 Hub+Agent,全量重新部署,部署后校验 `vcs.modified` 为空且 revision==HEAD。
---
## 【标题】`read_multiple_files` 在所有远端节点上失败(Hub-Agent 协议不一致)
**【严重度:中】**
**【复现步骤】**
1. `vps-mcp.py call read_multiple_files '{"device":"hwsg","paths":["/etc/hostname"],"limit":100}'` → 返回 `{"error": "unsupported action"}`。
2. 同样调用 `device=wjyhk`(本地)→ 正常返回文件内容。
3. 查源码:`internal/api/mcp_adapter.go:287` 的 `ReadMultipleFiles` 对远端走 `Cluster.ReadMultipleFiles`;Agent 侧 `cmd/agent/main.go:261` 在当前源码中有该 case,但生产 Agent 二进制(脏构建)不支持,落入 `default: unsupported action`(main.go:391)。
**【证据】**
```json
{"error": "unsupported action"}
```
(hwsg/N3450 等远端节点复现,wjyhk 本地正常)
**【影响分析】**
- MCP 工具列表向 AI 客户端 quảng cáo `read_multiple_files` 可用于所有设备,实际 5/6 节点不可用,功能性 bug。
- 根因是 Bug #1(脏构建)的直接后果;修复 Bug #1(干净重建+重部署)后本项自动解决。
- 在修复前,建议 Hub 对不支持该 action 的 Agent 返回明确错误而非透传 `unsupported action`,或在 capability 协商中隐藏该工具。
---
## 【标题】`/api/v1/process/session` 请求结构体无 JSON tag,snake_case 字段被静默丢弃
**【严重度:中】**
**【复现步骤】**
1. `POST /api/v1/process/session?action=start`,body `{"device":"hwsg","command":"echo hi","session_id":"my-id"}`(snake_case,如响应格式所示)。
2. 响应返回 `{"session_id":"04d39d85b150..."}`——**客户端传的 ID 被丢弃**,服务端生成了随机 ID。
3. 随后用 `my-id` 做 read/stop → `session not found`。
4. 改用精确大小写 `{"SessionID":"my-id"}` → 全流程正常。
**【证据】**
```go
// internal/api/api.go:784
var req struct {
Device, SessionID, Command, Workdir, Data string // 无 json tag!
Force bool
RingCapacity int `json:"ring_capacity"`
}
```
Go encoding/json 对无 tag 字段仅做大小写不敏感匹配,`session_id`(snake_case)无法匹配 `SessionID`,被静默忽略。
**【影响分析】**
- API 契约破裂:响应用 `session_id`(snake_case),请求却要求 `SessionID`(CamelCase);任何按常规 REST 惯例(或照着响应字段)写的客户端都会踩坑,且失败是静默的(拿到一个“成功”但对不上的 session)。
- 非安全漏洞,但属于生产功能 bug。修复:在结构体上加 `json:"device"` 等 snake_case tag(注意与 openapi.json 文档对齐)。
---
## 【标题】`/api/v1/process/session` 不支持 Hub 本节点(无本地回退)
**【严重度:中低】**
**【复现步骤】**
1. `POST /api/v1/process/session?action=start`,body `{"Device":"wjyhk","Command":"echo hi"}`。
2. 返回 `device offline`(HTTP 409)。
3. 对比:`POST /api/v1/exec` 同样 `device=wjyhk` 可正常执行(`exec` 有 `isRemote` 本地回退,api.go:744)。
**【证据】**
```go
// processSession 直接走 Cluster,无 isRemote 判断:
if s.Cluster == nil { http.Error(w, "cluster unavailable", 503); return }
...
result, err = s.Cluster.StartProcess(ctx, req.Device, ...) // wjyhk 无 agent WS 连接 → device offline
```
**【影响分析】**
- 功能不一致:exec/read/write 等在 Hub 本节点可用,唯独 session 管理不可用。用户在 Hub 本机无法使用长会话功能。
- 修复:给 processSession 加与 exec 相同的 `isRemote` 本地回退(Hub 侧需持有一个本地 SessionManager,或复用 executor 包)。
---
## 未发现问题的项(逐项如实记录)
1. **认证绕过**:无 token/错 token/空 Bearer 访问 `/api/v1/*` 与 `/panel/api/*` 均返回 401;`/healthz` 200 为预期设计。未发现绕过。
2. **畸形输入**:malformed JSON、空 body、300KB 超大 body(超 256KB MaxBytesReader 限制)均返回 400,无 panic。Hub 日志自 13:24 以来 0 panic、0 error。
3. **路径穿越**:`../../../etc/hostname` 可读、`\0` 被 `validPath` 拦截(400)。但本工具是已认证管理员工具,无沙箱设计约束,`..` 解析属操作系统正常行为,不视为漏洞。
4. **设备名注入**:空字符串回退本机(设计如此)、不存在设备/超长字符串/含 `\0` 的设备名均 `security mode unknown denies exec`,fail-closed,无 panic。
5. **Session 生命周期**:Agent 侧每分钟 `sessions.Cleanup()`,idle TTL 10min + hard TTL 存在;`SessionManager` 有互斥锁,5 并发创建 session 无竞态崩溃(2 成功、3 因达到上限 4 被正确拒绝,上限由 `MaxSessionBufferTotal/DefaultRingCapacity=4` 决定,符合设计)。
6. **并发压力**:10 并行原生 HTTP 请求全部 200、响应快;Hub 内存稳定(~20MB)。30 并行 MCP 调用大量超时系客户端 SSE 建连开销,非 Hub 问题。
7. **配额**:`ExecLimiter` 32 并发信号量存在;无单客户端速率限制(设计选择,非 bug)。
8. **Agent-MCP 畸形参数**:不存在的 tool/含 `\0` 的参数返回干净的 `MCP HTTP status 400`,无 panic、无信息泄漏。
9. **kill 进程**:API 只接受 SessionID,Agent 用内部 `cmd.Process` 句柄 kill,不接受客户端 PID,无 PID 重用误杀风险。
---
## 附:测试期间观察到的部署活动
- 13:36:06 Hub 被重部署(此前为 13:24),二进制 revision 由 38382d2 变为 556870b。测试期间生产处于活跃变更中,部分结论(如 Hub revision)以测试时刻为准。
- Agent 在各节点为同一脏构建(md5 35e965a9,13:22 部署),`vcs.modified=true`。
---
*安全测试员,2026-10-02*
+81
View File
@@ -0,0 +1,81 @@
# DC Refactoring Phase 1 Implementation Record
> 文档属性:历史实施记录。后续阶段和当前状态以当前架构规范与 v2.1 规范为准。
Date: 2026-10-02
## Completed
- Added immutable Hub `PolicySnapshot` protected by `RWMutex`.
- Added monotonic security policy version persisted in SQLite.
- Hub startup now rebuilds the snapshot from SQLite; snapshot load failure aborts startup rather than defaulting to High.
- Security setting writes use SQLite transactions and only publish the new snapshot after the durable write succeeds.
- Added a compile-time Tool Registry with fixed `RequiredRisk` for Low/Medium/High capabilities.
- Existing API security checks now resolve required risk through the registry instead of duplicating risk numbers in handlers.
- Security-setting audit records include old/new effective mode and snapshot version.
## Compatibility / Safety
- Existing API routes and Agent WebSocket protocol were not changed in this phase.
- No production Hub/Agent restart was performed.
- When `Server.Policy` is initialized, security checks use the in-memory snapshot and do not query SQLite on the request hot path.
- Existing tests that construct `Server` without a snapshot retain the legacy storage fallback for test/backward compatibility; production startup always initializes the snapshot.
## Verification
- `go test ./...` passed.
- `go test -race ./...` passed.
- Hub and Agent clean builds passed.
- No production service restart was performed; live rollout remains a separate controlled step to preserve the no-interruption requirement.
## Phase 2 Completed
- Added `edit_block` to the Agent execution engine.
- `old_text` must match exactly once; zero/multiple matches are rejected without mutation.
- Replacement uses a same-directory temporary file, preserves file permission bits, fsyncs the file, renames atomically, and syncs the directory.
- Added Agent RPC action `edit_block`, Hub `/api/v1/devices/file/edit_block`, MCP `edit_block`, and stdio proxy support.
- `edit_block` is registered as Medium risk and therefore follows the existing Hub policy snapshot gate.
- Added optional `sub_action` protocol field without changing existing message semantics.
- Added tests for unique replacement, duplicate/missing rejection, permissions, Low-mode denial, and MCP registration.
Phase 2 rollout remains deliberately separate from production process replacement. Existing production Agent connections have not been restarted.
## Phase 3 Completed
- Added a per-Agent `SessionManager` with a bounded session count (default 16).
- Added fixed-size 2 MiB stdout/stderr RingBuffers; old output is discarded when capacity is exceeded.
- Added long-running process actions: `start_process`, `read_process_output`, `interact_with_process`, `force_terminate`, `list_sessions`.
- Processes run in their own process group so termination/force termination covers the command tree.
- Added periodic completed-session cleanup.
- Added Hub RPC and HTTP `/api/v1/process/session` dispatch with action-based lifecycle operations.
- Added session tests for ring retention, output capture, termination, duplicate IDs, and session limits.
- Existing WebSocket request/response protocol remains compatible; new process actions are additive.
Production Hub/Agents were not restarted during Phase 3 implementation.
## Phase 3 Security Hardening / Concurrency Gate
- Added per-node operation arbitration in `cluster.Node.OpMu`.
- Low-risk read actions use `RLock` and may run concurrently.
- Medium/High mutations use exclusive `Lock`, preventing overlapping writes/control operations against the same node.
- Unknown actions fail closed as High risk for the concurrency gate.
- Session IDs are generated with 128-bit `crypto/rand` entropy when omitted by the API caller; PID is never used as identity.
- Session ownership is bound to a non-reversible SHA-256 fingerprint of the authenticated API credential and checked by Agent for read/input/terminate operations.
- Session TTL is enforced; stdin is capped at 64 KiB per call.
- Agent restart still leaves all sessions in process memory only, so old session state is not restored.
All validation passed with `go test ./...`, `go test -race ./...`, Hub/Agent builds, and `git diff --check`. No production process was restarted.
## Phase 4 Completed
- Added optional protocol/agent capability metadata: `ProtocolVersion`, `AgentVersion`, `Capabilities`.
- Hub records the capability set per connected Agent; when a modern Agent explicitly advertises capabilities, unsupported actions fail with `capability missing` rather than silently degrading.
- Old Agents remain compatible because capability metadata is optional and capability enforcement is only applied when a capability set is advertised.
- Added structured read-only filesystem operations: `list_directory`, `get_file_info`, `start_search`.
- Directory listing supports bounded recursive traversal and a maximum entry count.
- File metadata exposes type, size, mode and modification time.
- Search is context-cancellable and bounded by a result cap; symlinks are skipped to avoid traversal surprises.
- Added Hub endpoints `/api/v1/file/list`, `/api/v1/file/info`, `/api/v1/file/search`.
- Added executor tests for directory listing, file metadata and bounded search.
Phase 4 validation: full tests, race tests, Hub/Agent builds and `git diff --check` passed. Production Hub/Agents were not restarted.
+934
View File
@@ -0,0 +1,934 @@
# 《VPS-Commander 平滑升级改造与三级安全拦截实施方案》
## 1. 改造目标与背景
本项目计划全量复刻 **Desktop Commander(DC)** 在终端与文件系统上的核心工程能力(包括局部块级精准替换、后台长进程生命周期管理、交互式 stdin 注入、结构化目录遍历与只读检索),并将其无缝接入 **Low(低风险)/ Medium(中风险)/ High(高风险)** 三级安全门禁体系。
**核心红线与验收标准:**
1. **服务不中断**:升级过程不影响正在运行的 Agent 探针与 Hub 中心。
2. **协议向后兼容**:旧版 Agent 与新版 Hub 混合共存,老接口绝不废弃。
3. **性能零损耗**:杜绝动态运行时映射,安全校验在编译期即已绑定。
4. **轻量化保真**:继续保持纯 Go 静态编译的高效特性,严控内存占用(常驻内存锁定在 20MB 以内)。
---
## 2. 工具池全量复刻与三级风险定级表(静态强绑定)
所有功能根据系统破坏力与副作用大小,在**编译期**严格归属于三级风险体系:
| 风险等级 (Level) | 行为边界定义 | 包含的复刻工具 (DC 标杆) | 允许放行的安全模式 |
| :--- | :--- | :--- | :--- |
| 🟢 **Low(只读/感知)** | **纯只读、无状态改变、无系统副作用** | • `read_file` (支持切片与 Tail)<br>• `read_multiple_files`<br>• `list_directory` (结构化目录树)<br>• `get_file_info` (元数据)<br>• `start_search` / `get_more_search_results`<br>• `list_processes` / `list_sessions`<br>• `read_process_output` (拉取输出) | **Low**<br>**Medium**<br>**High** |
| 🟡 **Medium(文件写)** | **文件与目录变更,但严禁拉起任意二进制或执行命令** | • `edit_block` (局部文本块精准替换,核心)<br>• `write_file` (文件新建/全量写入)<br>• `create_directory` (新建目录)<br>• `move_file` (移动/重命名) | **Medium**<br>**High**<br>*(Low 拦截)* |
| 🔴 **High(完全控制)** | **具备操作系统执行权、进程生命周期调度与管道干预** | • `exec_command` (同步短命令)<br>• `start_process` (后台异步启动长进程)<br>• `interact_with_process` (stdin 交互写入)<br>• `kill_process` / `force_terminate` (终止进程) | **High**<br>*(Low / Medium 拦截)* |
---
## 3. 架构改造与平滑过渡设计
### 3.1 协议层平滑升级(零破坏向后兼容)
在 `internal/cluster/protocol.go` 中,保留原有字段,新增可选的扩展动作:
```go
type Message struct {
ID string `json:"id,omitempty"`
Action string `json:"action,omitempty"` // 保持原有字段: "read" / "write" / "exec" / "probe"
SubAction string `json:"sub_action,omitempty"` // ✨ 增量动作: "edit_block", "start_process" 等
Device string `json:"device,omitempty"`
Payload any `json:"payload,omitempty"`
...
}
```
* **兼容保障**:老版本 Agent 接收到带 `SubAction` 的 JSON 消息时会自动忽略多余字段,继续按老逻辑工作;升级后的 Agent 优先路由给 `SubAction` 处理。
### 3.2 Hub 门禁与高并发性能优化(读写分离)
现有系统每次请求均去 SQLite 查询策略,高并发下存在文件锁瓶颈。改造后引入 **RWMutex 内存策略快照**:
1. **读路径(Fast Path,纳秒级)**:
```go
// 常量数值定义,直接内联比较
const ( RiskLow = 1; RiskMedium = 2; RiskHigh = 3 )
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device string, requiredRisk int, detail string) bool {
allowed := s.getEffectiveRiskLevel(device) // 查内存 RLock,耗时 < 10ns
if allowed >= requiredRisk {
return true
}
// 记录 audit_logs ("security_denied", 403) 并返回拦截响应
return false
}
```
2. **写路径(Slow Path,低频)**:
* 仅在管理员通过 Web 界面更改安全策略时,写一次 SQLite 并原子更新内存缓存。
3. **老 API 零改动**:
* 原有 `/api/v1/devices/exec`、`/read`、`/write` 继续保留,老脚本老客户端零感知。
### 3.3 Agent 端核心引擎实现(防资源膨胀设计)
* **`edit_block` 引擎**:
* 读取原文件后校验 `old_text` 全局唯一性,唯一时单次替换并使用临时文件进行原子覆写(`os.Rename`)。
* 相比原有全量上传,网络传输和内存开销下降 95%。
* **长进程与 PTY 会话引擎(`start_process` 等)**:
* Agent 内部建立轻量 `SessionManager`,挂接内核标准输入输出管道。
* **硬编码内存锁(Circular RingBuffer)**:每个进程会话分配最大 2MB 环形日志缓冲区,达到上限自动覆盖最早输出,**从物理上杜绝日志死循环导致的内存溢出(OOM)**。
---
## 4. 资源开销评估与性能上限控制
得益于纯 Go 原生静态编译,系统坚决不引入任何 Node.js/Python 运行时,资源开销保持极致克制:
| 评估指标 | 改造前基准(实测) | 改造后预期 | 性能/资源防护机制 |
| :--- | :--- | :--- | :--- |
| **Agent 静默内存** | ~13 MB | **~15 MB - 18 MB** | 零后台轮询,事件驱动 |
| **Agent 峰值内存** | 随命令大小波动 | **基准 + (2MB × 活跃会话数)** | 环形缓冲区硬顶锁定,防内存泄露 |
| **Hub 服务端内存** | ~16 MB | **~18 MB - 22 MB** | 内存门禁仅占不到 10KB |
| **二进制体积** | ~9.4 MB | **~11 MB - 13 MB** | 静态单文件编译,极易分发部署 |
| **安全判定延迟** | 毫秒级(查 SQLite) | **纳秒级(内存读锁)** | 单机可轻松支撑 10W+ QPS 门禁并发 |
---
## 5. 四阶段实施与回滚路线图(稳健落地)
* **Phase 1:服务端门禁升级与内存读缓存**
* 在 Hub 端落地 `RWMutex` 安全策略缓存;
* API 入口统一接入 `requireSecurity(..., RiskLevel)`;
* *验证标准*:旧版 4 项基础功能与 Web 面板完好,并发查询 QPS 大幅提升。
* **Phase 2:落地中风险神器 `edit_block`**
* Agent 端实现块级精准替换算法;
* Hub 暴露 `/api/v1/devices/file/edit_block` 并注册至 MCP Adapter;
* *验证标准*:在 Medium 模式下可正常修配置文件,在 Low 模式下被精确阻断并记入审计。
* **Phase 3:落地高风险长进程引擎**
* Agent 端引入带 RingBuffer 的 `SessionManager`;
* 实现 `start_process`、`read_process_output`、`interact_with_process`、`kill_process`;
* *验证标准*:跑耗时任务不会超时断连,支持实时 Tail 查看输出与注入 stdin。
* **Phase 4:落地只读结构化文件与系统感知(Low)**
* 实现 `list_directory`、`get_file_info` 及后台异步只读搜索。
---
## 6. 评估与审计重点建议
1. **安全维度**:Low/Medium/High 对能力的切分是否彻底杜绝了提权与逃逸风险?
2. **性能维度**:使用内存 RWMutex + 编译期静态安全级别判定,是否彻底解决了单文件 SQLite 高频读瓶颈?
3. **稳定性维度**:为每个长进程会话限定 RingBuffer 内存上限,是否有效防止了边缘 VPS 探针被日志撑爆?
---
# 7. 架构收敛修订(2026-10-02)
> 本章节在进入代码实施前增加,用于两位外部 Agent 审核。原方案的工具分级、四阶段路线和向后兼容原则继续保留;本章节对安全权威、策略一致性、工具注册以及高风险 Session 生命周期作进一步约束。
## 7.1 安全等级的正确边界:静态工具风险 + 运行时设备策略
原方案中“静态强绑定”应准确解释为:**工具所需风险等级在编译期固定,是否允许执行在运行时由 Hub 的权威策略决定。**
不得将设备当前 Low/Medium/High 策略编译进 Agent,也不得允许 Agent 自行提升自身安全等级。
### 7.1.1 工具风险等级
每个工具在代码注册表中拥有不可运行时修改的 `RequiredRisk`:
```go
const (
RiskLow = 1
RiskMedium = 2
RiskHigh = 3
)
type ToolSpec struct {
Name string
RequiredRisk int
ReadOnly bool
}
```
示例:
```text
read_file / list_directory / search -> Low
edit_block / write_file / move_file -> Medium
exec_command / start_process / stdin -> High
```
禁止通过 Web 面板、Agent 配置文件或远端请求动态修改工具自身的 `RequiredRisk`。
### 7.1.2 设备有效策略
设备的 `EffectiveRisk` 是 Hub 运行时策略,不属于 Agent 自主能力。
请求授权模型:
```text
Request
-> identify device
-> identify ToolSpec.RequiredRisk
-> read Hub PolicySnapshot
-> compare EffectiveRisk >= RequiredRisk
-> allow / deny
```
因此完整安全边界为:
**编译期固定“工具需要什么权限” + 运行时决定“该设备当前获得什么权限”。**
---
## 7.2 Policy Store 与 Policy Snapshot 一致性模型
SQLite 继续作为持久化权威源(durable source of truth),但请求热路径禁止每次查询 SQLite。
### 7.2.1 数据流
```text
Admin Web
|
v
SQLite transaction
|
v
Build new immutable PolicySnapshot
|
v
Atomic publish / swap
|
v
Request fast path
```
请求只读取当前不可变 snapshot;不在请求过程中修改策略对象。
### 7.2.2 更新原则
策略修改必须满足:
1. SQLite 写入成功后才允许发布新 snapshot。
2. SQLite 写失败时,内存策略保持旧版本。
3. snapshot 发布必须是原子操作,不允许出现半更新状态。
4. Hub 启动时必须从 SQLite 完整重建 snapshot。
5. snapshot 应携带单调递增 `Version`,便于审计和诊断。
6. 审计记录应包含 `device`, `oldRisk`, `newRisk`, `version`, `actor`, `timestamp`。
推荐结构:
```go
type PolicySnapshot struct {
Version uint64
Devices map[string]DevicePolicy
CreatedAt time.Time
}
```
热路径原则:
```text
load current snapshot
-> lookup device
-> compare integer risk
-> allow/deny
```
不得在高频 API 请求中重新读取 SQLite 策略表。
### 7.2.3 故障安全
如果 Hub 无法加载有效策略 snapshot:
- 不得默认放行 High。
- 不得从请求参数接受临时风险等级。
- 对需要 Medium/High 的操作默认拒绝。
- Low 只读能力是否可继续开放,必须由启动时的明确安全默认策略决定,并记录审计事件。
---
## 7.3 Tool Registry:统一能力与风险注册表
避免各 API handler 自己实现不同的安全判断。所有能力必须进入统一 Tool Registry。
建议:
```go
type ToolSpec struct {
Name string
RequiredRisk int
Category string
ReadOnly bool
Description string
}
```
例如:
```text
read_file Low
read_multiple_files Low
list_directory Low
get_file_info Low
start_search Low
get_more_search_results Low
list_processes Low
list_sessions Low
read_process_output Low
edit_block Medium
write_file Medium
create_directory Medium
move_file Medium
exec_command High
start_process High
interact_with_process High
kill_process High
force_terminate High
```
API、MCP Adapter 和内部调用均通过 Registry 获取 `RequiredRisk`,不得在多个入口复制风险数字。
---
## 7.4 Agent 信任边界
Agent 是执行者,不是安全策略的最终裁决者。
Hub 是设备授权策略的权威来源。
但 Agent 仍必须执行本地最低限度安全校验,包括:
- 请求格式与参数校验;
- session 所有权校验;
- session 是否仍然有效;
- 单次输入/输出大小限制;
- 超时和资源限制;
- 不接受客户端自行声明的 `RiskLevel` 作为授权依据。
Agent 不得因为请求中携带:
```json
{"risk":"high"}
```
或类似字段而自行获得 High 权限。
如果协议未来需要携带授权信息,应使用 Hub 生成的受保护授权上下文,并绑定:
```text
device + request/session + policy version + expiry
```
具体签名/令牌方案在实现阶段单独评审。
---
## 7.5 High Risk SessionManager 安全模型
`start_process`、`interact_with_process`、`kill_process` 不应被视为普通 HTTP 命令,而应视为一个受生命周期管理的高风险 Session。
### 7.5.1 Session 属性
每个 Session 至少包含:
```go
type ProcessSession struct {
ID string
Owner string
Device string
PID int
CreatedAt time.Time
LastAccess time.Time
ExpiresAt time.Time
State string
OutputBytes uint64
}
```
Session ID 必须不可预测,并且不能复用操作系统 PID 作为唯一身份。
### 7.5.2 所有权
只有创建 Session 的授权调用方才能:
- 读取该 Session 输出;
- 向 stdin 写入数据;
- 终止该 Session。
管理员级操作如果未来需要跨 Owner 接管 Session,应定义明确的审计事件和单独权限,不得通过普通 session API 隐式获得。
### 7.5.3 生命周期
```text
start_process
|
v
RUNNING
/ \
/ \
EXITED EXPIRED
| |
+----+---+
v
CLEANUP
```
Agent 重启后所有旧 Session 必须失效,不得从持久化文件自动恢复可写 stdin 的旧 Session。
### 7.5.4 时间限制
Session 必须具备:
- 最大生命周期;
- 空闲超时;
- stdin 单次大小限制;
- stdin 速率限制;
- 输出缓冲区上限。
具体默认数值在实现前通过压测确定,不在设计阶段硬编码未经验证的数值。
---
## 7.6 RingBuffer 与全局资源上限
原方案中的“2MB × 活跃 Session”只能作为单 Session 上限,不应视为 Agent 的总内存预算。
必须同时存在:
```text
per-session output cap
+
max active sessions
+
agent-wide session buffer cap
+
process creation rate limit
```
例如:
```text
单 Session:最大 2MB output buffer
全局:最大 N 个活跃 Session
全局:最大 M MB Session buffer
```
当达到任意全局上限时,新 Session 必须被拒绝并记录审计,而不是继续消耗内存。
RingBuffer 的覆盖行为只能覆盖旧输出,不得覆盖 session 元数据、错误状态或安全审计记录。
---
## 7.7 审计要求
至少记录以下安全事件:
```text
security_denied
policy_changed
session_created
session_expired
session_killed
session_owner_denied
resource_limit_denied
```
High Risk 操作的审计信息必须包含:
```text
device
actor / owner
request id
session id(如适用)
tool
result
policy version
timestamp
```
审计日志不能因为 Session RingBuffer 达到上限而被覆盖。
---
## 7.8 协议兼容补充约束
旧 Agent 与新 Hub 混合运行期间:
1. 原有 `action=read/write/exec/probe` 字段继续有效。
2. 新 `SubAction` 为可选字段。
3. 新字段不能改变旧 Agent 对旧消息的既有语义。
4. Hub 必须根据 Agent capability/version 判断是否可以下发新 SubAction。
5. 对不支持新能力的 Agent,返回明确的 capability error,而不是让旧 Agent 猜测。
6. 安全门禁必须在能力路由之前执行,避免通过旧 API 绕过新 Tool Registry。
---
## 7.9 实施前必须完成的设计验收
在进入 Phase 1 代码改造前,两位审核 Agent 应重点审查:
### A. 权威性
- Hub 是否始终是 EffectiveRisk 的唯一权威来源?
- Agent 是否存在任何自升权路径?
- 旧 API 是否可能绕过 Tool Registry?
### B. 一致性
- SQLite commit 与 snapshot publish 顺序是否正确?
- Hub 重启能否确定性恢复策略?
- snapshot version 是否足以定位策略变更?
### C. Session 安全
- session ownership 是否不可伪造?
- Agent 重启后旧 session 是否必然失效?
- stdin、stdout、session 数量是否存在全局资源上限?
### D. 向后兼容
- 老 Agent + 新 Hub 是否继续工作?
- 新 Hub 是否能识别 Agent capability?
- 新能力是否可能通过旧接口绕过门禁?
### E. 性能
- 热路径是否完全脱离 SQLite?
- snapshot 是否真正 immutable / atomic?
- session ring buffer 是否存在隐藏的额外复制?
**只有上述问题通过审核后,才进入 Phase 1 实现。**
---
# 8. 审核意见收敛修订(2026-10-02)
本章节根据第一轮 Agent 审核结果补充。**Phase 1 在本章节阻断项完成前不得进入代码实施。**
## 8.1 阻断项一:设备身份认证
`identify device` 不得等同于读取请求中的 `device` 字段。设备名称只能作为路由提示,不能作为授权依据。
### 8.1.1 权威身份模型
每个 Agent 必须拥有唯一设备身份以及与之绑定的设备凭证。Hub 必须先完成设备认证,再建立:
```text
authenticated agent identity
↓
device ID
↓
PolicySnapshot lookup
↓
EffectiveRisk
```
推荐优先采用 **per-agent credential**;部署条件允许时使用 mTLS。若采用 Agent Token,Token 必须:
- 与单一 Agent 身份绑定;
- 可撤销;
- 不得由客户端自行指定 device 后复用;
- 传输必须经过受保护通道;
- 认证失败不得进入安全策略查询阶段。
`device` 请求字段不得覆盖认证得到的 canonical device identity。
### 8.1.2 身份与策略绑定
策略查询必须使用认证层产生的 canonical device ID:
```go
identity := authenticateAgent(r)
if !identity.OK {
deny()
}
policy := snapshot.Device(identity.DeviceID)
```
禁止:
```go
policy := snapshot.Device(r.Device)
```
设备注册、凭证轮换、凭证撤销必须产生审计事件。具体凭证格式与密钥轮换流程在 Phase 1 实施设计中单独冻结。
---
## 8.2 阻断项二:kill_process 作用域
`kill_process` / `force_terminate` **绝不能接受任意 PID 作为授权对象**。
High Risk Session 必须建立进程归属关系:
```text
Session
└── Process Group / Process Tree
├── root process
├── child
└── child...
```
默认允许终止的对象仅为该 Session 创建的进程树。
必须拒绝:
- 不属于当前 Session 的 PID;
- Hub / Agent 自身关键进程;
- 未经单独授权的其他用户进程;
- 通过伪造 PID、session ID 或 owner 字段进行的跨 Session 操作。
实现时应记录 root PID / process group ID,并通过 OS 级关系验证目标进程仍属于该 Session,而不是只相信客户端提供的 PID。
未来若需要管理员跨 Session 终止能力,必须作为独立能力和独立审计事件设计,不复用普通 `kill_process`。
---
## 8.3 阻断项三:Agent capability/version 握手
协议必须正式增加 capability/version 元数据,使 7.8 的混合版本策略可以实际落地。
建议扩展:
```go
type Message struct {
ID string `json:"id,omitempty"`
Action string `json:"action,omitempty"`
SubAction string `json:"sub_action,omitempty"`
Device string `json:"device,omitempty"`
Payload any `json:"payload,omitempty"`
ProtocolVersion string `json:"protocol_version,omitempty"`
AgentVersion string `json:"agent_version,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
```
为避免旧 Agent 解析失败,新增字段必须保持 optional;旧 Agent 忽略未知字段即可继续处理旧消息。
更严格的 capability 协商流程:
```text
Agent connect
↓
identity authentication
↓
protocol/version handshake
↓
capability registry
↓
Hub records effective capabilities
↓
request routing
```
Hub 不得仅根据版本字符串猜测能力。实际可用能力以 capability set 为准。
如果 Agent 不支持某个 `SubAction`:
```text
capability_missing
```
必须成为明确错误,不得静默降级到语义不同的危险操作。
---
## 8.4 威胁模型
三级安全体系主要解决的是 **调用方对受控设备的越权操作风险**,而不是保证已经被完全攻陷的 Agent 本身可信。
### T1:恶意调用方
目标:冒充设备、伪造风险等级、跨设备操作、跨 Session 操作。
防护:
- Agent 身份认证;
- canonical device ID;
- Hub authoritative PolicySnapshot;
- Session ownership;
- Tool Registry;
- 审计。
### T2:有 Bug 的调用方
目标:错误调用 High API、重复创建 Session、资源耗尽。
防护:
- 参数验证;
- per-device 并发限制;
- rate limit;
- Session/global resource cap;
- fail-closed。
### T3:被攻陷的 Agent
如果攻击者已经取得 Agent 进程的等价本地执行权,则 Agent 内部校验不能被视为可信边界。
因此:
> Hub 门禁保护的是“未经授权的远程调用不能获得设备能力”,而不是“Agent 被完全攻陷后仍能阻止本地攻击者”。
Agent 被攻陷属于独立威胁域,应依赖最小权限、系统账户隔离、凭证撤销、节点隔离和重新注册等机制处理。
文档不得把 Agent 侧校验描述为能够抵御完全控制 Agent 的攻击者。
---
## 8.5 审计敏感数据脱敏
现有 `audit_logs.command` 等字段不得无条件记录完整命令或参数。
审计系统必须采用结构化事件优先:
```text
command template / tool
arguments metadata
result
risk
actor
request id
```
对于可能包含 Secret 的字段,必须在进入持久化审计前脱敏,包括但不限于:
```text
password
passwd
token
access_token
refresh_token
api_key
secret
authorization
cookie
private_key
```
Shell 命令中的敏感值不能仅依赖字段名识别;实现阶段应定义命令审计策略,至少做到:
1. 不默认记录完整 stdin;
2. 对已识别敏感参数替换为 `[REDACTED]`;
3. Secret 不得通过错误消息重新写入 audit;
4. 原始命令仅在明确安全策略允许时保留。
---
## 8.6 回滚与混合版本路线
原第 5 节标题为“回滚路线图”,现补充实际策略。
### 8.6.1 Hub 升级失败
- 新版本不得在旧 schema 尚未兼容时直接删除旧字段;
- DB migration 必须可检测版本;
- migration 失败则 Hub 不进入正常服务状态;
- 策略 snapshot 可以从旧兼容 schema 重建;
- 升级前保留 DB 备份/快照。
### 8.6.2 新 Hub + 旧 Agent
旧 Agent 继续使用旧 API/旧 Action。
Hub 必须:
```text
认证旧 Agent
↓
读取其 capability
↓
只下发它声明支持的能力
```
不能因为 Hub 已升级就要求旧 Agent 自动支持新 SubAction。
### 8.6.3 新 Agent + 旧 Hub
新 Agent 必须保持旧协议兼容能力;若 Hub 不支持 capability handshake,新 Agent 使用 legacy compatibility mode,不得因此自行启用 High 新能力。
### 8.6.4 数据降级原则
数据库 schema 新增字段应尽量可选;新功能数据不能成为旧版本启动的硬依赖。
任何不可逆 migration 必须在正式 Phase 前单独评审。
---
## 8.7 Session ID 与进程安全参数
Session ID 必须使用 `crypto/rand` 生成,最低 **128-bit entropy**,并以不暴露内部 PID 的方式编码。
PID 仅作为内部 process identity 的组成部分,不作为 session credential。
Session authorization 必须同时验证:
```text
authenticated device
+ session ID
+ owner
+ session state
+ expiry
```
---
## 8.8 edit_block 的 TOCTOU 防护
`edit_block` 不能只做:
```text
read -> verify -> rename
```
因为读取后到替换前存在 TOCTOU 窗口。
实现至少需要以下一种一致性保护:
- 文件锁;或
- generation / mtime / size / hash 校验后再提交;或
- OS 支持的原子条件更新机制。
推荐:读取时计算 generation fingerprint,写回前重新验证;若文件已经发生变化则拒绝修改并返回 conflict,而不是覆盖第三方更新。
---
## 8.9 内存预算重新约束
原方案“Agent 常驻 20MB 以内”与 `2MB × N sessions` 必须统一解释。
新的约束是:
> **20MB 是 Agent 基础常驻预算;Session buffer 必须从剩余预算反推最大并发数,而不是无限叠加。**
因此实现前必须定义:
```text
BaseMemoryBudget
SessionBufferBudget
MaxActiveSessions
PerSessionBuffer
```
满足:
```text
BaseMemory + MaxSessionBufferBudget + safety margin
<= approved Agent memory ceiling
```
如果单 Session 仍采用 2MB,则 `MaxActiveSessions` 必须由压测和实际内存预算计算得出。
---
## 8.10 性能指标修正
删除或修正“整机 10W+ QPS”可能造成的误导。
准确表述应为:
> **安全门禁自身的策略读取路径不以 SQLite 为热路径,单次判定成本应保持在内存级别;端到端 API 吞吐仍受网络、Agent、磁盘、进程创建和实际 IO 限制。**
性能验收应分别测量:
1. PolicySnapshot lookup latency;
2. authorization decision latency;
3. API end-to-end latency;
4. Agent execution throughput;
5. process/session creation rate。
---
## 8.11 进程交互传输模型
`interact_with_process` 的实时 stdin/stdout 通道必须在实现前冻结。
设计目标:
```text
Hub / MCP
↓ stdin
Agent Session
↑ stdout/stderr stream
```
传输协议必须明确:
- session binding;
- reconnect 行为;
- backpressure;
- output cursor / offset;
- heartbeat / timeout;
- disconnect 后 Session 是否继续运行;
- reconnect 后 owner 如何重新认证。
如果采用 HTTP/SSE、WebSocket 或轮询,必须在 Phase 3 实施设计中明确其安全和资源模型,不能由 handler 临时决定。
---
## 8.12 非 Session 类资源限制
全局资源控制不仅适用于 `start_process`。
### exec_command
必须增加:
- per-device concurrent exec limit;
- 单命令执行时间上限;
- 输出大小上限;
- 创建速率限制。
防止通过大量同步 `exec_command` 造成 fork/process exhaustion。
### list_processes
进程命令行可能包含密码、Token、Cookie 等敏感信息。返回结果必须执行敏感信息处理,并限制返回规模。
### start_search / get_more_search_results
后台搜索属于全盘 IO 风险,应具备:
- per-device search concurrency;
- 最大搜索范围/深度;
- 最大结果数;
- 超时;
- 可取消任务;
- 全局 IO 预算。
---
## 8.13 Phase 1 红队验收
除原 A–E 正向验收外,Phase 1 必须增加以下对抗用例:
1. 伪造 `{"risk":"high"}` 是否被拒绝;
2. 使用合法 Agent A 凭证请求 device B 是否被拒绝;
3. 旧 API 是否能绕过 Tool Registry;
4. Session A 的 ID 是否能访问 Session B;
5. Session A 是否能 kill 非自身进程;
6. Agent 重启后旧 Session 是否失效;
7. Policy snapshot 更新过程中是否出现半更新状态;
8. SQLite 更新失败时是否错误发布新策略;
9. 旧 Agent + 新 Hub 是否保持旧功能;
10. 新能力是否在 capability 缺失时被错误下发;
11. audit 是否泄露 password/token/cookie/private key;
12. 并发 exec 是否能够超过 per-device 上限;
13. search 是否能够无限占用 IO;
14. RingBuffer / session 上限是否能防止内存线性增长。
---
## 8.14 Phase 1 开工闸门
Phase 1 只有在以下条件全部满足后才能开始:
```text
[ ] Agent identity authentication model frozen
[ ] Canonical device identity frozen
[ ] kill_process process-tree scope frozen
[ ] protocol capability/version handshake frozen
[ ] Threat model accepted
[ ] Audit redaction policy accepted
[ ] DB migration / rollback strategy accepted
[ ] Session ID generation frozen
[ ] edit_block consistency strategy frozen
[ ] Agent memory budget reconciled
[ ] Streaming transport model frozen or explicitly deferred to Phase 3
[ ] exec/search resource limits defined
[ ] Red-team test plan accepted
```
**本章节是 Phase 1 的设计闸门,不是可选建议。任何阻断项未关闭时,不得以“先实现再补安全”为理由进入代码改造。**
@@ -0,0 +1,109 @@
# 《VPS-Commander 平滑升级改造与三级安全拦截实施方案》
## 1. 改造目标与背景
本项目计划全量复刻 **Desktop Commander(DC)** 在终端与文件系统上的核心工程能力(包括局部块级精准替换、后台长进程生命周期管理、交互式 stdin 注入、结构化目录遍历与只读检索),并将其无缝接入 **Low(低风险)/ Medium(中风险)/ High(高风险)** 三级安全门禁体系。
**核心红线与验收标准:**
1. **服务不中断**:升级过程不影响正在运行的 Agent 探针与 Hub 中心。
2. **协议向后兼容**:旧版 Agent 与新版 Hub 混合共存,老接口绝不废弃。
3. **性能零损耗**:杜绝动态运行时映射,安全校验在编译期即已绑定。
4. **轻量化保真**:继续保持纯 Go 静态编译的高效特性,严控内存占用(常驻内存锁定在 20MB 以内)。
---
## 2. 工具池全量复刻与三级风险定级表(静态强绑定)
所有功能根据系统破坏力与副作用大小,在**编译期**严格归属于三级风险体系:
| 风险等级 (Level) | 行为边界定义 | 包含的复刻工具 (DC 标杆) | 允许放行的安全模式 |
| :--- | :--- | :--- | :--- |
| 🟢 **Low(只读/感知)** | **纯只读、无状态改变、无系统副作用** | • `read_file` (支持切片与 Tail)<br>• `read_multiple_files`<br>• `list_directory` (结构化目录树)<br>• `get_file_info` (元数据)<br>• `start_search` / `get_more_search_results`<br>• `list_processes` / `list_sessions`<br>• `read_process_output` (拉取输出) | **Low**<br>**Medium**<br>**High** |
| 🟡 **Medium(文件写)** | **文件与目录变更,但严禁拉起任意二进制或执行命令** | • `edit_block` (局部文本块精准替换,核心)<br>• `write_file` (文件新建/全量写入)<br>• `create_directory` (新建目录)<br>• `move_file` (移动/重命名) | **Medium**<br>**High**<br>*(Low 拦截)* |
| 🔴 **High(完全控制)** | **具备操作系统执行权、进程生命周期调度与管道干预** | • `exec_command` (同步短命令)<br>• `start_process` (后台异步启动长进程)<br>• `interact_with_process` (stdin 交互写入)<br>• `kill_process` / `force_terminate` (终止进程) | **High**<br>*(Low / Medium 拦截)* |
---
## 3. 架构改造与平滑过渡设计
### 3.1 协议层平滑升级(零破坏向后兼容)
在 `internal/cluster/protocol.go` 中,保留原有字段,新增可选的扩展动作:
```go
type Message struct {
ID string `json:"id,omitempty"`
Action string `json:"action,omitempty"` // 保持原有字段: "read" / "write" / "exec" / "probe"
SubAction string `json:"sub_action,omitempty"` // ✨ 增量动作: "edit_block", "start_process" 等
Device string `json:"device,omitempty"`
Payload any `json:"payload,omitempty"`
...
}
```
* **兼容保障**:老版本 Agent 接收到带 `SubAction` 的 JSON 消息时会自动忽略多余字段,继续按老逻辑工作;升级后的 Agent 优先路由给 `SubAction` 处理。
### 3.2 Hub 门禁与高并发性能优化(读写分离)
现有系统每次请求均去 SQLite 查询策略,高并发下存在文件锁瓶颈。改造后引入 **RWMutex 内存策略快照**:
1. **读路径(Fast Path,纳秒级)**:
```go
// 常量数值定义,直接内联比较
const ( RiskLow = 1; RiskMedium = 2; RiskHigh = 3 )
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device string, requiredRisk int, detail string) bool {
allowed := s.getEffectiveRiskLevel(device) // 查内存 RLock,耗时 < 10ns
if allowed >= requiredRisk {
return true
}
// 记录 audit_logs ("security_denied", 403) 并返回拦截响应
return false
}
```
2. **写路径(Slow Path,低频)**:
* 仅在管理员通过 Web 界面更改安全策略时,写一次 SQLite 并原子更新内存缓存。
3. **老 API 零改动**:
* 原有 `/api/v1/devices/exec`、`/read`、`/write` 继续保留,老脚本老客户端零感知。
### 3.3 Agent 端核心引擎实现(防资源膨胀设计)
* **`edit_block` 引擎**:
* 读取原文件后校验 `old_text` 全局唯一性,唯一时单次替换并使用临时文件进行原子覆写(`os.Rename`)。
* 相比原有全量上传,网络传输和内存开销下降 95%。
* **长进程与 PTY 会话引擎(`start_process` 等)**:
* Agent 内部建立轻量 `SessionManager`,挂接内核标准输入输出管道。
* **硬编码内存锁(Circular RingBuffer)**:每个进程会话分配最大 2MB 环形日志缓冲区,达到上限自动覆盖最早输出,**从物理上杜绝日志死循环导致的内存溢出(OOM)**。
---
## 4. 资源开销评估与性能上限控制
得益于纯 Go 原生静态编译,系统坚决不引入任何 Node.js/Python 运行时,资源开销保持极致克制:
| 评估指标 | 改造前基准(实测) | 改造后预期 | 性能/资源防护机制 |
| :--- | :--- | :--- | :--- |
| **Agent 静默内存** | ~13 MB | **~15 MB - 18 MB** | 零后台轮询,事件驱动 |
| **Agent 峰值内存** | 随命令大小波动 | **基准 + (2MB × 活跃会话数)** | 环形缓冲区硬顶锁定,防内存泄露 |
| **Hub 服务端内存** | ~16 MB | **~18 MB - 22 MB** | 内存门禁仅占不到 10KB |
| **二进制体积** | ~9.4 MB | **~11 MB - 13 MB** | 静态单文件编译,极易分发部署 |
| **安全判定延迟** | 毫秒级(查 SQLite) | **纳秒级(内存读锁)** | 单机可轻松支撑 10W+ QPS 门禁并发 |
---
## 5. 四阶段实施与回滚路线图(稳健落地)
* **Phase 1:服务端门禁升级与内存读缓存**
* 在 Hub 端落地 `RWMutex` 安全策略缓存;
* API 入口统一接入 `requireSecurity(..., RiskLevel)`;
* *验证标准*:旧版 4 项基础功能与 Web 面板完好,并发查询 QPS 大幅提升。
* **Phase 2:落地中风险神器 `edit_block`**
* Agent 端实现块级精准替换算法;
* Hub 暴露 `/api/v1/devices/file/edit_block` 并注册至 MCP Adapter;
* *验证标准*:在 Medium 模式下可正常修配置文件,在 Low 模式下被精确阻断并记入审计。
* **Phase 3:落地高风险长进程引擎**
* Agent 端引入带 RingBuffer 的 `SessionManager`;
* 实现 `start_process`、`read_process_output`、`interact_with_process`、`kill_process`;
* *验证标准*:跑耗时任务不会超时断连,支持实时 Tail 查看输出与注入 stdin。
* **Phase 4:落地只读结构化文件与系统感知(Low)**
* 实现 `list_directory`、`get_file_info` 及后台异步只读搜索。
---
## 6. 评估与审计重点建议
1. **安全维度**:Low/Medium/High 对能力的切分是否彻底杜绝了提权与逃逸风险?
2. **性能维度**:使用内存 RWMutex + 编译期静态安全级别判定,是否彻底解决了单文件 SQLite 高频读瓶颈?
3. **稳定性维度**:为每个长进程会话限定 RingBuffer 内存上限,是否有效防止了边缘 VPS 探针被日志撑爆?
@@ -0,0 +1,491 @@
# 《VPS-Commander 平滑升级改造与三级安全拦截实施方案》
## 1. 改造目标与背景
本项目计划全量复刻 **Desktop Commander(DC)** 在终端与文件系统上的核心工程能力(包括局部块级精准替换、后台长进程生命周期管理、交互式 stdin 注入、结构化目录遍历与只读检索),并将其无缝接入 **Low(低风险)/ Medium(中风险)/ High(高风险)** 三级安全门禁体系。
**核心红线与验收标准:**
1. **服务不中断**:升级过程不影响正在运行的 Agent 探针与 Hub 中心。
2. **协议向后兼容**:旧版 Agent 与新版 Hub 混合共存,老接口绝不废弃。
3. **性能零损耗**:杜绝动态运行时映射,安全校验在编译期即已绑定。
4. **轻量化保真**:继续保持纯 Go 静态编译的高效特性,严控内存占用(常驻内存锁定在 20MB 以内)。
---
## 2. 工具池全量复刻与三级风险定级表(静态强绑定)
所有功能根据系统破坏力与副作用大小,在**编译期**严格归属于三级风险体系:
| 风险等级 (Level) | 行为边界定义 | 包含的复刻工具 (DC 标杆) | 允许放行的安全模式 |
| :--- | :--- | :--- | :--- |
| 🟢 **Low(只读/感知)** | **纯只读、无状态改变、无系统副作用** | • `read_file` (支持切片与 Tail)<br>• `read_multiple_files`<br>• `list_directory` (结构化目录树)<br>• `get_file_info` (元数据)<br>• `start_search` / `get_more_search_results`<br>• `list_processes` / `list_sessions`<br>• `read_process_output` (拉取输出) | **Low**<br>**Medium**<br>**High** |
| 🟡 **Medium(文件写)** | **文件与目录变更,但严禁拉起任意二进制或执行命令** | • `edit_block` (局部文本块精准替换,核心)<br>• `write_file` (文件新建/全量写入)<br>• `create_directory` (新建目录)<br>• `move_file` (移动/重命名) | **Medium**<br>**High**<br>*(Low 拦截)* |
| 🔴 **High(完全控制)** | **具备操作系统执行权、进程生命周期调度与管道干预** | • `exec_command` (同步短命令)<br>• `start_process` (后台异步启动长进程)<br>• `interact_with_process` (stdin 交互写入)<br>• `kill_process` / `force_terminate` (终止进程) | **High**<br>*(Low / Medium 拦截)* |
---
## 3. 架构改造与平滑过渡设计
### 3.1 协议层平滑升级(零破坏向后兼容)
在 `internal/cluster/protocol.go` 中,保留原有字段,新增可选的扩展动作:
```go
type Message struct {
ID string `json:"id,omitempty"`
Action string `json:"action,omitempty"` // 保持原有字段: "read" / "write" / "exec" / "probe"
SubAction string `json:"sub_action,omitempty"` // ✨ 增量动作: "edit_block", "start_process" 等
Device string `json:"device,omitempty"`
Payload any `json:"payload,omitempty"`
...
}
```
* **兼容保障**:老版本 Agent 接收到带 `SubAction` 的 JSON 消息时会自动忽略多余字段,继续按老逻辑工作;升级后的 Agent 优先路由给 `SubAction` 处理。
### 3.2 Hub 门禁与高并发性能优化(读写分离)
现有系统每次请求均去 SQLite 查询策略,高并发下存在文件锁瓶颈。改造后引入 **RWMutex 内存策略快照**:
1. **读路径(Fast Path,纳秒级)**:
```go
// 常量数值定义,直接内联比较
const ( RiskLow = 1; RiskMedium = 2; RiskHigh = 3 )
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device string, requiredRisk int, detail string) bool {
allowed := s.getEffectiveRiskLevel(device) // 查内存 RLock,耗时 < 10ns
if allowed >= requiredRisk {
return true
}
// 记录 audit_logs ("security_denied", 403) 并返回拦截响应
return false
}
```
2. **写路径(Slow Path,低频)**:
* 仅在管理员通过 Web 界面更改安全策略时,写一次 SQLite 并原子更新内存缓存。
3. **老 API 零改动**:
* 原有 `/api/v1/devices/exec`、`/read`、`/write` 继续保留,老脚本老客户端零感知。
### 3.3 Agent 端核心引擎实现(防资源膨胀设计)
* **`edit_block` 引擎**:
* 读取原文件后校验 `old_text` 全局唯一性,唯一时单次替换并使用临时文件进行原子覆写(`os.Rename`)。
* 相比原有全量上传,网络传输和内存开销下降 95%。
* **长进程与 PTY 会话引擎(`start_process` 等)**:
* Agent 内部建立轻量 `SessionManager`,挂接内核标准输入输出管道。
* **硬编码内存锁(Circular RingBuffer)**:每个进程会话分配最大 2MB 环形日志缓冲区,达到上限自动覆盖最早输出,**从物理上杜绝日志死循环导致的内存溢出(OOM)**。
---
## 4. 资源开销评估与性能上限控制
得益于纯 Go 原生静态编译,系统坚决不引入任何 Node.js/Python 运行时,资源开销保持极致克制:
| 评估指标 | 改造前基准(实测) | 改造后预期 | 性能/资源防护机制 |
| :--- | :--- | :--- | :--- |
| **Agent 静默内存** | ~13 MB | **~15 MB - 18 MB** | 零后台轮询,事件驱动 |
| **Agent 峰值内存** | 随命令大小波动 | **基准 + (2MB × 活跃会话数)** | 环形缓冲区硬顶锁定,防内存泄露 |
| **Hub 服务端内存** | ~16 MB | **~18 MB - 22 MB** | 内存门禁仅占不到 10KB |
| **二进制体积** | ~9.4 MB | **~11 MB - 13 MB** | 静态单文件编译,极易分发部署 |
| **安全判定延迟** | 毫秒级(查 SQLite) | **纳秒级(内存读锁)** | 单机可轻松支撑 10W+ QPS 门禁并发 |
---
## 5. 四阶段实施与回滚路线图(稳健落地)
* **Phase 1:服务端门禁升级与内存读缓存**
* 在 Hub 端落地 `RWMutex` 安全策略缓存;
* API 入口统一接入 `requireSecurity(..., RiskLevel)`;
* *验证标准*:旧版 4 项基础功能与 Web 面板完好,并发查询 QPS 大幅提升。
* **Phase 2:落地中风险神器 `edit_block`**
* Agent 端实现块级精准替换算法;
* Hub 暴露 `/api/v1/devices/file/edit_block` 并注册至 MCP Adapter;
* *验证标准*:在 Medium 模式下可正常修配置文件,在 Low 模式下被精确阻断并记入审计。
* **Phase 3:落地高风险长进程引擎**
* Agent 端引入带 RingBuffer 的 `SessionManager`;
* 实现 `start_process`、`read_process_output`、`interact_with_process`、`kill_process`;
* *验证标准*:跑耗时任务不会超时断连,支持实时 Tail 查看输出与注入 stdin。
* **Phase 4:落地只读结构化文件与系统感知(Low)**
* 实现 `list_directory`、`get_file_info` 及后台异步只读搜索。
---
## 6. 评估与审计重点建议
1. **安全维度**:Low/Medium/High 对能力的切分是否彻底杜绝了提权与逃逸风险?
2. **性能维度**:使用内存 RWMutex + 编译期静态安全级别判定,是否彻底解决了单文件 SQLite 高频读瓶颈?
3. **稳定性维度**:为每个长进程会话限定 RingBuffer 内存上限,是否有效防止了边缘 VPS 探针被日志撑爆?
---
# 7. 架构收敛修订(2026-10-02)
> 本章节在进入代码实施前增加,用于两位外部 Agent 审核。原方案的工具分级、四阶段路线和向后兼容原则继续保留;本章节对安全权威、策略一致性、工具注册以及高风险 Session 生命周期作进一步约束。
## 7.1 安全等级的正确边界:静态工具风险 + 运行时设备策略
原方案中“静态强绑定”应准确解释为:**工具所需风险等级在编译期固定,是否允许执行在运行时由 Hub 的权威策略决定。**
不得将设备当前 Low/Medium/High 策略编译进 Agent,也不得允许 Agent 自行提升自身安全等级。
### 7.1.1 工具风险等级
每个工具在代码注册表中拥有不可运行时修改的 `RequiredRisk`:
```go
const (
RiskLow = 1
RiskMedium = 2
RiskHigh = 3
)
type ToolSpec struct {
Name string
RequiredRisk int
ReadOnly bool
}
```
示例:
```text
read_file / list_directory / search -> Low
edit_block / write_file / move_file -> Medium
exec_command / start_process / stdin -> High
```
禁止通过 Web 面板、Agent 配置文件或远端请求动态修改工具自身的 `RequiredRisk`。
### 7.1.2 设备有效策略
设备的 `EffectiveRisk` 是 Hub 运行时策略,不属于 Agent 自主能力。
请求授权模型:
```text
Request
-> identify device
-> identify ToolSpec.RequiredRisk
-> read Hub PolicySnapshot
-> compare EffectiveRisk >= RequiredRisk
-> allow / deny
```
因此完整安全边界为:
**编译期固定“工具需要什么权限” + 运行时决定“该设备当前获得什么权限”。**
---
## 7.2 Policy Store 与 Policy Snapshot 一致性模型
SQLite 继续作为持久化权威源(durable source of truth),但请求热路径禁止每次查询 SQLite。
### 7.2.1 数据流
```text
Admin Web
|
v
SQLite transaction
|
v
Build new immutable PolicySnapshot
|
v
Atomic publish / swap
|
v
Request fast path
```
请求只读取当前不可变 snapshot;不在请求过程中修改策略对象。
### 7.2.2 更新原则
策略修改必须满足:
1. SQLite 写入成功后才允许发布新 snapshot。
2. SQLite 写失败时,内存策略保持旧版本。
3. snapshot 发布必须是原子操作,不允许出现半更新状态。
4. Hub 启动时必须从 SQLite 完整重建 snapshot。
5. snapshot 应携带单调递增 `Version`,便于审计和诊断。
6. 审计记录应包含 `device`, `oldRisk`, `newRisk`, `version`, `actor`, `timestamp`。
推荐结构:
```go
type PolicySnapshot struct {
Version uint64
Devices map[string]DevicePolicy
CreatedAt time.Time
}
```
热路径原则:
```text
load current snapshot
-> lookup device
-> compare integer risk
-> allow/deny
```
不得在高频 API 请求中重新读取 SQLite 策略表。
### 7.2.3 故障安全
如果 Hub 无法加载有效策略 snapshot:
- 不得默认放行 High。
- 不得从请求参数接受临时风险等级。
- 对需要 Medium/High 的操作默认拒绝。
- Low 只读能力是否可继续开放,必须由启动时的明确安全默认策略决定,并记录审计事件。
---
## 7.3 Tool Registry:统一能力与风险注册表
避免各 API handler 自己实现不同的安全判断。所有能力必须进入统一 Tool Registry。
建议:
```go
type ToolSpec struct {
Name string
RequiredRisk int
Category string
ReadOnly bool
Description string
}
```
例如:
```text
read_file Low
read_multiple_files Low
list_directory Low
get_file_info Low
start_search Low
get_more_search_results Low
list_processes Low
list_sessions Low
read_process_output Low
edit_block Medium
write_file Medium
create_directory Medium
move_file Medium
exec_command High
start_process High
interact_with_process High
kill_process High
force_terminate High
```
API、MCP Adapter 和内部调用均通过 Registry 获取 `RequiredRisk`,不得在多个入口复制风险数字。
---
## 7.4 Agent 信任边界
Agent 是执行者,不是安全策略的最终裁决者。
Hub 是设备授权策略的权威来源。
但 Agent 仍必须执行本地最低限度安全校验,包括:
- 请求格式与参数校验;
- session 所有权校验;
- session 是否仍然有效;
- 单次输入/输出大小限制;
- 超时和资源限制;
- 不接受客户端自行声明的 `RiskLevel` 作为授权依据。
Agent 不得因为请求中携带:
```json
{"risk":"high"}
```
或类似字段而自行获得 High 权限。
如果协议未来需要携带授权信息,应使用 Hub 生成的受保护授权上下文,并绑定:
```text
device + request/session + policy version + expiry
```
具体签名/令牌方案在实现阶段单独评审。
---
## 7.5 High Risk SessionManager 安全模型
`start_process`、`interact_with_process`、`kill_process` 不应被视为普通 HTTP 命令,而应视为一个受生命周期管理的高风险 Session。
### 7.5.1 Session 属性
每个 Session 至少包含:
```go
type ProcessSession struct {
ID string
Owner string
Device string
PID int
CreatedAt time.Time
LastAccess time.Time
ExpiresAt time.Time
State string
OutputBytes uint64
}
```
Session ID 必须不可预测,并且不能复用操作系统 PID 作为唯一身份。
### 7.5.2 所有权
只有创建 Session 的授权调用方才能:
- 读取该 Session 输出;
- 向 stdin 写入数据;
- 终止该 Session。
管理员级操作如果未来需要跨 Owner 接管 Session,应定义明确的审计事件和单独权限,不得通过普通 session API 隐式获得。
### 7.5.3 生命周期
```text
start_process
|
v
RUNNING
/ \
/ \
EXITED EXPIRED
| |
+----+---+
v
CLEANUP
```
Agent 重启后所有旧 Session 必须失效,不得从持久化文件自动恢复可写 stdin 的旧 Session。
### 7.5.4 时间限制
Session 必须具备:
- 最大生命周期;
- 空闲超时;
- stdin 单次大小限制;
- stdin 速率限制;
- 输出缓冲区上限。
具体默认数值在实现前通过压测确定,不在设计阶段硬编码未经验证的数值。
---
## 7.6 RingBuffer 与全局资源上限
原方案中的“2MB × 活跃 Session”只能作为单 Session 上限,不应视为 Agent 的总内存预算。
必须同时存在:
```text
per-session output cap
+
max active sessions
+
agent-wide session buffer cap
+
process creation rate limit
```
例如:
```text
单 Session:最大 2MB output buffer
全局:最大 N 个活跃 Session
全局:最大 M MB Session buffer
```
当达到任意全局上限时,新 Session 必须被拒绝并记录审计,而不是继续消耗内存。
RingBuffer 的覆盖行为只能覆盖旧输出,不得覆盖 session 元数据、错误状态或安全审计记录。
---
## 7.7 审计要求
至少记录以下安全事件:
```text
security_denied
policy_changed
session_created
session_expired
session_killed
session_owner_denied
resource_limit_denied
```
High Risk 操作的审计信息必须包含:
```text
device
actor / owner
request id
session id(如适用)
tool
result
policy version
timestamp
```
审计日志不能因为 Session RingBuffer 达到上限而被覆盖。
---
## 7.8 协议兼容补充约束
旧 Agent 与新 Hub 混合运行期间:
1. 原有 `action=read/write/exec/probe` 字段继续有效。
2. 新 `SubAction` 为可选字段。
3. 新字段不能改变旧 Agent 对旧消息的既有语义。
4. Hub 必须根据 Agent capability/version 判断是否可以下发新 SubAction。
5. 对不支持新能力的 Agent,返回明确的 capability error,而不是让旧 Agent 猜测。
6. 安全门禁必须在能力路由之前执行,避免通过旧 API 绕过新 Tool Registry。
---
## 7.9 实施前必须完成的设计验收
在进入 Phase 1 代码改造前,两位审核 Agent 应重点审查:
### A. 权威性
- Hub 是否始终是 EffectiveRisk 的唯一权威来源?
- Agent 是否存在任何自升权路径?
- 旧 API 是否可能绕过 Tool Registry?
### B. 一致性
- SQLite commit 与 snapshot publish 顺序是否正确?
- Hub 重启能否确定性恢复策略?
- snapshot version 是否足以定位策略变更?
### C. Session 安全
- session ownership 是否不可伪造?
- Agent 重启后旧 session 是否必然失效?
- stdin、stdout、session 数量是否存在全局资源上限?
### D. 向后兼容
- 老 Agent + 新 Hub 是否继续工作?
- 新 Hub 是否能识别 Agent capability?
- 新能力是否可能通过旧接口绕过门禁?
### E. 性能
- 热路径是否完全脱离 SQLite?
- snapshot 是否真正 immutable / atomic?
- session ring buffer 是否存在隐藏的额外复制?
**只有上述问题通过审核后,才进入 Phase 1 实现。**
@@ -0,0 +1,433 @@
# VPS-Commander 双通道架构与安全整改——送审交接文档
**文档版本:** 2026-10-02 / Review Handoff v1
**项目:** VPS-Commander v2.0
**用途:** 提交外部审核,审核通过后作为生产上线前置依据
---
## 1. 本次交接目标
本次开发针对双通道架构重构及此前审核专家 A/B 提出的安全、并发、权限、会话和文件操作问题进行集中整改。
本文件只描述**当前代码实际完成状态**,不把尚未部署到生产的代码描述为“已上线”。
当前原则:
- 生产 Hub / Agent 在本轮整改过程中**没有重启**。
- 所有新增能力先在代码与测试环境完成验证。
- 生产切换采用分阶段、可回滚方式。
- 审核通过后,才进入生产上线阶段。
---
## 2. 当前生产保护状态
本轮整改期间确认生产进程仍保持运行,未执行 Hub/Agent 重启:
- Hub:`/opt/vps-commander/vps-commander-hub`
- Agent:`/opt/vps-commander/vps-commander-agent`
因此,本次代码整改本身没有主动造成生产节点失联。
**注意:** 当前生产进程运行的是现有部署版本,不等同于本工作树代码已经上线。
---
## 3. 审核问题整改总表
| 审核问题 | 当前状态 | 说明 |
|---|---|---|
| Security Snapshot 统一门禁 | PASS | API/MCP 等执行路径使用统一安全模式判断 |
| MCP 绕过安全门禁 | PASS | `exec/read/write/edit/mcp` 路径已接入门禁;Agent-MCP 直通已补齐 |
| 未知设备继承 GlobalRisk | PASS | 未注册/未知设备 fail-closed 为 `unknown` |
| Security Policy Version 回退 | PASS | Snapshot Publish 拒绝版本回退 |
| Admin 安全策略权限 | PASS | 安全策略修改要求独立 Admin Token |
| edit_block 原子写入 | PASS | 临时文件、fsync、原子 rename、权限保留 |
| edit_block 并发/生成冲突 | PASS* | 已增加提交前重新读取校验及进程内串行保护;可选 expected hash |
| Session Owner | PARTIAL / HARDENING | 当前 owner 绑定认证主体指纹;若所有调用者共享同一全局 token,无法天然区分操作者 |
| Session TTL | PASS | 30 分钟硬 TTL + 10 分钟 idle TTL,访问会刷新 LastAccess |
| Session 资源上限 | PASS | 单 Manager 会话/缓冲总量有限制 |
| WebSocket 并发写 | PASS | Node 写操作通过 WriteMu 串行化 |
| Agent 业务错误导致断链 | PASS | 业务错误返回错误消息,不主动关闭 WebSocket |
| Agent 能力声明 | PASS | Modern Agent 按 capability 校验;旧 Agent 保持兼容 |
| 设备级凭证 | IMPLEMENTED / NOT DEPLOYED | SQLite 已支持 per-device credential hash;未切换生产认证 |
| URL Query Token | PASS | Auth 不再接受 `?token/?key/?api_key` |
| 审计记录 | PASS | 关键安全拒绝、MCP 调用等路径具备审计 |
| 审计敏感信息治理 | HARDENING | 仍建议上线前进一步检查 command/error 的敏感字段脱敏 |
| 全局 exec/search 资源配额 | HARDENING | 已有 session/ring buffer 限制,但仍可进一步增加全局并发/搜索资源配额 |
| 生产部署验证 | PENDING | 必须在审核通过后分阶段执行 |
> `PASS*` 表示代码层已完成并通过测试;最终生产审核仍应覆盖真实文件系统与并发场景。
---
## 4. 已完成的核心安全机制
### 4.1 Security Snapshot
Hub 启动时加载安全策略 Snapshot。策略版本保存在 SQLite 中。
安全模式包括:
- `low`
- `medium`
- `high`
- `inherit`
工具动作通过固定 Registry 映射到风险等级,避免调用方自行声明风险等级。
### 4.2 Fail-Closed
对于未知、未注册或不在线的远程设备,不再默认继承 GlobalRisk。
此类设备的有效安全模式为 `unknown`,高风险执行因此被拒绝。
### 4.3 MCP 安全门禁
MCP 不再被视为绕过 Hub Security Snapshot 的旁路。
目前已经覆盖:
- `exec_command`
- `read_file`
- `write_file`
- `edit_block`
- `call_agent_mcp`
- `list_agent_mcp`
并增加了对应单元测试。
### 4.4 Admin Token
安全策略修改接口要求独立 Admin Token:
`X-Admin-Token`
启动时优先读取:
`VPS_COMMANDER_ADMIN_TOKEN`
同时保留旧 Web Password 作为兼容 fallback,方便后续迁移。
### 4.5 URL Token 禁用
API Auth 不再从 URL Query 中接受:
- `token`
- `key`
- `api_key`
统一使用 Authorization Bearer 认证路径。
---
## 5. 文件修改安全
`edit_block` 当前实现包含:
1. 唯一匹配检查
2. 初始内容 SHA-256 generation
3. 提交前重新读取
4. generation/hash 冲突检测
5. 进程内编辑串行化
6. 同目录临时文件
7. 写入后 fsync
8. atomic rename
9. 保留原文件权限
10. 目录同步
目标是避免“读取后文件被其他操作修改,随后旧内容覆盖新内容”的典型 lost-update 问题。
---
## 6. Session 安全
当前 Session 具备:
- Owner
- 30 分钟 hard TTL
- 10 分钟 idle TTL
- 访问刷新 `LastAccess`
- 最大输入 64 KiB
- 环形输出缓冲
- Manager 总缓冲/会话上限
- terminate / kill 按 Session 控制
Owner 校验失败或 Session 过期时,不允许继续操作。
### 已知边界
当前 Owner 来源仍然是 API 认证主体的 token fingerprint。在所有调用者共用同一个 API Token 的部署中,这个 fingerprint 无法区分不同人工操作者。
因此上线前如果要求强操作者隔离,应继续引入明确的 principal/operator identity。
---
## 7. WebSocket 稳定性
Agent 与 Hub 通信增加了写锁,避免多个 goroutine 同时向同一 WebSocket 写入。
Agent 业务请求错误不再直接导致 WebSocket 连接被关闭。
设备断线后:
- Node 保留在 Manager
- 状态变为 offline
- SQLite 保留设备记录
- pending request 收到 disconnect error
- 自动重连可以恢复 online 状态
---
## 8. 设备级凭证迁移
这是本轮新增的重要安全能力。
SQLite 新增:
`device_credentials`
数据库只保存 token 的 SHA-256 hash,不保存明文 token。
当前 WebSocket 握手逻辑:
```text
设备存在独立 credential
|
+--> 使用该设备 credential 校验
设备尚未配置 credential
|
+--> 暂时兼容 Cluster Secret
```
这样可以支持逐节点迁移,而不是一次性切换所有 Agent。
### 当前状态
**代码已经实现,但尚未在生产逐节点启用。**
这是有意保留的上线门禁,避免在没有审核和迁移计划的情况下直接造成 Agent 全部掉线。
---
## 9. 测试与验证结果
当前工作树已经完成:
```text
go test ./... PASS
go test -race ./... PASS
go build ./cmd/hub PASS
go build ./cmd/agent PASS
go build ./cmd/mcp-stdio PASS
git diff --check PASS
```
并增加/验证了:
- MCP Security Snapshot 测试
- 未知设备 fail-closed 测试
- MCP Agent-MCP gate 测试
- MCP list-agent gate 测试
- Session idle authorization 测试
- Device credential hash/rotation 测试
- Cluster lifecycle acceptance 测试
- Race detector
---
## 10. 审核者重点检查项
建议审核者重点确认以下问题,而不是重复审查已经验证的普通功能:
### A. 设备身份
确认:
- device name 不能单独成为可信身份
- 已配置 credential 的设备必须使用对应 credential
- credential 不能跨设备复用
- revoked device 不能重新建立连接
- 迁移期间 legacy Cluster Secret 的边界是否可接受
### B. Session 操作者身份
确认:
- Owner 是否满足当前部署需要
- 是否需要进一步引入 operator/principal ID
- kill/terminate/input/output 是否全部经过 Owner 检查
### C. 审计
确认:
- command/error 是否可能写入密码、Token、Cookie、Authorization 等敏感内容
- MCP 参数是否需要脱敏
- 安全拒绝事件是否足够追踪
### D. 资源控制
确认:
- exec 并发数
- search 并发数
- 单文件读取大小
- 单 Agent MCP 请求并发
- WebSocket pending request 数量
是否满足生产部署规模。
### E. 上线安全
审核通过后必须采用:
**备份 → 单节点 → 健康检查 → 保持旧进程可回滚 → 再逐节点扩散**
而不是直接全量替换。
---
## 11. 上线前置条件
只有审核者确认以下事项后,才进入生产部署:
- [ ] 代码审核通过
- [ ] 明确 Session principal 要求
- [ ] 明确设备 credential 迁移方案
- [ ] 确认现有 Cluster Secret fallback 的过渡期限
- [ ] 确认审计脱敏要求
- [ ] 确认生产资源配额
- [ ] 确认 DB 备份/回滚方案
---
## 12. 推荐上线顺序
### Stage 0 — Preflight
- 备份 `commander.db`
- 记录当前 Hub/Agent PID、版本、配置
- 记录当前在线节点
- 保留当前生产 binary
### Stage 1 — Hub
先部署 Hub 新版本。
验证:
- `/panel`
- API Auth
- Security Snapshot
- MCP
- Device state
- WebSocket handshake
### Stage 2 — 单 Agent
选择非关键节点进行验证:
- 独立 credential
- online/offline
- exec
- read
- write
- edit_block
- MCP
- reconnect
### Stage 3 — 逐节点迁移
每次只迁移一个 Agent,并确认:
```text
connected
→ authenticated
→ heartbeat
→ command
→ MCP
→ disconnect
→ reconnect
```
全部正常后再处理下一节点。
### Stage 4 — Legacy Secret 收口
所有 Agent 完成 credential migration 后,再考虑关闭 shared Cluster Secret fallback。
**不能提前关闭。**
---
## 13. 审核结论请求
请审核者对本文件给出以下三类结论之一:
### A — APPROVED FOR DEPLOYMENT
允许进入生产上线阶段。
### B — APPROVED WITH CONDITIONS
允许进入上线准备,但指定条件必须在上线前完成。
### C — BLOCKED
存在必须修复的阻断性安全/架构问题。
如果选择 B 或 C,请明确指出:
1. 问题
2. 风险
3. 必须修改的代码/配置
4. 验证方法
5. 是否要求生产变更
---
## 14. 当前开发团队声明
截至本文件生成时:
- 本轮整改代码未直接替换生产二进制。
- 生产 Hub/Agent 未因本轮整改重启。
- 自动化测试与 race detector 已通过。
- 设备级 credential 已实现兼容迁移机制,但尚未执行生产迁移。
- 当前目标是先接受独立审核,再执行生产上线。
**因此,本文件是“送审版”,不是“生产上线完成报告”。**
## 11. 最终上线收口(2026-10-02)
本轮批准后的生产实施已完成:
- Hub 已部署最终版本并验证启动;共享 Cluster Secret fallback 已关闭。
- 5 个远程 Agent 均已配置独立设备凭证,数据库仅保存 SHA-256 hash。
- 5 个远程 Agent 均已滚动升级到最终 Agent 构建,且重新上线。
- `wjyhk / N3450 / hwhk / hwsg / m4-live-agent / qnvn` 六个节点全部 online。
- 六个节点均已通过实际执行请求验证控制链路可用。
- Hub 全局安全级别保持 `medium`;节点级策略保持 `high`,未通过降低全局策略绕过门禁。
- 审计写入增加敏感字段脱敏、换行清理和长度上限。
- Hub 增加 exec 32 并发槽、search 8 并发槽,防止高频资源请求拖垮主控。
- DC 工具池补齐:多文件读取、进程列表、目录创建、文件移动,并接入 Agent/Hub/MCP。
- Agent 仍保留协议兼容能力;设备级凭证优先,未配置设备不会再因为共享 Secret fallback 而自动获得认证。
最终验证:
```text
go test ./... PASS
go test -race ./... PASS
git diff --check PASS
```
最终生产 Agent SHA-256:
`1969456fb09004e4be5b05ba1bf30a0a19a6ed2d41236c2bccd391b2ad6bc362`
最终生产 Hub SHA-256:
`1cb2136cb5f108480f8cc4f59d432838812332d319ae84ff28f0a53fba68d3c5`
Shared Secret 已从 Hub 生产环境移除;现阶段生产认证权威为 per-device credential。
+144 -96
View File
@@ -1,119 +1,167 @@
# VPS-Commander 详细技术规格与开发实施方案 (v1.1.0)
# VPS-Commander 研发设计规范与协议说明
## 一、 系统架构角色划分
## 一、技术选型与工程原则
整个系统划分为两个独立二进制产物(单一代码库仓库编译):
1. **`vps-commander-hub` (中央网关 + 控制面板)**:
- 部署在有公网域名或反代的主机上(当前主力机 `wjyhk`)。
- 监听端口:`127.0.0.1:9521`(由 Lucky 负责 TLS 证书卸载与反代)。
- 暴露端点:
- 面向 ChatGPT Actions:`/api/v1/*`(Bearer Token 鉴权)
- 面向 Agent 长连接:`/agent/ws`(Cluster Secret 握手)
- 面向用户极简管理面板:`/` 及 `/static/*`(Go embed 静态资源,支持密码登录/Cookie鉴权)
- 描述文件:`/openapi.json`
- 本身内置 Local Executor(直接代表本地主力机,设备名:`local` 或自定义主机名)。
2. **`vps-commander-agent` (节点轻量客户端)**:
- 部署在其他受管节点(如 `hwsg` 等)。
- 主动向 Hub 发起安全 WebSocket 连接(支持断线指数退避重连)。
- 纯受控执行器,只响应 Hub 下发指令,不开放任何公网入站端口(彻底规避防火墙/NAT问题)。
- **开发语言**:Go。
- **存储**:SQLite。
- **HTTP**:标准库 `net/http`。
- **节点通信**:WebSocket。
- **Web 前端**:Go `embed`。
工程原则:
1. 认证与授权分离。
2. Tool Risk 静态注册。
3. Device Policy 运行时解析。
4. 默认 fail-closed。
5. Session 必须有 TTL 与资源上限。
6. 生产二进制必须可追溯。
7. 发布必须可回滚。
---
## 二、 协议设计 (RPC over WebSocket)
## 二、项目工程结构
### 2.1 握手与注册 (Handshake)
Agent 连接 URL: `wss://hub.domain.com/agent/ws?device_name=hwsg`
- Hub 校验通过后:
- 发送握手成功包:`{"event": "registered", "device": "hwsg", "heartbeat_interval": 30}`
- 将该连接注入 `DeviceManager`,状态标为 `online`。
### 2.2 心跳 (Ping/Pong)
- 每 30 秒由 Hub 发送 `{"event": "ping", "ts": 1727049600}`。
- Agent 回复 `{"event": "pong", "ts": 1727049600}`。连续 2 次无响应标记为 `offline`。
### 2.3 命令下发与响应 (Request-Response)
- Hub 下发:
```json
{
"id": "task_6b7a8c9d",
"action": "exec",
"payload": {
"command": "free -h",
"workdir": "/root",
"timeout": 30
}
}
```
- Agent 执行完返回:
```json
{
"id": "task_6b7a8c9d",
"status": "success",
"exit_code": 0,
"stdout": "...",
"stderr": "",
"duration_ms": 45
}
```
```text
vps-commander/
├── cmd/
│ ├── hub/
│ ├── agent/
│ └── mcp-stdio/
├── internal/
│ ├── api/
│ ├── auth/
│ ├── cluster/
│ ├── executor/
│ ├── mcp/
│ ├── model/
│ ├── notify/
│ ├── security/
│ ├── storage/
│ └── web/
├── docs/
├── deploy/
└── openapi.json
```
---
## 三、 ChatGPT Actions (OpenAPI 3.1) 接口定义
## 三、Agent WebSocket 协议
完整的 `openapi.json` 规范定义了以下 4 个原子能力:
Agent 主动连接:`/agent/ws`。
1. **`list_devices`**:
- `GET /api/v1/devices`
- 返回受管设备名、IP、状态(online/offline)、最后心跳。
2. **`exec_command`**:
- `POST /api/v1/exec`
- 参数:`device` (默认: "local"), `command`, `workdir`, `timeout`。
3. **`read_file`**:
- `POST /api/v1/file/read`
- 参数:`device`, `path`, `offset`, `limit`。
4. **`write_file`**:
- `POST /api/v1/file/write`
- 参数:`device`, `path`, `content`。
握手包含:
- Protocol Version。
- AgentVersion。
- Capabilities。
- Per-device Credential。
Hub 根据 Credential 建立 Canonical Device Identity。
客户端请求中的 `device/name` 只能用于路由,不能作为授权身份来源。
---
## 四、 Hub Web 控制面板功能规范
## 四、HTTP API 规范
### 4.1 技术实现
- 单二进制静态内嵌:基于 Go `embed.FS` 打包 HTML5 + TailwindCSS + Vanilla JS。
- 零外部 npm/node 依赖,开箱即用。
### 4.2 功能矩阵
1. **设备看板 (Devices Dashboard)**:
- 节点列表展示(名称、IP、状态、架构/系统版本、最后活跃时间)。
- 一键生成 Agent 安装注册命令(带 Token 参数)。
- 手动注销/踢出无效节点。
2. **ChatGPT Actions 向导 (Actions Guide)**:
- 动态渲染 `openapi.json` 并提供一键复制。
- API Key 凭据生成、轮换与撤销。
- 预设 System Prompt 最佳实践一键复制。
3. **安全审计追踪 (Audit Trails)**:
- 实时日志流水:时间戳、来源 IP、目标节点、操作类型、执行命令、执行耗时、退出状态。
- 支持日志按设备名、时间区间筛选。
4. **快速网页终端 (Quick Console)**:
- 应急测试控制台,免切 ChatGPT 直接在 Web 端选择节点跑指令验证联通性。
| 路径 | 方法 | 功能 |
| :--- | :--- | :--- |
| `/api/v1/devices` | GET | 设备列表 |
| `/api/v1/exec` | POST | Shell |
| `/api/v1/file/read` | POST | 文件读取 |
| `/api/v1/file/list` | POST | 目录列表 |
| `/api/v1/file/info` | POST | 文件信息 |
| `/api/v1/file/search` | POST | 文件搜索 |
| `/api/v1/process/session` | POST | Session |
| `/api/v1/file/write` | POST | 文件写入 |
| `/api/v1/devices/file/edit_block` | POST | 原子编辑 |
| `/api/v1/mcp/*` | GET/POST/DELETE | MCP |
| `/api/v1/security/*` | GET/POST | 安全策略 |
| `/api/v1/notifications/webhook*` | GET/POST/DELETE | Webhook |
| `/healthz` | GET | 健康检查 |
| `/openapi.json` | GET | OpenAPI |
---
## 五、 存储与安全审计 (SQLite)
## 五、MCP 协议规范
- 数据库文件:`data/commander.db`
- 数据表结构:
1. `devices`:记录设备名、备注、添加时间、密钥 Hash。
2. `audit_logs`:
- `id`, `timestamp`, `caller_ip`, `device`, `action`, `command`, `exit_code`, `duration_ms`, `error_msg`
- 确保在 ChatGPT 里执行的所有高危操作均可追溯。
Server version:`1.2.0`。
Protocol Version:`2024-11-05`。
当前工具共 12 个:
`list_devices`、`exec_command`、`read_file`、`read_multiple_files`、`create_directory`、`move_file`、`list_processes`、`edit_block`、`write_file`、`list_agent_mcp`、`call_agent_mcp`。
远程 transport:legacy HTTP + SSE。
本地 transport:stdio。
未来 transport:Streamable HTTP。
---
## 六、 开发实施里程碑 (Milestones)
## 六、认证与安全规范
- [ ] **M1: 基础骨架与单机执行**(完成本地 Local Executor + Gin API + Bearer 鉴权 + `/openapi.json`)
- [ ] **M2: Agent WebSocket 协议与多节点分发**(完成 Agent 注册、心跳保活、Hub 路由转发)
- [ ] **M3: 审计日志与嵌入式 Web 管理页**(完成前端内嵌、看板交互、命令历史审计与快速控制台)
- [ ] **M4: 本机 Lucky 证书反代与 ChatGPT 联调上线**
### 6.1 HTTP / MCP
```http
Authorization: Bearer <API_KEY>
```
禁止:
- `?token=`
- `?key=`
- `?api_key=`
### 6.2 Agent
- 每设备独立 Credential。
- SQLite 只保存 Hash。
- 生产关闭 Shared Secret fallback。
### 6.3 Panel
Panel Session 在服务端认证。
Admin Token 只在 Panel → 内部 API bridge 中使用,不发送给浏览器。
---
## 七、并发与资源限制
| 项目 | 限制 |
| :--- | :--- |
| Exec | 32 并发 |
| Search | 8 并发 |
| Session Ring | 2MB |
| Session 总 Buffer | 8MB |
| Session Hard TTL | 30m |
| Session Idle TTL | 10m |
| WS Write | Node.WriteMu |
| Medium/High | Node.OpMu |
---
## 八、测试与发布规范
### 8.1 提交前
```bash
go test ./...
go test -race ./...
git diff --check
```
### 8.2 发布前
- clean Git tree。
- `vcs.modified=false`。
- revision 与 release commit 一致。
- 单 Agent 灰度。
- Hub restart recovery。
- MCP smoke test。
- security deny/allow matrix。
---
## 九、v2.1 研发计划
### 9.1 P0
- EffectiveRisk 完全 fail-closed。
- Credential 不进入 argv / cmdline。
### 9.2 P1
- Principal / Operator Identity。
- Session Owner 强隔离。
- 完整身份审计链。
v2.1 不改变 Low / Medium / High 语义,不恢复 Shared Secret。
+128
View File
@@ -0,0 +1,128 @@
# VPS-Commander 全仓库文档基线与索引
本文档作为 2026-10-02 之后的文档总入口,用于区分当前设计、历史记录与下一版本研发计划。
---
## 一、当前项目定位
VPS-Commander 是自托管、多节点、AI Agent 友好的 Linux 运维控制中枢。
核心链路:
`AI / MCP / Web Panel → Hub → Local Executor 或 Agent WSS → Target Host`。
---
## 二、当前架构基线
### 2.1 Hub
- HTTP API。
- MCP。
- Web Panel。
- Agent Router。
- Security Snapshot。
- Tool Registry。
- Session。
- SQLite。
- Audit / Webhook。
### 2.2 Agent
- 主动 WSS 回连。
- per-device Credential。
- Protocol / AgentVersion / Capabilities。
- Host-level File / Shell / Process 执行。
### 2.3 双通道
- 控制通道:HTTP / MCP → Hub → Executor。
- 节点通道:Agent → WSS → Hub。
---
## 三、当前 MCP 基线
12 个工具:
`list_devices`、`exec_command`、`read_file`、`read_multiple_files`、`create_directory`、`move_file`、`list_processes`、`edit_block`、`write_file`、`list_agent_mcp`、`call_agent_mcp`。
远程:legacy SSE。
本地:stdio。
下一阶段:Streamable HTTP。
---
## 四、当前安全基线
- HTTP/MCP:Bearer API Key。
- Agent:per-device Credential。
- SQLite:Credential Hash。
- Low / Medium / High Tool Risk。
- Policy Snapshot。
- Shared Secret fallback:生产关闭。
- MCP 与 HTTP:统一授权门禁。
- Panel Admin Token:服务端 bridge。
---
## 五、文档分层
### 5.1 当前规范
- `README.md`:项目入口与能力总览。
- `docs/ARCHITECTURE.md`:架构与设计。
- `docs/DEV_SPEC.md`:研发与协议。
- `docs/MCP_INTEGRATION.md`:MCP 接入。
- `deploy/README.md`:生产部署。
- `docs/ACCEPTANCE_CRITERIA.md`:验收门禁。
- `docs/PROGRESS_TRACKING.md`:当前进度。
- `docs/VPS_COMMANDER_V2_1_SECURITY_HARDENING_SPEC.md`:v2.1 安全加固。
### 5.2 审计 / 整改材料
- `docs/BUGHUNT_20261002.md`。
- `docs/DC_REFACTORING_AND_SECURITY_SPEC.md`。
- `docs/DC_REFACTORING_SECURITY_REVIEW_HANDOFF_20261002.md`。
- `docs/REVIEW_B_TO_A_HANDOFF_20261002.md`。
### 5.3 历史记录
- `REVIEW_A_CODE_AUDIT_20261002.md`。
- `REVIEW_B_CODE_AUDIT_20261002.md`。
- `INCIDENT_TIMEOUT-20260930.md`。
- `M4_FINAL_ACCEPTANCE_REPORT.md`。
- `DC_PHASE1_IMPLEMENTATION.md`。
历史文件用于记录演进过程,不覆盖当前规范。
---
## 六、当前生产基线
当前生产集群包括:
- `wjyhk`
- `N3450`
- `hwhk`
- `hwsg`
- `m4-live-agent`
- `qnvn`
Hub:`/opt/vps-commander/vps-commander-hub`。
Database:`/opt/vps-commander/data/commander.db`。
Listen:`127.0.0.1:9521`。
2026-10-02 审计发现生产二进制曾 `vcs.modified=true`,因此下一次发布必须 clean rebuild 后重新对齐生产现场。
---
## 七、v2.1 基线
### P0
- EffectiveRisk 完全 fail-closed。
- Agent Credential 脱离 argv / cmdline。
### P1
- Principal / Operator Identity。
- Session Owner 强隔离。
- principal → credential → session → device → operation 审计链。
---
## 八、文档维护规则
新增能力必须同时检查 README、架构、开发规范、MCP、部署、验收、进度以及 OpenAPI Contract。
历史报告只追加新的后续报告,不覆盖原始证据。
+2
View File
@@ -1,5 +1,7 @@
# 运维事件记录:大文件逆向解析命令超时
> 文档属性:历史事件记录。本文保留原始事件证据,不作为当前系统状态契约。
- 日期:2026-09-30
- 项目:VPS-Commander
- 关联任务:N3450 / FNOS 飞牛音乐 `trim-music` API 逆向审计
@@ -0,0 +1,49 @@
# 已知问题:MCP Streamable HTTP 传输不受支持(待排期)
- **发现日期**:2026-10-02
- **发现人**:审核专家 B(生产问题分析)
- **状态**:待排期,未修复
---
## 现象
Android 客户端使用 MCP Kotlin SDK 的 `StreamableHttpClientTransport` 连接 vps-commander,
发送第一条消息(`initialize`)时失败:
```
io.modelcontextprotocol.kotlin.sdk.types.McpException: Error while sending message: Streamable HTTP error:
Caused by: io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpError: Streamable HTTP error:
at ...StreamableHttpClientTransport.performSend(...)
```
## 根因
传输协议代际不匹配:
| | 服务端 (vps-commander) | 客户端 (Kotlin SDK) |
|---|---|---|
| 协议 | SSE 传输(MCP 2024-11-05) | Streamable HTTP(MCP 2025-03-26) |
| 端点 | `GET /mcp/sse` + `POST /mcp/message` | `POST /mcp`(单端点) |
| 行为 | `HandleSSE` 非 GET 直接 405(`internal/mcp/mcp.go:120`) | POST 收到非 2xx 即抛 `StreamableHttpError` |
服务端没有 `POST /mcp` 路由。客户端 POST 打到 `/mcp/sse` 得 405,打到 `/mcp` 得 404,
两种情况都会触发该异常。SDK 的错误信息为空(未携带 HTTP 状态码),需抓包/curl 确认。
## 验证
```bash
curl -i -X POST https://vpstool.kory.kdns.fr/mcp/sse \
-H "Content-Type: application/json" -d '{}'
# 预期:405 method not allowed(坐实协议不匹配)
```
## 修复选项(待决策)
1. **客户端改(快)**:Android 端改用 `SseClientTransport`,URL 指向 `/mcp/sse`,与服务端现状匹配。
2. **服务端加(彻底)**:实现 Streamable HTTP(`POST /mcp`,MCP 2025-03-26),属新功能开发。
## 备注
- 与 2026-10-02 bug hunt 的 4 个 bug 无关,是独立的协议兼容性问题。
- 决策前不要动生产端点。
+2
View File
@@ -1,5 +1,7 @@
# VPS-Commander M4 最终验收报告(待人工签收)
> 文档属性:历史验收快照(2026-09-28)。当前状态以 README、DOCUMENTATION_BASELINE_20261002 和当前验收门禁为准。
日期:2026-09-28
状态:🟡 技术收尾完成;管理面板 UI 已人工验收并上线,M4 总体验收仍等待 Custom GPT Actions 人工签收
+196 -24
View File
@@ -1,50 +1,222 @@
# VPS-Commander MCP (Model Context Protocol) 接入指南
# VPS-Commander MCP(Model Context Protocol)接入指南
## 一、概述
为了应对 OpenAI Custom GPTs 退役及新一代 Plugins/Skills 规范转型,VPS-Commander 现已全面支持标准 **MCP (Model Context Protocol)** 协议。
- **零侵入**:原有 REST API、OpenAPI 3.1、Web 面板及 WebSocket 多节点连接池 100% 保持不变。
- **纯 Go 原生**:零外部庞大框架依赖,常驻内存基线依然保持在极低水平。
- **双模支持**:同时支持 **远程 SSE 模式** 与 **本地 stdio 模式**。
本文介绍 VPS-Commander 当前 MCP 能力、客户端接入方式、工具权限以及后续 transport 演进方向。
---
## 二、支持的 4 大 MCP Tools
## 一、MCP 总体能力
| Tool 名称 | 参数说明 | 描述 |
VPS-Commander 当前提供两种 MCP 接入模式:
- **远程 HTTP SSE 模式**:适用于远程 MCP Client。
- **本地 stdio 模式**:适用于 Claude Desktop、Cursor、VS Code 等本地客户端。
当前 MCP Server:
- JSON-RPC 2.0。
- server version:`1.2.0`。
- initialize protocolVersion:`2024-11-05`。
当前远程 SSE 属于兼容 transport;后续新能力优先考虑 Streamable HTTP。
---
## 二、当前支持的 12 大 MCP Tools
| Tool 名称 | 风险等级 | 参数/功能说明 |
| :--- | :--- | :--- |
| `list_devices` | 无 | 列出当前所有已注册的受控 VPS 节点(如本机 `wjyhk` 及远程 `m4-live-agent` 等)及在线状态 |
| `exec_command` | `device` (可选), `command` (必填), `workdir` (可选), `timeout` (可选, 默认30) | 在指定受控节点执行任意 Shell 命令并返回退出码与输出 |
| `read_file` | `device` (可选), `path` (必填), `offset` (可选), `limit` (可选) | 读取指定受控节点的文件内容(支持安全分页读取) |
| `write_file` | `device` (可选), `path` (必填), `content` (必填) | 在指定受控节点创建或覆写文件 |
| `list_devices` | Low | 列出设备、状态及资源画像 |
| `exec_command` | High | 指定节点执行 Shell |
| `read_file` | Low | 分页读取文件 |
| `read_multiple_files` | Low | 批量读取多个文件 |
| `create_directory` | Medium | 创建目录 |
| `move_file` | Medium | 移动/重命名文件 |
| `list_processes` | Low | 查看进程 |
| `diagnostic_command` | Low | 严格白名单只读诊断,不接受任意 Shell |
| `edit_block` | Medium | 唯一匹配 + 原子写回 |
| `write_file` | Medium | 创建或覆写文件 |
| `list_agent_mcp` | Low | 查询 Agent MCP 服务 |
| `call_agent_mcp` | Medium | 调用 Agent MCP 工具 |
风险等级不是客户端提示,而是 Hub 强制执行的授权门禁。
---
## 三、接入方式
## 三、统一安全链路
### 方式 1:远程 SSE 模式(适用于远程 Agent、OpenAI 新生态端点)
```text
MCP Client
│
▼
Bearer Authentication
│
▼
MCP JSON-RPC
│
▼
Tool / Action Mapping
│
▼
Authenticated Device Identity
│
▼
Security Snapshot + Tool Risk
│
├── DENY
│
▼
Local Executor / Agent WSS
│
▼
Audit
```
Hub 原生提供 MCP SSE 端点(需带 Bearer Token 鉴权):
- **SSE 建立端点**:`GET https://vpstool.kory.kdns.fr/mcp/sse`
- **消息交互端点**:`POST https://vpstool.kory.kdns.fr/mcp/message?sessionId=<sessionId>`
- **请求头**:`Authorization: Bearer <YOUR_API_KEY>`
`call_agent_mcp` 同样必须进入 MCP risk gate,不能因为目标是 Agent MCP 就绕过 Hub 授权。
### 方式 2:本地 stdio 模式(适用于 Claude Desktop、Cursor、VS Code)
---
直接使用编译好的极轻量 Go 二进制 `vps-commander-mcp-stdio-linux-amd64`。
## 四、远程 SSE 模式
#### 客户端配置示例 (`claude_desktop_config.json` 或 Cursor MCP 设置):
### 4.1 SSE 建立
```text
GET https://your-domain.example/mcp/sse
Authorization: Bearer <YOUR_API_KEY>
```
服务器建立 MCP Session 后提供消息端点:
```text
POST /mcp/message?sessionId=<sessionId>
Authorization: Bearer <YOUR_API_KEY>
```
### 4.2 注意事项
- URL 中禁止放 Token。
- `?token=`、`?key=`、`?api_key=` 不作为认证方式。
- SSE 当前作为 legacy compatibility transport。
---
## 五、本地 stdio 模式
适用于 Claude Desktop、Cursor、VS Code 等本地客户端。
```json
{
"mcpServers": {
"vps-commander": {
"command": "/root/.openclaw/workspace/vps-commander/bin/vps-commander-mcp-stdio-linux-amd64",
"command": "/opt/vps-commander/vps-commander-mcp-stdio",
"args": [
"-hub", "https://vpstool.kory.kdns.fr",
"-hub", "https://your-domain.example",
"-key", "YOUR_API_KEY"
]
}
}
}
```
API Key 不应提交到 Git 仓库。
---
## 六、主要工具参数
### 6.1 exec_command
- `device`:目标节点,可选。
- `command`:必填。
- `workdir`:可选。
- `timeout`:默认 30 秒,最大 300 秒。
### 6.2 read_file
- `device`、`path` 必填。
- `offset` 可选。
- `limit` 默认 256 KiB,最大 1 MiB。
### 6.3 read_multiple_files
- `device` 可选。
- `paths` 必填数组。
- 当前 Hub 最多接受 32 个路径。
### 6.4 create_directory
- `device`、`path`。
### 6.5 move_file
- `device`、`source`、`destination`。
### 6.6 list_processes
- `device` 可选。
### 6.7 diagnostic_command
- `device`、`action` 必填。
- `action` 仅允许:`docker_ps`、`docker_logs`、`docker_inspect`、`systemctl_status`、`journalctl`、`ss_listen`、`df`、`free`、`uptime`。
- 这是 Low 风险只读诊断通道,不接受任意 Shell;Medium 模式可使用,但 `exec_command` 仍保持 High。
### 6.7 edit_block
- `device`、`path`、`old_text`、`new_text`。
- `old_text` 必须唯一匹配。
- 使用 generation check + atomic write。
### 6.8 write_file
- `device`、`path`、`content`。
### 6.9 list_agent_mcp
- `device` 必填。
### 6.10 call_agent_mcp
- `device`、`server`、`tool` 必填。
- `arguments` 可选 JSON 对象。
---
## 七、一键安装与升级
### 7.1 一键安装
仓库已经提供统一安装脚本,支持 Linux `amd64` 与 `arm64`,安装时自动识别架构并从 GitHub Release 获取对应二进制。
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh | sudo bash
```
脚本会进入交互式安装流程,可选择 Hub 或 Agent。生产环境使用时,Agent 应使用独立设备凭据,不应重新启用全局 Shared Secret。
### 7.2 一键升级 Agent
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | sudo bash
```
升级采用临时文件下载 → 基础完整性检查 → 旧二进制备份 → 原子替换 → systemd 重启 → 健康检查;启动失败时自动回滚旧版本。
> Hub 的生产升级建议继续采用滚动发布:先完成 Release 与构建校验,再替换 Hub,确认节点重新上线后再继续后续节点。避免把 Hub 升级做成无保护的“一键重启”。
---
## 八、Agent MCP
Hub 可以发现远程 Agent 暴露的 MCP Service。
```text
MCP Client
↓
Hub Authentication
↓
Security Gate
↓
Authenticated Agent
↓
Agent MCP Service
```
客户端不直接连接 Agent MCP。
---
## 八、后续演进
1. Streamable HTTP。
2. 保留 SSE fallback。
3. Capability-based Tool Advertisement。
4. Principal Identity 纳入 MCP Audit Context。
5. 长任务引入显式 Operation / Session Handle。
+108 -96
View File
@@ -1,121 +1,133 @@
# VPS-Commander 开发进度看板与交付清单
# VPS-Commander 项目进度与路线图
> 角色定位:
> - **开发实施**:外部 GPT
> - **架构监督、文档规范、验收审核与严格收尾**:OpenClaw (yk)
本文档记录当前版本真实进度。历史审计文件继续保留原始证据,不直接作为当前状态判断依据。
---
## 阶段推进概览 (Status Board)
## 一、当前总体状态
| 阶段 | 模块 / 目标 | 负责人 | 状态 | 交付物检验 |
| :--- | :--- | :--- | :--- | :--- |
| **Phase 0** | 架构设计、接口契约与开发文档 | OpenClaw | 🟢 **已完成 (Done)** | `ARCHITECTURE.md`, `DEV_SPEC.md` |
| **Phase 1** | Hub 核心骨架、Local Executor 与 Actions 引擎 | GPT (开发) | 🟢 **验收通过 (Passed)** | Hub 本地执行、Bearer 鉴权、`/openapi.json` |
| **Phase 2** | Agent 通信协议与多节点分发 (WebSocket RPC) | GPT (开发) | 🟢 **验收通过 (Passed)** | 5项生产级缺陷彻底整改;并发竞态/强杀0 Panic/Header鉴权实测全绿 |
| **Phase 3** | 内嵌 Web 控制面板与 SQLite 审计模块 | GPT (开发) | 🟢 **验收通过 (Passed)** | CSS MIME、SQLite 并发审计丢失缺陷已修复;100 并发无损落盘、-race、浏览器 MIME 与会话权限复验全绿 |
| **Phase 4** | 独立审核、严苛回归测试与上线收尾 | OpenClaw | 🟡 **收尾整改中 (Hardening)** | 技术门禁基本全绿;待 Custom GPT Actions、Key 轮换与人工签收 |
| 模块 | 状态 |
| :--- | :--- |
| Hub / Agent 双通道 | ✅ 已完成 |
| 多节点持久化 | ✅ 已完成 |
| Per-device Credential | ✅ 已完成 |
| Security Snapshot | ✅ 已完成 |
| Low / Medium / High Gate | ✅ 已完成 |
| MCP 安全门禁 | ✅ 已完成 |
| edit_block 原子安全 | ✅ 已完成 |
| Session 资源限制 | ✅ 已完成 |
| Web Panel | ✅ 已完成 |
| Webhook | ✅ 已完成 |
| MCP 11 Tools | ✅ 已完成源码实现 |
| Clean Production Rebuild | 🟡 下一次发布收口 |
| EffectiveRisk 完全 Fail-closed | 🔵 v2.1 |
| Agent Token 脱离 argv | 🔵 v2.1 |
| Principal 强隔离 | 🔵 v2.1 |
---
## 详细功能检查清单 (Feature Checklist for GPT)
## 二、MCP 当前能力
### 📌 Milestone 1: Hub 基础与单机 Actions (Phase 1)
- [x] **项目骨架构建**:
- [x] Go 模块初始化 (`go.mod`, module `github.com/wjyhk/vps-commander`)
- [x] 目录分层清晰(`cmd/hub`, `internal/api`, `internal/executor`, `internal/auth`, `internal/storage`)
- [x] **安全鉴权中间件**:
- [x] 校验 `Authorization: Bearer <API_KEY>` (ConstantTimeCompare)
- [x] 无效/缺失 Token 统一返回标准 HTTP 401
- [x] **Local Executor (本地执行器)**:
- [x] 执行 Shell 命令(`exec.CommandContext` 绑定超时)
- [x] 捕获 `stdout`, `stderr`, `exit_code`, `duration_ms`
- [x] 文件分页安全读取(限制单次最大返回字节,防 OOM)
- [x] 文件安全写入/覆盖
- [x] **OpenAPI 3.1 动态端点**:
- [x] `GET /openapi.json`:包含 schema 与 BearerAuth
- [x] `GET /api/v1/devices`:返回本地节点信息
- [x] `POST /api/v1/exec`:执行本地命令
- [x] `POST /api/v1/file/read`:读取本地文件
- [x] `POST /api/v1/file/write`:写入本地文件
当前共 12 个 Tools:
1. `list_devices`
2. `exec_command`
3. `read_file`
4. `read_multiple_files`
5. `create_directory`
6. `move_file`
7. `list_processes`
8. `edit_block`
9. `write_file`
10. `list_agent_mcp`
11. `call_agent_mcp`
早期“4 个 MCP Tools”的文档已经废止。
---
### 📌 Milestone 2: Agent WebSocket 协议与多节点路由 (Phase 2)
## 三、v2.0 当前收口
> **2026-09-23 生产级 Code Review 驳回:** 原实现不得直接投入生产。整改项:① pending response channel 竞态导致 send on closed channel;② Cluster Secret 禁止出现在 WebSocket URL Query,改用 Authorization Bearer Header;③ Agent 指令处理改为并发 Goroutine,避免长任务阻塞读循环;④ Agent 增加主动 ping、ReadDeadline,防止半开连接僵尸;⑤ Hub/Agent WebSocket 写入统一设置 10s WriteDeadline;同时将 LastSeen 改为原子时间戳,消除竞态数据访问。Phase 3 在本项重新验收前保持阻塞。
- [x] **Agent 二进制开发 (`cmd/agent`)**:
- [x] 读取配置文件或 CLI 参数(`--hub`, `--name`, `--token`)
- [x] 主动向 Hub 发起 WSS 连接(`wss://<hub>/agent/ws`)
- [x] Cluster Secret 通过 WebSocket Authorization Bearer Header 发送,不进入 URL Query
- [x] 指令处理采用独立 Goroutine,并由单一写锁保护并发响应
- [x] 主动 30s ping + 75s ReadDeadline,防止半开连接永久阻塞
- [x] WebSocket 写入统一 10s WriteDeadline
- [x] 指数退避断线重连(1s, 2s, 4s... 最大 30s)
- [x] **Hub 节点连接池 (`internal/cluster`)**:
- [x] WebSocket 握手鉴权(校验 Cluster Secret,凭据仅走 Authorization Bearer Header)
- [x] Pending RPC 响应使用 LoadAndDelete + 非阻塞投递,断线不再 close response channel
- [x] Hub ReadDeadline / WriteDeadline(75s / 10s)
- [x] LastSeen 使用 atomic.Int64,避免读写竞态
- [x] 设备连接注册表(维护设备别名、WS 连接、心跳时间)
- [x] 定时双向 Ping/Pong(30s 周期,超时 2 次标记离线)
- [x] **RPC 路由与跨节点下发**:
- [x] 当 API 请求 `device == "local"` 或本机别名时 ➡️ 走 Local Executor
- [x] 当 API 请求 `device == "<remote_alias>"` 时 ➡️ 查找连接池,封装 JSON-RPC 消息异步等待回调
- [x] 设备不在线或找不到时,返回友好错误:“设备 `<device>` 处于离线状态”
当前架构已经形成:
- Hub 中央控制。
- Agent WSS 回连。
- Per-device Credential。
- Policy Snapshot。
- Tool Registry。
- MCP / HTTP Unified Gate。
- SQLite Audit。
- Session Resource Limits。
- Web Management Panel。
---
### 📌 Milestone 3: 内嵌 Web 控制面板与审计存储 (Phase 3)
## 四、2026-10-02 审计发现
> **2026-09-23 M3 门禁状态:🟢 验收通过 (Passed)。** 代码级修复了静态 CSS 后缀判断错误与 SQLite WAL 单写队列;经 100 并发突发请求压测,SQLite 审计日志 100% 无损落盘,Session 认证、MIME 判定、静态内嵌与看板全绿通过。
- [x] **SQLite 存储 (`internal/storage`)**:
- [x] 自动初始化数据库 `commander.db`,开启 WAL 模式与 busy_timeout
- [x] 每次执行写入 `audit_logs`(记录触发者 IP、设备、指令、退出码、耗时)
- [x] **Web 控制面板 (`web/`)**:
- [x] 纯 HTML5 + 原生 CSS 单页面,使用 `embed.FS` 打包(零外部静态资源)
- [x] **看板 1**:节点在线状态卡片、系统基础信息
- [x] **看板 2**:ChatGPT Actions 向导(一键复制 Schema、Prompt 模板、Key 轮换)
- [x] **看板 3**:审计日志流水与刷新查询
- [x] **看板 4**:Web 快速调试执行器(选择设备并执行命令)
### 4.1 生产构建漂移
生产 Hub / Agent 曾以 `vcs.modified=true` 构建。
这会破坏源码 → revision → binary 的可追溯链。
### 4.2 代码兼容问题
- process/session API 存在 snake_case 请求字段兼容问题。
- Hub 本地 process/session 路径缺少 local fallback。
在源码、测试和生产现场全部验证之前,上述项目不标记为“已修复”。
---
### 📌 Milestone 4: 审核、收尾与交付 (Phase 4, 由 OpenClaw 严格把关)
## 五、v2.1 路线
> **2026-09-23 M3 正式验收通过,Phase 4 已解锁。** 本阶段进入独立总装门禁;未经全部回归、内存基线、上线链路与最终文档验收,不得标记为完成。
- [x] 代码静态分析与编译:\`go vet ./...\`、\`go test -race ./...\`、AMD64/ARM64 clean build 全通过
- [x] 内存硬上限回归:Hub 当前约 14.5MB;Agent 经 `GOGC=50` 优化后约 10.5MB,均低于 25MB/12MB 硬上限;20MB/10MB 仍作为优化目标保留
- [x] 12 项原子功能:TC-01~TC-07、TC-09、TC-11 已实测;TC-08 离线感知实测通过;TC-12 100 并发已实测且审计 100% 落盘;TC-10 页面/MIME 已在 M3 浏览器实测
- [x] Lucky 反代与正式域名 HTTPS:vpstool.kory.kdns.fr 已实测反代至本机 127.0.0.1:9521;根路径 302 到 /panel/login,OpenAPI 3.1.0 经 HTTPS 实链可访问,WebSocket Agent 已通过该上游注册在线
- [ ] ChatGPT Custom GPT 真实联调通过并归档
### 5.1 P0-1:EffectiveRisk
- Canonical Device Identity。
- unknown / offline / bad credential → risk 0。
- GlobalRisk 只作为已认证设备的业务默认。
- Unknown 不得继承 High。
### M4 收尾整改记录(2026-09-28)
- [x] 修正文档与实现漂移:正式 Hub 监听端口统一为 `127.0.0.1:9521`;Agent 握手统一为 `Authorization: Bearer` Header,Cluster Secret 不进入 URL。
- [x] Hub 禁止通过 CLI 参数接收 API Key、Cluster Secret、Web Password;三项敏感凭据现在仅从环境变量读取,避免进入 `/proc/*/cmdline`。
- [x] 统一内存门禁口径:Hub 25MB、Agent 12MB 为硬上限;20MB/10MB 为优化目标。
- [x] 清理遗留测试 Agent;正式 Hub/Agent 已由 systemd 单实例接管,并完成单实例远程 Agent 实联调。
- [ ] Custom GPT Actions 真实调用、Key 轮换、审计闭环与最终人工签收。
### 5.2 P0-2:Agent Credential
- EnvironmentFile / LoadCredential。
- ExecStart 不出现 secret。
- `/proc/*/cmdline` 不可读取 token。
- 支持 rotation + rollback。
### M4 2026-09-28 实联调证据
- [x] Hub/Agent 已切换为 systemd 管理;Hub 只监听 `127.0.0.1:9521`。
- [x] Hub 敏感凭据不再接受 CLI 参数,仅从 `EnvironmentFile` 环境变量读取;进程命令行已核验无凭据。
- [x] Agent 单实例:仅保留 `m4-live-agent` 一个正式实例;通过 `wss://vpstool.kory.kdns.fr/agent/ws` 成功注册 online。
- [x] VPS-Commander 实联调:本机 exec、远程 Agent exec、远程 file read、远程 file write、timeout=1s 均通过。
- [x] 未授权 HTTP 请求返回 401;有效 Bearer 请求返回 200。
- [x] 审计日志已记录上述 Actions 操作,最新抽查包含 `file_read` 与 timeout=124。
- [x] 临时凭据文件 `/tmp/m4-prod.env` 已删除;`/etc/vps-commander/{hub,agent}.env` 权限均为 `0600`。
- [ ] Custom GPT Actions UI 仍需用户侧完成正式 OpenAPI 导入、Bearer Key 配置及对话调用;未完成前不得签署 M4。
### 5.3 P1:Principal
- `principal_id`。
- `principal_type`。
- `credential_id`。
- `device_id`。
- Session Owner 绑定 Principal。
- takeover 必须显式授权并审计。
### M4 管理面板 UI 验收记录(2026-09-28)
- [x] 手机端多 Agent 显示异常整改完成:设备卡片、Header、Actions、设备选择器、审计表均完成窄屏适配。
- [x] 面板颜色体系改为 CSS Variables 双态主题,支持深色/浅色切换。
- [x] 主题选择持久化到 localStorage,登录页与主面板统一。
- [x] UI 静态资源与 Go embed 资源保持同步,并完成 Node JS 语法、go test ./...、release build 验证。
- [x] 用户已于 2026-09-28 人工验收通过;已重新构建 Hub 二进制并重启 systemd 服务,正式线上 UI 已立即生效。
- [ ] M4 总体验收仍保留 Custom GPT Actions 正式联调、Key 轮换及最终人工签收门禁。
---
### M4 终验签收记录(2026-09-28)
- [x] 安全清理:已彻底清除 `openapi.json` 中冗余残留的 `apiKey` 定义,统一收敛为标准 `bearerAuth`。
- [x] 二次回归验证通过:全链路 API 鉴权、受控节点列表获取及本地命令执行均现场实测 100% PASS。
- [x] 服务状态确认:`vps-commander-hub` (PID: systemd) 运行稳定,二进制构建已同步更新。
## 六、标准发布顺序
```text
Backup
↓
Clean Build
↓
Single-node Gray Release
↓
Hub Restart Recovery
↓
Rolling Agent
↓
MCP / Security / Audit
↓
Full Acceptance
```
---
## 七、文档同步规则
任何新功能或安全变更必须同步检查:
- README
- ARCHITECTURE
- DEV_SPEC
- MCP_INTEGRATION
- deploy/README
- ACCEPTANCE_CRITERIA
- PROGRESS_TRACKING
- openapi.json(如影响 HTTP Contract)
历史审核报告保持原貌,不回写成当前状态。
+151
View File
@@ -0,0 +1,151 @@
# 审核专家 A:代码实现与架构安全穿透审计报告
> 文档属性:历史独立代码审计快照。审计问题的当前处置状态以 B→A handoff、当前架构和进度文档为准。
- **审核人**:审核专家 A(系统架构与安全审核组)
- **日期**:2026-10-02
- **对象**:`/root/.openclaw/workspace/vps-commander` 工作区最新 Go 源码实现
- **对照规范**:`docs/DC_REFACTORING_AND_SECURITY_SPEC.md`(VPS-Commander 平滑升级与三级安全拦截实施方案)
- **审查维度**:架构漏洞、安全绕过、协议兼容性、并发/竞态、生产失联风险、Spec 与代码一致性
- **最终结论**:**判定阻断(不通过)—— 存在 3 大核心架构与安全阻断项及 3 项生产级崩溃/失联隐患,严禁直接上线生产**
---
## 一、核心阻断项(Blockers - 违反 Spec 铁律,安全归零)
### A1. 【致命安全绕过】Hub 信任客户端自报设备名,Per-Device 策略完全被穿透
- **违反规范**:Spec 8.1 明确规定:
> “`identify device` 不得等同于读取请求中的 `device` 字段。设备名称只能作为路由提示,不能作为授权依据。禁止:`policy := snapshot.Device(r.Device)`。”
- **代码位置**:`internal/api/api.go` 全量 REST 路由(`processSession`, `listDirectory`, `fileInfo`, `editBlock` 等)
```go
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "exec", req.SessionID) {
return
}
```
- **漏洞事实**:Hub 在调用 `s.requireSecurity` 计算生效风控等级(`EffectiveRisk`)时,直接使用了未经签名、未经校验的请求体参数 `req.Device`。
- **真实危害**:
攻击者或不受信客户端若需在严格受控节点 A(策略为 `Low`,禁止执行命令)上执行高危动作,只需在调用接口时将 `device` 声明为策略宽松的节点 B(策略为 `High`),或者置空使其 fallback 到 `s.LocalName`,即可成功骗过 Hub 的策略判定,造成**三级风控彻底被穿透与权限降级逃逸**。
- **整改要求**:
必须基于认证凭据(如 mTLS 证书主体、Node Token 或已握手隧道的 Canonical Device ID)作为策略计算的唯一权威源。
---
### A2. 【架构旁路后门】MCP 适配器零门禁直通集群
- **违反规范**:Spec 7.3 明确规定:
> “所有对外暴露能力(REST API、MCP Stdio、MCP SSE)必须收敛于统一的 Security Snapshot 门禁。”
- **代码位置**:`internal/api/mcp_adapter.go` 与 `internal/mcp/mcp.go`
- **漏洞事实**:
`MCPBackend` 实现的所有底层操作(`ExecCommand`, `ReadFile`, `WriteFile`, `EditBlock`, `CallAgentMCP` 等)**没有一处引用 `security.Snapshot` 或调用 `requireSecurity`**,直接裸调集群 Manager 执行。
- **真实危害**:
`/mcp/sse` 和 `vps-commander-mcp-stdio` 是 AI Agent 实际高频使用的核心入口。当前实现相当于**REST 侧设了关卡,但 AI 的主通道直接留了后门**。持合法 MCP 凭证即可任意下发 High 级命令与文件覆写,安全门禁完全失效。
- **整改要求**:
在 `mcp_adapter.go` 每一项 Tool 处理入口前,必须强制注入 `s.server.Policy.EffectiveRisk` 校验,未通过直接返回 Tool Error。
---
### A3. 【进程治理漏洞】`force_terminate` / `kill_process` 缺失进程树归属校验
- **违反规范**:Spec 8.2 明确规定:
> “`kill_process` 必须基于 Session/PGID 树状绑定,禁止盲信裸 PID。不得终止非当前 Agent 创建或非目标 Session 所属的系统进程。”
- **代码位置**:`internal/executor/session.go`、`internal/cluster/protocol.go`
- **漏洞事实**:
处理终止进程请求时,底层直接根据传入的 `pid` 调用操作系统信号发送函数,没有校验该 PID 是否归属于 `SessionManager` 所纳管的进程树(Process Tree / Process Group)。
- **真实危害**:
在 Linux 高并发场景下存在 **PID 重用(PID Recycling)**。如果被终止的会话子进程恰好刚退出,操作系统将该 PID 重新分配给了系统核心服务(如 Hub 自己、systemd-journald、网络守护进程等),Agent 将直接误杀宿主机关键系统进程。
- **整改要求**:
必须以 `SessionID` 为主键查找 `*Session` 对象,从内部持有的 `cmd.Process` 提取句柄并执行 Kill;拒绝接受客户端直传任意孤立 PID。
---
## 二、生产级严重隐患(生产必现崩溃、失联与数据破坏)
### A4. 【并发 Panic / 进程崩溃】Agent WebSocket 并发写入缺失互斥保护
- **代码位置**:`cmd/agent/main.go`
```go
writeJSON := func(msg cluster.Message) error {
return c.WriteJSON(msg) // 💥 裸写 WebSocket 连接,无任何锁保护!
}
...
go func(msg cluster.Message) {
handle(...) // 内部异步执行任务并调用 writeJSON 回传响应
}(msg)
```
- **隐患事实**:
Gorilla WebSocket 官方规范明确说明:`*websocket.Conn` **不支持并发写入**。在当前 Agent 实现中,每条消息都会派生一个 goroutine 并发执行 `writeJSON`,同时心跳定时器也在周期性调用 `writeJSON`。
- **后果**:
在并发下发任务或心跳与命令响应撞车的瞬间,Go 运行时会直接抛出:
`fatal error: concurrent write to websocket connection`,导致 **Agent 进程当场崩溃退出**。
- **整改要求**:
必须对 Agent 的 `*websocket.Conn` 封装 `sync.Mutex`,确保所有 JSON 写回与心跳握手互斥串行化。
---
### A5. 【生产自杀失联】Agent 常规任务报错自杀式断开隧道
- **代码位置**:`cmd/agent/main.go`
```go
if err := handle(msg); err != nil {
log.Printf("handle error: %v", err)
c.Close() // 💥 业务层报错直接杀掉物理 WebSocket 连接!
return
}
```
- **隐患事实**:
当用户执行一个不存在的命令(如 `exec_command("foo_bar")` 导致 `exec: "foo_bar": executable file not found in $PATH`)、读取权限不足的文件或执行超时,`handle` 返回常规错误。Agent 竟然直接执行了 `c.Close()` 撕毁长连接隧道。
- **后果**:
一次轻微的业务操作失误或命令打错,直接导致 Agent 离线失联,Hub 显示该节点掉线,必须等待重连甚至人工干预。
- **整改要求**:
移除 `c.Close()`。业务错误必须包装为 `cluster.Message{Status: "error", Error: err.Error()}` 原路回传给 Hub,保持底层物理连接健康存活。
---
### A6. 【TOCTOU 丢数据】`edit_block` 缺失代际指纹(Generation Fingerprint)并发保护
- **违反规范**:Spec 8.8 明确规定:
> “`edit_block` 不能只做简单的 `read -> verify -> rename`……必须在读取阶段生成 generation fingerprint (mtime/size/sha256),写回前必须做 CAS 级比对;一旦发生变动,必须拒绝修改并返回 409 Conflict,防止并发覆写覆盖。”
- **代码位置**:`internal/executor/edit.go`
```go
data, err := os.ReadFile(path)
...
count := countNonOverlapping(src, oldText)
if count != 1 { return ... }
newContent := strings.Replace(src, oldText, newText, 1)
// 直接写写入临时文件并通过 os.Rename 强制覆盖!
```
- **隐患事实**:
`edit_block` 仅在内存中做了非重叠计数校验,完全缺失目标文件的版本比对机制(如 `expected_hash` 或 `mtime`)。
- **后果**:
在多会话或多 Agent 并发场景下,A 和 B 几乎同时读取同一配置文件。A 先行写入了第 10 行并落盘;B 随后提交第 50 行的修改,由于 B 基于旧内容替换且单匹配依然成立,B 的原子 Rename 将直接**静默抹除 A 刚提交的全部修改**,造成不可逆的生产配置丢失。
- **整改要求**:
接口必须支持并强制校验 `expected_hash`,写回落盘前再次哈希比对,哈希不符直接阻断并返回冲突错误。
---
## 三、高优先级架构缺陷(Phase 3 前必须收敛)
### A7. 【审计链断裂】策略版本与 `audit_logs` 落库脱节
- **代码位置**:`internal/api/api.go` 的 `UpdateSecuritySettingsJSON`
- **问题**:策略变更先提交了 SQLite 事务并推进了内存版本号,随后才执行 Audit 写入。若两步之间服务异常断电或重启,会导致**版本号已变动,但审计表中无任何迹象与操作人**。审计日志必须在同一事务内完成提交。
### A8. 【资源泄漏】Session 清理机制单轨制
- **代码位置**:`internal/executor/session_manager.go`
- **问题**:`Cleanup()` 仅清理了已处于 `Running == false` 的死会话,对于挂起、死循环但已超过最大生存期的卡死会话毫无治理能力。必须落地 Spec 要求的「空闲超时 + 最大绝对生命期(Hard TTL)」双轨强制收割机制,并调用 `cmd.Wait()` 彻底回收僵尸进程。
---
## 四、值得肯定的实现亮点
1. **能力握手规范已落地**:`cluster.Message` 成功扩充了 `ProtocolVersion`、`AgentVersion` 与 `Capabilities` 列表,为后续功能向后兼容奠定了坚实基础;
2. **Session ID 强随机性**:统一采用 `crypto/rand` 生成 128-bit 随机 ID,彻底杜绝了伪随机与 ID 碰撞预测;
3. **文件写入原子性良好**:`edit_block` 与 `write_file` 均规范采用了临时文件写入、`Sync()` 刷盘及 `os.Rename` 替换机制。
---
## 五、专家 A 评审总结与准入判定
当前工作区代码虽然跑通了单元测试(`go test ./...` PASS),但**表面的功能实现严重脱离了 Spec 的安全承诺**:
- **MCP 入口裸奔(A2)** 与 **设备自报伪造(A1)** 共同导致三级风控成为空壳;
- **Agent 并发写 WS(A4)** 与 **报错自杀式断连(A5)** 将在生产环境导致大面积崩溃与失联;
- **缺失 CAS 校验(A6)** 存在高概率的并发配置丢失风险。
**准入结论**:**不予准入上线。必须依照上述清单完成 A1~A6 的靶向修复并通过覆盖性验收测试后,方可推进合并。**
+108
View File
@@ -0,0 +1,108 @@
# 审核专家 B:代码实现审计报告
> 文档属性:历史独立代码审计快照。不要将当时的 BLOCKER 列表直接视为当前未修复列表。
- **审核人**:审核专家 B(外部 Agent)
- **日期**:2026-10-02
- **对象**:`/root/.openclaw/workspace/vps-commander` 全量 Go 实现
- **对照文档**:《VPS-Commander 平滑升级改造与三级安全拦截实施方案》第 7 章
- **方法**:逐行审读安全、协议、执行器、API 四大核心包,非风格审查
- **结论**:**有条件不通过 —— 5 个阻断项未修复前不得进入 Phase 1**
---
## 一、阻断项(Blockers)
### B1. MCP 接口完全绕过三级安全门禁【严重】
- **位置**:`internal/api/mcp_adapter.go`、`internal/mcp/mcp.go`
- **事实**:两文件**零处**引用安全策略。`MCPBackend.ExecCommand/ReadFile/WriteFile/EditBlock/ListAgentMCP/CallAgentMCP`
直接执行,不调用 `requireSecurity`。
- **影响**:`/mcp/sse` 是 AI Agent 实际使用的主接口——安全模型只管住了 REST,
管 Agent 的通道完全敞开。审计过程中以普通 MCP 客户端身份调用 `exec_command` 未触发任何策略检查。
- **判定**:阻断。修复前不得向任何不可信调用方暴露 token。
### B2. 单一全局 token,可自行提权【严重】
- **位置**:`internal/api/api.go` → `UpdateSecuritySettingsJSON`(`/api/v1/security/settings/update`)
- **事实**:仅凭全局 API token 即可修改全局及任意设备的风险等级。实现中无 admin/user 角色区分,
Spec 7.2 假设的 "Admin Web" 不存在。
- **影响**:拿到 token 即拿到 admin,可把任意设备设为 High,三级门禁形同虚设。
- **判定**:阻断。策略变更必须独立鉴权(独立 admin 凭证或 mTLS 管理身份)。
### B3. 设备身份自报,per-device 策略不可执行【严重】
- **位置**:`internal/api/api.go:467`(`device := r.URL.Query().Get("device")`)、
`internal/cluster/manager.go:108`(`device_name` 取自 query)
- **事实**:设备名来自请求参数自报;Agent WS 仅以共享 cluster secret 认证,device_name 自报。
- **影响**:任意 token 持有者可冒充任意设备,挑选策略最松的设备执行。
- **判定**:阻断。需 per-device 凭证(mTLS 或 per-agent token)后 per-device 策略才有意义。
### B4. Session 所有权形同虚设【严重】
- **位置**:`internal/api/api.go:687` `sessionOwner(r)`
- **事实**:owner = 全局 token 的 SHA256。单 token 体系下所有调用者 owner 哈希相同,
`Session.Authorized()` 对任何已认证调用者恒为真。
- **影响**:Spec 7.5.2 的所有权模型空转,任意调用者可读写/注入/终止他人 Session。
- **判定**:阻断。与 B2 同源,需先解决调用者身份体系。
### B5. 未知设备 fail-open【严重】
- **位置**:`internal/security/policy.go` → `EffectiveRisk()`
- **事实**:设备不在策略表中 → 回退 `GlobalRisk`。若 GlobalRisk 为 High,拼错设备名反而获得最高权限。
- **违反**:Spec 7.2.3 明确要求 fail-closed(不得默认放行 High)。
- **判定**:阻断。未知设备应默认拒绝 Medium/High,或拒绝一切非常读操作。
---
## 二、高优先级(Phase 3 前修复)
### H1. Session 清理逻辑错误
- **位置**:`internal/executor/session_manager.go` → `Cleanup()`
- **事实**:以 `StartedAt` 计算所谓“空闲超时”(实为最大生命期);已过期但仍在运行的 session 永不清理(只删已结束的)→ 资源泄漏。
- **违反**:Spec 7.5.4 要求的空闲超时 + 最大生命期双轨制。
### H2. 无 agent 全局 Session 上限与进程创建速率限制
- **位置**:`internal/executor/session_manager.go`
- **事实**:`MaxSessionsPerManager = 16` 仅为单 manager 上限;`Start()` 存在 TOCTOU(解锁→启动进程→加锁复查),并发可短暂超限。
- **违反**:Spec 7.6。
### H3. 审计日志缺失关键字段
- **位置**:`internal/storage/storage.go:279` `Audit()`
- **事实**:无 `actor`、无 `policy_version`、无 `session_id`;命令明文入库,参数中的 secret 直接进 DB。
- **违反**:Spec 7.7。另需敏感参数脱敏。
### H4. Token 允许经 URL query 传递
- **位置**:`internal/auth/auth.go` → `Middleware.Handler`
- **事实**:接受 `?token=` / `?key=` / `?api_key=`。Token 将进入 access log、代理日志。
- **建议**:仅允许 Authorization header。
### H5. Policy version 无单调性校验
- **位置**:`internal/security/policy.go` → `Publish()`
- **事实**:接受任意版本(含回退)。
- **违反**:Spec 7.2.2。
---
## 三、值得肯定的实现
- **Capability 握手已实现**:`Message` 含 `ProtocolVersion`/`AgentVersion`/`Capabilities`,
`manager.go:333` 按能力门控——上一轮 spec 评审的阻断项在代码中已解决。
- **Session ID 使用 `crypto/rand`**(`api.go:698`),不可预测。
- **`edit_block` 使用临时文件 + 原子 rename**(`edit.go:41-62`),含目录 fsync。
- **REST 路径 `requireSecurity` 覆盖完整**:exec/read/write/mcp/edit_block 均接入。
---
## 四、总体评价
实现层面的信任模型实质是“持有 token 即上帝”:单 token 无角色分离(B2)、
设备身份自报(B3)、MCP 主通道零门禁(B1)、Session 所有权空转(B4)。
B1–B4 任一单独成立即足以让三级门禁失效,四者并存。
**在 B1(MCP 加门禁)、B2(策略变更独立鉴权)、B3(设备身份认证)修复并复审前,
不得向不可信调用方暴露 token,不得开放 `start_process` 等新能力给 Agent。**
---
*审核专家 B,2026-10-02*
+53
View File
@@ -0,0 +1,53 @@
# 审核专家 B 给 A 的意见同步(2026-10-02)
> 文档属性:历史审核交接快照。当前版本的后续任务以 VPS_COMMANDER_V2_1_SECURITY_HARDENING_SPEC.md 为准。
> 请 GPT(审核专家 A)阅读。本文是 B 对生产部署的独立审计结论,供 A 更新评审意见时参考。
---
## 1. 部署审计结论
生产 Hub(`/opt/vps-commander/vps-commander-hub`,13:24:11 重启)的 `vcs.revision=38382d2`,
HEAD(556870b)仅改文档,**二进制与送审代码一致**。6 节点 Agent 均已重启上线,全部 online。
**B 的最终判定:部署有效,上线成功。**
---
## 2. 关于 A 的三项阻断项的复核
| A 的阻断项 | B 的复核结论 |
|---|---|
| A1 设备名自报穿透 | **已修复**。`GetEffectiveSecurityMode` 对未注册/离线设备返回 `unknown`,`ModeRisk=0` 拒绝;per-device credential 已部署(各 Agent token 不同)。但注意:单 token 部署下自报问题依然存在,当前靠 per-device credential 解决 |
| A2 MCP 零门禁 | **已修复**。`mcp_adapter.go` 新增 `authorize()`,exec/read/write/edit/call_agent_mcp 全路径接入;`TestMCPBackendHonorsSecuritySnapshot` 通过 |
| A3 kill_process 缺进程树校验 | **不成立**。API 层只接受 SessionID(`api.go:824`),Agent 侧以 Session 内部持有的 `cmd.Process` 句柄执行 kill(`session.go:234`),从不接受客户端直传 PID。PID 重用攻击在此路径不可行。A 可能审计的是旧版本或误读了调用链 |
**建议 A 将结论从 BLOCKED 更新为 B(有条件通过)或 A(通过)。**
---
## 3. B 发现的残留项(A 可同步跟踪)
1. **`EffectiveRisk` 的 GlobalRisk 回退仍在**(`internal/security/policy.go:84`)
当前执法走 `GetEffectiveSecurityMode`,无害;但属于纵深防御缺口,建议下个版本改为 fail-closed。
2. **Agent token 暴露在进程命令行**
`ps` 可见 `-token <hex>`。均为自有 root 机器,风险可控;建议下次改走环境变量或配置文件。
3. **Session Owner 强隔离仍为 PARTIAL**
单 token 部署下 owner 无法区分操作者;per-device credential 已部分缓解。如需强隔离,需引入 operator/principal ID(送审文档第 11 节第 2 项)。
---
## 4. B 的上线前置条件落实情况
- [x] B1/B2/B5 代码层修复并经测试验证
- [x] sessionOwner 的 query 参数残留已清理
- [x] 设备 credential 逐节点迁移已部署
- [ ] EffectiveRisk 回退清理(下个版本)
- [ ] Session principal 强隔离决策(待定)
---
*审核专家 B,2026-10-02*
@@ -0,0 +1,169 @@
# VPS-Commander v2.1 安全纵深加固与身份隔离升级规范
> 版本:v2.1 Draft
> 日期:2026-10-02
> 来源:REVIEW_B_TO_A_HANDOFF_20261002.md
> 状态:下一版本升级输入,当前生产 v2.0 不因本规范降级或回滚
## 1. 升级定位
v2.0 已完成双通道架构、安全门禁、per-device credential、MCP 授权及生产上线。
v2.1 不重新设计已上线架构,而是针对生产审计发现的三个残留项做纵深加固:
1. EffectiveRisk 全部路径 fail-closed,彻底消除 GlobalRisk 回退放行可能。
2. Agent credential 脱离进程命令行,改用环境变量或受限配置文件。
3. 引入 operator/principal 身份,使 Session Owner 从 PARTIAL 升级为强隔离。
## 2. 非目标
- 不改变现有 Low / Medium / High 风险分级语义。
- 不取消现有 per-device credential。
- 不把 v2.0 的已通过安全门禁重新实现一遍。
- 不要求一次性引入 mTLS;mTLS 可作为后续增强方案。
- 不允许为了升级方便而重新启用全局 Shared Secret。
## 3. P0:EffectiveRisk Fail-Closed
### 3.1 现状
`internal/security/policy.go` 的 `EffectiveRisk` 仍存在 GlobalRisk fallback。
当前实际执法主要通过 `GetEffectiveSecurityMode`,因此生产风险已被控制,但该 fallback 属于纵深防御缺口。
### 3.2 目标行为
策略计算必须以经过认证的 Canonical Device ID 为唯一设备身份来源。
以下任何情况均不得回退 GlobalRisk 放行:
- Device ID 未注册;
- Device ID 已注册但当前不可用;
- credential 不匹配;
- policy snapshot 中不存在该设备;
- snapshot/version 无法验证;
- device identity 与请求声明不一致。
上述情况统一返回 `unknown` / deny,风险值为 0 或显式拒绝状态。
### 3.3 实现要求
- `EffectiveRisk` 默认 fail-closed。
- `GlobalRisk` 只能作为已认证设备不存在专属覆盖时的业务默认值;不得用于未知设备。
- 将“身份解析”和“策略计算”分成两个明确阶段。
- 策略函数不得直接信任 HTTP/MCP 请求体中的 `device` 字段。
- 增加单元测试覆盖未知设备、离线设备、错误 credential、空 snapshot、version regression。
## 4. P0:Agent Token 脱离命令行
### 4.1 现状
当前 Agent 使用 `-token <hex>` 启动参数。虽然生产机器均为自有 root 主机且风险可控,但 token 会出现在 `ps` 等进程信息中。
### 4.2 目标
生产 Agent 默认从受保护环境或配置文件读取 credential,命令行不再出现明文 token。
推荐优先级:systemd `EnvironmentFile` / `LoadCredential` > root-only 配置文件 > 其他安全存储。
### 4.3 实现要求
- 支持 `VPS_COMMANDER_AGENT_TOKEN` 环境变量。
- systemd ExecStart 不得包含 `-token <secret>`。
- 若保留 `-token` 兼容参数,仅允许开发/迁移场景,不作为生产推荐路径。
- `/etc/vps-commander/agent.env` 权限保持 root-only,并验证权限。
- 日志、诊断、panic、审计输出不得打印 token。
- 增加进程列表检查,确保生产启动后 `ps` 不出现 token 明文。
- 轮换 token 时支持无感迁移或可回滚切换。
## 5. P1:Session Principal 强隔离
### 5.1 现状
当前 Session Owner 基于认证上下文指纹,并支持 `X-Operator-ID`;但单 API token 部署下多个操作者仍可能共享同一 owner 身份。
因此现状态为 PARTIAL,而不是完整 operator/principal isolation。
### 5.2 目标身份模型
建立明确的 Principal:
- `principal_id`:稳定、不可由请求目标设备伪造的操作者身份。
- `principal_type`:至少区分 admin / operator / service。
- `credential_id`:用于追踪实际认证凭据。
- `device_id`:目标设备身份,不能替代 principal。
Session ownership 必须绑定 Principal,而不是只绑定全局 token。
### 5.3 授权规则
- 创建 Session 时记录 principal_id。
- 读取、输入、关闭、kill 等 Session 操作必须校验 owner principal。
- admin 是否可以接管其他 principal 的 Session 必须成为显式策略,而非隐式绕过。
- 一个 principal 不得通过修改请求中的 device/name/operator 字段伪造另一 principal。
- 审计日志记录 principal_id、credential_id、session_id、device_id、risk level。
- 敏感身份字段继续执行现有脱敏规则。
## 6. Principal 认证方案
v2.1 第一阶段建议保持现有 API Key 兼容,同时增加独立 Principal credential 层。
API authentication 与 authorization 必须继续分离:认证证明“是谁”,授权决定“能做什么”。
推荐数据模型:
- `principals(id, type, name, status, created_at, updated_at)`
- `principal_credentials(id, principal_id, credential_hash, status, created_at, updated_at)`
- Session 保存 `principal_id` 与创建时 credential_id。
不在数据库保存明文 credential。
## 7. 向后兼容与迁移
- v2.0 Agent 必须可在迁移窗口内继续连接,但新部署不得重新引入 Shared Secret。
- 现有 per-device credential 保持有效。
- 现有 Session 在升级过程中不得被无条件清空;升级后旧 Session 应进入兼容/只读或明确失效状态。
- Principal migration 可先将现有 API key 映射为一个系统 service principal,再逐步增加 operator principal。
- 每一步均提供回滚点,不允许因身份系统异常导致全部 Agent 失联。
## 8. 验收标准
### P0-1 EffectiveRisk
- 未知 device 永远 deny。
- 错误 credential 永远 deny。
- GlobalRisk=High 时,未知 device 仍不得获得 High。
- policy version 回退不得被接受。
- MCP、HTTP API、direct call_agent_mcp 三条路径结果一致。
### P0-2 Credential
- `ps` / `/proc/<pid>/cmdline` 不包含 Agent token。
- systemd 配置中不出现明文 token 参数。
- root-only credential 文件权限正确。
- token 轮换后旧 token 按策略失效,新 token 可连接。
### P1 Principal
- Principal A 创建的 Session,Principal B 默认无法读/写/kill。
- 修改 device、operator、session 参数不能越权。
- admin 接管能力若启用,必须有明确授权检查与审计记录。
- 审计可追溯 principal → session → device → operation。
## 9. 测试矩阵
必须同时通过:
- `go test ./...`
- `go test -race ./...`
- `git diff --check`
- EffectiveRisk fail-closed 单元测试。
- MCP 多路径授权一致性测试。
- token 不出现在 argv 的集成测试。
- Principal A/B Session 隔离集成测试。
- Hub 重启后 Agent 自动恢复测试。
- credential 轮换及回滚测试。
## 10. 发布门禁
v2.1 只有在 P0-1 与 P0-2 全部通过后才允许进入生产灰度。
P1 Principal 强隔离必须在正式发布前完成设计评审;若实现延期,不得伪称为完整强隔离。
生产发布必须遵循:备份 → 新版本旁路构建 → 单节点灰度 → Hub 重启恢复验证 → 全节点滚动 → 审计复核 → 正式验收。
任何一步发现 Agent 失联、权限越界或 credential 泄露迹象,立即停止扩散并回滚。
## 11. 与 v2.0 审计结论的关系
本规范来源于 2026-10-02 B→A 独立生产审计交接。
v2.0 的上线判定不因这些残留项改变;它们属于已识别、风险可控、下一版本必须处理的纵深安全事项。
原始依据:`docs/REVIEW_B_TO_A_HANDOFF_20261002.md`
+478 -24
View File
@@ -1,9 +1,12 @@
package api
import (
"sort"
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"io"
@@ -11,6 +14,7 @@ import (
"net/http"
"os"
"runtime"
"sort"
"strconv"
"strings"
"time"
@@ -20,6 +24,7 @@ import (
"github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/model"
"github.com/wjyhk/vps-commander/internal/notify"
"github.com/wjyhk/vps-commander/internal/security"
"github.com/wjyhk/vps-commander/internal/storage"
"github.com/wjyhk/vps-commander/internal/sysinfo"
panelweb "github.com/wjyhk/vps-commander/internal/web"
@@ -34,12 +39,17 @@ const (
)
type Server struct {
Auth *auth.Manager
Exec executor.Local
Cluster *cluster.Manager
Store *storage.Store
LocalName string
Notify *notify.Manager
Auth *auth.Manager
Exec executor.Local
Cluster *cluster.Manager
Store *storage.Store
LocalName string
Notify *notify.Manager
Policy *security.Snapshot
AdminToken string
ExecLimiter chan struct{}
SearchLimiter chan struct{}
LocalSessions *executor.SessionManager
}
const (
@@ -49,27 +59,71 @@ const (
SecurityInherit = "inherit"
)
func (s *Server) GetEffectiveSecurityMode(node string) string {
func (s *Server) LoadSecurityPolicySnapshot() error {
if s.Store == nil {
return SecurityMedium
return fmt.Errorf("security store unavailable")
}
if mode, ok := s.Store.GetNodeSecurityMode(node); ok && mode != "" && mode != SecurityInherit {
return mode
state, err := s.Store.LoadSecurityPolicy()
if err != nil {
return err
}
return s.Store.GetGlobalSecurityMode()
devices := make(map[string]security.DevicePolicy, len(state.Nodes))
for node, mode := range state.Nodes {
devices[node] = security.DevicePolicy{Mode: mode}
}
global := security.ModeRisk(state.GlobalMode)
if global == 0 {
global = security.RiskMedium
}
if s.Policy == nil {
s.Policy = security.New(global, devices, state.Version)
return nil
}
return s.Policy.Publish(global, devices, state.Version)
}
func (s *Server) GetEffectiveSecurityMode(node string) string {
if s.Policy == nil && s.Store != nil {
if mode, ok := s.Store.GetNodeSecurityMode(node); ok {
if mode != SecurityInherit {
return mode
}
return s.Store.GetGlobalSecurityMode()
}
if node == s.LocalName {
return s.Store.GetGlobalSecurityMode()
}
return "unknown"
}
if s.Policy != nil {
snap := s.Policy.Current()
risk := s.Policy.EffectiveRisk(node)
if p, ok := snap.Devices[node]; ok && security.ModeRisk(p.Mode) != 0 {
return p.Mode
}
if node != s.LocalName && (s.Cluster == nil || !s.Cluster.Online(node)) {
return "unknown"
}
for mode, v := range map[string]int{"low": security.RiskLow, "medium": security.RiskMedium, "high": security.RiskHigh} {
if v == risk {
return mode
}
}
}
if node == s.LocalName && s.Store != nil {
return s.Store.GetGlobalSecurityMode()
}
if s.Cluster != nil && s.Cluster.Online(node) && s.Store != nil {
return s.Store.GetGlobalSecurityMode()
}
return "unknown"
}
func securityAllows(mode, action string) bool {
switch action {
case "read", "probe":
return true
case "write", "mcp":
return mode == SecurityMedium || mode == SecurityHigh
case "exec":
return mode == SecurityHigh
default:
required, ok := security.RequiredRiskForAction(action)
if !ok {
return false
}
return security.ModeRisk(mode) >= required
}
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device, action, detail string) bool {
@@ -180,11 +234,53 @@ func (s *Server) SecuritySettingsJSON(w http.ResponseWriter, r *http.Request) {
}()})
}
func (s *Server) ProvisionDeviceCredentialJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
if s.AdminToken == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Admin-Token")), []byte(s.AdminToken)) != 1 {
http.Error(w, "admin authorization required", 403)
return
}
var q struct {
Device string `json:"device"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&q); err != nil || strings.TrimSpace(q.Device) == "" {
http.Error(w, "device required", 400)
return
}
if q.Device == s.LocalName || q.Device == "local" {
http.Error(w, "local control node does not use agent credential", 400)
return
}
if s.Cluster == nil || !s.Cluster.Online(q.Device) {
http.Error(w, "device offline", 409)
return
}
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
http.Error(w, "credential generation failed", 500)
return
}
token := hex.EncodeToString(b)
if err := s.Store.SetDeviceCredential(q.Device, token); err != nil {
http.Error(w, "credential save failed", 500)
return
}
_ = s.Store.Audit(clientIP(r), q.Device, "device_credential_provision", "device="+q.Device, 0, 0, "credential provisioned")
jsonOut(w, map[string]any{"ok": true, "device": q.Device, "token": token})
}
func (s *Server) UpdateSecuritySettingsJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
if s.AdminToken == "" || r.Header.Get("X-Admin-Token") != s.AdminToken {
http.Error(w, "admin authorization required", http.StatusForbidden)
return
}
var q struct {
Global string `json:"global"`
Node string `json:"node"`
@@ -194,21 +290,35 @@ func (s *Server) UpdateSecuritySettingsJSON(w http.ResponseWriter, r *http.Reque
http.Error(w, "bad json", 400)
return
}
oldGlobal := s.GetEffectiveSecurityMode(s.LocalName)
oldNode := ""
if q.Node != "" {
oldNode = s.GetEffectiveSecurityMode(q.Node)
}
if q.Global != "" {
if err := s.Store.SetGlobalSecurityMode(q.Global); err != nil {
http.Error(w, err.Error(), 400)
return
}
_ = s.Store.Audit(clientIP(r), "", "security_setting", "global="+q.Global, 0, 0, "")
}
if q.Node != "" {
if err := s.Store.SetNodeSecurityMode(q.Node, q.Mode); err != nil {
http.Error(w, err.Error(), 400)
return
}
_ = s.Store.Audit(clientIP(r), q.Node, "security_setting", "mode="+q.Mode, 0, 0, "")
}
jsonOut(w, map[string]any{"ok": true, "global": s.Store.GetGlobalSecurityMode(), "node": q.Node, "mode": q.Mode})
if err := s.LoadSecurityPolicySnapshot(); err != nil {
http.Error(w, "security snapshot publish failed", 500)
return
}
newGlobal := s.GetEffectiveSecurityMode(s.LocalName)
if q.Global != "" {
_ = s.Store.Audit(clientIP(r), "", "security_setting", "global="+q.Global, 0, 0, fmt.Sprintf("old=%s new=%s version=%d", oldGlobal, newGlobal, s.Policy.Current().Version))
}
if q.Node != "" {
_ = s.Store.Audit(clientIP(r), q.Node, "security_setting", "mode="+q.Mode, 0, 0, fmt.Sprintf("old=%s new=%s version=%d", oldNode, s.GetEffectiveSecurityMode(q.Node), s.Policy.Current().Version))
}
jsonOut(w, map[string]any{"ok": true, "global": s.Store.GetGlobalSecurityMode(), "node": q.Node, "mode": q.Mode, "version": s.Policy.Current().Version})
}
func (s *Server) clusterDeviceNames() []string {
@@ -223,7 +333,7 @@ func (s *Server) clusterDeviceNames() []string {
}
func (s *Server) Panel(password string) http.Handler {
p := panelweb.New(password, s)
p := panelweb.New(password, s.AdminToken, s)
go p.Cleanup()
return p.Handler()
}
@@ -482,7 +592,12 @@ func (s *Server) Routes() http.Handler {
mux.HandleFunc("/api/v1/devices", s.devices)
mux.HandleFunc("/api/v1/exec", s.exec)
mux.HandleFunc("/api/v1/file/read", s.fileRead)
mux.HandleFunc("/api/v1/file/list", s.listDirectory)
mux.HandleFunc("/api/v1/file/info", s.fileInfo)
mux.HandleFunc("/api/v1/file/search", s.searchFiles)
mux.HandleFunc("/api/v1/process/session", s.processSession)
mux.HandleFunc("/api/v1/file/write", s.fileWrite)
mux.HandleFunc("/api/v1/devices/file/edit_block", s.editBlock)
mux.HandleFunc("/api/v1/mcp/services", s.MCPServicesJSON)
mux.HandleFunc("/api/v1/mcp/service", s.DeleteMCPService)
mux.HandleFunc("/api/v1/mcp/list", s.ListAgentMCPJSON)
@@ -490,6 +605,7 @@ func (s *Server) Routes() http.Handler {
mux.HandleFunc("/api/v1/mcp/test", s.TestMCPJSON)
mux.HandleFunc("/api/v1/security/settings", s.SecuritySettingsJSON)
mux.HandleFunc("/api/v1/security/settings/update", s.UpdateSecuritySettingsJSON)
mux.HandleFunc("/api/v1/security/device-credentials/provision", s.ProvisionDeviceCredentialJSON)
mux.HandleFunc("/api/v1/notifications/webhooks", s.WebhookTargetsJSON)
mux.HandleFunc("/api/v1/notifications/webhook/update", s.UpdateWebhookTargetJSON)
mux.HandleFunc("/api/v1/notifications/webhook/delete", s.DeleteWebhookTargetJSON)
@@ -582,6 +698,21 @@ func (s *Server) agentWS(w http.ResponseWriter, r *http.Request) {
func (s *Server) isRemote(device string) bool {
return device != "" && device != "local" && device != s.LocalName
}
func (s *Server) acquireExec() func() {
if s.ExecLimiter == nil {
return func() {}
}
s.ExecLimiter <- struct{}{}
return func() { <-s.ExecLimiter }
}
func (s *Server) acquireSearch() func() {
if s.SearchLimiter == nil {
return func() {}
}
s.SearchLimiter <- struct{}{}
return func() { <-s.SearchLimiter }
}
func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
@@ -602,6 +733,8 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
if !s.requireSecurity(w, r, req.Device, "exec", req.Command) {
return
}
releaseExec := s.acquireExec()
defer releaseExec()
if req.Timeout <= 0 {
req.Timeout = 30
}
@@ -631,6 +764,269 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
}
jsonOut(w, model.ExecResponse{Device: req.Device, ExitCode: res.ExitCode, Stdout: res.Stdout, Stderr: res.Stderr, DurationMS: res.DurationMS})
}
func sessionOwner(r *http.Request) string {
v := r.Header.Get("Authorization") + "|" + r.Header.Get("X-Operator-ID") + "|" + clientIP(r)
h := sha256.Sum256([]byte(v))
return hex.EncodeToString(h[:])
}
func newSessionID() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func (s *Server) processSession(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var req struct {
Device string `json:"device"`
SessionID string `json:"session_id"`
Command string `json:"command"`
Workdir string `json:"workdir"`
Data string `json:"data"`
Force bool `json:"force"`
RingCapacity int `json:"ring_capacity"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&req); err != nil {
http.Error(w, "bad json", 400)
return
}
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "exec", req.SessionID) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
action := r.URL.Query().Get("action")
owner := sessionOwner(r)
var result any
var err error
if s.isRemote(req.Device) {
if s.Cluster == nil || !s.Cluster.Online(req.Device) {
http.Error(w, "device offline", 409)
return
}
switch action {
case "start":
if req.SessionID == "" {
req.SessionID, err = newSessionID()
if err != nil {
http.Error(w, "session id generation failed", 500)
return
}
}
result, err = s.Cluster.StartProcess(ctx, req.Device, cluster.StartProcessPayload{Command: req.Command, Workdir: req.Workdir, SessionID: req.SessionID, Owner: owner, RingCapacity: req.RingCapacity})
case "read":
result, err = s.Cluster.ReadProcessOutput(ctx, req.Device, req.SessionID, owner)
case "input":
err = s.Cluster.InteractProcess(ctx, req.Device, req.SessionID, req.Data, owner)
result = map[string]any{"ok": true}
case "stop":
err = s.Cluster.ForceTerminate(ctx, req.Device, req.SessionID, owner)
result = map[string]any{"ok": true}
case "list":
result, err = s.Cluster.ListSessions(ctx, req.Device)
default:
http.Error(w, "unknown action", 400)
return
}
} else {
if s.LocalSessions == nil {
http.Error(w, "local session manager unavailable", 503)
return
}
switch action {
case "start":
if req.SessionID == "" {
req.SessionID, err = newSessionID()
if err != nil {
http.Error(w, "session id generation failed", 500)
return
}
}
var sess *executor.Session
sess, err = s.LocalSessions.Start(context.Background(), req.SessionID, req.Command, req.Workdir, owner, req.RingCapacity)
if err == nil {
result = map[string]any{"session_id": sess.ID, "started_at": sess.StartedAt.Unix()}
}
case "read":
var sess *executor.Session
sess, ok := s.LocalSessions.Get(req.SessionID)
if !ok {
err = fmt.Errorf("session not found")
break
}
if !sess.Authorized(owner) {
err = fmt.Errorf("session ownership denied")
break
}
code, done, _ := sess.Status()
stdout, stderr := sess.Output()
result = cluster.ProcessOutputPayload{SessionID: req.SessionID, Stdout: stdout, Stderr: stderr, ExitCode: code, Running: !done}
case "input":
var sess *executor.Session
sess, ok := s.LocalSessions.Get(req.SessionID)
if !ok {
err = fmt.Errorf("session not found")
break
}
if !sess.Authorized(owner) {
err = fmt.Errorf("session ownership denied")
break
}
err = sess.Stdin([]byte(req.Data))
result = map[string]any{"ok": true}
case "stop":
var sess *executor.Session
sess, ok := s.LocalSessions.Get(req.SessionID)
if !ok {
err = fmt.Errorf("session not found")
break
}
if !sess.Authorized(owner) {
err = fmt.Errorf("session ownership denied")
break
}
err = s.LocalSessions.Stop(req.SessionID, true)
result = map[string]any{"ok": true}
case "list":
result = s.LocalSessions.List()
default:
http.Error(w, "unknown action", 400)
return
}
}
if err != nil {
http.Error(w, err.Error(), 409)
return
}
jsonOut(w, result)
}
func (s *Server) listDirectory(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var req struct {
Device, Path string
Recursive bool `json:"recursive"`
MaxEntries int `json:"max_entries"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&req); err != nil {
http.Error(w, "bad json", 400)
return
}
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "read", req.Path) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
var v []cluster.Entry
var err error
if s.isRemote(req.Device) {
v, err = s.Cluster.ListDirectory(ctx, req.Device, cluster.ListDirectoryPayload{Path: req.Path, Recursive: req.Recursive, MaxEntries: req.MaxEntries})
} else {
var ev []executor.Entry
ev, err = executor.ListDirectory(req.Path, req.Recursive, req.MaxEntries)
if err == nil {
b, _ := json.Marshal(ev)
err = json.Unmarshal(b, &v)
}
}
if err != nil {
http.Error(w, err.Error(), 409)
return
}
jsonOut(w, v)
}
func (s *Server) fileInfo(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var req struct{ Device, Path string }
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&req); err != nil {
http.Error(w, "bad json", 400)
return
}
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "read", req.Path) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
var v cluster.FileInfo
var err error
if s.isRemote(req.Device) {
v, err = s.Cluster.GetFileInfo(ctx, req.Device, cluster.FileInfoPayload{Path: req.Path})
} else {
var ev executor.FileInfo
ev, err = executor.GetFileInfo(req.Path)
if err == nil {
b, _ := json.Marshal(ev)
err = json.Unmarshal(b, &v)
}
}
if err != nil {
http.Error(w, err.Error(), 404)
return
}
jsonOut(w, v)
}
func (s *Server) searchFiles(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var req struct {
Device, Root, Query string
MaxResults int `json:"max_results"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&req); err != nil {
http.Error(w, "bad json", 400)
return
}
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "read", req.Root) {
return
}
releaseSearch := s.acquireSearch()
defer releaseSearch()
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
var v []cluster.SearchResult
var err error
if s.isRemote(req.Device) {
v, err = s.Cluster.Search(ctx, req.Device, cluster.SearchPayload{Root: req.Root, Query: req.Query, MaxResults: req.MaxResults})
} else {
var ev []executor.SearchResult
ev, err = executor.Search(ctx, req.Root, req.Query, req.MaxResults)
if err == nil {
b, _ := json.Marshal(ev)
err = json.Unmarshal(b, &v)
}
}
if err != nil {
http.Error(w, err.Error(), 409)
return
}
jsonOut(w, v)
}
func (s *Server) fileRead(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
@@ -706,6 +1102,64 @@ func (s *Server) fileRead(w http.ResponseWriter, r *http.Request) {
}
jsonOut(w, model.FileReadResponse{Device: req.Device, Path: req.Path, Offset: req.Offset, Content: content, Bytes: n, TotalSize: totalSize, HasMore: hasMore, EOF: eof})
}
func (s *Server) editBlock(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var req struct {
Device string `json:"device,omitempty"`
Path string `json:"path"`
OldText string `json:"old_text"`
NewText string `json:"new_text"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxFileLimit+64*1024)).Decode(&req); err != nil {
http.Error(w, "bad json or content too large", 400)
return
}
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "write", req.Path) {
return
}
if req.Path == "" || !validPath(req.Path) || req.OldText == "" {
http.Error(w, "path and old_text required", 400)
return
}
if len(req.OldText) > int(maxFileLimit) || len(req.NewText) > int(maxFileLimit) {
http.Error(w, "edit block too large", 413)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
var result executor.EditBlockResult
if s.isRemote(req.Device) {
if s.Cluster == nil || !s.Cluster.Online(req.Device) {
http.Error(w, "device offline", 409)
return
}
rr, err := s.Cluster.EditBlock(ctx, req.Device, cluster.EditBlockPayload{Path: req.Path, OldText: req.OldText, NewText: req.NewText})
if err != nil {
http.Error(w, err.Error(), 409)
return
}
result.BytesWritten = rr.BytesWritten
} else {
var err error
result, err = executor.EditBlock(req.Path, req.OldText, req.NewText)
if err != nil {
http.Error(w, err.Error(), 409)
return
}
}
if err := s.Store.Audit(clientIP(r), req.Device, "edit_block", req.Path, 0, 0, fmt.Sprintf("bytes_written=%d", result.BytesWritten)); err != nil {
http.Error(w, "audit write failed", 500)
return
}
jsonOut(w, map[string]any{"device": req.Device, "path": req.Path, "bytes_written": result.BytesWritten})
}
func (s *Server) fileWrite(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
+81 -2
View File
@@ -1,11 +1,15 @@
package api
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/storage"
@@ -59,8 +63,8 @@ func TestSecurityEffectiveModeAndExecGate(t *testing.T) {
}
defer store.DB.Close()
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local"}
if got := s.GetEffectiveSecurityMode("node-a"); got != "medium" {
t.Fatalf("default mode=%s", got)
if got := s.GetEffectiveSecurityMode("node-a"); got != "unknown" {
t.Fatalf("unknown mode=%s", got)
}
if err := store.SetNodeSecurityMode("node-a", "high"); err != nil {
t.Fatal(err)
@@ -88,3 +92,78 @@ func TestSecurityEffectiveModeAndExecGate(t *testing.T) {
t.Fatalf("missing denial audit: %+v", logs)
}
}
func TestProcessSessionLocalSnakeCaseAndLifecycle(t *testing.T) {
dir := t.TempDir()
store, err := storage.Open(filepath.Join(dir, "db.sqlite"))
if err != nil {
t.Fatal(err)
}
defer store.DB.Close()
if err := store.SetGlobalSecurityMode("high"); err != nil {
t.Fatal(err)
}
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local", LocalSessions: executor.NewSessionManager(0)}
if err := s.LoadSecurityPolicySnapshot(); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/v1/process/session?action=start", strings.NewReader(`{"device":"local","session_id":"session-test-001","command":"sleep 0.2; printf local-ok"}`))
w := httptest.NewRecorder()
s.processSession(w, req)
if w.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", w.Code, w.Body.String())
}
time.Sleep(400 * time.Millisecond)
req = httptest.NewRequest(http.MethodPost, "/api/v1/process/session?action=read", strings.NewReader(`{"device":"local","session_id":"session-test-001"}`))
w = httptest.NewRecorder()
s.processSession(w, req)
if w.Code != http.StatusOK {
t.Fatalf("read status=%d body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "local-ok") {
t.Fatalf("missing session output: %s", w.Body.String())
}
}
func TestEditBlockSecurityAndReplacement(t *testing.T) {
dir := t.TempDir()
store, err := storage.Open(filepath.Join(dir, "db.sqlite"))
if err != nil {
t.Fatal(err)
}
defer store.DB.Close()
if err := store.SetGlobalSecurityMode("medium"); err != nil {
t.Fatal(err)
}
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local"}
if err := s.LoadSecurityPolicySnapshot(); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, "config.txt")
if err := os.WriteFile(path, []byte("alpha\nTARGET\nomega\n"), 0644); err != nil {
t.Fatal(err)
}
r := httptest.NewRequest(http.MethodPost, "/api/v1/devices/file/edit_block", strings.NewReader(fmt.Sprintf(`{"path":%q,"old_text":"TARGET","new_text":"CHANGED"}`, path)))
w := httptest.NewRecorder()
s.editBlock(w, r)
if w.Code != 200 {
t.Fatalf("edit status=%d body=%s", w.Code, w.Body.String())
}
b, _ := os.ReadFile(path)
if string(b) != "alpha\nCHANGED\nomega\n" {
t.Fatalf("unexpected content: %q", b)
}
if err := store.SetGlobalSecurityMode("low"); err != nil {
t.Fatal(err)
}
if err := s.LoadSecurityPolicySnapshot(); err != nil {
t.Fatal(err)
}
r = httptest.NewRequest(http.MethodPost, "/api/v1/devices/file/edit_block", strings.NewReader(fmt.Sprintf(`{"path":%q,"old_text":"CHANGED","new_text":"NO"}`, path)))
w = httptest.NewRecorder()
s.editBlock(w, r)
if w.Code != 403 {
t.Fatalf("low mode status=%d body=%s", w.Code, w.Body.String())
}
}
+163
View File
@@ -24,6 +24,20 @@ func (s *Server) NewMCPBackend() *MCPBackend {
return &MCPBackend{server: s}
}
func (b *MCPBackend) authorize(device, action, clientIP string) error {
if device == "" {
device = b.server.LocalName
}
mode := b.server.GetEffectiveSecurityMode(device)
if !securityAllows(mode, action) {
if b.server.Store != nil {
_ = b.server.Store.Audit(clientIP, device, "security_denied", action, 403, 0, "MCP security gate")
}
return fmt.Errorf("security mode %s denies %s", mode, action)
}
return nil
}
func (b *MCPBackend) ListDevices(ctx context.Context) (any, error) {
out := []model.Device{{Name: b.server.LocalName, Status: "online", Local: true, Arch: runtime.GOARCH, OS: runtime.GOOS}}
if b.server.Cluster != nil {
@@ -44,6 +58,9 @@ func (b *MCPBackend) ExecCommand(ctx context.Context, clientIP, device, command,
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "exec", clientIP); err != nil {
return nil, err
}
if timeout <= 0 {
timeout = 30
}
@@ -81,10 +98,40 @@ func (b *MCPBackend) ExecCommand(ctx context.Context, clientIP, device, command,
}, nil
}
func (b *MCPBackend) DiagnosticCommand(ctx context.Context, clientIP, device string, req executor.DiagnosticRequest) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "diagnostic", clientIP); err != nil {
return nil, err
}
if req.Action == "" {
return nil, errors.New("diagnostic action required")
}
if b.server.isRemote(device) {
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
return nil, fmt.Errorf("device %s is offline", device)
}
res, err := b.server.Cluster.Diagnostic(ctx, device, req)
if err != nil {
return nil, err
}
return res, nil
}
res, err := executor.Diagnostic(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
func (b *MCPBackend) ReadFile(ctx context.Context, clientIP, device, path string, offset, limit int64) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "read", clientIP); err != nil {
return nil, err
}
if path == "" || !validPath(path) || offset < 0 {
return nil, errors.New("invalid path or offset")
}
@@ -150,10 +197,45 @@ func (b *MCPBackend) ReadFile(ctx context.Context, clientIP, device, path string
}, nil
}
func (b *MCPBackend) EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "write", clientIP); err != nil {
return nil, err
}
if path == "" || !validPath(path) || oldText == "" {
return nil, errors.New("path and old_text required")
}
if len(oldText) > int(maxFileLimit) || len(newText) > int(maxFileLimit) {
return nil, errors.New("edit block too large")
}
if b.server.isRemote(device) {
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
return nil, fmt.Errorf("device %s is offline", device)
}
res, err := b.server.Cluster.EditBlock(ctx, device, cluster.EditBlockPayload{Path: path, OldText: oldText, NewText: newText})
if err != nil {
return nil, err
}
_ = b.server.Store.Audit(clientIP, device, "edit_block", path, 0, 0, fmt.Sprintf("bytes_written=%d", res.BytesWritten))
return map[string]any{"device": device, "path": path, "bytes_written": res.BytesWritten}, nil
}
res, err := executor.EditBlock(path, oldText, newText)
if err != nil {
return nil, err
}
_ = b.server.Store.Audit(clientIP, device, "edit_block", path, 0, 0, fmt.Sprintf("bytes_written=%d", res.BytesWritten))
return map[string]any{"device": device, "path": path, "bytes_written": res.BytesWritten}, nil
}
func (b *MCPBackend) WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "write", clientIP); err != nil {
return nil, err
}
if path == "" || !validPath(path) {
return nil, errors.New("path required")
}
@@ -223,3 +305,84 @@ func (b *MCPBackend) CallAgentMCP(ctx context.Context, clientIP, device, server,
}
return v, err
}
// AuthorizeMCP exposes the same Hub-side gate to the MCP transport layer.
func (b *MCPBackend) AuthorizeMCP(device, action, clientIP string) error {
return b.authorize(device, action, clientIP)
}
func (b *MCPBackend) ReadMultipleFiles(ctx context.Context, clientIP, device string, paths []string, limit int64) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "read", clientIP); err != nil {
return nil, err
}
if len(paths) > 32 {
return nil, errors.New("too many paths")
}
if b.server.isRemote(device) {
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
return nil, fmt.Errorf("device %s is offline", device)
}
return b.server.Cluster.ReadMultipleFiles(ctx, device, cluster.ReadMultipleFilesPayload{Paths: paths, Limit: limit})
}
return executor.ReadMultipleFiles(paths, limit), nil
}
func (b *MCPBackend) CreateDirectory(ctx context.Context, clientIP, device, path string) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "write", clientIP); err != nil {
return nil, err
}
if b.server.isRemote(device) {
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
return nil, fmt.Errorf("device %s is offline", device)
}
if err := b.server.Cluster.CreateDirectory(ctx, device, cluster.CreateDirectoryPayload{Path: path}); err != nil {
return nil, err
}
} else {
if err := executor.CreateDirectory(path); err != nil {
return nil, err
}
}
return map[string]any{"device": device, "path": path, "ok": true}, nil
}
func (b *MCPBackend) MoveFile(ctx context.Context, clientIP, device, source, destination string) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "write", clientIP); err != nil {
return nil, err
}
if b.server.isRemote(device) {
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
return nil, fmt.Errorf("device %s is offline", device)
}
if err := b.server.Cluster.MoveFile(ctx, device, cluster.MoveFilePayload{Source: source, Destination: destination}); err != nil {
return nil, err
}
} else {
if err := executor.MoveFile(source, destination); err != nil {
return nil, err
}
}
return map[string]any{"device": device, "source": source, "destination": destination, "ok": true}, nil
}
func (b *MCPBackend) ListProcesses(ctx context.Context, clientIP, device string) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "read", clientIP); err != nil {
return nil, err
}
if b.server.isRemote(device) {
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
return nil, fmt.Errorf("device %s is offline", device)
}
return b.server.Cluster.ListProcesses(ctx, device)
}
return executor.ListProcesses()
}
+54
View File
@@ -0,0 +1,54 @@
package api
import (
"context"
"path/filepath"
"testing"
"github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/storage"
)
func TestMCPBackendHonorsSecuritySnapshot(t *testing.T) {
store, err := storage.Open(filepath.Join(t.TempDir(), "commander.db"))
if err != nil {
t.Fatal(err)
}
defer store.DB.Close()
if err := store.SetGlobalSecurityMode("low"); err != nil {
t.Fatal(err)
}
s := &Server{Store: store, LocalName: "local", Exec: executor.Local{MaxOutput: 1024 * 1024}}
if err := s.LoadSecurityPolicySnapshot(); err != nil {
t.Fatal(err)
}
b := s.NewMCPBackend()
if _, err := b.ExecCommand(context.Background(), "test", "local", "true", "", 5); err == nil {
t.Fatal("MCP exec must be denied in low mode")
}
if _, err := b.ReadFile(context.Background(), "test", "local", "/etc/hosts", 0, 128); err != nil {
t.Fatalf("MCP read should remain available in low mode: %v", err)
}
}
func TestUnknownDeviceFailsClosed(t *testing.T) {
store, err := storage.Open(filepath.Join(t.TempDir(), "commander.db"))
if err != nil {
t.Fatal(err)
}
defer store.DB.Close()
if err := store.SetGlobalSecurityMode("high"); err != nil {
t.Fatal(err)
}
s := &Server{Store: store, LocalName: "local", Exec: executor.Local{MaxOutput: 1024 * 1024}}
if err := s.LoadSecurityPolicySnapshot(); err != nil {
t.Fatal(err)
}
if got := s.GetEffectiveSecurityMode("not-registered"); got != "unknown" {
t.Fatalf("unknown device mode=%q", got)
}
b := s.NewMCPBackend()
if _, err := b.ExecCommand(context.Background(), "test", "not-registered", "true", "", 5); err == nil {
t.Fatal("unknown device must not inherit high risk")
}
}
+130
View File
@@ -616,6 +616,136 @@
}
}
}
},
"/api/v1/devices/file/edit_block": {
"post": {
"summary": "Atomically replace a unique text block on a device",
"security": [
{
"bearerAuth": []
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"path",
"old_text",
"new_text"
],
"properties": {
"device": {
"type": "string"
},
"path": {
"type": "string"
},
"old_text": {
"type": "string"
},
"new_text": {
"type": "string"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Edited"
},
"403": {
"description": "Security policy denied"
},
"409": {
"description": "Device offline or edit conflict"
},
"413": {
"description": "Edit block too large"
}
}
}
},
"/api/v1/process/session": {
"post": {
"summary": "Manage long-running process sessions",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "action",
"in": "query",
"required": true,
"schema": {
"type": "string",
"enum": [
"start",
"read",
"input",
"stop",
"list"
]
}
}
],
"responses": {
"200": {
"description": "Session operation result"
}
}
}
},
"/api/v1/file/list": {
"post": {
"summary": "List directory",
"security": [
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Successful result"
}
}
}
},
"/api/v1/file/info": {
"post": {
"summary": "Get file metadata",
"security": [
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Successful result"
}
}
}
},
"/api/v1/file/search": {
"post": {
"summary": "Search files",
"security": [
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Successful result"
}
}
}
}
}
}
+1 -6
View File
@@ -42,12 +42,7 @@ func (m Middleware) Handler(next http.Handler) http.Handler {
h := r.Header.Get("Authorization")
if strings.HasPrefix(h, "Bearer ") {
got = strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
} else if q := r.URL.Query().Get("token"); q != "" {
got = q
} else if q := r.URL.Query().Get("key"); q != "" {
got = q
} else if q := r.URL.Query().Get("api_key"); q != "" {
got = q
}
expected := m.Token
+216 -25
View File
@@ -2,17 +2,19 @@ package cluster
import (
"context"
"sort"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/security"
"github.com/wjyhk/vps-commander/internal/storage"
"github.com/wjyhk/vps-commander/internal/sysinfo"
)
@@ -27,22 +29,26 @@ type Manager struct {
}
type Node struct {
Name string
Conn *websocket.Conn
ConnectionID string
WriteMu sync.Mutex
Pending sync.Map
LastSeen atomic.Int64
LastHeartbeat atomic.Int64
Connected atomic.Bool
LastProfile *sysinfo.Profile
Arch string
OS string
IsLocal bool
RemoteIP string
CountryCode string
Country string
MCP *MCPRuntime
Name string
Conn *websocket.Conn
ConnectionID string
WriteMu sync.Mutex
OpMu sync.RWMutex
Pending sync.Map
LastSeen atomic.Int64
LastHeartbeat atomic.Int64
Connected atomic.Bool
LastProfile *sysinfo.Profile
Arch string
OS string
IsLocal bool
RemoteIP string
CountryCode string
Country string
MCP *MCPRuntime
ProtocolVersion string
AgentVersion string
Capabilities map[string]bool
}
type Result struct {
@@ -96,16 +102,31 @@ func (m *Manager) ServeWS(w http.ResponseWriter, r *http.Request) {
if len(auth) >= 7 && auth[:7] == "Bearer " {
provided = auth[7:]
}
if m.Secret == "" || subtle.ConstantTimeCompare([]byte(provided), []byte(m.Secret)) != 1 {
http.Error(w, "unauthorized", 401)
return
}
name := r.URL.Query().Get("device_name")
if name == "" {
http.Error(w, "device_name required", 400)
return
}
if m.Store != nil {
configured, err := m.Store.HasDeviceCredential(name)
if err != nil {
http.Error(w, "credential lookup failed", 500)
return
}
if configured {
valid, err := m.Store.VerifyDeviceCredential(name, provided)
if err != nil || !valid {
http.Error(w, "unauthorized", 401)
return
}
} else if m.Secret == "" || subtle.ConstantTimeCompare([]byte(provided), []byte(m.Secret)) != 1 {
http.Error(w, "unauthorized", 401)
return
}
} else if m.Secret == "" || subtle.ConstantTimeCompare([]byte(provided), []byte(m.Secret)) != 1 {
http.Error(w, "unauthorized", 401)
return
}
if m.Store != nil {
if revoked, _ := m.Store.IsRevoked(name); revoked {
http.Error(w, "device has been revoked by admin", 403)
@@ -128,6 +149,7 @@ func (m *Manager) ServeWS(w http.ResponseWriter, r *http.Request) {
CountryCode: cc,
Country: countryName,
MCP: NewMCPRuntime(),
Capabilities: make(map[string]bool),
}
n.LastSeen.Store(time.Now().UnixNano())
n.LastHeartbeat.Store(time.Now().UnixNano())
@@ -197,6 +219,18 @@ func (m *Manager) readLoop(n *Node) {
if msg.OS != "" {
n.OS = msg.OS
}
if msg.ProtocolVersion != "" {
n.ProtocolVersion = msg.ProtocolVersion
}
if msg.AgentVersion != "" {
n.AgentVersion = msg.AgentVersion
}
if msg.Capabilities != nil {
n.Capabilities = make(map[string]bool, len(msg.Capabilities))
for _, c := range msg.Capabilities {
n.Capabilities[c] = true
}
}
if msg.Profile != nil {
n.LastProfile = msg.Profile
n.LastHeartbeat.Store(now)
@@ -267,9 +301,9 @@ func (m *Manager) Devices() []map[string]any {
item := map[string]any{
"name": name, "status": status, "is_local": n.IsLocal,
"arch": n.Arch, "os": n.OS,
"remote_ip": n.RemoteIP,
"country_code": n.CountryCode,
"country": n.Country,
"remote_ip": n.RemoteIP,
"country_code": n.CountryCode,
"country": n.Country,
"last_heartbeat": n.LastHeartbeat.Load() / int64(time.Second),
}
if n.LastProfile != nil {
@@ -285,6 +319,25 @@ func (m *Manager) Devices() []map[string]any {
return out
}
func operationRisk(action string) int {
if r, ok := security.RequiredRiskForAction(action); ok {
return r
}
if spec, ok := security.Lookup(action); ok {
return spec.RequiredRisk
}
return security.RiskHigh
}
func (n *Node) acquireOperation(action string) func() {
if operationRisk(action) <= security.RiskLow {
n.OpMu.RLock()
return n.OpMu.RUnlock
}
n.OpMu.Lock()
return n.OpMu.Unlock
}
func (m *Manager) call(ctx context.Context, name, action string, payload any) (Message, error) {
m.mu.RLock()
n := m.nodes[name]
@@ -292,6 +345,12 @@ func (m *Manager) call(ctx context.Context, name, action string, payload any) (M
if n == nil || !m.Online(name) {
return Message{}, errors.New("device offline")
}
capability := actionCapability(action)
if capability != "" && len(n.Capabilities) > 0 && !n.Capabilities[capability] {
return Message{}, fmt.Errorf("capability missing: %s", capability)
}
release := n.acquireOperation(action)
defer release()
id := fmt.Sprintf("task_%d", time.Now().UnixNano())
ch := make(chan Message, 1)
n.Pending.Store(id, ch)
@@ -314,6 +373,90 @@ func (m *Manager) call(ctx context.Context, name, action string, payload any) (M
}
}
func actionCapability(action string) string {
switch action {
case "exec":
return "exec_command"
case "file_read":
return "read_file"
case "file_write":
return "write_file"
default:
return action
}
}
func (m *Manager) StartProcess(ctx context.Context, name string, p StartProcessPayload) (map[string]any, error) {
msg, err := m.call(ctx, name, "start_process", p)
if err != nil {
return nil, err
}
var out map[string]any
b, _ := json.Marshal(msg.Payload)
if err := json.Unmarshal(b, &out); err != nil {
return nil, err
}
return out, nil
}
func (m *Manager) ReadProcessOutput(ctx context.Context, name, sessionID, owner string) (ProcessOutputPayload, error) {
msg, err := m.call(ctx, name, "read_process_output", map[string]string{"session_id": sessionID, "owner": owner})
if err != nil {
return ProcessOutputPayload{}, err
}
var out ProcessOutputPayload
b, _ := json.Marshal(msg.Payload)
if err := json.Unmarshal(b, &out); err != nil {
return out, err
}
return out, nil
}
func (m *Manager) InteractProcess(ctx context.Context, name, sessionID, data, owner string) error {
_, err := m.call(ctx, name, "interact_with_process", ProcessInputPayload{SessionID: sessionID, Data: data, Owner: owner})
return err
}
func (m *Manager) ForceTerminate(ctx context.Context, name, sessionID, owner string) error {
_, err := m.call(ctx, name, "force_terminate", map[string]string{"session_id": sessionID, "owner": owner})
return err
}
func (m *Manager) ListSessions(ctx context.Context, name string) (any, error) {
msg, err := m.call(ctx, name, "list_sessions", nil)
if err != nil {
return nil, err
}
return msg.Payload, nil
}
func (m *Manager) ListDirectory(ctx context.Context, name string, p ListDirectoryPayload) ([]Entry, error) {
msg, err := m.call(ctx, name, "list_directory", p)
if err != nil {
return nil, err
}
var v []Entry
b, _ := json.Marshal(msg.Payload)
err = json.Unmarshal(b, &v)
return v, err
}
func (m *Manager) GetFileInfo(ctx context.Context, name string, p FileInfoPayload) (FileInfo, error) {
msg, err := m.call(ctx, name, "get_file_info", p)
if err != nil {
return FileInfo{}, err
}
var v FileInfo
b, _ := json.Marshal(msg.Payload)
err = json.Unmarshal(b, &v)
return v, err
}
func (m *Manager) Search(ctx context.Context, name string, p SearchPayload) ([]SearchResult, error) {
msg, err := m.call(ctx, name, "start_search", p)
if err != nil {
return nil, err
}
var v []SearchResult
b, _ := json.Marshal(msg.Payload)
err = json.Unmarshal(b, &v)
return v, err
}
func (m *Manager) Exec(ctx context.Context, name string, p ExecPayload) (Result, error) {
msg, err := m.call(ctx, name, "exec", p)
if err != nil {
@@ -322,6 +465,19 @@ func (m *Manager) Exec(ctx context.Context, name string, p ExecPayload) (Result,
return Result{msg.ExitCode, msg.Stdout, msg.Stderr, msg.DurationMS}, nil
}
func (m *Manager) Diagnostic(ctx context.Context, name string, req executor.DiagnosticRequest) (executor.DiagnosticResult, error) {
msg, err := m.call(ctx, name, "diagnostic_command", req)
if err != nil {
return executor.DiagnosticResult{}, err
}
b, _ := json.Marshal(msg.Payload)
var out executor.DiagnosticResult
if err := json.Unmarshal(b, &out); err != nil {
return out, err
}
return out, nil
}
func (m *Manager) ReadFile(ctx context.Context, name string, p FileReadPayload) (FileResult, error) {
msg, err := m.call(ctx, name, "file_read", p)
if err != nil {
@@ -335,6 +491,41 @@ func (m *Manager) ReadFile(ctx context.Context, name string, p FileReadPayload)
return v, nil
}
func (m *Manager) EditBlock(ctx context.Context, name string, p EditBlockPayload) (EditBlockResult, error) {
msg, err := m.call(ctx, name, "edit_block", p)
if err != nil {
return EditBlockResult{}, err
}
var v EditBlockResult
b, _ := json.Marshal(msg.Payload)
if err := json.Unmarshal(b, &v); err != nil {
return EditBlockResult{}, err
}
return v, nil
}
func (m *Manager) ReadMultipleFiles(ctx context.Context, name string, p ReadMultipleFilesPayload) (any, error) {
msg, err := m.call(ctx, name, "read_multiple_files", p)
if err != nil {
return nil, err
}
return msg.Payload, nil
}
func (m *Manager) CreateDirectory(ctx context.Context, name string, p CreateDirectoryPayload) error {
_, err := m.call(ctx, name, "create_directory", p)
return err
}
func (m *Manager) MoveFile(ctx context.Context, name string, p MoveFilePayload) error {
_, err := m.call(ctx, name, "move_file", p)
return err
}
func (m *Manager) ListProcesses(ctx context.Context, name string) (any, error) {
msg, err := m.call(ctx, name, "list_processes", nil)
if err != nil {
return nil, err
}
return msg.Payload, nil
}
func (m *Manager) WriteFile(ctx context.Context, name string, p FileWritePayload) (int64, error) {
msg, err := m.call(ctx, name, "file_write", p)
if err != nil {
+52
View File
@@ -0,0 +1,52 @@
package cluster
import (
"context"
"sync"
"testing"
"time"
)
func TestNodeOperationGateAllowsReadsAndSerializesWrites(t *testing.T) {
n := &Node{}
release1 := n.acquireOperation("file_read")
done := make(chan struct{})
go func() { release2 := n.acquireOperation("edit_block"); close(done); release2() }()
select {
case <-done:
t.Fatal("write entered while read active")
case <-time.After(50 * time.Millisecond):
}
release1()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("write did not proceed")
}
}
func TestNodeOperationGateAllowsConcurrentReads(t *testing.T) {
n := &Node{}
var wg sync.WaitGroup
wg.Add(2)
for i := 0; i < 2; i++ {
go func() {
defer wg.Done()
release := n.acquireOperation("file_read")
time.Sleep(30 * time.Millisecond)
release()
}()
}
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("reads did not complete")
}
}
func TestOperationRiskUnknownFailsClosed(t *testing.T) {
if operationRisk("unknown-danger") != 3 {
t.Fatal("unknown action must be high risk")
}
_ = context.Background()
}
+96 -15
View File
@@ -3,21 +3,25 @@ package cluster
import "github.com/wjyhk/vps-commander/internal/sysinfo"
type Message struct {
ID string `json:"id,omitempty"`
Event string `json:"event,omitempty"`
Action string `json:"action,omitempty"`
Device string `json:"device,omitempty"`
Arch string `json:"arch,omitempty"`
OS string `json:"os,omitempty"`
Status string `json:"status,omitempty"`
Payload any `json:"payload,omitempty"`
Profile *sysinfo.Profile `json:"profile,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
Error string `json:"error,omitempty"`
TS int64 `json:"ts,omitempty"`
ID string `json:"id,omitempty"`
Event string `json:"event,omitempty"`
Action string `json:"action,omitempty"`
SubAction string `json:"sub_action,omitempty"`
Device string `json:"device,omitempty"`
Arch string `json:"arch,omitempty"`
OS string `json:"os,omitempty"`
Status string `json:"status,omitempty"`
Payload any `json:"payload,omitempty"`
Profile *sysinfo.Profile `json:"profile,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
Error string `json:"error,omitempty"`
TS int64 `json:"ts,omitempty"`
ProtocolVersion string `json:"protocol_version,omitempty"`
AgentVersion string `json:"agent_version,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
type ExecPayload struct {
@@ -36,3 +40,80 @@ type FileWritePayload struct {
Path string `json:"path"`
Content string `json:"content"`
}
type EditBlockPayload struct {
Path string `json:"path"`
OldText string `json:"old_text"`
NewText string `json:"new_text"`
ExpectedHash string `json:"expected_hash,omitempty"`
}
type EditBlockResult struct {
BytesWritten int64 `json:"bytes_written"`
}
type StartProcessPayload struct {
Command string `json:"command"`
Workdir string `json:"workdir,omitempty"`
SessionID string `json:"session_id"`
Owner string `json:"owner,omitempty"`
RingCapacity int `json:"ring_capacity,omitempty"`
}
type ProcessInputPayload struct {
SessionID string `json:"session_id"`
Data string `json:"data"`
Owner string `json:"owner"`
}
type ProcessOutputPayload struct {
SessionID string `json:"session_id"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
ExitCode int `json:"exit_code"`
Running bool `json:"running"`
}
type ListDirectoryPayload struct {
Path string `json:"path"`
Recursive bool `json:"recursive,omitempty"`
MaxEntries int `json:"max_entries,omitempty"`
}
type FileInfoPayload struct {
Path string `json:"path"`
}
type ReadMultipleFilesPayload struct {
Paths []string `json:"paths"`
Limit int64 `json:"limit,omitempty"`
}
type CreateDirectoryPayload struct {
Path string `json:"path"`
}
type MoveFilePayload struct {
Source string `json:"source"`
Destination string `json:"destination"`
}
type SearchPayload struct {
Root string `json:"root"`
Query string `json:"query"`
MaxResults int `json:"max_results,omitempty"`
}
type Entry struct {
Name string `json:"name"`
Path string `json:"path"`
IsDir bool `json:"is_dir"`
Size int64 `json:"size"`
Mode string `json:"mode"`
}
type FileInfo struct {
Path string `json:"path"`
Name string `json:"name"`
IsDir bool `json:"is_dir"`
Size int64 `json:"size"`
Mode string `json:"mode"`
ModTime int64 `json:"mod_time"`
}
type SearchResult struct {
Path string `json:"path"`
Line int `json:"line,omitempty"`
Text string `json:"text,omitempty"`
}
+117
View File
@@ -0,0 +1,117 @@
package executor
import (
"context"
"errors"
"fmt"
"os/exec"
"strconv"
"strings"
"time"
)
// DiagnosticRequest is a structured, read-only diagnostic operation. It is deliberately
// not a shell command: every action maps to a fixed executable/argument set.
type DiagnosticRequest struct {
Action string `json:"action"`
Target string `json:"target,omitempty"`
Lines int `json:"lines,omitempty"`
}
type DiagnosticResult struct {
Action string `json:"action"`
Target string `json:"target,omitempty"`
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
DurationMS int64 `json:"duration_ms"`
}
func Diagnostic(ctx context.Context, req DiagnosticRequest) (DiagnosticResult, error) {
args, err := diagnosticArgs(req)
if err != nil {
return DiagnosticResult{}, err
}
if req.Lines <= 0 {
req.Lines = 100
}
if req.Lines > 500 {
req.Lines = 500
}
// docker logs is the only operation where a caller-controlled numeric limit is useful.
if req.Action == "docker_logs" {
args = []string{"logs", "--tail", strconv.Itoa(req.Lines), req.Target}
}
start := time.Now()
c, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
cmd := exec.CommandContext(c, args[0], args[1:]...)
out, runErr := cmd.CombinedOutput()
const maxOutput = 256 * 1024
if len(out) > maxOutput {
out = append(out[:maxOutput], []byte("\n[output truncated at 256 KiB]\n")...)
}
code := 0
if cmd.ProcessState != nil {
code = cmd.ProcessState.ExitCode()
}
result := DiagnosticResult{Action: req.Action, Target: req.Target, ExitCode: code, Stdout: string(out), DurationMS: time.Since(start).Milliseconds()}
if runErr != nil && code == -1 {
return result, fmt.Errorf("diagnostic failed: %w", runErr)
}
return result, nil
}
func diagnosticArgs(req DiagnosticRequest) ([]string, error) {
target := strings.TrimSpace(req.Target)
switch req.Action {
case "docker_ps":
if target != "" {
return nil, errors.New("docker_ps does not accept target")
}
return []string{"docker", "ps", "--no-trunc"}, nil
case "docker_logs":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid docker container target")
}
return []string{"docker", "logs", "--tail", "100", target}, nil
case "docker_inspect":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid docker target")
}
return []string{"docker", "inspect", target}, nil
case "systemctl_status":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid systemd unit")
}
return []string{"systemctl", "status", "--no-pager", "--full", target}, nil
case "journalctl":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid journal unit")
}
return []string{"journalctl", "--no-pager", "-u", target, "-n", "100"}, nil
case "ss_listen":
if target != "" {
return nil, errors.New("ss_listen does not accept target")
}
return []string{"ss", "-lntp"}, nil
case "df":
if target != "" {
return nil, errors.New("df does not accept target")
}
return []string{"df", "-h"}, nil
case "free":
if target != "" {
return nil, errors.New("free does not accept target")
}
return []string{"free", "-h"}, nil
case "uptime":
if target != "" {
return nil, errors.New("uptime does not accept target")
}
return []string{"uptime"}, nil
default:
return nil, fmt.Errorf("unsupported diagnostic action: %s", req.Action)
}
}
+24
View File
@@ -0,0 +1,24 @@
package executor
import (
"context"
"strings"
"testing"
)
func TestDiagnosticRejectsShellInjection(t *testing.T) {
_, err := Diagnostic(context.Background(), DiagnosticRequest{Action: "docker_logs", Target: "edgeever;rm -rf /"})
if err == nil || !strings.Contains(err.Error(), "invalid docker") {
t.Fatalf("expected target rejection, got %v", err)
}
}
func TestDiagnosticAllowsReadOnlyUptime(t *testing.T) {
got, err := Diagnostic(context.Background(), DiagnosticRequest{Action: "uptime"})
if err != nil {
t.Fatal(err)
}
if got.ExitCode != 0 || strings.TrimSpace(got.Stdout) == "" {
t.Fatalf("unexpected uptime result: %#v", got)
}
}
+130
View File
@@ -0,0 +1,130 @@
package executor
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
)
var ErrBlockNotUnique = errors.New("old_text must occur exactly once")
var ErrEditConflict = errors.New("file changed during edit")
var editMu sync.Mutex
type EditBlockResult struct {
BytesWritten int64
}
func EditBlock(path, oldText, newText string, expectedHash ...string) (EditBlockResult, error) {
editMu.Lock()
defer editMu.Unlock()
if path == "" {
return EditBlockResult{}, errors.New("path required")
}
if oldText == "" {
return EditBlockResult{}, errors.New("old_text required")
}
data, err := os.ReadFile(path)
if err != nil {
return EditBlockResult{}, err
}
initial := sha256.Sum256(data)
initialHash := hex.EncodeToString(initial[:])
if len(expectedHash) > 0 && expectedHash[0] != "" && expectedHash[0] != initialHash {
return EditBlockResult{}, ErrEditConflict
}
src := string(data)
count := countNonOverlapping(src, oldText)
if count != 1 {
if count == 0 {
return EditBlockResult{}, fmt.Errorf("%w: found 0 matches", ErrBlockNotUnique)
}
return EditBlockResult{}, fmt.Errorf("%w: found %d matches", ErrBlockNotUnique, count)
}
updated := replaceOnce(src, oldText, newText)
info, err := os.Stat(path)
if err != nil {
return EditBlockResult{}, err
}
// Re-read immediately before commit. This is the CAS check against
// writers outside this process; editMu serializes our own writers.
latest, err := os.ReadFile(path)
if err != nil {
return EditBlockResult{}, err
}
latestSum := sha256.Sum256(latest)
if hex.EncodeToString(latestSum[:]) != initialHash {
return EditBlockResult{}, ErrEditConflict
}
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".vps-commander-edit-*")
if err != nil {
return EditBlockResult{}, err
}
tmpName := tmp.Name()
defer os.Remove(tmpName)
if err := tmp.Chmod(info.Mode().Perm()); err != nil {
_ = tmp.Close()
return EditBlockResult{}, err
}
if _, err := tmp.WriteString(updated); err != nil {
_ = tmp.Close()
return EditBlockResult{}, err
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return EditBlockResult{}, err
}
if err := tmp.Close(); err != nil {
return EditBlockResult{}, err
}
if err := os.Rename(tmpName, path); err != nil {
return EditBlockResult{}, err
}
if d, err := os.Open(dir); err == nil {
_ = d.Sync()
_ = d.Close()
}
return EditBlockResult{BytesWritten: int64(len(updated))}, nil
}
func countNonOverlapping(src, old string) int {
n, count := 0, 0
for {
i := indexString(src[n:], old)
if i < 0 {
return count
}
count++
n += i + len(old)
if n > len(src) {
return count
}
}
}
func replaceOnce(src, old, new string) string {
i := indexString(src, old)
return src[:i] + new + src[i+len(old):]
}
func indexString(src, needle string) int {
if len(needle) == 0 {
return 0
}
for i := 0; i+len(needle) <= len(src); i++ {
if src[i:i+len(needle)] == needle {
return i
}
}
return -1
}
+52
View File
@@ -0,0 +1,52 @@
package executor
import (
"errors"
"os"
"path/filepath"
"testing"
)
func TestEditBlockUniqueAndAtomic(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.txt")
if err := os.WriteFile(path, []byte("a\nTARGET\nz\n"), 0640); err != nil {
t.Fatal(err)
}
res, err := EditBlock(path, "TARGET", "CHANGED")
if err != nil {
t.Fatal(err)
}
if res.BytesWritten != int64(len("a\nCHANGED\nz\n")) {
t.Fatalf("bytes=%d", res.BytesWritten)
}
got, _ := os.ReadFile(path)
if string(got) != "a\nCHANGED\nz\n" {
t.Fatalf("content=%q", got)
}
info, _ := os.Stat(path)
if info.Mode().Perm() != 0640 {
t.Fatalf("mode=%o, want 0640", info.Mode().Perm())
}
}
func TestEditBlockRejectsZeroAndMultipleMatchesWithoutMutation(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.txt")
original := "TARGET\nother\nTARGET\n"
if err := os.WriteFile(path, []byte(original), 0644); err != nil {
t.Fatal(err)
}
_, err := EditBlock(path, "MISSING", "x")
if !errors.Is(err, ErrBlockNotUnique) {
t.Fatalf("missing match error=%v", err)
}
_, err = EditBlock(path, "TARGET", "x")
if !errors.Is(err, ErrBlockNotUnique) {
t.Fatalf("multiple match error=%v", err)
}
got, _ := os.ReadFile(path)
if string(got) != original {
t.Fatalf("file mutated after rejected edit: %q", got)
}
}
+217
View File
@@ -0,0 +1,217 @@
package executor
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
)
type Entry struct {
Name string `json:"name"`
Path string `json:"path"`
IsDir bool `json:"is_dir"`
Size int64 `json:"size"`
Mode string `json:"mode"`
}
type FileInfo struct {
Path string `json:"path"`
Name string `json:"name"`
IsDir bool `json:"is_dir"`
Size int64 `json:"size"`
Mode string `json:"mode"`
ModTime int64 `json:"mod_time"`
}
type SearchResult struct {
Path string `json:"path"`
Line int `json:"line,omitempty"`
Text string `json:"text,omitempty"`
}
func ListDirectory(path string, recursive bool, maxEntries int) ([]Entry, error) {
if path == "" {
return nil, errors.New("path required")
}
if maxEntries <= 0 || maxEntries > 10000 {
maxEntries = 1000
}
out := make([]Entry, 0, maxEntries)
add := func(p string, d os.DirEntry) error {
if len(out) >= maxEntries {
return nil
}
info, err := d.Info()
if err != nil {
return err
}
out = append(out, Entry{Name: d.Name(), Path: p, IsDir: d.IsDir(), Size: info.Size(), Mode: info.Mode().String()})
return nil
}
if !recursive {
ds, err := os.ReadDir(path)
if err != nil {
return nil, err
}
for _, d := range ds {
if err := add(filepath.Join(path, d.Name()), d); err != nil {
return nil, err
}
}
return out, nil
}
err := filepath.WalkDir(path, func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if p == path {
return nil
}
if len(out) >= maxEntries {
return filepath.SkipDir
}
return add(p, d)
})
return out, err
}
func GetFileInfo(path string) (FileInfo, error) {
if path == "" {
return FileInfo{}, errors.New("path required")
}
i, err := os.Stat(path)
if err != nil {
return FileInfo{}, err
}
return FileInfo{Path: path, Name: i.Name(), IsDir: i.IsDir(), Size: i.Size(), Mode: i.Mode().String(), ModTime: i.ModTime().Unix()}, nil
}
func Search(ctx context.Context, root, query string, maxResults int) ([]SearchResult, error) {
if root == "" || query == "" {
return nil, errors.New("root and query required")
}
if maxResults <= 0 || maxResults > 1000 {
maxResults = 100
}
out := make([]SearchResult, 0, maxResults)
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
if len(out) >= maxResults {
return filepath.SkipDir
}
if d.IsDir() {
return nil
}
if d.Type()&os.ModeSymlink != 0 {
return nil
}
b, err := os.ReadFile(path)
if err != nil {
return nil
}
if strings.Contains(string(b), query) {
for n, line := range strings.Split(string(b), "\n") {
if strings.Contains(line, query) {
out = append(out, SearchResult{Path: path, Line: n + 1, Text: line})
if len(out) >= maxResults {
break
}
}
}
}
return nil
})
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
return out, err
}
type FileReadItem struct {
Path string `json:"path"`
Content string `json:"content,omitempty"`
Error string `json:"error,omitempty"`
}
type ProcessInfo struct {
PID int `json:"pid"`
Command string `json:"command"`
CPU string `json:"cpu,omitempty"`
MemoryKB uint64 `json:"memory_kb,omitempty"`
}
func ReadMultipleFiles(paths []string, limit int64) []FileReadItem {
if limit <= 0 || limit > 1024*1024 {
limit = 256 * 1024
}
out := make([]FileReadItem, 0, len(paths))
for _, p := range paths {
v := FileReadItem{Path: p}
b, e := os.ReadFile(p)
if e != nil {
v.Error = e.Error()
} else {
if int64(len(b)) > limit {
b = b[:limit]
}
v.Content = string(b)
}
out = append(out, v)
}
return out
}
func CreateDirectory(path string) error {
if strings.TrimSpace(path) == "" {
return errors.New("path required")
}
return os.MkdirAll(path, 0755)
}
func MoveFile(src, dst string) error {
if src == "" || dst == "" {
return errors.New("source and destination required")
}
return os.Rename(src, dst)
}
func ListProcesses() ([]ProcessInfo, error) {
ents, e := os.ReadDir("/proc")
if e != nil {
return nil, e
}
out := make([]ProcessInfo, 0)
for _, ent := range ents {
if !ent.IsDir() {
continue
}
pid, e := strconv.Atoi(ent.Name())
if e != nil {
continue
}
comm, _ := os.ReadFile(filepath.Join("/proc", ent.Name(), "comm"))
stat, _ := os.ReadFile(filepath.Join("/proc", ent.Name(), "statm"))
cmd, _ := os.ReadFile(filepath.Join("/proc", ent.Name(), "cmdline"))
v := ProcessInfo{PID: pid, Command: strings.TrimSpace(string(comm))}
if len(cmd) > 0 {
v.Command = strings.ReplaceAll(string(cmd), "\x00", " ")
v.Command = strings.TrimSpace(v.Command)
}
f := strings.Fields(string(stat))
if len(f) >= 2 {
if pages, e := strconv.ParseUint(f[1], 10, 64); e == nil {
v.MemoryKB = pages * uint64(os.Getpagesize()) / 1024
}
}
out = append(out, v)
}
return out, nil
}
var _ = fmt.Sprintf
var _ = exec.Command
+36
View File
@@ -0,0 +1,36 @@
package executor
import (
"context"
"os"
"path/filepath"
"testing"
)
func TestListDirectoryAndInfo(t *testing.T) {
d := t.TempDir()
if err := os.WriteFile(filepath.Join(d, "a.txt"), []byte("hello"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(d, "sub"), 0700); err != nil {
t.Fatal(err)
}
es, err := ListDirectory(d, false, 10)
if err != nil || len(es) != 2 {
t.Fatalf("entries=%v err=%v", es, err)
}
fi, err := GetFileInfo(filepath.Join(d, "a.txt"))
if err != nil || fi.Size != 5 {
t.Fatalf("info=%+v err=%v", fi, err)
}
}
func TestSearchHonorsContextAndLimit(t *testing.T) {
d := t.TempDir()
for i := 0; i < 3; i++ {
_ = os.WriteFile(filepath.Join(d, string(rune('a'+i))+".txt"), []byte("needle\n"), 0600)
}
r, err := Search(context.Background(), d, "needle", 2)
if err != nil || len(r) != 2 {
t.Fatalf("results=%v err=%v", r, err)
}
}
+248
View File
@@ -0,0 +1,248 @@
package executor
import (
"context"
"errors"
"io"
"os/exec"
"sync"
"syscall"
"time"
)
const (
DefaultRingCapacity = 2 * 1024 * 1024
MaxSessionInput = 64 * 1024
DefaultSessionTTL = 30 * time.Minute
SessionIdleTTL = 10 * time.Minute
MaxSessionBufferTotal = 8 * 1024 * 1024
)
type RingBuffer struct {
mu sync.RWMutex
buf []byte
head int
size int
}
func NewRingBuffer(capacity int) *RingBuffer {
if capacity <= 0 {
capacity = DefaultRingCapacity
}
return &RingBuffer{buf: make([]byte, capacity)}
}
func (r *RingBuffer) Write(p []byte) (int, error) {
total := len(p)
r.mu.Lock()
defer r.mu.Unlock()
for len(p) > 0 {
n := len(p)
if n > len(r.buf) {
p = p[n-len(r.buf):]
n = len(p)
}
first := len(r.buf) - r.head
if first > n {
first = n
}
copy(r.buf[r.head:r.head+first], p[:first])
if first < n {
copy(r.buf[:n-first], p[first:n])
}
r.head = (r.head + n) % len(r.buf)
r.size += n
if r.size > len(r.buf) {
r.size = len(r.buf)
}
p = p[n:]
}
return total, nil
}
func (r *RingBuffer) Snapshot() []byte {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]byte, r.size)
start := (r.head - r.size + len(r.buf)) % len(r.buf)
first := len(r.buf) - start
if first > r.size {
first = r.size
}
copy(out, r.buf[start:start+first])
if first < r.size {
copy(out[first:], r.buf[:r.size-first])
}
return out
}
type Session struct {
ID string
Command string
Owner string
StartedAt time.Time
ExpiresAt time.Time
LastAccess time.Time
cmd *exec.Cmd
stdin io.WriteCloser
stdout *RingBuffer
stderr *RingBuffer
done chan struct{}
mu sync.RWMutex
err error
exitCode int
}
func StartSession(ctx context.Context, id, command, workdir, owner string, capacity int) (*Session, error) {
if id == "" || command == "" {
return nil, errors.New("session id and command required")
}
cmd := exec.Command("/bin/sh", "-c", command)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if workdir != "" {
cmd.Dir = workdir
}
stdout := NewRingBuffer(capacity)
stderr := NewRingBuffer(capacity)
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
out, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
errOut, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
now := time.Now()
s := &Session{
ID: id, Command: command, Owner: owner, StartedAt: now, LastAccess: now, ExpiresAt: now.Add(DefaultSessionTTL), cmd: cmd,
stdin: stdin, stdout: stdout, stderr: stderr, done: make(chan struct{}), exitCode: -1,
}
if err := cmd.Start(); err != nil {
_ = stdin.Close()
return nil, err
}
go s.copy(out, stdout)
go s.copy(errOut, stderr)
go s.wait()
go func() {
select {
case <-ctx.Done():
s.Terminate()
case <-s.done:
}
}()
return s, nil
}
func (s *Session) copy(src io.Reader, dst io.Writer) {
_, _ = io.Copy(dst, src)
}
func (s *Session) wait() {
err := s.cmd.Wait()
s.mu.Lock()
s.err = err
if err == nil {
s.exitCode = 0
} else if ee, ok := err.(*exec.ExitError); ok {
s.exitCode = ee.ExitCode()
} else {
s.exitCode = 1
}
s.mu.Unlock()
close(s.done)
}
func (s *Session) Done() <-chan struct{} { return s.done }
func (s *Session) Status() (int, bool, error) {
select {
case <-s.done:
s.mu.RLock()
defer s.mu.RUnlock()
return s.exitCode, true, s.err
default:
return -1, false, nil
}
}
func (s *Session) Output() (stdout, stderr string) {
stdout, stderr = string(s.stdout.Snapshot()), string(s.stderr.Snapshot())
s.mu.Lock()
if time.Now().Before(s.ExpiresAt) {
s.LastAccess = time.Now()
}
s.mu.Unlock()
return stdout, stderr
}
func (s *Session) Stdin(data []byte) error {
if len(data) > MaxSessionInput {
return errors.New("session input too large")
}
s.mu.RLock()
stdin := s.stdin
s.mu.RUnlock()
if stdin == nil {
return errors.New("session stdin unavailable")
}
_, err := stdin.Write(data)
if err == nil {
s.mu.Lock()
s.LastAccess = time.Now()
s.mu.Unlock()
}
return err
}
func (s *Session) Authorized(owner string) bool {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
if owner == "" || s.Owner != owner || now.After(s.ExpiresAt) || now.Sub(s.LastAccess) > SessionIdleTTL {
return false
}
s.LastAccess = now
return true
}
func (s *Session) Expired() bool {
s.mu.RLock()
defer s.mu.RUnlock()
now := time.Now()
return now.After(s.ExpiresAt) || now.Sub(s.LastAccess) > SessionIdleTTL
}
func (s *Session) Terminate() error {
s.mu.RLock()
pid := 0
if s.cmd != nil && s.cmd.Process != nil {
pid = s.cmd.Process.Pid
}
s.mu.RUnlock()
if pid == 0 {
return nil
}
return syscall.Kill(-pid, syscall.SIGTERM)
}
func (s *Session) Kill() error {
s.mu.RLock()
pid := 0
if s.cmd != nil && s.cmd.Process != nil {
pid = s.cmd.Process.Pid
}
s.mu.RUnlock()
if pid == 0 {
return nil
}
return syscall.Kill(-pid, syscall.SIGKILL)
}
// Compile-time sanity for the output writer contract.
var _ io.Writer = (*RingBuffer)(nil)
+104
View File
@@ -0,0 +1,104 @@
package executor
import (
"context"
"errors"
"sync"
"time"
)
const MaxSessionsPerManager = MaxSessionBufferTotal / DefaultRingCapacity
type SessionInfo struct {
ID string `json:"id"`
Command string `json:"command"`
StartedAt time.Time `json:"started_at"`
Running bool `json:"running"`
ExitCode int `json:"exit_code"`
}
type SessionManager struct {
mu sync.RWMutex
sessions map[string]*Session
limit int
}
func NewSessionManager(limit int) *SessionManager {
if limit <= 0 || limit > MaxSessionsPerManager {
limit = MaxSessionsPerManager
}
return &SessionManager{sessions: make(map[string]*Session), limit: limit}
}
func (m *SessionManager) Start(ctx context.Context, id, command, workdir, owner string, capacity int) (*Session, error) {
m.mu.Lock()
if _, ok := m.sessions[id]; ok {
m.mu.Unlock()
return nil, errors.New("session already exists")
}
if len(m.sessions) >= m.limit {
m.mu.Unlock()
return nil, errors.New("session limit reached")
}
s, err := StartSession(ctx, id, command, workdir, owner, capacity)
if err != nil {
m.mu.Unlock()
return nil, err
}
if _, exists := m.sessions[id]; exists {
m.mu.Unlock()
_ = s.Kill()
return nil, errors.New("session already exists")
}
m.sessions[id] = s
m.mu.Unlock()
return s, nil
}
func (m *SessionManager) Get(id string) (*Session, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
s, ok := m.sessions[id]
return s, ok
}
func (m *SessionManager) Remove(id string) bool {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.sessions[id]; !ok {
return false
}
delete(m.sessions, id)
return true
}
func (m *SessionManager) List() []SessionInfo {
m.mu.RLock()
defer m.mu.RUnlock()
out := make([]SessionInfo, 0, len(m.sessions))
for _, s := range m.sessions {
code, done, _ := s.Status()
out = append(out, SessionInfo{ID: s.ID, Command: s.Command, StartedAt: s.StartedAt, Running: !done, ExitCode: code})
}
return out
}
func (m *SessionManager) Stop(id string, force bool) error {
s, ok := m.Get(id)
if !ok {
return errors.New("session not found")
}
if force {
return s.Kill()
}
return s.Terminate()
}
func (m *SessionManager) Cleanup() {
m.mu.Lock()
defer m.mu.Unlock()
for id, s := range m.sessions {
if s.Expired() {
_, done, _ := s.Status()
if !done {
_ = s.Kill()
continue
}
delete(m.sessions, id)
}
}
}
+72
View File
@@ -0,0 +1,72 @@
package executor
import (
"context"
"strings"
"testing"
"time"
)
func TestRingBufferKeepsNewestData(t *testing.T) {
r := NewRingBuffer(8)
_, _ = r.Write([]byte("12345678"))
_, _ = r.Write([]byte("90"))
if got := string(r.Snapshot()); got != "34567890" {
t.Fatalf("got %q", got)
}
}
func TestSessionCapturesAndTerminates(t *testing.T) {
s, err := StartSession(context.Background(), "t1", "printf hello; sleep 5", "", "owner", 1024)
if err != nil {
t.Fatal(err)
}
time.Sleep(100 * time.Millisecond)
out, _ := s.Output()
if !strings.Contains(out, "hello") {
t.Fatalf("out=%q", out)
}
if err := s.Terminate(); err != nil {
t.Fatal(err)
}
select {
case <-s.Done():
case <-time.After(2 * time.Second):
t.Fatal("session did not terminate")
}
}
func TestSessionManagerDuplicateAndLimit(t *testing.T) {
m := NewSessionManager(1)
s, err := m.Start(context.Background(), "a", "sleep 1", "", "owner", 128)
if err != nil {
t.Fatal(err)
}
defer s.Kill()
if _, err := m.Start(context.Background(), "b", "true", "", "owner", 128); err == nil {
t.Fatal("expected limit")
}
if _, err := m.Start(context.Background(), "a", "true", "", "owner", 128); err == nil {
t.Fatal("expected duplicate")
}
}
func TestSessionIdleAuthorizationTouch(t *testing.T) {
s, err := StartSession(context.Background(), "idle-test", "sleep 2", "", "owner", 128)
if err != nil {
t.Fatal(err)
}
defer s.Kill()
s.mu.Lock()
s.LastAccess = time.Now().Add(-(SessionIdleTTL + time.Second))
s.mu.Unlock()
if s.Authorized("owner") {
t.Fatal("idle-expired session must not authorize")
}
s.mu.Lock()
s.LastAccess = time.Now()
s.mu.Unlock()
if !s.Authorized("owner") {
t.Fatal("active session should authorize")
}
}
+121
View File
@@ -12,6 +12,7 @@ import (
"time"
"github.com/wjyhk/vps-commander/internal/auth"
"github.com/wjyhk/vps-commander/internal/executor"
)
// MCP Protocol / JSON-RPC 2.0 Types
@@ -74,6 +75,18 @@ type ActionBackend interface {
ExecCommand(ctx context.Context, clientIP, device, command, workdir string, timeout int) (any, error)
ReadFile(ctx context.Context, clientIP, device, path string, offset, limit int64) (any, error)
WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error)
EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error)
}
type DiagnosticBackend interface {
DiagnosticCommand(ctx context.Context, clientIP, device string, req executor.DiagnosticRequest) (any, error)
}
type ExtendedBackend interface {
ReadMultipleFiles(ctx context.Context, clientIP, device string, paths []string, limit int64) (any, error)
CreateDirectory(ctx context.Context, clientIP, device, path string) (any, error)
MoveFile(ctx context.Context, clientIP, device, source, destination string) (any, error)
ListProcesses(ctx context.Context, clientIP, device string) (any, error)
}
type AgentMCPBackend interface {
@@ -81,6 +94,10 @@ type AgentMCPBackend interface {
CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error)
}
type SecurityGate interface {
AuthorizeMCP(device, action, clientIP string) error
}
type Server struct {
Backend ActionBackend
Auth *auth.Manager
@@ -264,6 +281,16 @@ func (s *Server) handleRequest(ctx context.Context, r *http.Request, req JSONRPC
Required: []string{"path"},
},
},
{Name: "read_multiple_files", Description: "一次读取多个文件", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "paths": {Type: "array", Description: "文件路径数组"}, "limit": {Type: "integer", Description: "单文件最大字节数"}}, Required: []string{"paths"}}},
{Name: "create_directory", Description: "创建目录", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "path": {Type: "string", Description: "目录路径"}}, Required: []string{"path"}}},
{Name: "move_file", Description: "移动或重命名文件", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "source": {Type: "string", Description: "源路径"}, "destination": {Type: "string", Description: "目标路径"}}, Required: []string{"source", "destination"}}},
{Name: "list_processes", Description: "列出受控节点当前进程", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}}}},
{Name: "diagnostic_command", Description: "执行严格白名单的只读系统诊断,不接受任意 Shell", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "action": {Type: "string", Description: "docker_ps|docker_logs|docker_inspect|systemctl_status|journalctl|ss_listen|df|free|uptime"}, "target": {Type: "string", Description: "容器名或 systemd unit(按 action 使用)"}, "lines": {Type: "integer", Description: "docker_logs 最大行数,1-500"}}, Required: []string{"action"}}},
{
Name: "edit_block",
Description: "对指定文件执行唯一文本块的原子替换;old_text 必须恰好匹配一次",
InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标节点名称"}, "path": {Type: "string", Description: "目标文件路径"}, "old_text": {Type: "string", Description: "必须唯一匹配的原文本块"}, "new_text": {Type: "string", Description: "替换后的文本块"}}, Required: []string{"path", "old_text", "new_text"}},
},
{
Name: "write_file",
Description: "向指定受控节点创建或覆写文件",
@@ -369,6 +396,90 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
}
return res, false
case "read_multiple_files":
var a struct {
Device string `json:"device"`
Paths []string `json:"paths"`
Limit int64 `json:"limit"`
}
_ = json.Unmarshal(params.Arguments, &a)
b, ok := s.Backend.(ExtendedBackend)
if !ok {
return map[string]string{"error": "extended tools unavailable"}, true
}
res, err := b.ReadMultipleFiles(ctx, clientIP, a.Device, a.Paths, a.Limit)
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "create_directory":
var a struct{ Device, Path string }
_ = json.Unmarshal(params.Arguments, &a)
b, ok := s.Backend.(ExtendedBackend)
if !ok {
return map[string]string{"error": "extended tools unavailable"}, true
}
res, err := b.CreateDirectory(ctx, clientIP, a.Device, a.Path)
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "move_file":
var a struct{ Device, Source, Destination string }
_ = json.Unmarshal(params.Arguments, &a)
b, ok := s.Backend.(ExtendedBackend)
if !ok {
return map[string]string{"error": "extended tools unavailable"}, true
}
res, err := b.MoveFile(ctx, clientIP, a.Device, a.Source, a.Destination)
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "diagnostic_command":
var a struct {
Device string `json:"device"`
Action string `json:"action"`
Target string `json:"target"`
Lines int `json:"lines"`
}
_ = json.Unmarshal(params.Arguments, &a)
b, ok := s.Backend.(DiagnosticBackend)
if !ok {
return map[string]string{"error": "diagnostic tools unavailable"}, true
}
res, err := b.DiagnosticCommand(ctx, clientIP, a.Device, executor.DiagnosticRequest{Action: a.Action, Target: a.Target, Lines: a.Lines})
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "list_processes":
var a struct {
Device string `json:"device"`
}
_ = json.Unmarshal(params.Arguments, &a)
b, ok := s.Backend.(ExtendedBackend)
if !ok {
return map[string]string{"error": "extended tools unavailable"}, true
}
res, err := b.ListProcesses(ctx, clientIP, a.Device)
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "edit_block":
var args struct{ Device, Path, OldText, NewText string }
_ = json.Unmarshal(params.Arguments, &args)
if args.Path == "" || args.OldText == "" {
return map[string]string{"error": "path and old_text are required"}, true
}
res, err := s.Backend.EditBlock(ctx, clientIP, args.Device, args.Path, args.OldText, args.NewText)
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "write_file":
var args struct {
Device string `json:"device"`
@@ -394,6 +505,11 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
if !ok {
return map[string]string{"error": "agent MCP unavailable"}, true
}
if gate, ok := s.Backend.(SecurityGate); ok {
if err := gate.AuthorizeMCP(args.Device, "read", clientIP); err != nil {
return map[string]string{"error": err.Error()}, true
}
}
res, err := b.ListAgentMCP(ctx, args.Device)
if err != nil {
return map[string]string{"error": err.Error()}, true
@@ -416,6 +532,11 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
if len(args.Arguments) > 0 {
_ = json.Unmarshal(args.Arguments, &av)
}
if gate, ok := s.Backend.(SecurityGate); ok {
if err := gate.AuthorizeMCP(args.Device, "mcp", clientIP); err != nil {
return map[string]string{"error": err.Error()}, true
}
}
res, err := b.CallAgentMCP(ctx, clientIP, args.Device, args.Server, args.Tool, av)
if err != nil {
return map[string]string{"error": err.Error()}, true
+67 -2
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
@@ -24,6 +25,9 @@ func (m *mockBackend) ReadFile(ctx context.Context, clientIP, device, path strin
func (m *mockBackend) WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error) {
return map[string]any{"device": device, "path": path, "bytes": len(content)}, nil
}
func (m *mockBackend) EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error) {
return map[string]any{"device": device, "path": path, "bytes_written": len(newText)}, nil
}
func TestMCPInitializeAndListTools(t *testing.T) {
srv := NewServer(&mockBackend{}, nil)
@@ -75,8 +79,25 @@ func TestMCPInitializeAndListTools(t *testing.T) {
t.Fatalf("expected map result")
}
tools, ok := resMap["tools"].([]any)
if !ok || len(tools) != 6 {
t.Fatalf("expected 6 tools, got %d", len(tools))
if !ok || len(tools) != 12 {
t.Fatalf("expected 11 tools, got %d", len(tools))
}
foundWriteFile := false
for _, raw := range tools {
tool, ok := raw.(map[string]any)
if !ok {
t.Fatalf("tool entry is not an object: %#v", raw)
}
name, _ := tool["name"].(string)
if name == "" {
t.Fatalf("tool entry has empty name: %#v", tool)
}
if name == "write_file" {
foundWriteFile = true
}
}
if !foundWriteFile {
t.Fatalf("write_file missing from tools/list")
}
}
@@ -110,3 +131,47 @@ func TestMCPCallTool(t *testing.T) {
t.Fatalf("expected stdout in result, got %s", contentStr)
}
}
type gatedMockBackend struct {
mockBackend
deniedAction string
}
func (g *gatedMockBackend) AuthorizeMCP(device, action, clientIP string) error {
if action == g.deniedAction {
return fmt.Errorf("denied %s", action)
}
return nil
}
func (g *gatedMockBackend) ListAgentMCP(ctx context.Context, device string) (any, error) {
return map[string]any{"device": device}, nil
}
func (g *gatedMockBackend) CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error) {
return map[string]any{"device": device, "server": server, "tool": tool}, nil
}
func TestMCPAgentCallUsesSecurityGate(t *testing.T) {
backend := &gatedMockBackend{deniedAction: "mcp"}
srv := NewServer(backend, nil)
params := json.RawMessage("{\"name\":\"call_agent_mcp\",\"arguments\":{\"device\":\"node1\",\"server\":\"s\",\"tool\":\"t\"}}")
req := JSONRPCRequest{JSONRPC: "2.0", ID: 10, Method: "tools/call", Params: params}
resp := srv.HandleDirectRequest(context.Background(), req)
result, ok := resp.Result.(CallToolResult)
if !ok || !result.IsError || !strings.Contains(result.Content[0].Text, "denied mcp") {
t.Fatalf("expected MCP denial, got %#v", resp)
}
}
func TestMCPListAgentUsesReadGate(t *testing.T) {
backend := &gatedMockBackend{deniedAction: "read"}
srv := NewServer(backend, nil)
params := json.RawMessage("{\"name\":\"list_agent_mcp\",\"arguments\":{\"device\":\"node1\"}}")
req := JSONRPCRequest{JSONRPC: "2.0", ID: 11, Method: "tools/call", Params: params}
resp := srv.HandleDirectRequest(context.Background(), req)
result, ok := resp.Result.(CallToolResult)
if !ok || !result.IsError || !strings.Contains(result.Content[0].Text, "denied read") {
t.Fatalf("expected MCP list denial, got %#v", resp)
}
}
+98
View File
@@ -0,0 +1,98 @@
package security
import (
"errors"
"sync"
"time"
)
const (
RiskLow = 1
RiskMedium = 2
RiskHigh = 3
)
type DevicePolicy struct {
Mode string
}
type PolicySnapshot struct {
Version uint64
GlobalRisk int
Devices map[string]DevicePolicy
CreatedAt time.Time
}
type Snapshot struct {
mu sync.RWMutex
data PolicySnapshot
}
func New(globalRisk int, devices map[string]DevicePolicy, version uint64) *Snapshot {
if globalRisk < RiskLow || globalRisk > RiskHigh {
globalRisk = RiskMedium
}
cp := make(map[string]DevicePolicy, len(devices))
for k, v := range devices {
cp[k] = v
}
return &Snapshot{data: PolicySnapshot{
Version: version, GlobalRisk: globalRisk, Devices: cp, CreatedAt: time.Now(),
}}
}
func (s *Snapshot) Current() PolicySnapshot {
s.mu.RLock()
defer s.mu.RUnlock()
cp := make(map[string]DevicePolicy, len(s.data.Devices))
for k, v := range s.data.Devices {
cp[k] = v
}
snap := s.data
snap.Devices = cp
return snap
}
func (s *Snapshot) Publish(globalRisk int, devices map[string]DevicePolicy, version uint64) error {
if globalRisk < RiskLow || globalRisk > RiskHigh {
return errors.New("invalid global risk")
}
cp := make(map[string]DevicePolicy, len(devices))
for k, v := range devices {
cp[k] = v
}
s.mu.Lock()
if version < s.data.Version {
s.mu.Unlock()
return errors.New("policy version regression")
}
s.data = PolicySnapshot{
Version: version, GlobalRisk: globalRisk, Devices: cp, CreatedAt: time.Now(),
}
s.mu.Unlock()
return nil
}
func (s *Snapshot) EffectiveRisk(device string) int {
s.mu.RLock()
defer s.mu.RUnlock()
if p, ok := s.data.Devices[device]; ok {
if risk := ModeRisk(p.Mode); risk != 0 {
return risk
}
}
return s.data.GlobalRisk
}
func ModeRisk(mode string) int {
switch mode {
case "low":
return RiskLow
case "medium":
return RiskMedium
case "high":
return RiskHigh
default:
return 0
}
}
+35
View File
@@ -0,0 +1,35 @@
package security
import "testing"
func TestSnapshotEffectiveRiskAndPublish(t *testing.T) {
s := New(RiskMedium, map[string]DevicePolicy{"hwsg": {Mode: "high"}}, 7)
if got := s.EffectiveRisk("hwsg"); got != RiskHigh {
t.Fatalf("hwsg risk=%d, want %d", got, RiskHigh)
}
if got := s.EffectiveRisk("n3450"); got != RiskMedium {
t.Fatalf("default risk=%d, want %d", got, RiskMedium)
}
if err := s.Publish(RiskLow, map[string]DevicePolicy{"n3450": {Mode: "medium"}}, 8); err != nil {
t.Fatal(err)
}
cur := s.Current()
if cur.Version != 8 {
t.Fatalf("version=%d, want 8", cur.Version)
}
if got := s.EffectiveRisk("hwsg"); got != RiskLow {
t.Fatalf("old node risk=%d, want %d", got, RiskLow)
}
if got := s.EffectiveRisk("n3450"); got != RiskMedium {
t.Fatalf("override risk=%d, want %d", got, RiskMedium)
}
}
func TestModeRiskRejectsUnknown(t *testing.T) {
if got := ModeRisk("inherit"); got != 0 {
t.Fatalf("inherit risk=%d, want 0", got)
}
if got := ModeRisk("root"); got != 0 {
t.Fatalf("unknown risk=%d, want 0", got)
}
}
+53
View File
@@ -0,0 +1,53 @@
package security
type ToolSpec struct {
Name string
RequiredRisk int
Category string
ReadOnly bool
}
var registry = map[string]ToolSpec{
"read_file": {Name: "read_file", RequiredRisk: RiskLow, Category: "file", ReadOnly: true},
"read_multiple_files": {Name: "read_multiple_files", RequiredRisk: RiskLow, Category: "file", ReadOnly: true},
"list_directory": {Name: "list_directory", RequiredRisk: RiskLow, Category: "file", ReadOnly: true},
"get_file_info": {Name: "get_file_info", RequiredRisk: RiskLow, Category: "file", ReadOnly: true},
"start_search": {Name: "start_search", RequiredRisk: RiskLow, Category: "search", ReadOnly: true},
"get_more_search_results": {Name: "get_more_search_results", RequiredRisk: RiskLow, Category: "search", ReadOnly: true},
"list_processes": {Name: "list_processes", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"diagnostic_command": {Name: "diagnostic_command", RequiredRisk: RiskLow, Category: "diagnostic", ReadOnly: true},
"list_sessions": {Name: "list_sessions", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"read_process_output": {Name: "read_process_output", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"edit_block": {Name: "edit_block", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
"write_file": {Name: "write_file", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
"create_directory": {Name: "create_directory", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
"move_file": {Name: "move_file", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
"exec_command": {Name: "exec_command", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
"start_process": {Name: "start_process", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
"interact_with_process": {Name: "interact_with_process", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
"kill_process": {Name: "kill_process", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
"force_terminate": {Name: "force_terminate", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
"mcp_call": {Name: "mcp_call", RequiredRisk: RiskMedium, Category: "mcp", ReadOnly: false},
}
var actionTools = map[string]string{
"read": "read_file", "probe": "read_file", "write": "write_file",
"mcp": "mcp_call", "exec": "exec_command",
}
func Lookup(name string) (ToolSpec, bool) {
v, ok := registry[name]
return v, ok
}
func RequiredRiskForAction(action string) (int, bool) {
name, ok := actionTools[action]
if !ok {
return 0, false
}
spec, ok := registry[name]
if !ok {
return 0, false
}
return spec.RequiredRisk, true
}
+145 -6
View File
@@ -1,12 +1,15 @@
package storage
import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
_ "modernc.org/sqlite"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
@@ -45,7 +48,7 @@ func (s *Store) init() error {
"CREATE TABLE IF NOT EXISTS audit_logs (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER NOT NULL, caller_ip TEXT, device TEXT, action TEXT, command TEXT, " +
"exit_code INTEGER, duration_ms INTEGER, error_msg TEXT); " +
"CREATE TABLE IF NOT EXISTS revoked_devices (name TEXT PRIMARY KEY, revoked_at INTEGER NOT NULL, reason TEXT); CREATE TABLE IF NOT EXISTS security_settings (node_name TEXT PRIMARY KEY, mode TEXT NOT NULL, updated_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS mcp_services (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, transport TEXT NOT NULL, command TEXT, args_json TEXT, env_json TEXT, url TEXT, headers_json TEXT, scope TEXT NOT NULL DEFAULT 'all', target_nodes_json TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS idx_mcp_services_enabled ON mcp_services(enabled);")
"CREATE TABLE IF NOT EXISTS revoked_devices (name TEXT PRIMARY KEY, revoked_at INTEGER NOT NULL, reason TEXT); CREATE TABLE IF NOT EXISTS device_credentials (name TEXT PRIMARY KEY, token_hash TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS security_settings (node_name TEXT PRIMARY KEY, mode TEXT NOT NULL, updated_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS security_policy_meta (id INTEGER PRIMARY KEY CHECK(id=1), version INTEGER NOT NULL); INSERT OR IGNORE INTO security_policy_meta(id,version) VALUES(1,1); CREATE TABLE IF NOT EXISTS mcp_services (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, transport TEXT NOT NULL, command TEXT, args_json TEXT, env_json TEXT, url TEXT, headers_json TEXT, scope TEXT NOT NULL DEFAULT 'all', target_nodes_json TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS idx_mcp_services_enabled ON mcp_services(enabled);")
if err != nil {
return err
}
@@ -276,9 +279,20 @@ type AuditLog struct {
ErrorMsg string `json:"error_msg"`
}
var auditSecretRE = regexp.MustCompile(`(?i)(authorization|bearer|token|api[_-]?key|password|secret|cookie)(\s*[:=]\s+)([^\s,;]+)`)
func redactAudit(v string) string {
v = auditSecretRE.ReplaceAllString(v, `$1$2[REDACTED]`)
v = strings.ReplaceAll(v, "\r", " ")
v = strings.ReplaceAll(v, "\n", " ")
if len(v) > 8192 {
v = v[:8192]
}
return v
}
func (s *Store) Audit(ip, device, action, command string, code int, ms int64, msg string) error {
_, err := s.DB.Exec("INSERT INTO audit_logs(timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg) VALUES(?,?,?,?,?,?,?,?)",
time.Now().Unix(), ip, device, action, command, code, ms, msg)
time.Now().Unix(), ip, device, action, redactAudit(command), code, ms, redactAudit(msg))
return err
}
@@ -387,6 +401,59 @@ func normalizeSecurityMode(mode string) string {
return ""
}
type SecurityPolicyState struct {
GlobalMode string
Nodes map[string]string
Version uint64
}
func (s *Store) LoadSecurityPolicy() (SecurityPolicyState, error) {
state := SecurityPolicyState{GlobalMode: "medium", Nodes: map[string]string{}, Version: 1}
if err := s.DB.QueryRow("SELECT mode FROM security_settings WHERE node_name='' LIMIT 1").Scan(&state.GlobalMode); err != nil && err != sql.ErrNoRows {
return state, err
}
if m := normalizeSecurityMode(state.GlobalMode); m != "" && m != "inherit" {
state.GlobalMode = m
} else {
state.GlobalMode = "medium"
}
var version int64
if err := s.DB.QueryRow("SELECT version FROM security_policy_meta WHERE id=1").Scan(&version); err != nil {
return state, err
}
if version > 0 {
state.Version = uint64(version)
}
rows, err := s.DB.Query("SELECT node_name,mode FROM security_settings WHERE node_name<>''")
if err != nil {
return state, err
}
defer rows.Close()
for rows.Next() {
var node, mode string
if err := rows.Scan(&node, &mode); err != nil {
return state, err
}
if m := normalizeSecurityMode(mode); m != "" {
state.Nodes[node] = m
}
}
return state, rows.Err()
}
func (s *Store) bumpSecurityPolicyVersion(tx *sql.Tx) error {
_, err := tx.Exec("UPDATE security_policy_meta SET version=version+1 WHERE id=1")
return err
}
func (s *Store) SecurityPolicyVersion() uint64 {
var version int64
if err := s.DB.QueryRow("SELECT version FROM security_policy_meta WHERE id=1").Scan(&version); err != nil || version < 1 {
return 1
}
return uint64(version)
}
func (s *Store) GetGlobalSecurityMode() string {
var mode string
err := s.DB.QueryRow("SELECT mode FROM security_settings WHERE node_name='' LIMIT 1").Scan(&mode)
@@ -404,8 +471,18 @@ func (s *Store) SetGlobalSecurityMode(mode string) error {
if mode == "" || mode == "inherit" {
return errors.New("invalid global security mode")
}
_, err := s.DB.Exec("INSERT INTO security_settings(node_name,mode,updated_at) VALUES('',?,?) ON CONFLICT(node_name) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at", mode, time.Now().Unix())
return err
tx, err := s.DB.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err = tx.Exec("INSERT INTO security_settings(node_name,mode,updated_at) VALUES('',?,?) ON CONFLICT(node_name) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at", mode, time.Now().Unix()); err != nil {
return err
}
if err = s.bumpSecurityPolicyVersion(tx); err != nil {
return err
}
return tx.Commit()
}
func (s *Store) GetNodeSecurityMode(node string) (string, bool) {
@@ -429,8 +506,18 @@ func (s *Store) SetNodeSecurityMode(node, mode string) error {
if mode == "" {
return errors.New("invalid security mode")
}
_, err := s.DB.Exec("INSERT INTO security_settings(node_name,mode,updated_at) VALUES(?,?,?) ON CONFLICT(node_name) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at", node, mode, time.Now().Unix())
return err
tx, err := s.DB.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err = tx.Exec("INSERT INTO security_settings(node_name,mode,updated_at) VALUES(?,?,?) ON CONFLICT(node_name) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at", node, mode, time.Now().Unix()); err != nil {
return err
}
if err = s.bumpSecurityPolicyVersion(tx); err != nil {
return err
}
return tx.Commit()
}
type SecuritySetting struct {
@@ -454,3 +541,55 @@ func (s *Store) ListNodeSecurityModes() ([]SecuritySetting, error) {
}
return out, rows.Err()
}
func hashDeviceToken(token string) string {
h := sha256.Sum256([]byte(token))
return hex.EncodeToString(h[:])
}
// SetDeviceCredential stores only a SHA-256 hash of the per-device token.
func (s *Store) DeviceCredentialConfigured(name string) (bool, error) {
return s.HasDeviceCredential(name)
}
func (s *Store) SetDeviceCredential(name, token string) error {
if strings.TrimSpace(name) == "" || token == "" {
return errors.New("device name and token required")
}
now := time.Now().Unix()
_, err := s.DB.Exec(`INSERT INTO device_credentials(name,token_hash,created_at,updated_at)
VALUES(?,?,?,?) ON CONFLICT(name) DO UPDATE SET token_hash=excluded.token_hash,updated_at=excluded.updated_at`, name, hashDeviceToken(token), now, now)
return err
}
func (s *Store) VerifyDeviceCredential(name, token string) (bool, error) {
if name == "" || token == "" {
return false, nil
}
var stored string
err := s.DB.QueryRow("SELECT token_hash FROM device_credentials WHERE name=?", name).Scan(&stored)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
return subtleConstantTimeEqual(stored, hashDeviceToken(token)), nil
}
func subtleConstantTimeEqual(a, b string) bool {
if len(a) != len(b) {
return false
}
var v byte
for i := range a {
v |= a[i] ^ b[i]
}
return v == 0
}
func (s *Store) HasDeviceCredential(name string) (bool, error) {
var count int
err := s.DB.QueryRow("SELECT COUNT(*) FROM device_credentials WHERE name=?", name).Scan(&count)
return count > 0, err
}
+35
View File
@@ -58,3 +58,38 @@ func TestAuditConcurrent100NoLoss(t *testing.T) {
t.Fatalf("busy_timeout=%d, want >=5000", busy)
}
}
func TestDeviceCredentialHashAndRotation(t *testing.T) {
s, err := Open(filepath.Join(t.TempDir(), "commander.db"))
if err != nil {
t.Fatal(err)
}
defer s.DB.Close()
if err := s.SetDeviceCredential("node-1", "secret-one"); err != nil {
t.Fatal(err)
}
configured, err := s.HasDeviceCredential("node-1")
if err != nil || !configured {
t.Fatalf("credential should be configured: %v", err)
}
valid, err := s.VerifyDeviceCredential("node-1", "secret-one")
if err != nil || !valid {
t.Fatalf("valid credential rejected: %v", err)
}
valid, err = s.VerifyDeviceCredential("node-1", "wrong")
if err != nil || valid {
t.Fatal("wrong credential accepted")
}
if err := s.SetDeviceCredential("node-1", "secret-two"); err != nil {
t.Fatal(err)
}
valid, err = s.VerifyDeviceCredential("node-1", "secret-one")
if err != nil || valid {
t.Fatal("old credential accepted after rotation")
}
valid, err = s.VerifyDeviceCredential("node-1", "secret-two")
if err != nil || !valid {
t.Fatal("rotated credential rejected")
}
}
+10 -6
View File
@@ -24,14 +24,15 @@ type Runner interface {
}
type Panel struct {
Password string
Runner Runner
mu sync.RWMutex
sessions map[string]time.Time
Password string
AdminToken string
Runner Runner
mu sync.RWMutex
sessions map[string]time.Time
}
func New(password string, runner Runner) *Panel {
return &Panel{Password: password, Runner: runner, sessions: make(map[string]time.Time)}
func New(password, adminToken string, runner Runner) *Panel {
return &Panel{Password: password, AdminToken: adminToken, Runner: runner, sessions: make(map[string]time.Time)}
}
func (p *Panel) Handler() http.Handler {
@@ -110,6 +111,9 @@ func (p *Panel) securitySettings(w http.ResponseWriter, r *http.Request) {
http.Error(w, "security API unavailable", 501)
}
func (p *Panel) updateSecuritySettings(w http.ResponseWriter, r *http.Request) {
if p.AdminToken != "" {
r.Header.Set("X-Admin-Token", p.AdminToken)
}
if v, ok := p.Runner.(securityPanelRunner); ok {
v.UpdateSecuritySettingsJSON(w, r)
return
+1 -1
View File
@@ -16,7 +16,7 @@ func (testRunner) RotateAPIKey(w http.ResponseWriter, r *http.Request) {}
func (testRunner) DeleteDevice(w http.ResponseWriter, r *http.Request) {}
func TestStaticCSSContentType(t *testing.T) {
p := New("test-password", testRunner{})
p := New("test-password", "admin", testRunner{})
req := httptest.NewRequest("GET", "/static/app.css", nil)
rec := httptest.NewRecorder()
+160 -91
View File
@@ -2,7 +2,8 @@
"openapi": "3.1.0",
"info": {
"title": "VPS-Commander",
"version": "1.1.0"
"version": "2.0.0",
"description": "Current VPS-Commander HTTP contract. MCP tools are documented in docs/MCP_INTEGRATION.md."
},
"servers": [
{
@@ -163,124 +164,192 @@
"paths": {
"/api/v1/devices": {
"get": {
"operationId": "list_devices",
"security": [
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Devices",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Device"
}
}
}
}
"description": "OK"
}
}
}
},
"/api/v1/exec": {
"post": {
"operationId": "exec_command",
"security": [
{
"bearerAuth": []
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ExecRequest"
}
}
}
},
"responses": {
"200": {
"description": "Execution result",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ExecResponse"
}
}
}
"description": "OK"
}
}
}
},
"/api/v1/file/read": {
"post": {
"operationId": "read_file",
"security": [
{
"bearerAuth": []
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/FileReadRequest"
}
}
}
},
"responses": {
"200": {
"description": "File content",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/FileReadResponse"
}
}
}
"description": "OK"
}
}
}
},
"/api/v1/file/list": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/file/info": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/file/search": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/process/session": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/file/write": {
"post": {
"operationId": "write_file",
"security": [
{
"bearerAuth": []
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/FileWriteRequest"
}
}
}
},
"responses": {
"200": {
"description": "Write result",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/FileWriteResponse"
}
}
}
"description": "OK"
}
}
}
},
"/api/v1/devices/file/edit_block": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/mcp/services": {
"get": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/mcp/service": {
"delete": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/mcp/list": {
"get": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/mcp/call": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/mcp/test": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/security/settings": {
"get": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/security/settings/update": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/security/device-credentials/provision": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/notifications/webhooks": {
"get": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/notifications/webhook/update": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/notifications/webhook/delete": {
"delete": {
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/v1/notifications/webhook/test": {
"post": {
"responses": {
"200": {
"description": "OK"
}
}
}
}
}
}
}