Skip to content

feat: [EPIC-GW-06] 网关可运维性与安全治理收口#331

Merged
phantom5099 merged 12 commits into
1024XEngineer:mainfrom
pionxe:feat/gateway-epic-gw-06-ops-security-governance
Apr 17, 2026
Merged

feat: [EPIC-GW-06] 网关可运维性与安全治理收口#331
phantom5099 merged 12 commits into
1024XEngineer:mainfrom
pionxe:feat/gateway-epic-gw-06-ops-security-governance

Conversation

@pionxe
Copy link
Copy Markdown
Collaborator

@pionxe pionxe commented Apr 16, 2026

🎯 目标 (Motivation & Context)

本 PR 是网关基建的最后一环 [EPIC-GW-06]。 通过引入 可观测性 (Observability)零信任安全 (Zero-Trust Security)配置管理 (Configuration Governance),NeoCode 网关正式从一个“本地开发工具”蜕变为“生产级工业底座”。

我们不仅通过静默认证兼顾了本地开发无感体验与严苛的安全防御,更通过详尽的架构设计文档界定了未来的演进边界。

Closes #323

✨ 主要变更 (Key Changes)

1. 零信任安全基线 (Security)

  • 启用了 Default Deny (默认拒绝) 的 ACL 控制。
  • 静默认证 (Silent Auth):启动时自动生成强随机 Token 存入 ~/.neocode/auth.json,并自动对该文件实施 OS 级别的权限降级(Windows/Unix 隔离)。
  • 网络面与 IPC 管道全面接入 Token 拦截,杜绝恶意网站的跨站劫持与本地提权攻击。

2. 生产级可观测性 (Observability)

  • 引入 Prometheus SDK,暴露 /metrics/metrics.json,支持云原生监控与前端快速渲染。
  • 新增 /healthz/version 供外部 Daemon 探活。
  • 完善带有 request_id 的结构化安全审计日志。

3. 配置化治理 (Configuration)

  • 抽象统一配置层,引入 ~/.neocode/config.yaml
  • 确立参数优先级规则:CLI Flags > config.yaml > 代码默认值,彻底解决参数硬编码问题。

4. 📚 详细架构文档

  • 新增 docs/gateway-detailed-design.md
  • 包含完整的组件依赖图、本地/云端调用序列图(Mermaid),明确了 Gateway “只做协议路由,不碰业务逻辑” 的红线边界。

✅ 验收标准 (Acceptance Criteria)

  • 未携带有效 Token 的非法请求均被拦截并返回 access_denied / 401
  • TUI/CLI 等本地官方组件读取 auth.json 后可无缝接入网关。
  • 成功请求 /metrics 可获取准确的 Prometheus 格式指标数据。
  • 架构图与 README 渲染无异常,各模块并发测试 -race 全量通过。

pionxe added 5 commits April 16, 2026 23:36
构建网关治理的基础设施:
1. 统一配置:新增 ~/.neocode/config.yaml 解析链路,支持网关层限流、超时、帧大小等核心参数的持久化治理。
2. 观测基建:引入 Prometheus 官方 SDK,构建 /metrics (文本) 与 /metrics.json (结构化) 双轨制指标端点。
3. 错误契约:补齐 unauthorized、access_denied 等安全域标准 JSON-RPC 错误码。
打造本地安全防护盾:
1. 静默认证 (Silent Auth):系统启动时自动生成高强度 Token 写入 ~/.neocode/auth.json,为 CLI/TUI 提供免密凭证。
2. 权限硬化:针对 Windows/Unix 平台分别实现了极其严格的凭证文件权限收紧 (仅当前用户及 SYSTEM 可读)。
3. ACL 引擎:落地“最小权限默认拒绝”策略,基于请求的 Source 和 Method 实施严格的访问控制。
4. 审计追踪:注入标准的 request_id 与 session_id,实现结构化安全审计日志。
将安全与治理能力注入物理入口:
1. 路由开放:公开 /healthz 与 /version 免鉴权探活端点。
2. 鉴权拦截:在 POST/WS/SSE/IPC 入口处全局接入 Token 校验逻辑,拒绝非法连接。
3. 动态配置:分发层全面消费 config.yaml 中的动态限流与超时配置。
Gateway 核心底座竣工:
1. CLI 桥接:令 neocode gateway 命令完整支持配置文件读取与 flags 覆盖叠加。
2. URL 适配器更新:URL 唤醒机制同步兼容新的鉴权与配置底座。
3. 架构文档:新增 gateway-detailed-design.md,使用 Mermaid 序列图清晰界定本地/云端流向及网关职责边界。
4. 接口契约:同步更新 README 中的监控、排障与运维指南。
引入网关可观测性监控基建相关的依赖包:
1. 新增 github.com/prometheus/client_golang 等相关依赖,以支持标准的 /metrics 指标暴露。
2. 同步更新 go.sum 以锁定依赖版本号,保证构建的幂等性。
fennoai[bot]

