feat(auth+zhiyid): 监听默认本机(ZHIYI_BIND) + 密钥强制(去硬编码回落) + /metrics 纳管 + 过渡期 legacy 兼容

卡 t_4fab32c1 的 AC1/AC2/AC3 实现 + 小怡 09-21 21:5x 过渡期补丁(legacy 行放行+限频告警)。
已部署并验收:127.0.0.1:7821 / 无key 401 / legacy 200 / 主密钥 200 / /metrics 无key 401 / /health 200 / LAN 不可达。
回滚点:~/.hermes/backups/zhiyid-sec-20260921/zhiyid-new.bin-2151
This commit is contained in:
xiaoyi
2026-09-21 21:56:47 +08:00
parent e01181e40f
commit 3a3e019c03
2 changed files with 108 additions and 9 deletions
+11 -3
View File
@@ -20,11 +20,18 @@ func main() {
port = "7821"
}
// t_4fab32c1 AC1: 监听地址可配,默认 127.0.0.1(仅本机)
// 旧代码写死 0.0.0.0,局域网内任何机器均可访问记忆库 API。
bind := os.Getenv("ZHIYI_BIND")
if bind == "" {
bind = "127.0.0.1"
}
srv := &http.Server{
Addr: "0.0.0.0:" + port,
Addr: bind + ":" + port,
Handler: api.NewServer(),
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second, // full consolidation takes ~15s, need headroom
WriteTimeout: 60 * time.Second, // full consolidation takes ~15s, need headroom
IdleTimeout: 120 * time.Second,
}
@@ -44,7 +51,8 @@ func main() {
}
}()
log.Printf("[zhiyid] 织忆 MemoryWeave 启动 — 端口 %s", port)
// t_4fab32c1 AC1: 日志输出实际绑定的地址
log.Printf("[zhiyid] 织忆 MemoryWeave 启动 — 绑定 %s:%s", bind, port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("[zhiyid] 启动失败: %v", err)
}
+97 -6
View File
@@ -2,6 +2,8 @@
package middleware
import (
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"net/http"
@@ -121,23 +123,108 @@ func init() {
// ─── HTTP 中间件 ─────────────────────────────────────────────
// Auth 认证中间件 (X-API-Key)
// t_4fab32c1 AC2: 密钥强制(无硬编码回落)。
// 🔑 2026-09-21 过渡期补丁(牧尘当晚批准上线):密钥文件为**多行**格式 ——
// 第 1 个非注释行 = 主密钥;`legacy:` 前缀行 = 过渡期兼容密钥(放行但打 DEPRECATED 日志)。
// 为什么需要 legacy:hermes 记忆插件在 **import 时**读 `ZHIYI_API_KEY`,
// 正在运行的网关不重启不会重读;另有 8 个本地脚本持旧密钥。
// 若直接轮换值 → 瞬间打断记忆读写(recall/commit 全 401)。
// 收口条件:客户端迁移完(网关重启后)删除 key 文件里的 legacy 行。
const keyFile = "/var/lib/memoryweave/.api-key"
// parseKeys 纯解析:data=key 文件内容,envKey=环境变量值。抽出来是为了可被单测直接覆盖。
func parseKeys(data, envKey string) (primary string, legacy []string) {
primary = strings.TrimSpace(envKey)
for _, line := range strings.Split(data, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if strings.HasPrefix(line, "legacy:") {
if k := strings.TrimSpace(strings.TrimPrefix(line, "legacy:")); k != "" {
legacy = append(legacy, k)
}
continue
}
if primary == "" {
primary = line
}
}
return primary, legacy
}
// loadKeys 返回 (主密钥, 过渡期兼容密钥列表)
func loadKeys() (primary string, legacy []string) {
data := ""
if b, err := os.ReadFile(keyFile); err == nil {
data = string(b)
}
return parseKeys(data, os.Getenv("API_KEY"))
}
var (
legacyUseMu sync.Mutex
legacyLast = map[string]time.Time{}
)
// noteLegacyUse 对 legacy 密钥放行做限频告警(每密钥 10 分钟一次)
func noteLegacyUse(key string) {
legacyUseMu.Lock()
last := legacyLast[key]
legacyLast[key] = time.Now()
legacyUseMu.Unlock()
if time.Since(last) > 10*time.Minute {
shown := key
if len(shown) > 6 {
shown = shown[:6] + "…"
}
log.Printf("[auth] DEPRECATED: 放行了过渡期 legacy 密钥(%s)。请迁移调用方到主密钥,并删除 %s 的 legacy 行收口。", shown, keyFile)
}
}
func isLegacy(list []string, key string) bool {
for _, k := range list {
if k == key {
return true
}
}
return false
}
func Auth(next http.Handler) http.Handler {
apiKey := os.Getenv("API_KEY")
apiKey, legacyKeys := loadKeys()
if apiKey == "" {
apiKey = "zhiyi-dev-key-2026"
// 生成随机密钥并持久化(无任何可用密钥时拒绝启动或落盘随机密钥)
buf := make([]byte, 32)
if _, err := rand.Read(buf); err != nil {
log.Fatalf("[auth] API_KEY 未设且无法生成随机密钥: %v — 拒绝启动", err)
}
apiKey = hex.EncodeToString(buf)
if err := os.MkdirAll("/var/lib/memoryweave", 0700); err != nil {
log.Printf("[auth] WARNING: 已生成随机密钥但无法创建目录: %v — 密钥仅存于内存,重启后失效", err)
} else if err := os.WriteFile(keyFile, []byte(apiKey+"\n"), 0600); err != nil {
log.Printf("[auth] WARNING: 已生成随机密钥但写入 %s 失败: %v — 密钥仅存于内存,重启后失效", keyFile, err)
} else {
log.Printf("[auth] API_KEY 未设 — 已生成随机密钥并写入 %s (0600)。请同步给调用方(zhiyi-cli / hermes 等)。", keyFile)
}
}
if len(legacyKeys) > 0 {
log.Printf("[auth] 已加载 %d 个过渡期 legacy 密钥(放行+告警);收口:迁移调用方后删除 %s 的 legacy 行", len(legacyKeys), keyFile)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// /health, /metrics, /static/*, / 不需要认证(/ 供 Web UI 使用)
if r.URL.Path == "/health" || r.URL.Path == "/metrics" ||
// t_4fab32c1 AC3: /metrics 纳入鉴权(旧版在免鉴权白名单内,无 key 即可
// 读取 episode 总数/进程 RSS/队列深度等运维指标,暴露系统内部状态)。
// /health 保留免鉴权(供 systemd / 监控探针使用);
// /static/* 和 / 保留免鉴权(Web UI 静态资源)。
if r.URL.Path == "/health" ||
strings.HasPrefix(r.URL.Path, "/static/") || r.URL.Path == "/" {
next.ServeHTTP(w, r)
return
}
key := r.Header.Get("X-API-Key")
if key != apiKey {
if key != apiKey && !isLegacy(legacyKeys, key) {
// t_2d4e3b92: 统一错误体 schema — 非 2xx + {"error":{"code","message","retry_after_s"}}
// 此前为扁平 {"error":"..."},调用方难以与成功体区分(曾导致把 401/429 误读为「召回 0 条」)。
w.Header().Set("Content-Type", "application/json")
@@ -146,6 +233,10 @@ func Auth(next http.Handler) http.Handler {
return
}
if key != apiKey {
noteLegacyUse(key) // 过渡期:legacy 密钥放行但留审计痕迹
}
// 提取 agent ID(从 X-Agent-ID 头或 URL 路径)
agentID := r.Header.Get("X-Agent-ID")
if agentID == "" {