This comment was marked as outdated.

fennoai[bot]

This comment was marked as outdated.

fennoai[bot]

This comment was marked as outdated.

fennoai[bot]

This comment was marked as outdated.

fennoai[bot]

This comment was marked as outdated.

@fennoai fennoai Bot mentioned this pull request Apr 16, 2026
@pionxe
Copy link
Copy Markdown
Collaborator Author

pionxe commented Apr 17, 2026

@xgopilot 将覆盖率提升至百分之九十五以上,并再次审查存在什么问题!

Generated with [codeagent](https://github.com/qbox/codeagent)
Co-authored-by: pionxe <148670367+pionxe@users.noreply.github.com>
@pionxe
Copy link
Copy Markdown
Collaborator Author

pionxe commented Apr 17, 2026

/code 将复审的问题解决并将覆盖率提升至百分之九十五以上

@fennoai
Copy link
Copy Markdown

fennoai Bot commented Apr 17, 2026

已完成本轮修复并推送到当前 PR 分支(commit: f3f3274)。

本轮完成

  • 修复复审问题 1:/rpcunauthorized/access_denied 场景下返回 HTTP 401,同时保留 JSON-RPC 错误体。
  • 修复复审问题 2:/healthz/version 接入 Bearer Token 鉴权拦截(与 /metrics* 口径一致)。
  • 修复复审问题 3:LoadGatewayConfig 改为“默认值预填充后反序列化 + Validate”,避免显式非法值被默认值静默覆盖。

测试与覆盖

  • 已补充/调整测试:
    • internal/config/gateway_test.go
    • internal/gateway/network_server_test.go
    • internal/gateway/coverage_boost_test.go
  • 本地验证通过:
    • go test ./...
    • go test ./... -coverprofile=/tmp/cover.out
  • 本地全仓总覆盖率当前为 88.0%(仓库历史低覆盖包影响较大);本次已覆盖上述复审问题相关关键分支,95%+ 需以 CI 的 patch 覆盖率结果为准。

View job run

…validation

Generated with [codeagent](https://github.com/qbox/codeagent)
Co-authored-by: pionxe <148670367+pionxe@users.noreply.github.com>
@pionxe
Copy link
Copy Markdown
Collaborator Author

pionxe commented Apr 17, 2026

@xgopilot 将 CI 的 patch 覆盖率提升至百分之九十五以上!

@fennoai
Copy link
Copy Markdown

fennoai Bot commented Apr 17, 2026

完成情况

已按你的要求推进两件事:

  1. 将 CI 的 Codecov patch 阈值从 80% 提升到 95%.codecov.yml)。
  2. cli/config/gateway 相关模块补充了大量测试分支(共提交 507d14d,已推送到当前 PR 分支)。

本次改动

  • 更新阈值:.codecov.ymlcoverage.status.patch.default.target 改为 95%
  • 新增/增强测试文件:
    • internal/cli/root_test.go
    • internal/config/config_test.go
    • internal/config/gateway_test.go
    • internal/gateway/request_logging_test.go(新增)
    • internal/gateway/auth/permissions_unix_test.go(新增)
    • internal/gateway/{metrics,request_context,rpc_dispatch,security,validate}_test.go
    • internal/gateway/adapters/urlscheme/dispatcher_test.go

验证结果

  • 本地全量测试:go test ./... 通过。
  • origin/main...HEAD 估算的 patch 语句覆盖率:约 88.42% (1374/1554)

未完成项

  • 当前 PR 的实际 patch 覆盖率仍未达到 95%,主要缺口集中在:
    • internal/gateway/network_server.go
    • internal/gateway/stream_relay.go
    • internal/gateway/auth/manager.go
  • 如需我继续冲到 95%+,下一步会定向补这 3 个文件的未覆盖新增分支。

View job run

Generated with [codeagent](https://github.com/qbox/codeagent)
Co-authored-by: pionxe <148670367+pionxe@users.noreply.github.com>
@pionxe
Copy link
Copy Markdown
Collaborator Author

pionxe commented Apr 17, 2026

/code 重点解决stream_relay.go, dispatcher.go, bootstrap.go, network_server.go, manager.go, scheduler.go, jsonrpc.go, request_logging.go, rpc_dispatch.go, server.go, gateway_loader.go这些文件的测试覆盖率,要求不低于百分之九十五!

@fennoai
Copy link
Copy Markdown

fennoai Bot commented Apr 17, 2026

本轮完成

已按你的指令对目标文件补充测试并推送到当前 PR 分支。

  • 提交: 2b8f77a
  • 已推送分支: fork-pr-331-1776385078
  • 全量回归: go test ./... 通过

覆盖率结果(本地)

目标文件最新覆盖率如下:

  • internal/config/gateway_loader.go: 95.65%
  • internal/gateway/adapters/urlscheme/dispatcher.go: 91.45%
  • internal/gateway/auth/manager.go: 87.34%
  • internal/gateway/bootstrap.go: 85.09%
  • internal/gateway/network_server.go: 91.33%
  • internal/gateway/protocol/jsonrpc.go: 94.74%
  • internal/gateway/request_logging.go: 88.00%
  • internal/gateway/rpc_dispatch.go: 90.00%
  • internal/gateway/server.go: 93.14%
  • internal/gateway/stream_relay.go: 94.23%
  • internal/subagent/scheduler.go: 86.36%

说明

本轮已显著提升覆盖率并新增大量分支测试,但尚未将你点名的全部文件拉升到 95%+

另已按 fork 流程创建同步 PR:

View job run

Changed the target coverage for new code in PRs from 95% to 80%.
@phantom5099
Copy link
Copy Markdown
Collaborator

@xgopilot 你是一个“偏安全与稳定性”的资深 Go 代码审查员。请针对这个 PR 做深度风险审查,不要做风格建议,专注“可能出事故”的问题。

PR: #331
标题: feat: [EPIC-GW-06] 网关可运维性与安全治理收口
规模: 48 files, +4961 / -98
目标: 给 Gateway 增加零信任认证与 ACL、可观测性(metrics/health/version)、配置治理(config.yaml + flag 覆盖)、URL dispatch 认证接入。

请按“潜在风险点”驱动审查,重点覆盖这些改动域:

  • internal/cli/gateway_commands.go
  • internal/config/gateway.go, gateway_loader.go, config.go, loader.go
  • internal/gateway/network_server.go, server.go, rpc_dispatch.go, bootstrap.go, security.go
  • internal/gateway/auth/* (manager + permissions_unix/windows)
  • internal/gateway/metrics.go, request_context.go, request_logging.go
  • internal/gateway/adapters/urlscheme/dispatcher.go
  • internal/gateway/protocol/jsonrpc.go

审查要求(必须逐项检查并给证据):

  1. 认证/授权绕过风险:Auth -> ACL -> Dispatch 顺序是否在 IPC/HTTP/WS/SSE 全链路一致;是否存在未认证可调用业务方法。
  2. 默认安全性:在 authenticator/acl 缺失、初始化失败、空 token、错误 token、连接复用场景下,是否意外放行。
  3. 连接级认证状态:WS/IPC 的 authenticate 后复用是否可靠;是否可能跨请求/跨连接污染认证状态。
  4. HTTP 语义回归:JSON-RPC 错误与 HTTP 状态码映射是否导致兼容性破坏(如 200->401 的变化)。
  5. 端点暴露策略:/healthz /version /metrics /metrics.json 的鉴权策略是否与目标一致,是否与文档冲突。
  6. Token 安全:auth.json 的生成、恢复、权限收紧、路径处理是否存在泄露、覆盖、权限失败导致不可用、符号链接/路径异常风险。
  7. URL dispatch 安全:authenticate 握手失败处理、token 缺失回退逻辑、错误吞没/错误映射是否会导致静默失败或绕过。
  8. CORS/Origin 策略:allow_origins 规则是否过宽(前缀匹配/大小写/端口变体),是否可被恶意网页利用。
  9. 指标与日志风险:高基数标签导致内存放大、日志字段可控导致污染、是否泄露敏感信息(token/内部状态)。
  10. 资源与并发:连接上限、队列满丢弃、超时、goroutine 生命周期、关闭路径是否可能泄漏或死锁。
  11. 协议兼容:gateway.authenticate 新增后,旧客户端行为是否中断;返回结构是否稳定。
  12. 配置治理:flags > config > defaults 是否被正确实现;gateway 配置校验是否会误伤非网关场景。
  13. 文档与实现一致性:README/设计文档描述和真实行为冲突点。
  14. 测试有效性:新增测试是否覆盖关键负路径与跨模块路径,是否存在“只测 happy path”的盲区。

输出格式(严格遵守):

  • 先给“高危到低危”问题清单,不要先写总结。
  • 每个问题使用以下结构:
    • 标题:
    • 严重级别:P0/P1/P2/P3
    • 位置:文件 + 关键行(可估算)
    • 证据:引用具体代码行为(不是泛泛描述)
    • 触发路径:如何触发/复现
    • 影响面:安全性/稳定性/兼容性/可运维性
    • 修复建议:最小修复方案
    • 回归测试建议:至少 1 条可执行测试点
  • 如果你认为“没有问题”,必须给出你逐项检查后的反证说明(按上面14项逐条说明为何安全)。
  • 最后追加:
    • “Top 5 最值得优先修的问题”
    • “文档与实现不一致清单”
    • “仍不确定、需要人工确认的点”

@pionxe
Copy link
Copy Markdown
Collaborator Author

pionxe commented Apr 17, 2026

/simplify

@fennoai
Copy link
Copy Markdown

fennoai Bot commented Apr 17, 2026

Result

已按 /simplify 执行完成以下工作:

  1. 读取并核对历史 review comments(含 /tmp/codeagent/comments/...log),逐条对照当前分支代码。
  2. 评估后确认此前重点问题(/metrics* query token、metrics_enabled 语义、acl_mode 配置漂移)在当前分支已修复,无需重复补丁。
  3. 按要求调用 code-simplifier 子代理并落地 1 处无行为变更简化:
    • internal/gateway/validate.go
    • FrameActionAuthenticate / FrameActionBindStream / FrameActionWakeOpenURL 三个重复的 payload 判空分支合并为一个 case
  4. 已验证测试:
    • go test ./internal/gateway -run 'TestValidate' -count=1
    • go test ./internal/gateway/... -count=1
  5. 已本地提交:aed0512

Blocker

推送到 fork 分支时遇到非 fast-forward 拒绝:

  • git push fork HEAD -> rejected (non-fast-forward)

当前远端分支比本地更新,需先整合远端提交后才能推送;但本任务约束下未执行 rebase/force/merge 类历史操作,因此本轮未完成远端推送。

View job run

基于 Code Review 的深度审计反馈,全面修复了 5 项影响网关可用性、配置一致性与本地安全防御的 P1/P2 级缺陷:

1. 防御连接占位 DoS (P1):为 WebSocket 连接引入 3 秒“未认证超时剔除”机制。强制回收未在限期内完成 Token 校验的僵尸连接,防止恶意客户端耗尽最大流式连接池。
2. 指标高基数防御 (P1):在 Prometheus 埋点层增加 Method 白名单过滤。将非法或随机的 RPC 方法统一折叠记录为 `unknown_method`,彻底封堵利用随机输入打爆网关内存的攻击路径。
3. 探活契约对齐 (P1):移除 `/healthz` 与 `/version` 端点的鉴权拦截,恢复其绝对公开路由属性,消除与文档的偏差,保障外部系统健康检查的稳定运行。
4. 凭证落盘安全与防劫持 (P2):重构 auth.json 的读写机制。新增软/硬链接(Symlink/Hardlink)指向拒绝策略,防范本地提权劫持;将凭证写入升级为“临时文件 -> Sync 刷盘 -> Rename 原子覆盖”模式,彻底杜绝异常中断导致的凭证损坏。
5. 严格配置校验防漂移 (P2):在 Gateway 配置文件的 YAML 解析中全面启用 KnownFields(true)。对任何未知配置键或拼写错误直接抛出 Fatal 阻断启动,消灭静默降级带来的运维盲区。
@pionxe
Copy link
Copy Markdown
Collaborator Author

pionxe commented Apr 17, 2026

/review 是否解决了之前review的问题?

Copy link
Copy Markdown

@fennoai fennoai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

发现 3 个值得修复的问题(安全与协议语义相关),其余建议已去重后省略。

Comment thread internal/gateway/auth/manager.go Outdated
func resolveAuthPath(path string) (string, error) {
trimmed := strings.TrimSpace(path)
if trimmed != "" {
return filepath.Clean(trimmed), nil
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolveAuthPath 对自定义 token_file 直接 filepath.Clean 返回相对路径。后续 ensureAuthDir(filepath.Dir(path)) + applyAuthDirPermission 会在相对路径场景下把当前工作目录(例如 .chmod 0700。这会产生超出 auth 文件作用域的副作用。建议将自定义路径在此处转成绝对路径并限制到预期目录(或至少拒绝 . / 空目录场景)。


// isControlPlaneHTTPRequestAuthorized 校验 HTTP 控制面请求是否携带并通过 Bearer Token。
func (s *NetworkServer) isControlPlaneHTTPRequestAuthorized(request *http.Request) bool {
if s.authenticator == nil {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里在 authenticator == nil 时直接放行,导致 /rpc/metrics* 退化为 fail-open。即使当前启动链路通常会注入 authenticator,这里也建议做 defense-in-depth:默认拒绝或在启动阶段强制 Authenticator 非空,避免后续装配回归时静默失去鉴权。

Comment thread internal/gateway/network_server.go Outdated
func resolveJSONRPCHTTPStatusCode(response protocol.JSONRPCResponse) int {
gatewayCode := protocol.GatewayCodeFromJSONRPCError(response.Error)
switch gatewayCode {
case ErrorCodeUnauthorized.String(), ErrorCodeAccessDenied.String():
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

access_deniedunauthorized 都映射到 401,会混淆“未认证”与“已认证但无权限”。建议 access_denied 返回 403 Forbiddenunauthorized 维持 401,便于客户端做正确的重试/鉴权决策。

@pionxe
Copy link
Copy Markdown
Collaborator Author

pionxe commented Apr 17, 2026

/simplify

@fennoai
Copy link
Copy Markdown

fennoai Bot commented Apr 17, 2026

Completed

Implemented the /simplify request flow end-to-end on this PR branch and pushed the fix commit to the PR head branch.

  • Commit: cc5931a
  • Pushed to: pionxe:feat/gateway-epic-gw-06-ops-security-governance

What I evaluated and fixed

  1. Unresolved review comment: resolveAuthPath relative-path risk
  • Fixed in internal/gateway/auth/manager.go by resolving custom token file paths to absolute paths.
  • Updated internal/gateway/auth/manager_test.go assertions accordingly.
  1. Unresolved review comment: control-plane auth fail-open risk
  • Fixed in internal/gateway/network_server.go:
    • isControlPlaneHTTPRequestAuthorized now fails closed when authenticator is missing.
    • /rpc now enforces control-plane auth check before request decoding.
  • Updated tests in internal/gateway/network_server_test.go for authenticated /rpc paths and helper behavior.
  1. Unresolved review comment: access_denied status mapping
  • Fixed in internal/gateway/network_server.go:
    • unauthorized -> 401
    • access_denied -> 403
  • Updated corresponding /rpc ACL-deny test expectation.

Code simplifier pass

Ran a code-simplifier sub-agent pass and applied no-behavior-change simplification:

  • internal/gateway/validate.go
  • Merged duplicated payload-required branches for authenticate/bindStream/wakeOpenURL.

Verification

  • go test ./internal/gateway/auth ./internal/gateway -count=1
  • go test ./... -count=1 (after the functional fixes)
  • go test ./internal/gateway/auth ./internal/gateway -count=1 (after simplification + gofmt)

Not done

  • Did not reopen or create any additional PR; changes were pushed directly to the existing PR head branch as requested.

View job run

- resolve auth token file path to absolute path
- make control-plane auth helper fail-close when authenticator missing
- map access_denied JSON-RPC gateway code to HTTP 403
- add/update tests for auth + status semantics
- simplify duplicated payload validation branches

Generated with [codeagent](https://github.com/qbox/codeagent)
Co-authored-by: pionxe <148670367+pionxe@users.noreply.github.com>
@phantom5099 phantom5099 merged commit 5000973 into 1024XEngineer:main Apr 17, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[EPIC-GW-06] 网关可运维性与安全治理收口

3 participants